diff --git a/README.md b/README.md index eb10d7d..9c0d9bf 100644 --- a/README.md +++ b/README.md @@ -117,7 +117,7 @@ They can be accessed in the workflow file using `${{ secrets.YOUR_KEY_NAME }}`. ### 4. `ai-model-name` (Optional) -Specify the name of the model you want to use to generate suggestions. Fallbacks to `gpt-4o-2024-08-06` for OpenAI, `claude-3-7-sonnet-latest` for Anthropic, `gemini-2.5-pro-preview-05-06` for Google's Gemini, `pixtral-12b-2409` for Mistral, and `deepseek/deepseek-r1` for OpenRouter if not specified. Here's a list of supported models: +Specify the name of the model you want to use to generate suggestions. Fallbacks to `gpt-5` for OpenAI, `claude-3-7-sonnet-latest` for Anthropic, `gemini-2.5-pro-preview-06-05` for Google's Gemini, `pixtral-12b-2409` for Mistral, and `google/gemini-2.5-pro-preview-06-05` for OpenRouter if not specified. Here's a list of supported models: For OpenAI: @@ -141,7 +141,7 @@ For Mistral: For OpenRouter: -- [deepseek/deepseek-r1](https://openrouter.ai/deepseek/deepseek-r1). +- Any of the models listed [here in OpenRouter](https://openrouter.ai/models?fmt=table&supported_parameters=response_format) that support `structured outputs`/`response_format`. For Google: diff --git a/dist/index.js b/dist/index.js index 0593143..91001c4 100644 --- a/dist/index.js +++ b/dist/index.js @@ -3723,7 +3723,7 @@ var __importStar = (this && this.__importStar) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.agentsStream = agentsStream; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const encodings_js_1 = __nccwpck_require__(5125); const event_streams_js_1 = __nccwpck_require__(3835); const M = __importStar(__nccwpck_require__(312)); @@ -4367,7 +4367,7 @@ var __importStar = (this && this.__importStar) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.chatStream = chatStream; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const encodings_js_1 = __nccwpck_require__(5125); const event_streams_js_1 = __nccwpck_require__(3835); const M = __importStar(__nccwpck_require__(312)); @@ -4898,7 +4898,7 @@ var __importStar = (this && this.__importStar) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.filesDownload = filesDownload; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const encodings_js_1 = __nccwpck_require__(5125); const M = __importStar(__nccwpck_require__(312)); const schemas_js_1 = __nccwpck_require__(7055); @@ -5557,7 +5557,7 @@ var __importStar = (this && this.__importStar) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.fimStream = fimStream; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const encodings_js_1 = __nccwpck_require__(5125); const event_streams_js_1 = __nccwpck_require__(3835); const M = __importStar(__nccwpck_require__(312)); @@ -7055,7 +7055,7 @@ exports.stringToBytes = stringToBytes; exports.stringFromBytes = stringFromBytes; exports.stringToBase64 = stringToBase64; exports.stringFromBase64 = stringFromBase64; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); function bytesToBase64(u8arr) { return btoa(String.fromCodePoint(...u8arr)); } @@ -7566,7 +7566,7 @@ exports.envSchema = void 0; exports.env = env; exports.resetEnv = resetEnv; const dlv_js_1 = __nccwpck_require__(5541); -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); exports.envSchema = z.object({ MISTRAL_API_KEY: z.string().optional(), MISTRAL_DEBUG: z.coerce.boolean().optional(), @@ -8619,7 +8619,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.parse = parse; exports.safeParse = safeParse; exports.collectExtraKeys = collectExtraKeys; -const zod_1 = __nccwpck_require__(4809); +const zod_1 = __nccwpck_require__(2046); const sdkvalidationerror_js_1 = __nccwpck_require__(2169); const fp_js_1 = __nccwpck_require__(1443); /** @@ -9173,7 +9173,7 @@ exports.agentsCompletionRequestToolChoiceToJSON = agentsCompletionRequestToolCho exports.agentsCompletionRequestToolChoiceFromJSON = agentsCompletionRequestToolChoiceFromJSON; exports.agentsCompletionRequestToJSON = agentsCompletionRequestToJSON; exports.agentsCompletionRequestFromJSON = agentsCompletionRequestFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); const assistantmessage_js_1 = __nccwpck_require__(9240); @@ -9406,7 +9406,7 @@ exports.agentsCompletionStreamRequestToolChoiceToJSON = agentsCompletionStreamRe exports.agentsCompletionStreamRequestToolChoiceFromJSON = agentsCompletionStreamRequestToolChoiceFromJSON; exports.agentsCompletionStreamRequestToJSON = agentsCompletionStreamRequestToJSON; exports.agentsCompletionStreamRequestFromJSON = agentsCompletionStreamRequestFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); const assistantmessage_js_1 = __nccwpck_require__(9240); @@ -9631,7 +9631,7 @@ var __importStar = (this && this.__importStar) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ApiEndpoint$ = exports.ApiEndpoint$outboundSchema = exports.ApiEndpoint$inboundSchema = exports.ApiEndpoint = void 0; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const enums_js_1 = __nccwpck_require__(9271); exports.ApiEndpoint = { RootV1ChatCompletions: "/v1/chat/completions", @@ -9700,7 +9700,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ArchiveFTModelOut$ = exports.ArchiveFTModelOut$outboundSchema = exports.ArchiveFTModelOut$inboundSchema = exports.ArchiveFTModelOutObject$ = exports.ArchiveFTModelOutObject$outboundSchema = exports.ArchiveFTModelOutObject$inboundSchema = exports.ArchiveFTModelOutObject = void 0; exports.archiveFTModelOutToJSON = archiveFTModelOutToJSON; exports.archiveFTModelOutFromJSON = archiveFTModelOutFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const schemas_js_1 = __nccwpck_require__(7055); exports.ArchiveFTModelOutObject = { Model: "model", @@ -9789,7 +9789,7 @@ exports.assistantMessageContentToJSON = assistantMessageContentToJSON; exports.assistantMessageContentFromJSON = assistantMessageContentFromJSON; exports.assistantMessageToJSON = assistantMessageToJSON; exports.assistantMessageFromJSON = assistantMessageFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); const contentchunk_js_1 = __nccwpck_require__(2889); @@ -9910,7 +9910,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.BaseModelCard$ = exports.BaseModelCard$outboundSchema = exports.BaseModelCard$inboundSchema = exports.Type$ = exports.Type$outboundSchema = exports.Type$inboundSchema = exports.Type = void 0; exports.baseModelCardToJSON = baseModelCardToJSON; exports.baseModelCardFromJSON = baseModelCardFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); const modelcapabilities_js_1 = __nccwpck_require__(8296); @@ -10029,7 +10029,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.BatchError$ = exports.BatchError$outboundSchema = exports.BatchError$inboundSchema = void 0; exports.batchErrorToJSON = batchErrorToJSON; exports.batchErrorFromJSON = batchErrorFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ exports.BatchError$inboundSchema = z.object({ @@ -10096,7 +10096,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.BatchJobIn$ = exports.BatchJobIn$outboundSchema = exports.BatchJobIn$inboundSchema = void 0; exports.batchJobInToJSON = batchJobInToJSON; exports.batchJobInFromJSON = batchJobInFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); const apiendpoint_js_1 = __nccwpck_require__(6238); @@ -10181,7 +10181,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.BatchJobOut$ = exports.BatchJobOut$outboundSchema = exports.BatchJobOut$inboundSchema = exports.BatchJobOutObject$ = exports.BatchJobOutObject$outboundSchema = exports.BatchJobOutObject$inboundSchema = exports.BatchJobOutObject = void 0; exports.batchJobOutToJSON = batchJobOutToJSON; exports.batchJobOutFromJSON = batchJobOutFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); const batcherror_js_1 = __nccwpck_require__(7357); @@ -10325,7 +10325,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.BatchJobsOut$ = exports.BatchJobsOut$outboundSchema = exports.BatchJobsOut$inboundSchema = exports.BatchJobsOutObject$ = exports.BatchJobsOutObject$outboundSchema = exports.BatchJobsOutObject$inboundSchema = exports.BatchJobsOutObject = void 0; exports.batchJobsOutToJSON = batchJobsOutToJSON; exports.batchJobsOutFromJSON = batchJobsOutFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const schemas_js_1 = __nccwpck_require__(7055); const batchjobout_js_1 = __nccwpck_require__(834); exports.BatchJobsOutObject = { @@ -10411,7 +10411,7 @@ var __importStar = (this && this.__importStar) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.BatchJobStatus$ = exports.BatchJobStatus$outboundSchema = exports.BatchJobStatus$inboundSchema = exports.BatchJobStatus = void 0; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); exports.BatchJobStatus = { Queued: "QUEUED", Running: "RUNNING", @@ -10480,7 +10480,7 @@ exports.chatClassificationRequestInputsToJSON = chatClassificationRequestInputsT exports.chatClassificationRequestInputsFromJSON = chatClassificationRequestInputsFromJSON; exports.chatClassificationRequestToJSON = chatClassificationRequestToJSON; exports.chatClassificationRequestFromJSON = chatClassificationRequestFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); const assistantmessage_js_1 = __nccwpck_require__(9240); @@ -10793,7 +10793,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ChatCompletionChoice$ = exports.ChatCompletionChoice$outboundSchema = exports.ChatCompletionChoice$inboundSchema = exports.FinishReason$ = exports.FinishReason$outboundSchema = exports.FinishReason$inboundSchema = exports.FinishReason = void 0; exports.chatCompletionChoiceToJSON = chatCompletionChoiceToJSON; exports.chatCompletionChoiceFromJSON = chatCompletionChoiceFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); const enums_js_1 = __nccwpck_require__(9271); @@ -10908,7 +10908,7 @@ exports.chatCompletionRequestToolChoiceToJSON = chatCompletionRequestToolChoiceT exports.chatCompletionRequestToolChoiceFromJSON = chatCompletionRequestToolChoiceFromJSON; exports.chatCompletionRequestToJSON = chatCompletionRequestToJSON; exports.chatCompletionRequestFromJSON = chatCompletionRequestFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); const assistantmessage_js_1 = __nccwpck_require__(9240); @@ -11144,7 +11144,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ChatCompletionResponse$ = exports.ChatCompletionResponse$outboundSchema = exports.ChatCompletionResponse$inboundSchema = void 0; exports.chatCompletionResponseToJSON = chatCompletionResponseToJSON; exports.chatCompletionResponseFromJSON = chatCompletionResponseFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const schemas_js_1 = __nccwpck_require__(7055); const chatcompletionchoice_js_1 = __nccwpck_require__(208); const usageinfo_js_1 = __nccwpck_require__(1804); @@ -11227,7 +11227,7 @@ exports.chatCompletionStreamRequestToolChoiceToJSON = chatCompletionStreamReques exports.chatCompletionStreamRequestToolChoiceFromJSON = chatCompletionStreamRequestToolChoiceFromJSON; exports.chatCompletionStreamRequestToJSON = chatCompletionStreamRequestToJSON; exports.chatCompletionStreamRequestFromJSON = chatCompletionStreamRequestFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); const assistantmessage_js_1 = __nccwpck_require__(9240); @@ -11462,7 +11462,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CheckpointOut$ = exports.CheckpointOut$outboundSchema = exports.CheckpointOut$inboundSchema = void 0; exports.checkpointOutToJSON = checkpointOutToJSON; exports.checkpointOutFromJSON = checkpointOutFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); const metricout_js_1 = __nccwpck_require__(427); @@ -11543,7 +11543,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ClassificationObject$ = exports.ClassificationObject$outboundSchema = exports.ClassificationObject$inboundSchema = void 0; exports.classificationObjectToJSON = classificationObjectToJSON; exports.classificationObjectFromJSON = classificationObjectFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ @@ -11621,7 +11621,7 @@ exports.classificationRequestInputsToJSON = classificationRequestInputsToJSON; exports.classificationRequestInputsFromJSON = classificationRequestInputsFromJSON; exports.classificationRequestToJSON = classificationRequestToJSON; exports.classificationRequestFromJSON = classificationRequestFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ @@ -11718,7 +11718,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ClassificationResponse$ = exports.ClassificationResponse$outboundSchema = exports.ClassificationResponse$inboundSchema = void 0; exports.classificationResponseToJSON = classificationResponseToJSON; exports.classificationResponseFromJSON = classificationResponseFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const schemas_js_1 = __nccwpck_require__(7055); const classificationobject_js_1 = __nccwpck_require__(4480); /** @internal */ @@ -11788,7 +11788,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CompletionChunk$ = exports.CompletionChunk$outboundSchema = exports.CompletionChunk$inboundSchema = void 0; exports.completionChunkToJSON = completionChunkToJSON; exports.completionChunkFromJSON = completionChunkFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const schemas_js_1 = __nccwpck_require__(7055); const completionresponsestreamchoice_js_1 = __nccwpck_require__(9937); const usageinfo_js_1 = __nccwpck_require__(1804); @@ -11865,7 +11865,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CompletionEvent$ = exports.CompletionEvent$outboundSchema = exports.CompletionEvent$inboundSchema = void 0; exports.completionEventToJSON = completionEventToJSON; exports.completionEventFromJSON = completionEventFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const schemas_js_1 = __nccwpck_require__(7055); const completionchunk_js_1 = __nccwpck_require__(2804); /** @internal */ @@ -11942,7 +11942,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CompletionResponseStreamChoice$ = exports.CompletionResponseStreamChoice$outboundSchema = exports.CompletionResponseStreamChoice$inboundSchema = exports.CompletionResponseStreamChoiceFinishReason$ = exports.CompletionResponseStreamChoiceFinishReason$outboundSchema = exports.CompletionResponseStreamChoiceFinishReason$inboundSchema = exports.CompletionResponseStreamChoiceFinishReason = void 0; exports.completionResponseStreamChoiceToJSON = completionResponseStreamChoiceToJSON; exports.completionResponseStreamChoiceFromJSON = completionResponseStreamChoiceFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); const enums_js_1 = __nccwpck_require__(9271); @@ -12050,7 +12050,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ContentChunk$ = exports.ContentChunk$outboundSchema = exports.ContentChunk$inboundSchema = void 0; exports.contentChunkToJSON = contentChunkToJSON; exports.contentChunkFromJSON = contentChunkFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const schemas_js_1 = __nccwpck_require__(7055); const imageurlchunk_js_1 = __nccwpck_require__(4316); const referencechunk_js_1 = __nccwpck_require__(7809); @@ -12130,7 +12130,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DeleteFileOut$ = exports.DeleteFileOut$outboundSchema = exports.DeleteFileOut$inboundSchema = void 0; exports.deleteFileOutToJSON = deleteFileOutToJSON; exports.deleteFileOutFromJSON = deleteFileOutFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ exports.DeleteFileOut$inboundSchema = z.object({ @@ -12199,7 +12199,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DeleteModelOut$ = exports.DeleteModelOut$outboundSchema = exports.DeleteModelOut$inboundSchema = void 0; exports.deleteModelOutToJSON = deleteModelOutToJSON; exports.deleteModelOutFromJSON = deleteModelOutFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ exports.DeleteModelOut$inboundSchema = z.object({ @@ -12270,7 +12270,7 @@ exports.contentToJSON = contentToJSON; exports.contentFromJSON = contentFromJSON; exports.deltaMessageToJSON = deltaMessageToJSON; exports.deltaMessageFromJSON = deltaMessageFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); const contentchunk_js_1 = __nccwpck_require__(2889); @@ -12375,7 +12375,7 @@ exports.detailedJobOutRepositoriesToJSON = detailedJobOutRepositoriesToJSON; exports.detailedJobOutRepositoriesFromJSON = detailedJobOutRepositoriesFromJSON; exports.detailedJobOutToJSON = detailedJobOutToJSON; exports.detailedJobOutFromJSON = detailedJobOutFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); const checkpointout_js_1 = __nccwpck_require__(1225); @@ -12596,7 +12596,7 @@ exports.inputsToJSON = inputsToJSON; exports.inputsFromJSON = inputsFromJSON; exports.embeddingRequestToJSON = embeddingRequestToJSON; exports.embeddingRequestFromJSON = embeddingRequestFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ @@ -12698,7 +12698,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.EmbeddingResponse$ = exports.EmbeddingResponse$outboundSchema = exports.EmbeddingResponse$inboundSchema = void 0; exports.embeddingResponseToJSON = embeddingResponseToJSON; exports.embeddingResponseFromJSON = embeddingResponseFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const schemas_js_1 = __nccwpck_require__(7055); const embeddingresponsedata_js_1 = __nccwpck_require__(2101); const usageinfo_js_1 = __nccwpck_require__(1804); @@ -12773,7 +12773,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.EmbeddingResponseData$ = exports.EmbeddingResponseData$outboundSchema = exports.EmbeddingResponseData$inboundSchema = void 0; exports.embeddingResponseDataToJSON = embeddingResponseDataToJSON; exports.embeddingResponseDataFromJSON = embeddingResponseDataFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ exports.EmbeddingResponseData$inboundSchema = z.object({ @@ -12842,7 +12842,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.EventOut$ = exports.EventOut$outboundSchema = exports.EventOut$inboundSchema = void 0; exports.eventOutToJSON = eventOutToJSON; exports.eventOutFromJSON = eventOutFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ @@ -12918,7 +12918,7 @@ var __importStar = (this && this.__importStar) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.FilePurpose$ = exports.FilePurpose$outboundSchema = exports.FilePurpose$inboundSchema = exports.FilePurpose = void 0; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const enums_js_1 = __nccwpck_require__(9271); exports.FilePurpose = { FineTune: "fine-tune", @@ -12984,7 +12984,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.FileSchema$ = exports.FileSchema$outboundSchema = exports.FileSchema$inboundSchema = void 0; exports.fileSchemaToJSON = fileSchemaToJSON; exports.fileSchemaFromJSON = fileSchemaFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); const filepurpose_js_1 = __nccwpck_require__(1087); @@ -13081,7 +13081,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.FileSignedURL$ = exports.FileSignedURL$outboundSchema = exports.FileSignedURL$inboundSchema = void 0; exports.fileSignedURLToJSON = fileSignedURLToJSON; exports.fileSignedURLFromJSON = fileSignedURLFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ exports.FileSignedURL$inboundSchema = z.object({ @@ -13148,7 +13148,7 @@ exports.fimCompletionRequestStopToJSON = fimCompletionRequestStopToJSON; exports.fimCompletionRequestStopFromJSON = fimCompletionRequestStopFromJSON; exports.fimCompletionRequestToJSON = fimCompletionRequestToJSON; exports.fimCompletionRequestFromJSON = fimCompletionRequestFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ @@ -13267,7 +13267,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.FIMCompletionResponse$ = exports.FIMCompletionResponse$outboundSchema = exports.FIMCompletionResponse$inboundSchema = void 0; exports.fimCompletionResponseToJSON = fimCompletionResponseToJSON; exports.fimCompletionResponseFromJSON = fimCompletionResponseFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const schemas_js_1 = __nccwpck_require__(7055); const chatcompletionchoice_js_1 = __nccwpck_require__(208); const usageinfo_js_1 = __nccwpck_require__(1804); @@ -13346,7 +13346,7 @@ exports.fimCompletionStreamRequestStopToJSON = fimCompletionStreamRequestStopToJ exports.fimCompletionStreamRequestStopFromJSON = fimCompletionStreamRequestStopFromJSON; exports.fimCompletionStreamRequestToJSON = fimCompletionStreamRequestToJSON; exports.fimCompletionStreamRequestFromJSON = fimCompletionStreamRequestFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ @@ -13465,7 +13465,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.FTModelCapabilitiesOut$ = exports.FTModelCapabilitiesOut$outboundSchema = exports.FTModelCapabilitiesOut$inboundSchema = void 0; exports.ftModelCapabilitiesOutToJSON = ftModelCapabilitiesOutToJSON; exports.ftModelCapabilitiesOutFromJSON = ftModelCapabilitiesOutFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ @@ -13551,7 +13551,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.FTModelCard$ = exports.FTModelCard$outboundSchema = exports.FTModelCard$inboundSchema = exports.FTModelCardType$ = exports.FTModelCardType$outboundSchema = exports.FTModelCardType$inboundSchema = exports.FTModelCardType = void 0; exports.ftModelCardToJSON = ftModelCardToJSON; exports.ftModelCardFromJSON = ftModelCardFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); const modelcapabilities_js_1 = __nccwpck_require__(8296); @@ -13676,7 +13676,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.FTModelOut$ = exports.FTModelOut$outboundSchema = exports.FTModelOut$inboundSchema = exports.FTModelOutObject$ = exports.FTModelOutObject$outboundSchema = exports.FTModelOutObject$inboundSchema = exports.FTModelOutObject = void 0; exports.ftModelOutToJSON = ftModelOutToJSON; exports.ftModelOutFromJSON = ftModelOutFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); const ftmodelcapabilitiesout_js_1 = __nccwpck_require__(7296); @@ -13793,7 +13793,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.FunctionT$ = exports.FunctionT$outboundSchema = exports.FunctionT$inboundSchema = void 0; exports.functionToJSON = functionToJSON; exports.functionFromJSON = functionFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ exports.FunctionT$inboundSchema = z.object({ @@ -13864,7 +13864,7 @@ exports.argumentsToJSON = argumentsToJSON; exports.argumentsFromJSON = argumentsFromJSON; exports.functionCallToJSON = functionCallToJSON; exports.functionCallFromJSON = functionCallFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ exports.Arguments$inboundSchema = z.union([z.record(z.any()), z.string()]); @@ -13952,7 +13952,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.FunctionName$ = exports.FunctionName$outboundSchema = exports.FunctionName$inboundSchema = void 0; exports.functionNameToJSON = functionNameToJSON; exports.functionNameFromJSON = functionNameFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ exports.FunctionName$inboundSchema = z.object({ @@ -14017,7 +14017,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.GithubRepositoryIn$ = exports.GithubRepositoryIn$outboundSchema = exports.GithubRepositoryIn$inboundSchema = exports.GithubRepositoryInType$ = exports.GithubRepositoryInType$outboundSchema = exports.GithubRepositoryInType$inboundSchema = exports.GithubRepositoryInType = void 0; exports.githubRepositoryInToJSON = githubRepositoryInToJSON; exports.githubRepositoryInFromJSON = githubRepositoryInFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const schemas_js_1 = __nccwpck_require__(7055); exports.GithubRepositoryInType = { Github: "github", @@ -14110,7 +14110,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.GithubRepositoryOut$ = exports.GithubRepositoryOut$outboundSchema = exports.GithubRepositoryOut$inboundSchema = exports.GithubRepositoryOutType$ = exports.GithubRepositoryOutType$outboundSchema = exports.GithubRepositoryOutType$inboundSchema = exports.GithubRepositoryOutType = void 0; exports.githubRepositoryOutToJSON = githubRepositoryOutToJSON; exports.githubRepositoryOutFromJSON = githubRepositoryOutFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); exports.GithubRepositoryOutType = { @@ -14212,7 +14212,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ImageURL$ = exports.ImageURL$outboundSchema = exports.ImageURL$inboundSchema = void 0; exports.imageURLToJSON = imageURLToJSON; exports.imageURLFromJSON = imageURLFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ exports.ImageURL$inboundSchema = z.object({ @@ -14281,7 +14281,7 @@ exports.imageURLChunkImageURLToJSON = imageURLChunkImageURLToJSON; exports.imageURLChunkImageURLFromJSON = imageURLChunkImageURLFromJSON; exports.imageURLChunkToJSON = imageURLChunkToJSON; exports.imageURLChunkFromJSON = imageURLChunkFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); const imageurl_js_1 = __nccwpck_require__(7893); @@ -14510,7 +14510,7 @@ exports.jobInRepositoriesToJSON = jobInRepositoriesToJSON; exports.jobInRepositoriesFromJSON = jobInRepositoriesFromJSON; exports.jobInToJSON = jobInToJSON; exports.jobInFromJSON = jobInFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); const githubrepositoryin_js_1 = __nccwpck_require__(4323); @@ -14650,7 +14650,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.JobMetadataOut$ = exports.JobMetadataOut$outboundSchema = exports.JobMetadataOut$inboundSchema = void 0; exports.jobMetadataOutToJSON = jobMetadataOutToJSON; exports.jobMetadataOutFromJSON = jobMetadataOutFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ @@ -14750,7 +14750,7 @@ exports.repositoriesToJSON = repositoriesToJSON; exports.repositoriesFromJSON = repositoriesFromJSON; exports.jobOutToJSON = jobOutToJSON; exports.jobOutFromJSON = jobOutFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); const githubrepositoryout_js_1 = __nccwpck_require__(2410); @@ -14972,7 +14972,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.JobsOut$ = exports.JobsOut$outboundSchema = exports.JobsOut$inboundSchema = exports.JobsOutObject$ = exports.JobsOutObject$outboundSchema = exports.JobsOutObject$inboundSchema = exports.JobsOutObject = void 0; exports.jobsOutToJSON = jobsOutToJSON; exports.jobsOutFromJSON = jobsOutFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const schemas_js_1 = __nccwpck_require__(7055); const jobout_js_1 = __nccwpck_require__(6186); exports.JobsOutObject = { @@ -15060,7 +15060,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.LegacyJobMetadataOut$ = exports.LegacyJobMetadataOut$outboundSchema = exports.LegacyJobMetadataOut$inboundSchema = exports.LegacyJobMetadataOutObject$ = exports.LegacyJobMetadataOutObject$outboundSchema = exports.LegacyJobMetadataOutObject$inboundSchema = exports.LegacyJobMetadataOutObject = void 0; exports.legacyJobMetadataOutToJSON = legacyJobMetadataOutToJSON; exports.legacyJobMetadataOutFromJSON = legacyJobMetadataOutFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); exports.LegacyJobMetadataOutObject = { @@ -15186,7 +15186,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ListFilesOut$ = exports.ListFilesOut$outboundSchema = exports.ListFilesOut$inboundSchema = void 0; exports.listFilesOutToJSON = listFilesOutToJSON; exports.listFilesOutFromJSON = listFilesOutFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const schemas_js_1 = __nccwpck_require__(7055); const fileschema_js_1 = __nccwpck_require__(5662); /** @internal */ @@ -15256,7 +15256,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.MetricOut$ = exports.MetricOut$outboundSchema = exports.MetricOut$inboundSchema = void 0; exports.metricOutToJSON = metricOutToJSON; exports.metricOutFromJSON = metricOutFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ @@ -15338,7 +15338,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ModelCapabilities$ = exports.ModelCapabilities$outboundSchema = exports.ModelCapabilities$inboundSchema = void 0; exports.modelCapabilitiesToJSON = modelCapabilitiesToJSON; exports.modelCapabilitiesFromJSON = modelCapabilitiesFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ @@ -15428,7 +15428,7 @@ exports.dataToJSON = dataToJSON; exports.dataFromJSON = dataFromJSON; exports.modelListToJSON = modelListToJSON; exports.modelListFromJSON = modelListFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const schemas_js_1 = __nccwpck_require__(7055); const basemodelcard_js_1 = __nccwpck_require__(579); const ftmodelcard_js_1 = __nccwpck_require__(3942); @@ -15547,7 +15547,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ReferenceChunk$ = exports.ReferenceChunk$outboundSchema = exports.ReferenceChunk$inboundSchema = exports.ReferenceChunkType$ = exports.ReferenceChunkType$outboundSchema = exports.ReferenceChunkType$inboundSchema = exports.ReferenceChunkType = void 0; exports.referenceChunkToJSON = referenceChunkToJSON; exports.referenceChunkFromJSON = referenceChunkFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); exports.ReferenceChunkType = { @@ -15641,7 +15641,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ResponseFormat$ = exports.ResponseFormat$outboundSchema = exports.ResponseFormat$inboundSchema = void 0; exports.responseFormatToJSON = responseFormatToJSON; exports.responseFormatFromJSON = responseFormatFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const schemas_js_1 = __nccwpck_require__(7055); const responseformats_js_1 = __nccwpck_require__(6190); /** @internal */ @@ -15705,7 +15705,7 @@ var __importStar = (this && this.__importStar) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ResponseFormats$ = exports.ResponseFormats$outboundSchema = exports.ResponseFormats$inboundSchema = exports.ResponseFormats = void 0; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); /** * An object specifying the format that the model must output. Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is in JSON. When using JSON mode you MUST also instruct the model to produce JSON yourself with a system or a user message. */ @@ -15766,7 +15766,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.RetrieveFileOut$ = exports.RetrieveFileOut$outboundSchema = exports.RetrieveFileOut$inboundSchema = void 0; exports.retrieveFileOutToJSON = retrieveFileOutToJSON; exports.retrieveFileOutFromJSON = retrieveFileOutFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); const filepurpose_js_1 = __nccwpck_require__(1087); @@ -15863,7 +15863,7 @@ var __importStar = (this && this.__importStar) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.SampleType$ = exports.SampleType$outboundSchema = exports.SampleType$inboundSchema = exports.SampleType = void 0; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const enums_js_1 = __nccwpck_require__(9271); exports.SampleType = { Pretrain: "pretrain", @@ -15932,7 +15932,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Security$ = exports.Security$outboundSchema = exports.Security$inboundSchema = void 0; exports.securityToJSON = securityToJSON; exports.securityFromJSON = securityFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ @@ -16004,7 +16004,7 @@ var __importStar = (this && this.__importStar) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Source$ = exports.Source$outboundSchema = exports.Source$inboundSchema = exports.Source = void 0; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const enums_js_1 = __nccwpck_require__(9271); exports.Source = { Upload: "upload", @@ -16074,7 +16074,7 @@ exports.systemMessageContentToJSON = systemMessageContentToJSON; exports.systemMessageContentFromJSON = systemMessageContentFromJSON; exports.systemMessageToJSON = systemMessageToJSON; exports.systemMessageFromJSON = systemMessageFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const schemas_js_1 = __nccwpck_require__(7055); const textchunk_js_1 = __nccwpck_require__(599); exports.Role = { @@ -16181,7 +16181,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.TextChunk$ = exports.TextChunk$outboundSchema = exports.TextChunk$inboundSchema = exports.TextChunkType$ = exports.TextChunkType$outboundSchema = exports.TextChunkType$inboundSchema = exports.TextChunkType = void 0; exports.textChunkToJSON = textChunkToJSON; exports.textChunkFromJSON = textChunkFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const schemas_js_1 = __nccwpck_require__(7055); exports.TextChunkType = { Text: "text", @@ -16266,7 +16266,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Tool$ = exports.Tool$outboundSchema = exports.Tool$inboundSchema = void 0; exports.toolToJSON = toolToJSON; exports.toolFromJSON = toolFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const schemas_js_1 = __nccwpck_require__(7055); const function_js_1 = __nccwpck_require__(6603); const tooltypes_js_1 = __nccwpck_require__(6340); @@ -16336,7 +16336,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ToolCall$ = exports.ToolCall$outboundSchema = exports.ToolCall$inboundSchema = void 0; exports.toolCallToJSON = toolCallToJSON; exports.toolCallFromJSON = toolCallFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const schemas_js_1 = __nccwpck_require__(7055); const functioncall_js_1 = __nccwpck_require__(347); const tooltypes_js_1 = __nccwpck_require__(6340); @@ -16407,7 +16407,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ToolChoice$ = exports.ToolChoice$outboundSchema = exports.ToolChoice$inboundSchema = void 0; exports.toolChoiceToJSON = toolChoiceToJSON; exports.toolChoiceFromJSON = toolChoiceFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const schemas_js_1 = __nccwpck_require__(7055); const functionname_js_1 = __nccwpck_require__(9636); const tooltypes_js_1 = __nccwpck_require__(6340); @@ -16474,7 +16474,7 @@ var __importStar = (this && this.__importStar) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ToolChoiceEnum$ = exports.ToolChoiceEnum$outboundSchema = exports.ToolChoiceEnum$inboundSchema = exports.ToolChoiceEnum = void 0; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); exports.ToolChoiceEnum = { Auto: "auto", None: "none", @@ -16536,7 +16536,7 @@ exports.toolMessageContentToJSON = toolMessageContentToJSON; exports.toolMessageContentFromJSON = toolMessageContentFromJSON; exports.toolMessageToJSON = toolMessageToJSON; exports.toolMessageFromJSON = toolMessageFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); const contentchunk_js_1 = __nccwpck_require__(2889); @@ -16654,7 +16654,7 @@ var __importStar = (this && this.__importStar) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ToolTypes$ = exports.ToolTypes$outboundSchema = exports.ToolTypes$inboundSchema = exports.ToolTypes = void 0; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const enums_js_1 = __nccwpck_require__(9271); exports.ToolTypes = { Function: "function", @@ -16719,7 +16719,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.TrainingFile$ = exports.TrainingFile$outboundSchema = exports.TrainingFile$inboundSchema = void 0; exports.trainingFileToJSON = trainingFileToJSON; exports.trainingFileFromJSON = trainingFileFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ @@ -16795,7 +16795,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.TrainingParameters$ = exports.TrainingParameters$outboundSchema = exports.TrainingParameters$inboundSchema = void 0; exports.trainingParametersToJSON = trainingParametersToJSON; exports.trainingParametersFromJSON = trainingParametersFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ @@ -16891,7 +16891,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.TrainingParametersIn$ = exports.TrainingParametersIn$outboundSchema = exports.TrainingParametersIn$inboundSchema = void 0; exports.trainingParametersInToJSON = trainingParametersInToJSON; exports.trainingParametersInFromJSON = trainingParametersInFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ @@ -16987,7 +16987,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.UnarchiveFTModelOut$ = exports.UnarchiveFTModelOut$outboundSchema = exports.UnarchiveFTModelOut$inboundSchema = exports.UnarchiveFTModelOutObject$ = exports.UnarchiveFTModelOutObject$outboundSchema = exports.UnarchiveFTModelOutObject$inboundSchema = exports.UnarchiveFTModelOutObject = void 0; exports.unarchiveFTModelOutToJSON = unarchiveFTModelOutToJSON; exports.unarchiveFTModelOutFromJSON = unarchiveFTModelOutFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const schemas_js_1 = __nccwpck_require__(7055); exports.UnarchiveFTModelOutObject = { Model: "model", @@ -17074,7 +17074,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.UpdateFTModelIn$ = exports.UpdateFTModelIn$outboundSchema = exports.UpdateFTModelIn$inboundSchema = void 0; exports.updateFTModelInToJSON = updateFTModelInToJSON; exports.updateFTModelInFromJSON = updateFTModelInFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ exports.UpdateFTModelIn$inboundSchema = z.object({ @@ -17141,7 +17141,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.UploadFileOut$ = exports.UploadFileOut$outboundSchema = exports.UploadFileOut$inboundSchema = void 0; exports.uploadFileOutToJSON = uploadFileOutToJSON; exports.uploadFileOutFromJSON = uploadFileOutFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); const filepurpose_js_1 = __nccwpck_require__(1087); @@ -17238,7 +17238,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.UsageInfo$ = exports.UsageInfo$outboundSchema = exports.UsageInfo$inboundSchema = void 0; exports.usageInfoToJSON = usageInfoToJSON; exports.usageInfoFromJSON = usageInfoFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ @@ -17322,7 +17322,7 @@ exports.userMessageContentToJSON = userMessageContentToJSON; exports.userMessageContentFromJSON = userMessageContentFromJSON; exports.userMessageToJSON = userMessageToJSON; exports.userMessageFromJSON = userMessageFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const schemas_js_1 = __nccwpck_require__(7055); const contentchunk_js_1 = __nccwpck_require__(2889); exports.UserMessageRole = { @@ -17431,7 +17431,7 @@ exports.locToJSON = locToJSON; exports.locFromJSON = locFromJSON; exports.validationErrorToJSON = validationErrorToJSON; exports.validationErrorFromJSON = validationErrorFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ exports.Loc$inboundSchema = z.union([z.string(), z.number().int()]); @@ -17522,7 +17522,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.WandbIntegration$ = exports.WandbIntegration$outboundSchema = exports.WandbIntegration$inboundSchema = exports.WandbIntegrationType$ = exports.WandbIntegrationType$outboundSchema = exports.WandbIntegrationType$inboundSchema = exports.WandbIntegrationType = void 0; exports.wandbIntegrationToJSON = wandbIntegrationToJSON; exports.wandbIntegrationFromJSON = wandbIntegrationFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); exports.WandbIntegrationType = { @@ -17624,7 +17624,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.WandbIntegrationOut$ = exports.WandbIntegrationOut$outboundSchema = exports.WandbIntegrationOut$inboundSchema = exports.WandbIntegrationOutType$ = exports.WandbIntegrationOutType$outboundSchema = exports.WandbIntegrationOutType$inboundSchema = exports.WandbIntegrationOutType = void 0; exports.wandbIntegrationOutToJSON = wandbIntegrationOutToJSON; exports.wandbIntegrationOutFromJSON = wandbIntegrationOutFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); exports.WandbIntegrationOutType = { @@ -17804,7 +17804,7 @@ var __importStar = (this && this.__importStar) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.HTTPValidationError$ = exports.HTTPValidationError$outboundSchema = exports.HTTPValidationError$inboundSchema = exports.HTTPValidationError = void 0; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const components = __importStar(__nccwpck_require__(8471)); class HTTPValidationError extends Error { constructor(err) { @@ -17937,7 +17937,7 @@ var __importStar = (this && this.__importStar) || function (mod) { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.SDKValidationError = void 0; exports.formatZodError = formatZodError; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); class SDKValidationError extends Error { constructor(message, cause, rawValue) { super(`${message}: ${cause}`); @@ -18049,7 +18049,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DeleteModelV1ModelsModelIdDeleteRequest$ = exports.DeleteModelV1ModelsModelIdDeleteRequest$outboundSchema = exports.DeleteModelV1ModelsModelIdDeleteRequest$inboundSchema = void 0; exports.deleteModelV1ModelsModelIdDeleteRequestToJSON = deleteModelV1ModelsModelIdDeleteRequestToJSON; exports.deleteModelV1ModelsModelIdDeleteRequestFromJSON = deleteModelV1ModelsModelIdDeleteRequestFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ @@ -18123,7 +18123,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.FilesApiRoutesDeleteFileRequest$ = exports.FilesApiRoutesDeleteFileRequest$outboundSchema = exports.FilesApiRoutesDeleteFileRequest$inboundSchema = void 0; exports.filesApiRoutesDeleteFileRequestToJSON = filesApiRoutesDeleteFileRequestToJSON; exports.filesApiRoutesDeleteFileRequestFromJSON = filesApiRoutesDeleteFileRequestFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ @@ -18197,7 +18197,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.FilesApiRoutesDownloadFileRequest$ = exports.FilesApiRoutesDownloadFileRequest$outboundSchema = exports.FilesApiRoutesDownloadFileRequest$inboundSchema = void 0; exports.filesApiRoutesDownloadFileRequestToJSON = filesApiRoutesDownloadFileRequestToJSON; exports.filesApiRoutesDownloadFileRequestFromJSON = filesApiRoutesDownloadFileRequestFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ @@ -18271,7 +18271,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.FilesApiRoutesGetSignedUrlRequest$ = exports.FilesApiRoutesGetSignedUrlRequest$outboundSchema = exports.FilesApiRoutesGetSignedUrlRequest$inboundSchema = void 0; exports.filesApiRoutesGetSignedUrlRequestToJSON = filesApiRoutesGetSignedUrlRequestToJSON; exports.filesApiRoutesGetSignedUrlRequestFromJSON = filesApiRoutesGetSignedUrlRequestFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ @@ -18347,7 +18347,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.FilesApiRoutesListFilesRequest$ = exports.FilesApiRoutesListFilesRequest$outboundSchema = exports.FilesApiRoutesListFilesRequest$inboundSchema = void 0; exports.filesApiRoutesListFilesRequestToJSON = filesApiRoutesListFilesRequestToJSON; exports.filesApiRoutesListFilesRequestFromJSON = filesApiRoutesListFilesRequestFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); const components = __importStar(__nccwpck_require__(8471)); @@ -18436,7 +18436,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.FilesApiRoutesRetrieveFileRequest$ = exports.FilesApiRoutesRetrieveFileRequest$outboundSchema = exports.FilesApiRoutesRetrieveFileRequest$inboundSchema = void 0; exports.filesApiRoutesRetrieveFileRequestToJSON = filesApiRoutesRetrieveFileRequestToJSON; exports.filesApiRoutesRetrieveFileRequestFromJSON = filesApiRoutesRetrieveFileRequestFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ @@ -18512,7 +18512,7 @@ exports.fileToJSON = fileToJSON; exports.fileFromJSON = fileFromJSON; exports.filesApiRoutesUploadFileMultiPartBodyParamsToJSON = filesApiRoutesUploadFileMultiPartBodyParamsToJSON; exports.filesApiRoutesUploadFileMultiPartBodyParamsFromJSON = filesApiRoutesUploadFileMultiPartBodyParamsFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const schemas_js_1 = __nccwpck_require__(7055); const blobs_js_1 = __nccwpck_require__(1057); const components = __importStar(__nccwpck_require__(8471)); @@ -18664,7 +18664,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.JobsApiRoutesBatchCancelBatchJobRequest$ = exports.JobsApiRoutesBatchCancelBatchJobRequest$outboundSchema = exports.JobsApiRoutesBatchCancelBatchJobRequest$inboundSchema = void 0; exports.jobsApiRoutesBatchCancelBatchJobRequestToJSON = jobsApiRoutesBatchCancelBatchJobRequestToJSON; exports.jobsApiRoutesBatchCancelBatchJobRequestFromJSON = jobsApiRoutesBatchCancelBatchJobRequestFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ @@ -18738,7 +18738,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.JobsApiRoutesBatchGetBatchJobRequest$ = exports.JobsApiRoutesBatchGetBatchJobRequest$outboundSchema = exports.JobsApiRoutesBatchGetBatchJobRequest$inboundSchema = void 0; exports.jobsApiRoutesBatchGetBatchJobRequestToJSON = jobsApiRoutesBatchGetBatchJobRequestToJSON; exports.jobsApiRoutesBatchGetBatchJobRequestFromJSON = jobsApiRoutesBatchGetBatchJobRequestFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ @@ -18812,7 +18812,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.JobsApiRoutesBatchGetBatchJobsRequest$ = exports.JobsApiRoutesBatchGetBatchJobsRequest$outboundSchema = exports.JobsApiRoutesBatchGetBatchJobsRequest$inboundSchema = void 0; exports.jobsApiRoutesBatchGetBatchJobsRequestToJSON = jobsApiRoutesBatchGetBatchJobsRequestToJSON; exports.jobsApiRoutesBatchGetBatchJobsRequestFromJSON = jobsApiRoutesBatchGetBatchJobsRequestFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); const components = __importStar(__nccwpck_require__(8471)); @@ -18903,7 +18903,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.JobsApiRoutesFineTuningArchiveFineTunedModelRequest$ = exports.JobsApiRoutesFineTuningArchiveFineTunedModelRequest$outboundSchema = exports.JobsApiRoutesFineTuningArchiveFineTunedModelRequest$inboundSchema = void 0; exports.jobsApiRoutesFineTuningArchiveFineTunedModelRequestToJSON = jobsApiRoutesFineTuningArchiveFineTunedModelRequestToJSON; exports.jobsApiRoutesFineTuningArchiveFineTunedModelRequestFromJSON = jobsApiRoutesFineTuningArchiveFineTunedModelRequestFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ @@ -18977,7 +18977,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.JobsApiRoutesFineTuningCancelFineTuningJobRequest$ = exports.JobsApiRoutesFineTuningCancelFineTuningJobRequest$outboundSchema = exports.JobsApiRoutesFineTuningCancelFineTuningJobRequest$inboundSchema = void 0; exports.jobsApiRoutesFineTuningCancelFineTuningJobRequestToJSON = jobsApiRoutesFineTuningCancelFineTuningJobRequestToJSON; exports.jobsApiRoutesFineTuningCancelFineTuningJobRequestFromJSON = jobsApiRoutesFineTuningCancelFineTuningJobRequestFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ @@ -19051,7 +19051,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.JobsApiRoutesFineTuningCreateFineTuningJobResponse$ = exports.JobsApiRoutesFineTuningCreateFineTuningJobResponse$outboundSchema = exports.JobsApiRoutesFineTuningCreateFineTuningJobResponse$inboundSchema = void 0; exports.jobsApiRoutesFineTuningCreateFineTuningJobResponseToJSON = jobsApiRoutesFineTuningCreateFineTuningJobResponseToJSON; exports.jobsApiRoutesFineTuningCreateFineTuningJobResponseFromJSON = jobsApiRoutesFineTuningCreateFineTuningJobResponseFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const schemas_js_1 = __nccwpck_require__(7055); const components = __importStar(__nccwpck_require__(8471)); /** @internal */ @@ -19119,7 +19119,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.JobsApiRoutesFineTuningGetFineTuningJobRequest$ = exports.JobsApiRoutesFineTuningGetFineTuningJobRequest$outboundSchema = exports.JobsApiRoutesFineTuningGetFineTuningJobRequest$inboundSchema = void 0; exports.jobsApiRoutesFineTuningGetFineTuningJobRequestToJSON = jobsApiRoutesFineTuningGetFineTuningJobRequestToJSON; exports.jobsApiRoutesFineTuningGetFineTuningJobRequestFromJSON = jobsApiRoutesFineTuningGetFineTuningJobRequestFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ @@ -19193,7 +19193,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.JobsApiRoutesFineTuningGetFineTuningJobsRequest$ = exports.JobsApiRoutesFineTuningGetFineTuningJobsRequest$outboundSchema = exports.JobsApiRoutesFineTuningGetFineTuningJobsRequest$inboundSchema = exports.Status$ = exports.Status$outboundSchema = exports.Status$inboundSchema = exports.Status = void 0; exports.jobsApiRoutesFineTuningGetFineTuningJobsRequestToJSON = jobsApiRoutesFineTuningGetFineTuningJobsRequestToJSON; exports.jobsApiRoutesFineTuningGetFineTuningJobsRequestFromJSON = jobsApiRoutesFineTuningGetFineTuningJobsRequestFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); /** @@ -19323,7 +19323,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.JobsApiRoutesFineTuningStartFineTuningJobRequest$ = exports.JobsApiRoutesFineTuningStartFineTuningJobRequest$outboundSchema = exports.JobsApiRoutesFineTuningStartFineTuningJobRequest$inboundSchema = void 0; exports.jobsApiRoutesFineTuningStartFineTuningJobRequestToJSON = jobsApiRoutesFineTuningStartFineTuningJobRequestToJSON; exports.jobsApiRoutesFineTuningStartFineTuningJobRequestFromJSON = jobsApiRoutesFineTuningStartFineTuningJobRequestFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ @@ -19397,7 +19397,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.JobsApiRoutesFineTuningUnarchiveFineTunedModelRequest$ = exports.JobsApiRoutesFineTuningUnarchiveFineTunedModelRequest$outboundSchema = exports.JobsApiRoutesFineTuningUnarchiveFineTunedModelRequest$inboundSchema = void 0; exports.jobsApiRoutesFineTuningUnarchiveFineTunedModelRequestToJSON = jobsApiRoutesFineTuningUnarchiveFineTunedModelRequestToJSON; exports.jobsApiRoutesFineTuningUnarchiveFineTunedModelRequestFromJSON = jobsApiRoutesFineTuningUnarchiveFineTunedModelRequestFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ @@ -19471,7 +19471,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.JobsApiRoutesFineTuningUpdateFineTunedModelRequest$ = exports.JobsApiRoutesFineTuningUpdateFineTunedModelRequest$outboundSchema = exports.JobsApiRoutesFineTuningUpdateFineTunedModelRequest$inboundSchema = void 0; exports.jobsApiRoutesFineTuningUpdateFineTunedModelRequestToJSON = jobsApiRoutesFineTuningUpdateFineTunedModelRequestToJSON; exports.jobsApiRoutesFineTuningUpdateFineTunedModelRequestFromJSON = jobsApiRoutesFineTuningUpdateFineTunedModelRequestFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); const components = __importStar(__nccwpck_require__(8471)); @@ -19552,7 +19552,7 @@ exports.retrieveModelV1ModelsModelIdGetRequestToJSON = retrieveModelV1ModelsMode exports.retrieveModelV1ModelsModelIdGetRequestFromJSON = retrieveModelV1ModelsModelIdGetRequestFromJSON; exports.retrieveModelV1ModelsModelIdGetResponseRetrieveModelV1ModelsModelIdGetToJSON = retrieveModelV1ModelsModelIdGetResponseRetrieveModelV1ModelsModelIdGetToJSON; exports.retrieveModelV1ModelsModelIdGetResponseRetrieveModelV1ModelsModelIdGetFromJSON = retrieveModelV1ModelsModelIdGetResponseRetrieveModelV1ModelsModelIdGetFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); const components = __importStar(__nccwpck_require__(8471)); @@ -20220,7 +20220,7 @@ var __importStar = (this && this.__importStar) || function (mod) { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.blobLikeSchema = void 0; exports.isBlobLike = isBlobLike; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); exports.blobLikeSchema = z.custom(isBlobLike, { message: "expected a Blob, File or Blob-like object", fatal: true, @@ -24012,642 +24012,6 @@ var request = withDefaults(import_endpoint.endpoint, { 0 && (0); -/***/ }), - -/***/ 7413: -/***/ ((module, exports, __nccwpck_require__) => { - -/** - * @author Toru Nagashima - * See LICENSE file in root directory for full license. - */ - - -Object.defineProperty(exports, "__esModule", ({ value: true })); - -var eventTargetShim = __nccwpck_require__(6577); - -/** - * The signal class. - * @see https://dom.spec.whatwg.org/#abortsignal - */ -class AbortSignal extends eventTargetShim.EventTarget { - /** - * AbortSignal cannot be constructed directly. - */ - constructor() { - super(); - throw new TypeError("AbortSignal cannot be constructed directly"); - } - /** - * Returns `true` if this `AbortSignal`'s `AbortController` has signaled to abort, and `false` otherwise. - */ - get aborted() { - const aborted = abortedFlags.get(this); - if (typeof aborted !== "boolean") { - throw new TypeError(`Expected 'this' to be an 'AbortSignal' object, but got ${this === null ? "null" : typeof this}`); - } - return aborted; - } -} -eventTargetShim.defineEventAttribute(AbortSignal.prototype, "abort"); -/** - * Create an AbortSignal object. - */ -function createAbortSignal() { - const signal = Object.create(AbortSignal.prototype); - eventTargetShim.EventTarget.call(signal); - abortedFlags.set(signal, false); - return signal; -} -/** - * Abort a given signal. - */ -function abortSignal(signal) { - if (abortedFlags.get(signal) !== false) { - return; - } - abortedFlags.set(signal, true); - signal.dispatchEvent({ type: "abort" }); -} -/** - * Aborted flag for each instances. - */ -const abortedFlags = new WeakMap(); -// Properties should be enumerable. -Object.defineProperties(AbortSignal.prototype, { - aborted: { enumerable: true }, -}); -// `toString()` should return `"[object AbortSignal]"` -if (typeof Symbol === "function" && typeof Symbol.toStringTag === "symbol") { - Object.defineProperty(AbortSignal.prototype, Symbol.toStringTag, { - configurable: true, - value: "AbortSignal", - }); -} - -/** - * The AbortController. - * @see https://dom.spec.whatwg.org/#abortcontroller - */ -class AbortController { - /** - * Initialize this controller. - */ - constructor() { - signals.set(this, createAbortSignal()); - } - /** - * Returns the `AbortSignal` object associated with this object. - */ - get signal() { - return getSignal(this); - } - /** - * Abort and signal to any observers that the associated activity is to be aborted. - */ - abort() { - abortSignal(getSignal(this)); - } -} -/** - * Associated signals. - */ -const signals = new WeakMap(); -/** - * Get the associated signal of a given controller. - */ -function getSignal(controller) { - const signal = signals.get(controller); - if (signal == null) { - throw new TypeError(`Expected 'this' to be an 'AbortController' object, but got ${controller === null ? "null" : typeof controller}`); - } - return signal; -} -// Properties should be enumerable. -Object.defineProperties(AbortController.prototype, { - signal: { enumerable: true }, - abort: { enumerable: true }, -}); -if (typeof Symbol === "function" && typeof Symbol.toStringTag === "symbol") { - Object.defineProperty(AbortController.prototype, Symbol.toStringTag, { - configurable: true, - value: "AbortController", - }); -} - -exports.AbortController = AbortController; -exports.AbortSignal = AbortSignal; -exports["default"] = AbortController; - -module.exports = AbortController -module.exports.AbortController = module.exports["default"] = AbortController -module.exports.AbortSignal = AbortSignal -//# sourceMappingURL=abort-controller.js.map - - -/***/ }), - -/***/ 3873: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const HttpAgent = __nccwpck_require__(2532); -module.exports = HttpAgent; -module.exports.HttpAgent = HttpAgent; -module.exports.HttpsAgent = __nccwpck_require__(414); -module.exports.constants = __nccwpck_require__(6160); - - -/***/ }), - -/***/ 2532: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const OriginalAgent = (__nccwpck_require__(8611).Agent); -const ms = __nccwpck_require__(3724); -const debug = (__nccwpck_require__(9023).debuglog)('agentkeepalive'); -const { - INIT_SOCKET, - CURRENT_ID, - CREATE_ID, - SOCKET_CREATED_TIME, - SOCKET_NAME, - SOCKET_REQUEST_COUNT, - SOCKET_REQUEST_FINISHED_COUNT, -} = __nccwpck_require__(6160); - -// OriginalAgent come from -// - https://github.com/nodejs/node/blob/v8.12.0/lib/_http_agent.js -// - https://github.com/nodejs/node/blob/v10.12.0/lib/_http_agent.js - -// node <= 10 -let defaultTimeoutListenerCount = 1; -const majorVersion = parseInt(process.version.split('.', 1)[0].substring(1)); -if (majorVersion >= 11 && majorVersion <= 12) { - defaultTimeoutListenerCount = 2; -} else if (majorVersion >= 13) { - defaultTimeoutListenerCount = 3; -} - -function deprecate(message) { - console.log('[agentkeepalive:deprecated] %s', message); -} - -class Agent extends OriginalAgent { - constructor(options) { - options = options || {}; - options.keepAlive = options.keepAlive !== false; - // default is keep-alive and 4s free socket timeout - // see https://medium.com/ssense-tech/reduce-networking-errors-in-nodejs-23b4eb9f2d83 - if (options.freeSocketTimeout === undefined) { - options.freeSocketTimeout = 4000; - } - // Legacy API: keepAliveTimeout should be rename to `freeSocketTimeout` - if (options.keepAliveTimeout) { - deprecate('options.keepAliveTimeout is deprecated, please use options.freeSocketTimeout instead'); - options.freeSocketTimeout = options.keepAliveTimeout; - delete options.keepAliveTimeout; - } - // Legacy API: freeSocketKeepAliveTimeout should be rename to `freeSocketTimeout` - if (options.freeSocketKeepAliveTimeout) { - deprecate('options.freeSocketKeepAliveTimeout is deprecated, please use options.freeSocketTimeout instead'); - options.freeSocketTimeout = options.freeSocketKeepAliveTimeout; - delete options.freeSocketKeepAliveTimeout; - } - - // Sets the socket to timeout after timeout milliseconds of inactivity on the socket. - // By default is double free socket timeout. - if (options.timeout === undefined) { - // make sure socket default inactivity timeout >= 8s - options.timeout = Math.max(options.freeSocketTimeout * 2, 8000); - } - - // support humanize format - options.timeout = ms(options.timeout); - options.freeSocketTimeout = ms(options.freeSocketTimeout); - options.socketActiveTTL = options.socketActiveTTL ? ms(options.socketActiveTTL) : 0; - - super(options); - - this[CURRENT_ID] = 0; - - // create socket success counter - this.createSocketCount = 0; - this.createSocketCountLastCheck = 0; - - this.createSocketErrorCount = 0; - this.createSocketErrorCountLastCheck = 0; - - this.closeSocketCount = 0; - this.closeSocketCountLastCheck = 0; - - // socket error event count - this.errorSocketCount = 0; - this.errorSocketCountLastCheck = 0; - - // request finished counter - this.requestCount = 0; - this.requestCountLastCheck = 0; - - // including free socket timeout counter - this.timeoutSocketCount = 0; - this.timeoutSocketCountLastCheck = 0; - - this.on('free', socket => { - // https://github.com/nodejs/node/pull/32000 - // Node.js native agent will check socket timeout eqs agent.options.timeout. - // Use the ttl or freeSocketTimeout to overwrite. - const timeout = this.calcSocketTimeout(socket); - if (timeout > 0 && socket.timeout !== timeout) { - socket.setTimeout(timeout); - } - }); - } - - get freeSocketKeepAliveTimeout() { - deprecate('agent.freeSocketKeepAliveTimeout is deprecated, please use agent.options.freeSocketTimeout instead'); - return this.options.freeSocketTimeout; - } - - get timeout() { - deprecate('agent.timeout is deprecated, please use agent.options.timeout instead'); - return this.options.timeout; - } - - get socketActiveTTL() { - deprecate('agent.socketActiveTTL is deprecated, please use agent.options.socketActiveTTL instead'); - return this.options.socketActiveTTL; - } - - calcSocketTimeout(socket) { - /** - * return <= 0: should free socket - * return > 0: should update socket timeout - * return undefined: not find custom timeout - */ - let freeSocketTimeout = this.options.freeSocketTimeout; - const socketActiveTTL = this.options.socketActiveTTL; - if (socketActiveTTL) { - // check socketActiveTTL - const aliveTime = Date.now() - socket[SOCKET_CREATED_TIME]; - const diff = socketActiveTTL - aliveTime; - if (diff <= 0) { - return diff; - } - if (freeSocketTimeout && diff < freeSocketTimeout) { - freeSocketTimeout = diff; - } - } - // set freeSocketTimeout - if (freeSocketTimeout) { - // set free keepalive timer - // try to use socket custom freeSocketTimeout first, support headers['keep-alive'] - // https://github.com/node-modules/urllib/blob/b76053020923f4d99a1c93cf2e16e0c5ba10bacf/lib/urllib.js#L498 - const customFreeSocketTimeout = socket.freeSocketTimeout || socket.freeSocketKeepAliveTimeout; - return customFreeSocketTimeout || freeSocketTimeout; - } - } - - keepSocketAlive(socket) { - const result = super.keepSocketAlive(socket); - // should not keepAlive, do nothing - if (!result) return result; - - const customTimeout = this.calcSocketTimeout(socket); - if (typeof customTimeout === 'undefined') { - return true; - } - if (customTimeout <= 0) { - debug('%s(requests: %s, finished: %s) free but need to destroy by TTL, request count %s, diff is %s', - socket[SOCKET_NAME], socket[SOCKET_REQUEST_COUNT], socket[SOCKET_REQUEST_FINISHED_COUNT], customTimeout); - return false; - } - if (socket.timeout !== customTimeout) { - socket.setTimeout(customTimeout); - } - return true; - } - - // only call on addRequest - reuseSocket(...args) { - // reuseSocket(socket, req) - super.reuseSocket(...args); - const socket = args[0]; - const req = args[1]; - req.reusedSocket = true; - const agentTimeout = this.options.timeout; - if (getSocketTimeout(socket) !== agentTimeout) { - // reset timeout before use - socket.setTimeout(agentTimeout); - debug('%s reset timeout to %sms', socket[SOCKET_NAME], agentTimeout); - } - socket[SOCKET_REQUEST_COUNT]++; - debug('%s(requests: %s, finished: %s) reuse on addRequest, timeout %sms', - socket[SOCKET_NAME], socket[SOCKET_REQUEST_COUNT], socket[SOCKET_REQUEST_FINISHED_COUNT], - getSocketTimeout(socket)); - } - - [CREATE_ID]() { - const id = this[CURRENT_ID]++; - if (this[CURRENT_ID] === Number.MAX_SAFE_INTEGER) this[CURRENT_ID] = 0; - return id; - } - - [INIT_SOCKET](socket, options) { - // bugfix here. - // https on node 8, 10 won't set agent.options.timeout by default - // TODO: need to fix on node itself - if (options.timeout) { - const timeout = getSocketTimeout(socket); - if (!timeout) { - socket.setTimeout(options.timeout); - } - } - - if (this.options.keepAlive) { - // Disable Nagle's algorithm: http://blog.caustik.com/2012/04/08/scaling-node-js-to-100k-concurrent-connections/ - // https://fengmk2.com/benchmark/nagle-algorithm-delayed-ack-mock.html - socket.setNoDelay(true); - } - this.createSocketCount++; - if (this.options.socketActiveTTL) { - socket[SOCKET_CREATED_TIME] = Date.now(); - } - // don't show the hole '-----BEGIN CERTIFICATE----' key string - socket[SOCKET_NAME] = `sock[${this[CREATE_ID]()}#${options._agentKey}]`.split('-----BEGIN', 1)[0]; - socket[SOCKET_REQUEST_COUNT] = 1; - socket[SOCKET_REQUEST_FINISHED_COUNT] = 0; - installListeners(this, socket, options); - } - - createConnection(options, oncreate) { - let called = false; - const onNewCreate = (err, socket) => { - if (called) return; - called = true; - - if (err) { - this.createSocketErrorCount++; - return oncreate(err); - } - this[INIT_SOCKET](socket, options); - oncreate(err, socket); - }; - - const newSocket = super.createConnection(options, onNewCreate); - if (newSocket) onNewCreate(null, newSocket); - return newSocket; - } - - get statusChanged() { - const changed = this.createSocketCount !== this.createSocketCountLastCheck || - this.createSocketErrorCount !== this.createSocketErrorCountLastCheck || - this.closeSocketCount !== this.closeSocketCountLastCheck || - this.errorSocketCount !== this.errorSocketCountLastCheck || - this.timeoutSocketCount !== this.timeoutSocketCountLastCheck || - this.requestCount !== this.requestCountLastCheck; - if (changed) { - this.createSocketCountLastCheck = this.createSocketCount; - this.createSocketErrorCountLastCheck = this.createSocketErrorCount; - this.closeSocketCountLastCheck = this.closeSocketCount; - this.errorSocketCountLastCheck = this.errorSocketCount; - this.timeoutSocketCountLastCheck = this.timeoutSocketCount; - this.requestCountLastCheck = this.requestCount; - } - return changed; - } - - getCurrentStatus() { - return { - createSocketCount: this.createSocketCount, - createSocketErrorCount: this.createSocketErrorCount, - closeSocketCount: this.closeSocketCount, - errorSocketCount: this.errorSocketCount, - timeoutSocketCount: this.timeoutSocketCount, - requestCount: this.requestCount, - freeSockets: inspect(this.freeSockets), - sockets: inspect(this.sockets), - requests: inspect(this.requests), - }; - } -} - -// node 8 don't has timeout attribute on socket -// https://github.com/nodejs/node/pull/21204/files#diff-e6ef024c3775d787c38487a6309e491dR408 -function getSocketTimeout(socket) { - return socket.timeout || socket._idleTimeout; -} - -function installListeners(agent, socket, options) { - debug('%s create, timeout %sms', socket[SOCKET_NAME], getSocketTimeout(socket)); - - // listener socket events: close, timeout, error, free - function onFree() { - // create and socket.emit('free') logic - // https://github.com/nodejs/node/blob/master/lib/_http_agent.js#L311 - // no req on the socket, it should be the new socket - if (!socket._httpMessage && socket[SOCKET_REQUEST_COUNT] === 1) return; - - socket[SOCKET_REQUEST_FINISHED_COUNT]++; - agent.requestCount++; - debug('%s(requests: %s, finished: %s) free', - socket[SOCKET_NAME], socket[SOCKET_REQUEST_COUNT], socket[SOCKET_REQUEST_FINISHED_COUNT]); - - // should reuse on pedding requests? - const name = agent.getName(options); - if (socket.writable && agent.requests[name] && agent.requests[name].length) { - // will be reuse on agent free listener - socket[SOCKET_REQUEST_COUNT]++; - debug('%s(requests: %s, finished: %s) will be reuse on agent free event', - socket[SOCKET_NAME], socket[SOCKET_REQUEST_COUNT], socket[SOCKET_REQUEST_FINISHED_COUNT]); - } - } - socket.on('free', onFree); - - function onClose(isError) { - debug('%s(requests: %s, finished: %s) close, isError: %s', - socket[SOCKET_NAME], socket[SOCKET_REQUEST_COUNT], socket[SOCKET_REQUEST_FINISHED_COUNT], isError); - agent.closeSocketCount++; - } - socket.on('close', onClose); - - // start socket timeout handler - function onTimeout() { - // onTimeout and emitRequestTimeout(_http_client.js) - // https://github.com/nodejs/node/blob/v12.x/lib/_http_client.js#L711 - const listenerCount = socket.listeners('timeout').length; - // node <= 10, default listenerCount is 1, onTimeout - // 11 < node <= 12, default listenerCount is 2, onTimeout and emitRequestTimeout - // node >= 13, default listenerCount is 3, onTimeout, - // onTimeout(https://github.com/nodejs/node/pull/32000/files#diff-5f7fb0850412c6be189faeddea6c5359R333) - // and emitRequestTimeout - const timeout = getSocketTimeout(socket); - const req = socket._httpMessage; - const reqTimeoutListenerCount = req && req.listeners('timeout').length || 0; - debug('%s(requests: %s, finished: %s) timeout after %sms, listeners %s, defaultTimeoutListenerCount %s, hasHttpRequest %s, HttpRequest timeoutListenerCount %s', - socket[SOCKET_NAME], socket[SOCKET_REQUEST_COUNT], socket[SOCKET_REQUEST_FINISHED_COUNT], - timeout, listenerCount, defaultTimeoutListenerCount, !!req, reqTimeoutListenerCount); - if (debug.enabled) { - debug('timeout listeners: %s', socket.listeners('timeout').map(f => f.name).join(', ')); - } - agent.timeoutSocketCount++; - const name = agent.getName(options); - if (agent.freeSockets[name] && agent.freeSockets[name].indexOf(socket) !== -1) { - // free socket timeout, destroy quietly - socket.destroy(); - // Remove it from freeSockets list immediately to prevent new requests - // from being sent through this socket. - agent.removeSocket(socket, options); - debug('%s is free, destroy quietly', socket[SOCKET_NAME]); - } else { - // if there is no any request socket timeout handler, - // agent need to handle socket timeout itself. - // - // custom request socket timeout handle logic must follow these rules: - // 1. Destroy socket first - // 2. Must emit socket 'agentRemove' event tell agent remove socket - // from freeSockets list immediately. - // Otherise you may be get 'socket hang up' error when reuse - // free socket and timeout happen in the same time. - if (reqTimeoutListenerCount === 0) { - const error = new Error('Socket timeout'); - error.code = 'ERR_SOCKET_TIMEOUT'; - error.timeout = timeout; - // must manually call socket.end() or socket.destroy() to end the connection. - // https://nodejs.org/dist/latest-v10.x/docs/api/net.html#net_socket_settimeout_timeout_callback - socket.destroy(error); - agent.removeSocket(socket, options); - debug('%s destroy with timeout error', socket[SOCKET_NAME]); - } - } - } - socket.on('timeout', onTimeout); - - function onError(err) { - const listenerCount = socket.listeners('error').length; - debug('%s(requests: %s, finished: %s) error: %s, listenerCount: %s', - socket[SOCKET_NAME], socket[SOCKET_REQUEST_COUNT], socket[SOCKET_REQUEST_FINISHED_COUNT], - err, listenerCount); - agent.errorSocketCount++; - if (listenerCount === 1) { - // if socket don't contain error event handler, don't catch it, emit it again - debug('%s emit uncaught error event', socket[SOCKET_NAME]); - socket.removeListener('error', onError); - socket.emit('error', err); - } - } - socket.on('error', onError); - - function onRemove() { - debug('%s(requests: %s, finished: %s) agentRemove', - socket[SOCKET_NAME], - socket[SOCKET_REQUEST_COUNT], socket[SOCKET_REQUEST_FINISHED_COUNT]); - // We need this function for cases like HTTP 'upgrade' - // (defined by WebSockets) where we need to remove a socket from the - // pool because it'll be locked up indefinitely - socket.removeListener('close', onClose); - socket.removeListener('error', onError); - socket.removeListener('free', onFree); - socket.removeListener('timeout', onTimeout); - socket.removeListener('agentRemove', onRemove); - } - socket.on('agentRemove', onRemove); -} - -module.exports = Agent; - -function inspect(obj) { - const res = {}; - for (const key in obj) { - res[key] = obj[key].length; - } - return res; -} - - -/***/ }), - -/***/ 6160: -/***/ ((module) => { - - - -module.exports = { - // agent - CURRENT_ID: Symbol('agentkeepalive#currentId'), - CREATE_ID: Symbol('agentkeepalive#createId'), - INIT_SOCKET: Symbol('agentkeepalive#initSocket'), - CREATE_HTTPS_CONNECTION: Symbol('agentkeepalive#createHttpsConnection'), - // socket - SOCKET_CREATED_TIME: Symbol('agentkeepalive#socketCreatedTime'), - SOCKET_NAME: Symbol('agentkeepalive#socketName'), - SOCKET_REQUEST_COUNT: Symbol('agentkeepalive#socketRequestCount'), - SOCKET_REQUEST_FINISHED_COUNT: Symbol('agentkeepalive#socketRequestFinishedCount'), -}; - - -/***/ }), - -/***/ 414: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const OriginalHttpsAgent = (__nccwpck_require__(5692).Agent); -const HttpAgent = __nccwpck_require__(2532); -const { - INIT_SOCKET, - CREATE_HTTPS_CONNECTION, -} = __nccwpck_require__(6160); - -class HttpsAgent extends HttpAgent { - constructor(options) { - super(options); - - this.defaultPort = 443; - this.protocol = 'https:'; - this.maxCachedSessions = this.options.maxCachedSessions; - /* istanbul ignore next */ - if (this.maxCachedSessions === undefined) { - this.maxCachedSessions = 100; - } - - this._sessionCache = { - map: {}, - list: [], - }; - } - - createConnection(options, oncreate) { - const socket = this[CREATE_HTTPS_CONNECTION](options, oncreate); - this[INIT_SOCKET](socket, options); - return socket; - } -} - -// https://github.com/nodejs/node/blob/master/lib/https.js#L89 -HttpsAgent.prototype[CREATE_HTTPS_CONNECTION] = OriginalHttpsAgent.prototype.createConnection; - -[ - 'getName', - '_getSession', - '_cacheSession', - // https://github.com/nodejs/node/pull/4982 - '_evictSession', -].forEach(function(method) { - /* istanbul ignore next */ - if (typeof OriginalHttpsAgent.prototype[method] === 'function') { - HttpsAgent.prototype[method] = OriginalHttpsAgent.prototype[method]; - } -}); - -module.exports = HttpsAgent; - - /***/ }), /***/ 8793: @@ -26089,1105 +25453,227 @@ exports.Deprecation = Deprecation; /***/ }), -/***/ 6577: -/***/ ((module, exports) => { +/***/ 877: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * @author Toru Nagashima - * @copyright 2015 Toru Nagashima. All rights reserved. - * See LICENSE file in root directory for full license. +/*! + * fill-range + * + * Copyright (c) 2014-present, Jon Schlinkert. + * Licensed under the MIT License. */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -/** - * @typedef {object} PrivateData - * @property {EventTarget} eventTarget The event target. - * @property {{type:string}} event The original event object. - * @property {number} eventPhase The current event phase. - * @property {EventTarget|null} currentTarget The current event target. - * @property {boolean} canceled The flag to prevent default. - * @property {boolean} stopped The flag to stop propagation. - * @property {boolean} immediateStopped The flag to stop propagation immediately. - * @property {Function|null} passiveListener The listener if the current listener is passive. Otherwise this is null. - * @property {number} timeStamp The unix time. - * @private - */ +const util = __nccwpck_require__(9023); +const toRegexRange = __nccwpck_require__(7551); -/** - * Private data for event wrappers. - * @type {WeakMap} - * @private - */ -const privateData = new WeakMap(); +const isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val); -/** - * Cache for wrapper classes. - * @type {WeakMap} - * @private - */ -const wrappers = new WeakMap(); +const transform = toNumber => { + return value => toNumber === true ? Number(value) : String(value); +}; -/** - * Get private data. - * @param {Event} event The event object to get private data. - * @returns {PrivateData} The private data of the event. - * @private - */ -function pd(event) { - const retv = privateData.get(event); - console.assert( - retv != null, - "'this' is expected an Event object, but got", - event - ); - return retv -} +const isValidValue = value => { + return typeof value === 'number' || (typeof value === 'string' && value !== ''); +}; -/** - * https://dom.spec.whatwg.org/#set-the-canceled-flag - * @param data {PrivateData} private data. - */ -function setCancelFlag(data) { - if (data.passiveListener != null) { - if ( - typeof console !== "undefined" && - typeof console.error === "function" - ) { - console.error( - "Unable to preventDefault inside passive event listener invocation.", - data.passiveListener - ); - } - return - } - if (!data.event.cancelable) { - return - } +const isNumber = num => Number.isInteger(+num); - data.canceled = true; - if (typeof data.event.preventDefault === "function") { - data.event.preventDefault(); - } -} +const zeros = input => { + let value = `${input}`; + let index = -1; + if (value[0] === '-') value = value.slice(1); + if (value === '0') return false; + while (value[++index] === '0'); + return index > 0; +}; -/** - * @see https://dom.spec.whatwg.org/#interface-event - * @private - */ -/** - * The event wrapper. - * @constructor - * @param {EventTarget} eventTarget The event target of this dispatching. - * @param {Event|{type:string}} event The original event to wrap. - */ -function Event(eventTarget, event) { - privateData.set(this, { - eventTarget, - event, - eventPhase: 2, - currentTarget: eventTarget, - canceled: false, - stopped: false, - immediateStopped: false, - passiveListener: null, - timeStamp: event.timeStamp || Date.now(), - }); +const stringify = (start, end, options) => { + if (typeof start === 'string' || typeof end === 'string') { + return true; + } + return options.stringify === true; +}; - // https://heycam.github.io/webidl/#Unforgeable - Object.defineProperty(this, "isTrusted", { value: false, enumerable: true }); +const pad = (input, maxLength, toNumber) => { + if (maxLength > 0) { + let dash = input[0] === '-' ? '-' : ''; + if (dash) input = input.slice(1); + input = (dash + input.padStart(dash ? maxLength - 1 : maxLength, '0')); + } + if (toNumber === false) { + return String(input); + } + return input; +}; - // Define accessors - const keys = Object.keys(event); - for (let i = 0; i < keys.length; ++i) { - const key = keys[i]; - if (!(key in this)) { - Object.defineProperty(this, key, defineRedirectDescriptor(key)); - } - } -} +const toMaxLen = (input, maxLength) => { + let negative = input[0] === '-' ? '-' : ''; + if (negative) { + input = input.slice(1); + maxLength--; + } + while (input.length < maxLength) input = '0' + input; + return negative ? ('-' + input) : input; +}; -// Should be enumerable, but class methods are not enumerable. -Event.prototype = { - /** - * The type of this event. - * @type {string} - */ - get type() { - return pd(this).event.type - }, +const toSequence = (parts, options, maxLen) => { + parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0); + parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0); - /** - * The target of this event. - * @type {EventTarget} - */ - get target() { - return pd(this).eventTarget - }, + let prefix = options.capture ? '' : '?:'; + let positives = ''; + let negatives = ''; + let result; - /** - * The target of this event. - * @type {EventTarget} - */ - get currentTarget() { - return pd(this).currentTarget - }, + if (parts.positives.length) { + positives = parts.positives.map(v => toMaxLen(String(v), maxLen)).join('|'); + } - /** - * @returns {EventTarget[]} The composed path of this event. - */ - composedPath() { - const currentTarget = pd(this).currentTarget; - if (currentTarget == null) { - return [] - } - return [currentTarget] - }, + if (parts.negatives.length) { + negatives = `-(${prefix}${parts.negatives.map(v => toMaxLen(String(v), maxLen)).join('|')})`; + } - /** - * Constant of NONE. - * @type {number} - */ - get NONE() { - return 0 - }, + if (positives && negatives) { + result = `${positives}|${negatives}`; + } else { + result = positives || negatives; + } - /** - * Constant of CAPTURING_PHASE. - * @type {number} - */ - get CAPTURING_PHASE() { - return 1 - }, + if (options.wrap) { + return `(${prefix}${result})`; + } - /** - * Constant of AT_TARGET. - * @type {number} - */ - get AT_TARGET() { - return 2 - }, + return result; +}; - /** - * Constant of BUBBLING_PHASE. - * @type {number} - */ - get BUBBLING_PHASE() { - return 3 - }, +const toRange = (a, b, isNumbers, options) => { + if (isNumbers) { + return toRegexRange(a, b, { wrap: false, ...options }); + } - /** - * The target of this event. - * @type {number} - */ - get eventPhase() { - return pd(this).eventPhase - }, + let start = String.fromCharCode(a); + if (a === b) return start; - /** - * Stop event bubbling. - * @returns {void} - */ - stopPropagation() { - const data = pd(this); + let stop = String.fromCharCode(b); + return `[${start}-${stop}]`; +}; - data.stopped = true; - if (typeof data.event.stopPropagation === "function") { - data.event.stopPropagation(); - } - }, +const toRegex = (start, end, options) => { + if (Array.isArray(start)) { + let wrap = options.wrap === true; + let prefix = options.capture ? '' : '?:'; + return wrap ? `(${prefix}${start.join('|')})` : start.join('|'); + } + return toRegexRange(start, end, options); +}; - /** - * Stop event bubbling. - * @returns {void} - */ - stopImmediatePropagation() { - const data = pd(this); +const rangeError = (...args) => { + return new RangeError('Invalid range arguments: ' + util.inspect(...args)); +}; - data.stopped = true; - data.immediateStopped = true; - if (typeof data.event.stopImmediatePropagation === "function") { - data.event.stopImmediatePropagation(); - } - }, +const invalidRange = (start, end, options) => { + if (options.strictRanges === true) throw rangeError([start, end]); + return []; +}; - /** - * The flag to be bubbling. - * @type {boolean} - */ - get bubbles() { - return Boolean(pd(this).event.bubbles) - }, +const invalidStep = (step, options) => { + if (options.strictRanges === true) { + throw new TypeError(`Expected step "${step}" to be a number`); + } + return []; +}; - /** - * The flag to be cancelable. - * @type {boolean} - */ - get cancelable() { - return Boolean(pd(this).event.cancelable) - }, +const fillNumbers = (start, end, step = 1, options = {}) => { + let a = Number(start); + let b = Number(end); - /** - * Cancel this event. - * @returns {void} - */ - preventDefault() { - setCancelFlag(pd(this)); - }, + if (!Number.isInteger(a) || !Number.isInteger(b)) { + if (options.strictRanges === true) throw rangeError([start, end]); + return []; + } - /** - * The flag to indicate cancellation state. - * @type {boolean} - */ - get defaultPrevented() { - return pd(this).canceled - }, + // fix negative zero + if (a === 0) a = 0; + if (b === 0) b = 0; - /** - * The flag to be composed. - * @type {boolean} - */ - get composed() { - return Boolean(pd(this).event.composed) - }, + let descending = a > b; + let startString = String(start); + let endString = String(end); + let stepString = String(step); + step = Math.max(Math.abs(step), 1); - /** - * The unix time of this event. - * @type {number} - */ - get timeStamp() { - return pd(this).timeStamp - }, + let padded = zeros(startString) || zeros(endString) || zeros(stepString); + let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0; + let toNumber = padded === false && stringify(start, end, options) === false; + let format = options.transform || transform(toNumber); - /** - * The target of this event. - * @type {EventTarget} - * @deprecated - */ - get srcElement() { - return pd(this).eventTarget - }, + if (options.toRegex && step === 1) { + return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options); + } - /** - * The flag to stop event bubbling. - * @type {boolean} - * @deprecated - */ - get cancelBubble() { - return pd(this).stopped - }, - set cancelBubble(value) { - if (!value) { - return - } - const data = pd(this); + let parts = { negatives: [], positives: [] }; + let push = num => parts[num < 0 ? 'negatives' : 'positives'].push(Math.abs(num)); + let range = []; + let index = 0; - data.stopped = true; - if (typeof data.event.cancelBubble === "boolean") { - data.event.cancelBubble = true; - } - }, + while (descending ? a >= b : a <= b) { + if (options.toRegex === true && step > 1) { + push(a); + } else { + range.push(pad(format(a, index), maxLen, toNumber)); + } + a = descending ? a - step : a + step; + index++; + } - /** - * The flag to indicate cancellation state. - * @type {boolean} - * @deprecated - */ - get returnValue() { - return !pd(this).canceled - }, - set returnValue(value) { - if (!value) { - setCancelFlag(pd(this)); - } - }, + if (options.toRegex === true) { + return step > 1 + ? toSequence(parts, options, maxLen) + : toRegex(range, null, { wrap: false, ...options }); + } - /** - * Initialize this event object. But do nothing under event dispatching. - * @param {string} type The event type. - * @param {boolean} [bubbles=false] The flag to be possible to bubble up. - * @param {boolean} [cancelable=false] The flag to be possible to cancel. - * @deprecated - */ - initEvent() { - // Do nothing. - }, + return range; }; -// `constructor` is not enumerable. -Object.defineProperty(Event.prototype, "constructor", { - value: Event, - configurable: true, - writable: true, -}); - -// Ensure `event instanceof window.Event` is `true`. -if (typeof window !== "undefined" && typeof window.Event !== "undefined") { - Object.setPrototypeOf(Event.prototype, window.Event.prototype); +const fillLetters = (start, end, step = 1, options = {}) => { + if ((!isNumber(start) && start.length > 1) || (!isNumber(end) && end.length > 1)) { + return invalidRange(start, end, options); + } - // Make association for wrappers. - wrappers.set(window.Event.prototype, Event); -} + let format = options.transform || (val => String.fromCharCode(val)); + let a = `${start}`.charCodeAt(0); + let b = `${end}`.charCodeAt(0); -/** - * Get the property descriptor to redirect a given property. - * @param {string} key Property name to define property descriptor. - * @returns {PropertyDescriptor} The property descriptor to redirect the property. - * @private - */ -function defineRedirectDescriptor(key) { - return { - get() { - return pd(this).event[key] - }, - set(value) { - pd(this).event[key] = value; - }, - configurable: true, - enumerable: true, - } -} + let descending = a > b; + let min = Math.min(a, b); + let max = Math.max(a, b); -/** - * Get the property descriptor to call a given method property. - * @param {string} key Property name to define property descriptor. - * @returns {PropertyDescriptor} The property descriptor to call the method property. - * @private - */ -function defineCallDescriptor(key) { - return { - value() { - const event = pd(this).event; - return event[key].apply(event, arguments) - }, - configurable: true, - enumerable: true, - } -} + if (options.toRegex && step === 1) { + return toRange(min, max, false, options); + } -/** - * Define new wrapper class. - * @param {Function} BaseEvent The base wrapper class. - * @param {Object} proto The prototype of the original event. - * @returns {Function} The defined wrapper class. - * @private - */ -function defineWrapper(BaseEvent, proto) { - const keys = Object.keys(proto); - if (keys.length === 0) { - return BaseEvent - } + let range = []; + let index = 0; - /** CustomEvent */ - function CustomEvent(eventTarget, event) { - BaseEvent.call(this, eventTarget, event); - } + while (descending ? a >= b : a <= b) { + range.push(format(a, index)); + a = descending ? a - step : a + step; + index++; + } - CustomEvent.prototype = Object.create(BaseEvent.prototype, { - constructor: { value: CustomEvent, configurable: true, writable: true }, - }); + if (options.toRegex === true) { + return toRegex(range, null, { wrap: false, options }); + } - // Define accessors. - for (let i = 0; i < keys.length; ++i) { - const key = keys[i]; - if (!(key in BaseEvent.prototype)) { - const descriptor = Object.getOwnPropertyDescriptor(proto, key); - const isFunc = typeof descriptor.value === "function"; - Object.defineProperty( - CustomEvent.prototype, - key, - isFunc - ? defineCallDescriptor(key) - : defineRedirectDescriptor(key) - ); - } - } + return range; +}; - return CustomEvent -} - -/** - * Get the wrapper class of a given prototype. - * @param {Object} proto The prototype of the original event to get its wrapper. - * @returns {Function} The wrapper class. - * @private - */ -function getWrapper(proto) { - if (proto == null || proto === Object.prototype) { - return Event - } - - let wrapper = wrappers.get(proto); - if (wrapper == null) { - wrapper = defineWrapper(getWrapper(Object.getPrototypeOf(proto)), proto); - wrappers.set(proto, wrapper); - } - return wrapper -} - -/** - * Wrap a given event to management a dispatching. - * @param {EventTarget} eventTarget The event target of this dispatching. - * @param {Object} event The event to wrap. - * @returns {Event} The wrapper instance. - * @private - */ -function wrapEvent(eventTarget, event) { - const Wrapper = getWrapper(Object.getPrototypeOf(event)); - return new Wrapper(eventTarget, event) -} - -/** - * Get the immediateStopped flag of a given event. - * @param {Event} event The event to get. - * @returns {boolean} The flag to stop propagation immediately. - * @private - */ -function isStopped(event) { - return pd(event).immediateStopped -} - -/** - * Set the current event phase of a given event. - * @param {Event} event The event to set current target. - * @param {number} eventPhase New event phase. - * @returns {void} - * @private - */ -function setEventPhase(event, eventPhase) { - pd(event).eventPhase = eventPhase; -} - -/** - * Set the current target of a given event. - * @param {Event} event The event to set current target. - * @param {EventTarget|null} currentTarget New current target. - * @returns {void} - * @private - */ -function setCurrentTarget(event, currentTarget) { - pd(event).currentTarget = currentTarget; -} - -/** - * Set a passive listener of a given event. - * @param {Event} event The event to set current target. - * @param {Function|null} passiveListener New passive listener. - * @returns {void} - * @private - */ -function setPassiveListener(event, passiveListener) { - pd(event).passiveListener = passiveListener; -} - -/** - * @typedef {object} ListenerNode - * @property {Function} listener - * @property {1|2|3} listenerType - * @property {boolean} passive - * @property {boolean} once - * @property {ListenerNode|null} next - * @private - */ - -/** - * @type {WeakMap>} - * @private - */ -const listenersMap = new WeakMap(); - -// Listener types -const CAPTURE = 1; -const BUBBLE = 2; -const ATTRIBUTE = 3; - -/** - * Check whether a given value is an object or not. - * @param {any} x The value to check. - * @returns {boolean} `true` if the value is an object. - */ -function isObject(x) { - return x !== null && typeof x === "object" //eslint-disable-line no-restricted-syntax -} - -/** - * Get listeners. - * @param {EventTarget} eventTarget The event target to get. - * @returns {Map} The listeners. - * @private - */ -function getListeners(eventTarget) { - const listeners = listenersMap.get(eventTarget); - if (listeners == null) { - throw new TypeError( - "'this' is expected an EventTarget object, but got another value." - ) - } - return listeners -} - -/** - * Get the property descriptor for the event attribute of a given event. - * @param {string} eventName The event name to get property descriptor. - * @returns {PropertyDescriptor} The property descriptor. - * @private - */ -function defineEventAttributeDescriptor(eventName) { - return { - get() { - const listeners = getListeners(this); - let node = listeners.get(eventName); - while (node != null) { - if (node.listenerType === ATTRIBUTE) { - return node.listener - } - node = node.next; - } - return null - }, - - set(listener) { - if (typeof listener !== "function" && !isObject(listener)) { - listener = null; // eslint-disable-line no-param-reassign - } - const listeners = getListeners(this); - - // Traverse to the tail while removing old value. - let prev = null; - let node = listeners.get(eventName); - while (node != null) { - if (node.listenerType === ATTRIBUTE) { - // Remove old value. - if (prev !== null) { - prev.next = node.next; - } else if (node.next !== null) { - listeners.set(eventName, node.next); - } else { - listeners.delete(eventName); - } - } else { - prev = node; - } - - node = node.next; - } - - // Add new value. - if (listener !== null) { - const newNode = { - listener, - listenerType: ATTRIBUTE, - passive: false, - once: false, - next: null, - }; - if (prev === null) { - listeners.set(eventName, newNode); - } else { - prev.next = newNode; - } - } - }, - configurable: true, - enumerable: true, - } -} - -/** - * Define an event attribute (e.g. `eventTarget.onclick`). - * @param {Object} eventTargetPrototype The event target prototype to define an event attrbite. - * @param {string} eventName The event name to define. - * @returns {void} - */ -function defineEventAttribute(eventTargetPrototype, eventName) { - Object.defineProperty( - eventTargetPrototype, - `on${eventName}`, - defineEventAttributeDescriptor(eventName) - ); -} - -/** - * Define a custom EventTarget with event attributes. - * @param {string[]} eventNames Event names for event attributes. - * @returns {EventTarget} The custom EventTarget. - * @private - */ -function defineCustomEventTarget(eventNames) { - /** CustomEventTarget */ - function CustomEventTarget() { - EventTarget.call(this); - } - - CustomEventTarget.prototype = Object.create(EventTarget.prototype, { - constructor: { - value: CustomEventTarget, - configurable: true, - writable: true, - }, - }); - - for (let i = 0; i < eventNames.length; ++i) { - defineEventAttribute(CustomEventTarget.prototype, eventNames[i]); - } - - return CustomEventTarget -} - -/** - * EventTarget. - * - * - This is constructor if no arguments. - * - This is a function which returns a CustomEventTarget constructor if there are arguments. - * - * For example: - * - * class A extends EventTarget {} - * class B extends EventTarget("message") {} - * class C extends EventTarget("message", "error") {} - * class D extends EventTarget(["message", "error"]) {} - */ -function EventTarget() { - /*eslint-disable consistent-return */ - if (this instanceof EventTarget) { - listenersMap.set(this, new Map()); - return - } - if (arguments.length === 1 && Array.isArray(arguments[0])) { - return defineCustomEventTarget(arguments[0]) - } - if (arguments.length > 0) { - const types = new Array(arguments.length); - for (let i = 0; i < arguments.length; ++i) { - types[i] = arguments[i]; - } - return defineCustomEventTarget(types) - } - throw new TypeError("Cannot call a class as a function") - /*eslint-enable consistent-return */ -} - -// Should be enumerable, but class methods are not enumerable. -EventTarget.prototype = { - /** - * Add a given listener to this event target. - * @param {string} eventName The event name to add. - * @param {Function} listener The listener to add. - * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener. - * @returns {void} - */ - addEventListener(eventName, listener, options) { - if (listener == null) { - return - } - if (typeof listener !== "function" && !isObject(listener)) { - throw new TypeError("'listener' should be a function or an object.") - } - - const listeners = getListeners(this); - const optionsIsObj = isObject(options); - const capture = optionsIsObj - ? Boolean(options.capture) - : Boolean(options); - const listenerType = capture ? CAPTURE : BUBBLE; - const newNode = { - listener, - listenerType, - passive: optionsIsObj && Boolean(options.passive), - once: optionsIsObj && Boolean(options.once), - next: null, - }; - - // Set it as the first node if the first node is null. - let node = listeners.get(eventName); - if (node === undefined) { - listeners.set(eventName, newNode); - return - } - - // Traverse to the tail while checking duplication.. - let prev = null; - while (node != null) { - if ( - node.listener === listener && - node.listenerType === listenerType - ) { - // Should ignore duplication. - return - } - prev = node; - node = node.next; - } - - // Add it. - prev.next = newNode; - }, - - /** - * Remove a given listener from this event target. - * @param {string} eventName The event name to remove. - * @param {Function} listener The listener to remove. - * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener. - * @returns {void} - */ - removeEventListener(eventName, listener, options) { - if (listener == null) { - return - } - - const listeners = getListeners(this); - const capture = isObject(options) - ? Boolean(options.capture) - : Boolean(options); - const listenerType = capture ? CAPTURE : BUBBLE; - - let prev = null; - let node = listeners.get(eventName); - while (node != null) { - if ( - node.listener === listener && - node.listenerType === listenerType - ) { - if (prev !== null) { - prev.next = node.next; - } else if (node.next !== null) { - listeners.set(eventName, node.next); - } else { - listeners.delete(eventName); - } - return - } - - prev = node; - node = node.next; - } - }, - - /** - * Dispatch a given event. - * @param {Event|{type:string}} event The event to dispatch. - * @returns {boolean} `false` if canceled. - */ - dispatchEvent(event) { - if (event == null || typeof event.type !== "string") { - throw new TypeError('"event.type" should be a string.') - } - - // If listeners aren't registered, terminate. - const listeners = getListeners(this); - const eventName = event.type; - let node = listeners.get(eventName); - if (node == null) { - return true - } - - // Since we cannot rewrite several properties, so wrap object. - const wrappedEvent = wrapEvent(this, event); - - // This doesn't process capturing phase and bubbling phase. - // This isn't participating in a tree. - let prev = null; - while (node != null) { - // Remove this listener if it's once - if (node.once) { - if (prev !== null) { - prev.next = node.next; - } else if (node.next !== null) { - listeners.set(eventName, node.next); - } else { - listeners.delete(eventName); - } - } else { - prev = node; - } - - // Call this listener - setPassiveListener( - wrappedEvent, - node.passive ? node.listener : null - ); - if (typeof node.listener === "function") { - try { - node.listener.call(this, wrappedEvent); - } catch (err) { - if ( - typeof console !== "undefined" && - typeof console.error === "function" - ) { - console.error(err); - } - } - } else if ( - node.listenerType !== ATTRIBUTE && - typeof node.listener.handleEvent === "function" - ) { - node.listener.handleEvent(wrappedEvent); - } - - // Break if `event.stopImmediatePropagation` was called. - if (isStopped(wrappedEvent)) { - break - } - - node = node.next; - } - setPassiveListener(wrappedEvent, null); - setEventPhase(wrappedEvent, 0); - setCurrentTarget(wrappedEvent, null); - - return !wrappedEvent.defaultPrevented - }, -}; - -// `constructor` is not enumerable. -Object.defineProperty(EventTarget.prototype, "constructor", { - value: EventTarget, - configurable: true, - writable: true, -}); - -// Ensure `eventTarget instanceof window.EventTarget` is `true`. -if ( - typeof window !== "undefined" && - typeof window.EventTarget !== "undefined" -) { - Object.setPrototypeOf(EventTarget.prototype, window.EventTarget.prototype); -} - -exports.defineEventAttribute = defineEventAttribute; -exports.EventTarget = EventTarget; -exports["default"] = EventTarget; - -module.exports = EventTarget -module.exports.EventTarget = module.exports["default"] = EventTarget -module.exports.defineEventAttribute = defineEventAttribute -//# sourceMappingURL=event-target-shim.js.map - - -/***/ }), - -/***/ 877: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -/*! - * fill-range - * - * Copyright (c) 2014-present, Jon Schlinkert. - * Licensed under the MIT License. - */ - - - -const util = __nccwpck_require__(9023); -const toRegexRange = __nccwpck_require__(7551); - -const isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val); - -const transform = toNumber => { - return value => toNumber === true ? Number(value) : String(value); -}; - -const isValidValue = value => { - return typeof value === 'number' || (typeof value === 'string' && value !== ''); -}; - -const isNumber = num => Number.isInteger(+num); - -const zeros = input => { - let value = `${input}`; - let index = -1; - if (value[0] === '-') value = value.slice(1); - if (value === '0') return false; - while (value[++index] === '0'); - return index > 0; -}; - -const stringify = (start, end, options) => { - if (typeof start === 'string' || typeof end === 'string') { - return true; - } - return options.stringify === true; -}; - -const pad = (input, maxLength, toNumber) => { - if (maxLength > 0) { - let dash = input[0] === '-' ? '-' : ''; - if (dash) input = input.slice(1); - input = (dash + input.padStart(dash ? maxLength - 1 : maxLength, '0')); - } - if (toNumber === false) { - return String(input); - } - return input; -}; - -const toMaxLen = (input, maxLength) => { - let negative = input[0] === '-' ? '-' : ''; - if (negative) { - input = input.slice(1); - maxLength--; - } - while (input.length < maxLength) input = '0' + input; - return negative ? ('-' + input) : input; -}; - -const toSequence = (parts, options, maxLen) => { - parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0); - parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0); - - let prefix = options.capture ? '' : '?:'; - let positives = ''; - let negatives = ''; - let result; - - if (parts.positives.length) { - positives = parts.positives.map(v => toMaxLen(String(v), maxLen)).join('|'); - } - - if (parts.negatives.length) { - negatives = `-(${prefix}${parts.negatives.map(v => toMaxLen(String(v), maxLen)).join('|')})`; - } - - if (positives && negatives) { - result = `${positives}|${negatives}`; - } else { - result = positives || negatives; - } - - if (options.wrap) { - return `(${prefix}${result})`; - } - - return result; -}; - -const toRange = (a, b, isNumbers, options) => { - if (isNumbers) { - return toRegexRange(a, b, { wrap: false, ...options }); - } - - let start = String.fromCharCode(a); - if (a === b) return start; - - let stop = String.fromCharCode(b); - return `[${start}-${stop}]`; -}; - -const toRegex = (start, end, options) => { - if (Array.isArray(start)) { - let wrap = options.wrap === true; - let prefix = options.capture ? '' : '?:'; - return wrap ? `(${prefix}${start.join('|')})` : start.join('|'); - } - return toRegexRange(start, end, options); -}; - -const rangeError = (...args) => { - return new RangeError('Invalid range arguments: ' + util.inspect(...args)); -}; - -const invalidRange = (start, end, options) => { - if (options.strictRanges === true) throw rangeError([start, end]); - return []; -}; - -const invalidStep = (step, options) => { - if (options.strictRanges === true) { - throw new TypeError(`Expected step "${step}" to be a number`); - } - return []; -}; - -const fillNumbers = (start, end, step = 1, options = {}) => { - let a = Number(start); - let b = Number(end); - - if (!Number.isInteger(a) || !Number.isInteger(b)) { - if (options.strictRanges === true) throw rangeError([start, end]); - return []; - } - - // fix negative zero - if (a === 0) a = 0; - if (b === 0) b = 0; - - let descending = a > b; - let startString = String(start); - let endString = String(end); - let stepString = String(step); - step = Math.max(Math.abs(step), 1); - - let padded = zeros(startString) || zeros(endString) || zeros(stepString); - let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0; - let toNumber = padded === false && stringify(start, end, options) === false; - let format = options.transform || transform(toNumber); - - if (options.toRegex && step === 1) { - return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options); - } - - let parts = { negatives: [], positives: [] }; - let push = num => parts[num < 0 ? 'negatives' : 'positives'].push(Math.abs(num)); - let range = []; - let index = 0; - - while (descending ? a >= b : a <= b) { - if (options.toRegex === true && step > 1) { - push(a); - } else { - range.push(pad(format(a, index), maxLen, toNumber)); - } - a = descending ? a - step : a + step; - index++; - } - - if (options.toRegex === true) { - return step > 1 - ? toSequence(parts, options, maxLen) - : toRegex(range, null, { wrap: false, ...options }); - } - - return range; -}; - -const fillLetters = (start, end, step = 1, options = {}) => { - if ((!isNumber(start) && start.length > 1) || (!isNumber(end) && end.length > 1)) { - return invalidRange(start, end, options); - } - - let format = options.transform || (val => String.fromCharCode(val)); - let a = `${start}`.charCodeAt(0); - let b = `${end}`.charCodeAt(0); - - let descending = a > b; - let min = Math.min(a, b); - let max = Math.max(a, b); - - if (options.toRegex && step === 1) { - return toRange(min, max, false, options); - } - - let range = []; - let index = 0; - - while (descending ? a >= b : a <= b) { - range.push(format(a, index)); - a = descending ? a - step : a + step; - index++; - } - - if (options.toRegex === true) { - return toRegex(range, null, { wrap: false, options }); - } - - return range; -}; - -const fill = (start, end, step, options = {}) => { - if (end == null && isValidValue(start)) { - return [start]; - } +const fill = (start, end, step, options = {}) => { + if (end == null && isValidValue(start)) { + return [start]; + } if (!isValidValue(start) || !isValidValue(end)) { return invalidRange(start, end, options); @@ -27220,37 +25706,6 @@ const fill = (start, end, step, options = {}) => { module.exports = fill; -/***/ }), - -/***/ 3724: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -/*! - * humanize-ms - index.js - * Copyright(c) 2014 dead_horse - * MIT Licensed - */ - - - -/** - * Module dependencies. - */ - -var util = __nccwpck_require__(9023); -var ms = __nccwpck_require__(744); - -module.exports = function (t) { - if (typeof t === 'number') return t; - var r = ms(t); - if (r === undefined) { - var err = new Error(util.format('humanize-ms(%j) result undefined', t)); - console.warn(err.stack); - } - return r; -}; - - /***/ }), /***/ 3102: @@ -27759,6774 +26214,4875 @@ module.exports = micromatch; /***/ }), -/***/ 744: -/***/ ((module) => { - -/** - * Helpers. - */ - -var s = 1000; -var m = s * 60; -var h = m * 60; -var d = h * 24; -var w = d * 7; -var y = d * 365.25; - -/** - * Parse or format the given `val`. - * - * Options: - * - * - `long` verbose formatting [false] - * - * @param {String|Number} val - * @param {Object} [options] - * @throws {Error} throw an error if val is not a non-empty string or a number - * @return {String|Number} - * @api public - */ - -module.exports = function (val, options) { - options = options || {}; - var type = typeof val; - if (type === 'string' && val.length > 0) { - return parse(val); - } else if (type === 'number' && isFinite(val)) { - return options.long ? fmtLong(val) : fmtShort(val); - } - throw new Error( - 'val is not a non-empty string or a valid number. val=' + - JSON.stringify(val) - ); -}; +/***/ 5560: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * Parse the given `str` and return milliseconds. - * - * @param {String} str - * @return {Number} - * @api private - */ +var wrappy = __nccwpck_require__(8264) +module.exports = wrappy(once) +module.exports.strict = wrappy(onceStrict) -function parse(str) { - str = String(str); - if (str.length > 100) { - return; - } - var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( - str - ); - if (!match) { - return; - } - var n = parseFloat(match[1]); - var type = (match[2] || 'ms').toLowerCase(); - switch (type) { - case 'years': - case 'year': - case 'yrs': - case 'yr': - case 'y': - return n * y; - case 'weeks': - case 'week': - case 'w': - return n * w; - case 'days': - case 'day': - case 'd': - return n * d; - case 'hours': - case 'hour': - case 'hrs': - case 'hr': - case 'h': - return n * h; - case 'minutes': - case 'minute': - case 'mins': - case 'min': - case 'm': - return n * m; - case 'seconds': - case 'second': - case 'secs': - case 'sec': - case 's': - return n * s; - case 'milliseconds': - case 'millisecond': - case 'msecs': - case 'msec': - case 'ms': - return n; - default: - return undefined; - } -} +once.proto = once(function () { + Object.defineProperty(Function.prototype, 'once', { + value: function () { + return once(this) + }, + configurable: true + }) -/** - * Short format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ + Object.defineProperty(Function.prototype, 'onceStrict', { + value: function () { + return onceStrict(this) + }, + configurable: true + }) +}) -function fmtShort(ms) { - var msAbs = Math.abs(ms); - if (msAbs >= d) { - return Math.round(ms / d) + 'd'; - } - if (msAbs >= h) { - return Math.round(ms / h) + 'h'; - } - if (msAbs >= m) { - return Math.round(ms / m) + 'm'; - } - if (msAbs >= s) { - return Math.round(ms / s) + 's'; +function once (fn) { + var f = function () { + if (f.called) return f.value + f.called = true + return f.value = fn.apply(this, arguments) } - return ms + 'ms'; + f.called = false + return f } -/** - * Long format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ - -function fmtLong(ms) { - var msAbs = Math.abs(ms); - if (msAbs >= d) { - return plural(ms, msAbs, d, 'day'); - } - if (msAbs >= h) { - return plural(ms, msAbs, h, 'hour'); - } - if (msAbs >= m) { - return plural(ms, msAbs, m, 'minute'); - } - if (msAbs >= s) { - return plural(ms, msAbs, s, 'second'); +function onceStrict (fn) { + var f = function () { + if (f.called) + throw new Error(f.onceError) + f.called = true + return f.value = fn.apply(this, arguments) } - return ms + ' ms'; -} - -/** - * Pluralization helper. - */ - -function plural(ms, msAbs, n, name) { - var isPlural = msAbs >= n * 1.5; - return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); + var name = fn.name || 'Function wrapped with `once`' + f.onceError = name + " shouldn't be called more than once" + f.called = false + return f } /***/ }), -/***/ 6705: -/***/ ((module, exports, __nccwpck_require__) => { +/***/ 2766: +/***/ ((module) => { +module.exports = (promise, onFinally) => { + onFinally = onFinally || (() => {}); -Object.defineProperty(exports, "__esModule", ({ value: true })); - -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - -var Stream = _interopDefault(__nccwpck_require__(2203)); -var http = _interopDefault(__nccwpck_require__(8611)); -var Url = _interopDefault(__nccwpck_require__(7016)); -var whatwgUrl = _interopDefault(__nccwpck_require__(2686)); -var https = _interopDefault(__nccwpck_require__(5692)); -var zlib = _interopDefault(__nccwpck_require__(3106)); - -// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js - -// fix for "Readable" isn't a named export issue -const Readable = Stream.Readable; - -const BUFFER = Symbol('buffer'); -const TYPE = Symbol('type'); - -class Blob { - constructor() { - this[TYPE] = ''; - - const blobParts = arguments[0]; - const options = arguments[1]; - - const buffers = []; - let size = 0; - - if (blobParts) { - const a = blobParts; - const length = Number(a.length); - for (let i = 0; i < length; i++) { - const element = a[i]; - let buffer; - if (element instanceof Buffer) { - buffer = element; - } else if (ArrayBuffer.isView(element)) { - buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength); - } else if (element instanceof ArrayBuffer) { - buffer = Buffer.from(element); - } else if (element instanceof Blob) { - buffer = element[BUFFER]; - } else { - buffer = Buffer.from(typeof element === 'string' ? element : String(element)); - } - size += buffer.length; - buffers.push(buffer); - } - } - - this[BUFFER] = Buffer.concat(buffers); + return promise.then( + val => new Promise(resolve => { + resolve(onFinally()); + }).then(() => val), + err => new Promise(resolve => { + resolve(onFinally()); + }).then(() => { + throw err; + }) + ); +}; - let type = options && options.type !== undefined && String(options.type).toLowerCase(); - if (type && !/[^\u0020-\u007E]/.test(type)) { - this[TYPE] = type; - } - } - get size() { - return this[BUFFER].length; - } - get type() { - return this[TYPE]; - } - text() { - return Promise.resolve(this[BUFFER].toString()); - } - arrayBuffer() { - const buf = this[BUFFER]; - const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); - return Promise.resolve(ab); - } - stream() { - const readable = new Readable(); - readable._read = function () {}; - readable.push(this[BUFFER]); - readable.push(null); - return readable; - } - toString() { - return '[object Blob]'; - } - slice() { - const size = this.size; - - const start = arguments[0]; - const end = arguments[1]; - let relativeStart, relativeEnd; - if (start === undefined) { - relativeStart = 0; - } else if (start < 0) { - relativeStart = Math.max(size + start, 0); - } else { - relativeStart = Math.min(start, size); - } - if (end === undefined) { - relativeEnd = size; - } else if (end < 0) { - relativeEnd = Math.max(size + end, 0); - } else { - relativeEnd = Math.min(end, size); - } - const span = Math.max(relativeEnd - relativeStart, 0); - const buffer = this[BUFFER]; - const slicedBuffer = buffer.slice(relativeStart, relativeStart + span); - const blob = new Blob([], { type: arguments[2] }); - blob[BUFFER] = slicedBuffer; - return blob; - } -} +/***/ }), -Object.defineProperties(Blob.prototype, { - size: { enumerable: true }, - type: { enumerable: true }, - slice: { enumerable: true } -}); +/***/ 6459: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -Object.defineProperty(Blob.prototype, Symbol.toStringTag, { - value: 'Blob', - writable: false, - enumerable: false, - configurable: true -}); +Object.defineProperty(exports, "__esModule", ({ value: true })); +const EventEmitter = __nccwpck_require__(301); +const p_timeout_1 = __nccwpck_require__(4802); +const priority_queue_1 = __nccwpck_require__(5905); +// eslint-disable-next-line @typescript-eslint/no-empty-function +const empty = () => { }; +const timeoutError = new p_timeout_1.TimeoutError(); /** - * fetch-error.js - * - * FetchError interface for operational errors - */ +Promise queue with concurrency control. +*/ +class PQueue extends EventEmitter { + constructor(options) { + var _a, _b, _c, _d; + super(); + this._intervalCount = 0; + this._intervalEnd = 0; + this._pendingCount = 0; + this._resolveEmpty = empty; + this._resolveIdle = empty; + // eslint-disable-next-line @typescript-eslint/consistent-type-assertions + options = Object.assign({ carryoverConcurrencyCount: false, intervalCap: Infinity, interval: 0, concurrency: Infinity, autoStart: true, queueClass: priority_queue_1.default }, options); + if (!(typeof options.intervalCap === 'number' && options.intervalCap >= 1)) { + throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(_b = (_a = options.intervalCap) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : ''}\` (${typeof options.intervalCap})`); + } + if (options.interval === undefined || !(Number.isFinite(options.interval) && options.interval >= 0)) { + throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(_d = (_c = options.interval) === null || _c === void 0 ? void 0 : _c.toString()) !== null && _d !== void 0 ? _d : ''}\` (${typeof options.interval})`); + } + this._carryoverConcurrencyCount = options.carryoverConcurrencyCount; + this._isIntervalIgnored = options.intervalCap === Infinity || options.interval === 0; + this._intervalCap = options.intervalCap; + this._interval = options.interval; + this._queue = new options.queueClass(); + this._queueClass = options.queueClass; + this.concurrency = options.concurrency; + this._timeout = options.timeout; + this._throwOnTimeout = options.throwOnTimeout === true; + this._isPaused = options.autoStart === false; + } + get _doesIntervalAllowAnother() { + return this._isIntervalIgnored || this._intervalCount < this._intervalCap; + } + get _doesConcurrentAllowAnother() { + return this._pendingCount < this._concurrency; + } + _next() { + this._pendingCount--; + this._tryToStartAnother(); + this.emit('next'); + } + _resolvePromises() { + this._resolveEmpty(); + this._resolveEmpty = empty; + if (this._pendingCount === 0) { + this._resolveIdle(); + this._resolveIdle = empty; + this.emit('idle'); + } + } + _onResumeInterval() { + this._onInterval(); + this._initializeIntervalIfNeeded(); + this._timeoutId = undefined; + } + _isIntervalPaused() { + const now = Date.now(); + if (this._intervalId === undefined) { + const delay = this._intervalEnd - now; + if (delay < 0) { + // Act as the interval was done + // We don't need to resume it here because it will be resumed on line 160 + this._intervalCount = (this._carryoverConcurrencyCount) ? this._pendingCount : 0; + } + else { + // Act as the interval is pending + if (this._timeoutId === undefined) { + this._timeoutId = setTimeout(() => { + this._onResumeInterval(); + }, delay); + } + return true; + } + } + return false; + } + _tryToStartAnother() { + if (this._queue.size === 0) { + // We can clear the interval ("pause") + // Because we can redo it later ("resume") + if (this._intervalId) { + clearInterval(this._intervalId); + } + this._intervalId = undefined; + this._resolvePromises(); + return false; + } + if (!this._isPaused) { + const canInitializeInterval = !this._isIntervalPaused(); + if (this._doesIntervalAllowAnother && this._doesConcurrentAllowAnother) { + const job = this._queue.dequeue(); + if (!job) { + return false; + } + this.emit('active'); + job(); + if (canInitializeInterval) { + this._initializeIntervalIfNeeded(); + } + return true; + } + } + return false; + } + _initializeIntervalIfNeeded() { + if (this._isIntervalIgnored || this._intervalId !== undefined) { + return; + } + this._intervalId = setInterval(() => { + this._onInterval(); + }, this._interval); + this._intervalEnd = Date.now() + this._interval; + } + _onInterval() { + if (this._intervalCount === 0 && this._pendingCount === 0 && this._intervalId) { + clearInterval(this._intervalId); + this._intervalId = undefined; + } + this._intervalCount = this._carryoverConcurrencyCount ? this._pendingCount : 0; + this._processQueue(); + } + /** + Executes all queued functions until it reaches the limit. + */ + _processQueue() { + // eslint-disable-next-line no-empty + while (this._tryToStartAnother()) { } + } + get concurrency() { + return this._concurrency; + } + set concurrency(newConcurrency) { + if (!(typeof newConcurrency === 'number' && newConcurrency >= 1)) { + throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${newConcurrency}\` (${typeof newConcurrency})`); + } + this._concurrency = newConcurrency; + this._processQueue(); + } + /** + Adds a sync or async task to the queue. Always returns a promise. + */ + async add(fn, options = {}) { + return new Promise((resolve, reject) => { + const run = async () => { + this._pendingCount++; + this._intervalCount++; + try { + const operation = (this._timeout === undefined && options.timeout === undefined) ? fn() : p_timeout_1.default(Promise.resolve(fn()), (options.timeout === undefined ? this._timeout : options.timeout), () => { + if (options.throwOnTimeout === undefined ? this._throwOnTimeout : options.throwOnTimeout) { + reject(timeoutError); + } + return undefined; + }); + resolve(await operation); + } + catch (error) { + reject(error); + } + this._next(); + }; + this._queue.enqueue(run, options); + this._tryToStartAnother(); + this.emit('add'); + }); + } + /** + Same as `.add()`, but accepts an array of sync or async functions. -/** - * Create FetchError instance - * - * @param String message Error message for human - * @param String type Error type for machine - * @param String systemError For Node.js system error - * @return FetchError - */ -function FetchError(message, type, systemError) { - Error.call(this, message); + @returns A promise that resolves when all functions are resolved. + */ + async addAll(functions, options) { + return Promise.all(functions.map(async (function_) => this.add(function_, options))); + } + /** + Start (or resume) executing enqueued tasks within concurrency limit. No need to call this if queue is not paused (via `options.autoStart = false` or by `.pause()` method.) + */ + start() { + if (!this._isPaused) { + return this; + } + this._isPaused = false; + this._processQueue(); + return this; + } + /** + Put queue execution on hold. + */ + pause() { + this._isPaused = true; + } + /** + Clear the queue. + */ + clear() { + this._queue = new this._queueClass(); + } + /** + Can be called multiple times. Useful if you for example add additional items at a later time. - this.message = message; - this.type = type; + @returns A promise that settles when the queue becomes empty. + */ + async onEmpty() { + // Instantly resolve if the queue is empty + if (this._queue.size === 0) { + return; + } + return new Promise(resolve => { + const existingResolve = this._resolveEmpty; + this._resolveEmpty = () => { + existingResolve(); + resolve(); + }; + }); + } + /** + The difference with `.onEmpty` is that `.onIdle` guarantees that all work from the queue has finished. `.onEmpty` merely signals that the queue is empty, but it could mean that some promises haven't completed yet. - // when err.type is `system`, err.code contains system error code - if (systemError) { - this.code = this.errno = systemError.code; - } + @returns A promise that settles when the queue becomes empty, and all promises have completed; `queue.size === 0 && queue.pending === 0`. + */ + async onIdle() { + // Instantly resolve if none pending and if nothing else is queued + if (this._pendingCount === 0 && this._queue.size === 0) { + return; + } + return new Promise(resolve => { + const existingResolve = this._resolveIdle; + this._resolveIdle = () => { + existingResolve(); + resolve(); + }; + }); + } + /** + Size of the queue. + */ + get size() { + return this._queue.size; + } + /** + Size of the queue, filtered by the given options. - // hide custom error implementation details from end-users - Error.captureStackTrace(this, this.constructor); + For example, this can be used to find the number of items remaining in the queue with a specific priority level. + */ + sizeBy(options) { + // eslint-disable-next-line unicorn/no-fn-reference-in-iterator + return this._queue.filter(options).length; + } + /** + Number of pending promises. + */ + get pending() { + return this._pendingCount; + } + /** + Whether the queue is currently paused. + */ + get isPaused() { + return this._isPaused; + } + get timeout() { + return this._timeout; + } + /** + Set the timeout for future operations. + */ + set timeout(milliseconds) { + this._timeout = milliseconds; + } } +exports["default"] = PQueue; -FetchError.prototype = Object.create(Error.prototype); -FetchError.prototype.constructor = FetchError; -FetchError.prototype.name = 'FetchError'; - -let convert; -try { - convert = (__nccwpck_require__(2078).convert); -} catch (e) {} -const INTERNALS = Symbol('Body internals'); +/***/ }), -// fix an issue where "PassThrough" isn't a named export for node <10 -const PassThrough = Stream.PassThrough; +/***/ 9015: +/***/ ((__unused_webpack_module, exports) => { -/** - * Body mixin - * - * Ref: https://fetch.spec.whatwg.org/#body - * - * @param Stream body Readable stream - * @param Object opts Response options - * @return Void - */ -function Body(body) { - var _this = this; - - var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, - _ref$size = _ref.size; - - let size = _ref$size === undefined ? 0 : _ref$size; - var _ref$timeout = _ref.timeout; - let timeout = _ref$timeout === undefined ? 0 : _ref$timeout; - - if (body == null) { - // body is undefined or null - body = null; - } else if (isURLSearchParams(body)) { - // body is a URLSearchParams - body = Buffer.from(body.toString()); - } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') { - // body is ArrayBuffer - body = Buffer.from(body); - } else if (ArrayBuffer.isView(body)) { - // body is ArrayBufferView - body = Buffer.from(body.buffer, body.byteOffset, body.byteLength); - } else if (body instanceof Stream) ; else { - // none of the above - // coerce to string then buffer - body = Buffer.from(String(body)); - } - this[INTERNALS] = { - body, - disturbed: false, - error: null - }; - this.size = size; - this.timeout = timeout; - if (body instanceof Stream) { - body.on('error', function (err) { - const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err); - _this[INTERNALS].error = error; - }); - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +// Port of lower_bound from https://en.cppreference.com/w/cpp/algorithm/lower_bound +// Used to compute insertion index to keep queue sorted after insertion +function lowerBound(array, value, comparator) { + let first = 0; + let count = array.length; + while (count > 0) { + const step = (count / 2) | 0; + let it = first + step; + if (comparator(array[it], value) <= 0) { + first = ++it; + count -= step + 1; + } + else { + count = step; + } + } + return first; } +exports["default"] = lowerBound; -Body.prototype = { - get body() { - return this[INTERNALS].body; - }, - - get bodyUsed() { - return this[INTERNALS].disturbed; - }, - - /** - * Decode response as ArrayBuffer - * - * @return Promise - */ - arrayBuffer() { - return consumeBody.call(this).then(function (buf) { - return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); - }); - }, - - /** - * Return raw response as Blob - * - * @return Promise - */ - blob() { - let ct = this.headers && this.headers.get('content-type') || ''; - return consumeBody.call(this).then(function (buf) { - return Object.assign( - // Prevent copying - new Blob([], { - type: ct.toLowerCase() - }), { - [BUFFER]: buf - }); - }); - }, - - /** - * Decode response as json - * - * @return Promise - */ - json() { - var _this2 = this; - - return consumeBody.call(this).then(function (buffer) { - try { - return JSON.parse(buffer.toString()); - } catch (err) { - return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json')); - } - }); - }, - - /** - * Decode response as text - * - * @return Promise - */ - text() { - return consumeBody.call(this).then(function (buffer) { - return buffer.toString(); - }); - }, - - /** - * Decode response as buffer (non-spec api) - * - * @return Promise - */ - buffer() { - return consumeBody.call(this); - }, - - /** - * Decode response as text, while automatically detecting the encoding and - * trying to decode to UTF-8 (non-spec api) - * - * @return Promise - */ - textConverted() { - var _this3 = this; - - return consumeBody.call(this).then(function (buffer) { - return convertBody(buffer, _this3.headers); - }); - } -}; - -// In browsers, all properties are enumerable. -Object.defineProperties(Body.prototype, { - body: { enumerable: true }, - bodyUsed: { enumerable: true }, - arrayBuffer: { enumerable: true }, - blob: { enumerable: true }, - json: { enumerable: true }, - text: { enumerable: true } -}); - -Body.mixIn = function (proto) { - for (const name of Object.getOwnPropertyNames(Body.prototype)) { - // istanbul ignore else: future proof - if (!(name in proto)) { - const desc = Object.getOwnPropertyDescriptor(Body.prototype, name); - Object.defineProperty(proto, name, desc); - } - } -}; - -/** - * Consume and convert an entire Body to a Buffer. - * - * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body - * - * @return Promise - */ -function consumeBody() { - var _this4 = this; - - if (this[INTERNALS].disturbed) { - return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`)); - } - - this[INTERNALS].disturbed = true; - - if (this[INTERNALS].error) { - return Body.Promise.reject(this[INTERNALS].error); - } - - let body = this.body; - - // body is null - if (body === null) { - return Body.Promise.resolve(Buffer.alloc(0)); - } - - // body is blob - if (isBlob(body)) { - body = body.stream(); - } - // body is buffer - if (Buffer.isBuffer(body)) { - return Body.Promise.resolve(body); - } +/***/ }), - // istanbul ignore if: should never happen - if (!(body instanceof Stream)) { - return Body.Promise.resolve(Buffer.alloc(0)); - } +/***/ 5905: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // body is stream - // get ready to actually consume the body - let accum = []; - let accumBytes = 0; - let abort = false; - - return new Body.Promise(function (resolve, reject) { - let resTimeout; - - // allow timeout on slow response body - if (_this4.timeout) { - resTimeout = setTimeout(function () { - abort = true; - reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout')); - }, _this4.timeout); - } - // handle stream errors - body.on('error', function (err) { - if (err.name === 'AbortError') { - // if the request was aborted, reject with this Error - abort = true; - reject(err); - } else { - // other errors, such as incorrect content-encoding - reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err)); - } - }); +Object.defineProperty(exports, "__esModule", ({ value: true })); +const lower_bound_1 = __nccwpck_require__(9015); +class PriorityQueue { + constructor() { + this._queue = []; + } + enqueue(run, options) { + options = Object.assign({ priority: 0 }, options); + const element = { + priority: options.priority, + run + }; + if (this.size && this._queue[this.size - 1].priority >= options.priority) { + this._queue.push(element); + return; + } + const index = lower_bound_1.default(this._queue, element, (a, b) => b.priority - a.priority); + this._queue.splice(index, 0, element); + } + dequeue() { + const item = this._queue.shift(); + return item === null || item === void 0 ? void 0 : item.run; + } + filter(options) { + return this._queue.filter((element) => element.priority === options.priority).map((element) => element.run); + } + get size() { + return this._queue.length; + } +} +exports["default"] = PriorityQueue; - body.on('data', function (chunk) { - if (abort || chunk === null) { - return; - } - if (_this4.size && accumBytes + chunk.length > _this4.size) { - abort = true; - reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size')); - return; - } +/***/ }), - accumBytes += chunk.length; - accum.push(chunk); - }); +/***/ 301: +/***/ ((module) => { - body.on('end', function () { - if (abort) { - return; - } - clearTimeout(resTimeout); - try { - resolve(Buffer.concat(accum, accumBytes)); - } catch (err) { - // handle streams that have accumulated too much data (issue #414) - reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err)); - } - }); - }); -} +var has = Object.prototype.hasOwnProperty + , prefix = '~'; /** - * Detect buffer encoding and convert to target encoding - * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding + * Constructor to create a storage for our `EE` objects. + * An `Events` instance is a plain object whose properties are event names. * - * @param Buffer buffer Incoming buffer - * @param String encoding Target encoding - * @return String + * @constructor + * @private */ -function convertBody(buffer, headers) { - if (typeof convert !== 'function') { - throw new Error('The package `encoding` must be installed to use the textConverted() function'); - } - - const ct = headers.get('content-type'); - let charset = 'utf-8'; - let res, str; - - // header - if (ct) { - res = /charset=([^;]*)/i.exec(ct); - } - - // no charset in content type, peek at response body for at most 1024 bytes - str = buffer.slice(0, 1024).toString(); - - // html5 - if (!res && str) { - res = / 0 && arguments[0] !== undefined ? arguments[0] : undefined; - - this[MAP] = Object.create(null); - - if (init instanceof Headers) { - const rawHeaders = init.raw(); - const headerNames = Object.keys(rawHeaders); - - for (const headerName of headerNames) { - for (const value of rawHeaders[headerName]) { - this.append(headerName, value); - } - } - - return; - } - - // We don't worry about converting prop to ByteString here as append() - // will handle it. - if (init == null) ; else if (typeof init === 'object') { - const method = init[Symbol.iterator]; - if (method != null) { - if (typeof method !== 'function') { - throw new TypeError('Header pairs must be iterable'); - } - - // sequence> - // Note: per spec we have to first exhaust the lists then process them - const pairs = []; - for (const pair of init) { - if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') { - throw new TypeError('Each header pair must be iterable'); - } - pairs.push(Array.from(pair)); - } - - for (const pair of pairs) { - if (pair.length !== 2) { - throw new TypeError('Each header pair must be a name/value tuple'); - } - this.append(pair[0], pair[1]); - } - } else { - // record - for (const key of Object.keys(init)) { - const value = init[key]; - this.append(key, value); - } - } - } else { - throw new TypeError('Provided initializer must be an object'); - } - } - - /** - * Return combined header value given name - * - * @param String name Header name - * @return Mixed - */ - get(name) { - name = `${name}`; - validateName(name); - const key = find(this[MAP], name); - if (key === undefined) { - return null; - } - - return this[MAP][key].join(', '); - } - - /** - * Iterate over all headers - * - * @param Function callback Executed for each item with parameters (value, name, thisArg) - * @param Boolean thisArg `this` context for callback function - * @return Void - */ - forEach(callback) { - let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; - - let pairs = getHeaders(this); - let i = 0; - while (i < pairs.length) { - var _pairs$i = pairs[i]; - const name = _pairs$i[0], - value = _pairs$i[1]; - - callback.call(thisArg, value, name, this); - pairs = getHeaders(this); - i++; - } - } - - /** - * Overwrite header values given name - * - * @param String name Header name - * @param String value Header value - * @return Void - */ - set(name, value) { - name = `${name}`; - value = `${value}`; - validateName(name); - validateValue(value); - const key = find(this[MAP], name); - this[MAP][key !== undefined ? key : name] = [value]; - } - - /** - * Append a value onto existing header - * - * @param String name Header name - * @param String value Header value - * @return Void - */ - append(name, value) { - name = `${name}`; - value = `${value}`; - validateName(name); - validateValue(value); - const key = find(this[MAP], name); - if (key !== undefined) { - this[MAP][key].push(value); - } else { - this[MAP][name] = [value]; - } - } - - /** - * Check for header name existence - * - * @param String name Header name - * @return Boolean - */ - has(name) { - name = `${name}`; - validateName(name); - return find(this[MAP], name) !== undefined; - } + * @param {(String|Symbol)} event The event name. + * @returns {Array} The registered listeners. + * @public + */ +EventEmitter.prototype.listeners = function listeners(event) { + var evt = prefix ? prefix + event : event + , handlers = this._events[evt]; - /** - * Delete all header values given name - * - * @param String name Header name - * @return Void - */ - delete(name) { - name = `${name}`; - validateName(name); - const key = find(this[MAP], name); - if (key !== undefined) { - delete this[MAP][key]; - } - } + if (!handlers) return []; + if (handlers.fn) return [handlers.fn]; - /** - * Return raw headers (non-spec api) - * - * @return Object - */ - raw() { - return this[MAP]; - } + for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) { + ee[i] = handlers[i].fn; + } - /** - * Get an iterator on keys. - * - * @return Iterator - */ - keys() { - return createHeadersIterator(this, 'key'); - } + return ee; +}; - /** - * Get an iterator on values. - * - * @return Iterator - */ - values() { - return createHeadersIterator(this, 'value'); - } +/** + * Return the number of listeners listening to a given event. + * + * @param {(String|Symbol)} event The event name. + * @returns {Number} The number of listeners. + * @public + */ +EventEmitter.prototype.listenerCount = function listenerCount(event) { + var evt = prefix ? prefix + event : event + , listeners = this._events[evt]; - /** - * Get an iterator on entries. - * - * This is the default iterator of the Headers object. - * - * @return Iterator - */ - [Symbol.iterator]() { - return createHeadersIterator(this, 'key+value'); - } -} -Headers.prototype.entries = Headers.prototype[Symbol.iterator]; + if (!listeners) return 0; + if (listeners.fn) return 1; + return listeners.length; +}; -Object.defineProperty(Headers.prototype, Symbol.toStringTag, { - value: 'Headers', - writable: false, - enumerable: false, - configurable: true -}); +/** + * Calls each of the listeners registered for a given event. + * + * @param {(String|Symbol)} event The event name. + * @returns {Boolean} `true` if the event had listeners, else `false`. + * @public + */ +EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { + var evt = prefix ? prefix + event : event; -Object.defineProperties(Headers.prototype, { - get: { enumerable: true }, - forEach: { enumerable: true }, - set: { enumerable: true }, - append: { enumerable: true }, - has: { enumerable: true }, - delete: { enumerable: true }, - keys: { enumerable: true }, - values: { enumerable: true }, - entries: { enumerable: true } -}); + if (!this._events[evt]) return false; -function getHeaders(headers) { - let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value'; + var listeners = this._events[evt] + , len = arguments.length + , args + , i; - const keys = Object.keys(headers[MAP]).sort(); - return keys.map(kind === 'key' ? function (k) { - return k.toLowerCase(); - } : kind === 'value' ? function (k) { - return headers[MAP][k].join(', '); - } : function (k) { - return [k.toLowerCase(), headers[MAP][k].join(', ')]; - }); -} + if (listeners.fn) { + if (listeners.once) this.removeListener(event, listeners.fn, undefined, true); -const INTERNAL = Symbol('internal'); + switch (len) { + case 1: return listeners.fn.call(listeners.context), true; + case 2: return listeners.fn.call(listeners.context, a1), true; + case 3: return listeners.fn.call(listeners.context, a1, a2), true; + case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; + case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; + case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; + } -function createHeadersIterator(target, kind) { - const iterator = Object.create(HeadersIteratorPrototype); - iterator[INTERNAL] = { - target, - kind, - index: 0 - }; - return iterator; -} + for (i = 1, args = new Array(len -1); i < len; i++) { + args[i - 1] = arguments[i]; + } -const HeadersIteratorPrototype = Object.setPrototypeOf({ - next() { - // istanbul ignore if - if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) { - throw new TypeError('Value of `this` is not a HeadersIterator'); - } + listeners.fn.apply(listeners.context, args); + } else { + var length = listeners.length + , j; - var _INTERNAL = this[INTERNAL]; - const target = _INTERNAL.target, - kind = _INTERNAL.kind, - index = _INTERNAL.index; - - const values = getHeaders(target, kind); - const len = values.length; - if (index >= len) { - return { - value: undefined, - done: true - }; - } + for (i = 0; i < length; i++) { + if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true); - this[INTERNAL].index = index + 1; + switch (len) { + case 1: listeners[i].fn.call(listeners[i].context); break; + case 2: listeners[i].fn.call(listeners[i].context, a1); break; + case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break; + case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break; + default: + if (!args) for (j = 1, args = new Array(len -1); j < len; j++) { + args[j - 1] = arguments[j]; + } - return { - value: values[index], - done: false - }; - } -}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))); + listeners[i].fn.apply(listeners[i].context, args); + } + } + } -Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, { - value: 'HeadersIterator', - writable: false, - enumerable: false, - configurable: true -}); + return true; +}; /** - * Export the Headers object in a form that Node.js can consume. + * Add a listener for a given event. * - * @param Headers headers - * @return Object + * @param {(String|Symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + * @public */ -function exportNodeCompatibleHeaders(headers) { - const obj = Object.assign({ __proto__: null }, headers[MAP]); - - // http.request() only supports string as Host header. This hack makes - // specifying custom Host header possible. - const hostHeaderKey = find(headers[MAP], 'Host'); - if (hostHeaderKey !== undefined) { - obj[hostHeaderKey] = obj[hostHeaderKey][0]; - } - - return obj; -} +EventEmitter.prototype.on = function on(event, fn, context) { + return addListener(this, event, fn, context, false); +}; /** - * Create a Headers object from an object of headers, ignoring those that do - * not conform to HTTP grammar productions. + * Add a one-time listener for a given event. * - * @param Object obj Object of headers - * @return Headers - */ -function createHeadersLenient(obj) { - const headers = new Headers(); - for (const name of Object.keys(obj)) { - if (invalidTokenRegex.test(name)) { - continue; - } - if (Array.isArray(obj[name])) { - for (const val of obj[name]) { - if (invalidHeaderCharRegex.test(val)) { - continue; - } - if (headers[MAP][name] === undefined) { - headers[MAP][name] = [val]; - } else { - headers[MAP][name].push(val); - } - } - } else if (!invalidHeaderCharRegex.test(obj[name])) { - headers[MAP][name] = [obj[name]]; - } - } - return headers; -} - -const INTERNALS$1 = Symbol('Response internals'); - -// fix an issue where "STATUS_CODES" aren't a named export for node <10 -const STATUS_CODES = http.STATUS_CODES; + * @param {(String|Symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + * @public + */ +EventEmitter.prototype.once = function once(event, fn, context) { + return addListener(this, event, fn, context, true); +}; /** - * Response class + * Remove the listeners of a given event. * - * @param Stream body Readable stream - * @param Object opts Response options - * @return Void + * @param {(String|Symbol)} event The event name. + * @param {Function} fn Only remove the listeners that match this function. + * @param {*} context Only remove the listeners that have this context. + * @param {Boolean} once Only remove one-time listeners. + * @returns {EventEmitter} `this`. + * @public */ -class Response { - constructor() { - let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; - let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; +EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) { + var evt = prefix ? prefix + event : event; - Body.call(this, body, opts); + if (!this._events[evt]) return this; + if (!fn) { + clearEvent(this, evt); + return this; + } - const status = opts.status || 200; - const headers = new Headers(opts.headers); + var listeners = this._events[evt]; - if (body != null && !headers.has('Content-Type')) { - const contentType = extractContentType(body); - if (contentType) { - headers.append('Content-Type', contentType); - } - } + if (listeners.fn) { + if ( + listeners.fn === fn && + (!once || listeners.once) && + (!context || listeners.context === context) + ) { + clearEvent(this, evt); + } + } else { + for (var i = 0, events = [], length = listeners.length; i < length; i++) { + if ( + listeners[i].fn !== fn || + (once && !listeners[i].once) || + (context && listeners[i].context !== context) + ) { + events.push(listeners[i]); + } + } - this[INTERNALS$1] = { - url: opts.url, - status, - statusText: opts.statusText || STATUS_CODES[status], - headers, - counter: opts.counter - }; - } + // + // Reset the array, or remove it completely if we have no more listeners. + // + if (events.length) this._events[evt] = events.length === 1 ? events[0] : events; + else clearEvent(this, evt); + } - get url() { - return this[INTERNALS$1].url || ''; - } + return this; +}; - get status() { - return this[INTERNALS$1].status; - } +/** + * Remove all listeners, or those of the specified event. + * + * @param {(String|Symbol)} [event] The event name. + * @returns {EventEmitter} `this`. + * @public + */ +EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { + var evt; - /** - * Convenience property representing if the request ended normally - */ - get ok() { - return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300; - } + if (event) { + evt = prefix ? prefix + event : event; + if (this._events[evt]) clearEvent(this, evt); + } else { + this._events = new Events(); + this._eventsCount = 0; + } - get redirected() { - return this[INTERNALS$1].counter > 0; - } + return this; +}; - get statusText() { - return this[INTERNALS$1].statusText; - } +// +// Alias methods names because people roll like that. +// +EventEmitter.prototype.off = EventEmitter.prototype.removeListener; +EventEmitter.prototype.addListener = EventEmitter.prototype.on; - get headers() { - return this[INTERNALS$1].headers; - } +// +// Expose the prefix. +// +EventEmitter.prefixed = prefix; - /** - * Clone this response - * - * @return Response - */ - clone() { - return new Response(clone(this), { - url: this.url, - status: this.status, - statusText: this.statusText, - headers: this.headers, - ok: this.ok, - redirected: this.redirected - }); - } +// +// Allow `EventEmitter` to be imported as module namespace. +// +EventEmitter.EventEmitter = EventEmitter; + +// +// Expose the module. +// +if (true) { + module.exports = EventEmitter; } -Body.mixIn(Response.prototype); -Object.defineProperties(Response.prototype, { - url: { enumerable: true }, - status: { enumerable: true }, - ok: { enumerable: true }, - redirected: { enumerable: true }, - statusText: { enumerable: true }, - headers: { enumerable: true }, - clone: { enumerable: true } -}); +/***/ }), -Object.defineProperty(Response.prototype, Symbol.toStringTag, { - value: 'Response', - writable: false, - enumerable: false, - configurable: true -}); +/***/ 2103: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -const INTERNALS$2 = Symbol('Request internals'); -const URL = Url.URL || whatwgUrl.URL; -// fix an issue where "format", "parse" aren't a named export for node <10 -const parse_url = Url.parse; -const format_url = Url.format; +const retry = __nccwpck_require__(5546); -/** - * Wrapper around `new URL` to handle arbitrary URLs - * - * @param {string} urlStr - * @return {void} - */ -function parseURL(urlStr) { - /* - Check whether the URL is absolute or not - Scheme: https://tools.ietf.org/html/rfc3986#section-3.1 - Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.3 - */ - if (/^[a-zA-Z][a-zA-Z\d+\-.]*:/.exec(urlStr)) { - urlStr = new URL(urlStr).toString(); - } +const networkErrorMsgs = [ + 'Failed to fetch', // Chrome + 'NetworkError when attempting to fetch resource.', // Firefox + 'The Internet connection appears to be offline.', // Safari + 'Network request failed' // `cross-fetch` +]; - // Fallback to old implementation for arbitrary URLs - return parse_url(urlStr); -} +class AbortError extends Error { + constructor(message) { + super(); -const streamDestructionSupported = 'destroy' in Stream.Readable.prototype; + if (message instanceof Error) { + this.originalError = message; + ({message} = message); + } else { + this.originalError = new Error(message); + this.originalError.stack = this.stack; + } -/** - * Check if a value is an instance of Request. - * - * @param Mixed input - * @return Boolean - */ -function isRequest(input) { - return typeof input === 'object' && typeof input[INTERNALS$2] === 'object'; + this.name = 'AbortError'; + this.message = message; + } } -function isAbortSignal(signal) { - const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal); - return !!(proto && proto.constructor.name === 'AbortSignal'); -} +const decorateErrorWithCounts = (error, attemptNumber, options) => { + // Minus 1 from attemptNumber because the first attempt does not count as a retry + const retriesLeft = options.retries - (attemptNumber - 1); -/** - * Request class - * - * @param Mixed input Url or Request instance - * @param Object init Custom options - * @return Void - */ -class Request { - constructor(input) { - let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - - let parsedURL; - - // normalize input - if (!isRequest(input)) { - if (input && input.href) { - // in order to support Node.js' Url objects; though WHATWG's URL objects - // will fall into this branch also (since their `toString()` will return - // `href` property anyway) - parsedURL = parseURL(input.href); - } else { - // coerce input to a string before attempting to parse - parsedURL = parseURL(`${input}`); - } - input = {}; - } else { - parsedURL = parseURL(input.url); - } + error.attemptNumber = attemptNumber; + error.retriesLeft = retriesLeft; + return error; +}; - let method = init.method || input.method || 'GET'; - method = method.toUpperCase(); +const isNetworkError = errorMessage => networkErrorMsgs.includes(errorMessage); - if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) { - throw new TypeError('Request with GET/HEAD method cannot have body'); - } +const pRetry = (input, options) => new Promise((resolve, reject) => { + options = { + onFailedAttempt: () => {}, + retries: 10, + ...options + }; - let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null; + const operation = retry.operation(options); - Body.call(this, inputBody, { - timeout: init.timeout || input.timeout || 0, - size: init.size || input.size || 0 - }); + operation.attempt(async attemptNumber => { + try { + resolve(await input(attemptNumber)); + } catch (error) { + if (!(error instanceof Error)) { + reject(new TypeError(`Non-error was thrown: "${error}". You should only throw errors.`)); + return; + } + + if (error instanceof AbortError) { + operation.stop(); + reject(error.originalError); + } else if (error instanceof TypeError && !isNetworkError(error.message)) { + operation.stop(); + reject(error); + } else { + decorateErrorWithCounts(error, attemptNumber, options); - const headers = new Headers(init.headers || input.headers || {}); + try { + await options.onFailedAttempt(error); + } catch (error) { + reject(error); + return; + } - if (inputBody != null && !headers.has('Content-Type')) { - const contentType = extractContentType(inputBody); - if (contentType) { - headers.append('Content-Type', contentType); + if (!operation.retry(error)) { + reject(operation.mainError()); + } } } + }); +}); - let signal = isRequest(input) ? input.signal : null; - if ('signal' in init) signal = init.signal; +module.exports = pRetry; +// TODO: remove this in the next major version +module.exports["default"] = pRetry; - if (signal != null && !isAbortSignal(signal)) { - throw new TypeError('Expected signal to be an instanceof AbortSignal'); - } +module.exports.AbortError = AbortError; - this[INTERNALS$2] = { - method, - redirect: init.redirect || input.redirect || 'follow', - headers, - parsedURL, - signal - }; - - // node-fetch-only options - this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20; - this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true; - this.counter = init.counter || input.counter || 0; - this.agent = init.agent || input.agent; - } - get method() { - return this[INTERNALS$2].method; - } +/***/ }), - get url() { - return format_url(this[INTERNALS$2].parsedURL); - } +/***/ 4802: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - get headers() { - return this[INTERNALS$2].headers; - } - get redirect() { - return this[INTERNALS$2].redirect; - } - get signal() { - return this[INTERNALS$2].signal; - } +const pFinally = __nccwpck_require__(2766); - /** - * Clone this request - * - * @return Request - */ - clone() { - return new Request(this); +class TimeoutError extends Error { + constructor(message) { + super(message); + this.name = 'TimeoutError'; } } -Body.mixIn(Request.prototype); - -Object.defineProperty(Request.prototype, Symbol.toStringTag, { - value: 'Request', - writable: false, - enumerable: false, - configurable: true -}); - -Object.defineProperties(Request.prototype, { - method: { enumerable: true }, - url: { enumerable: true }, - headers: { enumerable: true }, - redirect: { enumerable: true }, - clone: { enumerable: true }, - signal: { enumerable: true } -}); - -/** - * Convert a Request to Node.js http request options. - * - * @param Request A Request instance - * @return Object The options object to be passed to http.request - */ -function getNodeRequestOptions(request) { - const parsedURL = request[INTERNALS$2].parsedURL; - const headers = new Headers(request[INTERNALS$2].headers); - - // fetch step 1.3 - if (!headers.has('Accept')) { - headers.set('Accept', '*/*'); - } - - // Basic fetch - if (!parsedURL.protocol || !parsedURL.hostname) { - throw new TypeError('Only absolute URLs are supported'); +const pTimeout = (promise, milliseconds, fallback) => new Promise((resolve, reject) => { + if (typeof milliseconds !== 'number' || milliseconds < 0) { + throw new TypeError('Expected `milliseconds` to be a positive number'); } - if (!/^https?:$/.test(parsedURL.protocol)) { - throw new TypeError('Only HTTP(S) protocols are supported'); + if (milliseconds === Infinity) { + resolve(promise); + return; } - if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) { - throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8'); - } + const timer = setTimeout(() => { + if (typeof fallback === 'function') { + try { + resolve(fallback()); + } catch (error) { + reject(error); + } - // HTTP-network-or-cache fetch steps 2.4-2.7 - let contentLengthValue = null; - if (request.body == null && /^(POST|PUT)$/i.test(request.method)) { - contentLengthValue = '0'; - } - if (request.body != null) { - const totalBytes = getTotalBytes(request); - if (typeof totalBytes === 'number') { - contentLengthValue = String(totalBytes); + return; } - } - if (contentLengthValue) { - headers.set('Content-Length', contentLengthValue); - } - - // HTTP-network-or-cache fetch step 2.11 - if (!headers.has('User-Agent')) { - headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)'); - } - - // HTTP-network-or-cache fetch step 2.15 - if (request.compress && !headers.has('Accept-Encoding')) { - headers.set('Accept-Encoding', 'gzip,deflate'); - } - - let agent = request.agent; - if (typeof agent === 'function') { - agent = agent(parsedURL); - } - - // HTTP-network fetch step 4.2 - // chunked encoding is handled by Node.js - return Object.assign({}, parsedURL, { - method: request.method, - headers: exportNodeCompatibleHeaders(headers), - agent - }); -} + const message = typeof fallback === 'string' ? fallback : `Promise timed out after ${milliseconds} milliseconds`; + const timeoutError = fallback instanceof Error ? fallback : new TimeoutError(message); -/** - * abort-error.js - * - * AbortError interface for cancelled requests - */ + if (typeof promise.cancel === 'function') { + promise.cancel(); + } -/** - * Create AbortError instance - * - * @param String message Error message for human - * @return AbortError - */ -function AbortError(message) { - Error.call(this, message); + reject(timeoutError); + }, milliseconds); - this.type = 'aborted'; - this.message = message; + // TODO: Use native `finally` keyword when targeting Node.js 10 + pFinally( + // eslint-disable-next-line promise/prefer-await-to-then + promise.then(resolve, reject), + () => { + clearTimeout(timer); + } + ); +}); - // hide custom error implementation details from end-users - Error.captureStackTrace(this, this.constructor); -} +module.exports = pTimeout; +// TODO: Remove this for the next major release +module.exports["default"] = pTimeout; -AbortError.prototype = Object.create(Error.prototype); -AbortError.prototype.constructor = AbortError; -AbortError.prototype.name = 'AbortError'; +module.exports.TimeoutError = TimeoutError; -const URL$1 = Url.URL || whatwgUrl.URL; -// fix an issue where "PassThrough", "resolve" aren't a named export for node <10 -const PassThrough$1 = Stream.PassThrough; +/***/ }), -const isDomainOrSubdomain = function isDomainOrSubdomain(destination, original) { - const orig = new URL$1(original).hostname; - const dest = new URL$1(destination).hostname; +/***/ 2673: +/***/ ((module) => { - return orig === dest || orig[orig.length - dest.length - 1] === '.' && orig.endsWith(dest); -}; +function _typeof(obj){"@babel/helpers - typeof";return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj},_typeof(obj)}function _createForOfIteratorHelper(o,allowArrayLike){var it=typeof Symbol!=="undefined"&&o[Symbol.iterator]||o["@@iterator"];if(!it){if(Array.isArray(o)||(it=_unsupportedIterableToArray(o))||allowArrayLike&&o&&typeof o.length==="number"){if(it)o=it;var i=0;var F=function F(){};return{s:F,n:function n(){if(i>=o.length)return{done:true};return{done:false,value:o[i++]}},e:function e(_e2){throw _e2},f:F}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var normalCompletion=true,didErr=false,err;return{s:function s(){it=it.call(o)},n:function n(){var step=it.next();normalCompletion=step.done;return step},e:function e(_e3){didErr=true;err=_e3},f:function f(){try{if(!normalCompletion&&it["return"]!=null)it["return"]()}finally{if(didErr)throw err}}}}function _defineProperty(obj,key,value){key=_toPropertyKey(key);if(key in obj){Object.defineProperty(obj,key,{value:value,enumerable:true,configurable:true,writable:true})}else{obj[key]=value}return obj}function _toPropertyKey(arg){var key=_toPrimitive(arg,"string");return _typeof(key)==="symbol"?key:String(key)}function _toPrimitive(input,hint){if(_typeof(input)!=="object"||input===null)return input;var prim=input[Symbol.toPrimitive];if(prim!==undefined){var res=prim.call(input,hint||"default");if(_typeof(res)!=="object")return res;throw new TypeError("@@toPrimitive must return a primitive value.")}return(hint==="string"?String:Number)(input)}function _slicedToArray(arr,i){return _arrayWithHoles(arr)||_iterableToArrayLimit(arr,i)||_unsupportedIterableToArray(arr,i)||_nonIterableRest()}function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _unsupportedIterableToArray(o,minLen){if(!o)return;if(typeof o==="string")return _arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);if(n==="Object"&&o.constructor)n=o.constructor.name;if(n==="Map"||n==="Set")return Array.from(o);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return _arrayLikeToArray(o,minLen)}function _arrayLikeToArray(arr,len){if(len==null||len>arr.length)len=arr.length;for(var i=0,arr2=new Array(len);i { - // allow custom promise - if (!fetch.Promise) { - throw new Error('native promise missing, set fetch.Promise to your favorite alternative'); - } - Body.Promise = fetch.Promise; - // wrap http.request into fetch - return new fetch.Promise(function (resolve, reject) { - // build request object - const request = new Request(url, opts); - const options = getNodeRequestOptions(request); +module.exports = __nccwpck_require__(8016); - const send = (options.protocol === 'https:' ? https : http).request; - const signal = request.signal; - let response = null; +/***/ }), - const abort = function abort() { - let error = new AbortError('The user aborted a request.'); - reject(error); - if (request.body && request.body instanceof Stream.Readable) { - destroyStream(request.body, error); - } - if (!response || !response.body) return; - response.body.emit('error', error); - }; +/***/ 5595: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (signal && signal.aborted) { - abort(); - return; - } - const abortAndFinalize = function abortAndFinalize() { - abort(); - finalize(); - }; - // send request - const req = send(options); - let reqTimeout; +const path = __nccwpck_require__(6928); +const WIN_SLASH = '\\\\/'; +const WIN_NO_SLASH = `[^${WIN_SLASH}]`; - if (signal) { - signal.addEventListener('abort', abortAndFinalize); - } +/** + * Posix glob regex + */ - function finalize() { - req.abort(); - if (signal) signal.removeEventListener('abort', abortAndFinalize); - clearTimeout(reqTimeout); - } +const DOT_LITERAL = '\\.'; +const PLUS_LITERAL = '\\+'; +const QMARK_LITERAL = '\\?'; +const SLASH_LITERAL = '\\/'; +const ONE_CHAR = '(?=.)'; +const QMARK = '[^/]'; +const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`; +const START_ANCHOR = `(?:^|${SLASH_LITERAL})`; +const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`; +const NO_DOT = `(?!${DOT_LITERAL})`; +const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`; +const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`; +const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`; +const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`; +const STAR = `${QMARK}*?`; - if (request.timeout) { - req.once('socket', function (socket) { - reqTimeout = setTimeout(function () { - reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout')); - finalize(); - }, request.timeout); - }); - } +const POSIX_CHARS = { + DOT_LITERAL, + PLUS_LITERAL, + QMARK_LITERAL, + SLASH_LITERAL, + ONE_CHAR, + QMARK, + END_ANCHOR, + DOTS_SLASH, + NO_DOT, + NO_DOTS, + NO_DOT_SLASH, + NO_DOTS_SLASH, + QMARK_NO_DOT, + STAR, + START_ANCHOR +}; - req.on('error', function (err) { - reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err)); +/** + * Windows glob regex + */ - if (response && response.body) { - destroyStream(response.body, err); - } +const WINDOWS_CHARS = { + ...POSIX_CHARS, - finalize(); - }); + SLASH_LITERAL: `[${WIN_SLASH}]`, + QMARK: WIN_NO_SLASH, + STAR: `${WIN_NO_SLASH}*?`, + DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`, + NO_DOT: `(?!${DOT_LITERAL})`, + NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, + NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`, + NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, + QMARK_NO_DOT: `[^.${WIN_SLASH}]`, + START_ANCHOR: `(?:^|[${WIN_SLASH}])`, + END_ANCHOR: `(?:[${WIN_SLASH}]|$)` +}; - fixResponseChunkedTransferBadEnding(req, function (err) { - if (signal && signal.aborted) { - return; - } +/** + * POSIX Bracket Regex + */ - if (response && response.body) { - destroyStream(response.body, err); - } - }); +const POSIX_REGEX_SOURCE = { + alnum: 'a-zA-Z0-9', + alpha: 'a-zA-Z', + ascii: '\\x00-\\x7F', + blank: ' \\t', + cntrl: '\\x00-\\x1F\\x7F', + digit: '0-9', + graph: '\\x21-\\x7E', + lower: 'a-z', + print: '\\x20-\\x7E ', + punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~', + space: ' \\t\\r\\n\\v\\f', + upper: 'A-Z', + word: 'A-Za-z0-9_', + xdigit: 'A-Fa-f0-9' +}; - /* c8 ignore next 18 */ - if (parseInt(process.version.substring(1)) < 14) { - // Before Node.js 14, pipeline() does not fully support async iterators and does not always - // properly handle when the socket close/end events are out of order. - req.on('socket', function (s) { - s.addListener('close', function (hadError) { - // if a data listener is still present we didn't end cleanly - const hasDataListener = s.listenerCount('data') > 0; - - // if end happened before close but the socket didn't emit an error, do it now - if (response && hasDataListener && !hadError && !(signal && signal.aborted)) { - const err = new Error('Premature close'); - err.code = 'ERR_STREAM_PREMATURE_CLOSE'; - response.body.emit('error', err); - } - }); - }); - } +module.exports = { + MAX_LENGTH: 1024 * 64, + POSIX_REGEX_SOURCE, - req.on('response', function (res) { - clearTimeout(reqTimeout); + // regular expressions + REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g, + REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/, + REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/, + REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g, + REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g, + REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g, - const headers = createHeadersLenient(res.headers); + // Replace globs with equivalent patterns to reduce parsing time. + REPLACEMENTS: { + '***': '*', + '**/**': '**', + '**/**/**': '**' + }, - // HTTP fetch step 5 - if (fetch.isRedirect(res.statusCode)) { - // HTTP fetch step 5.2 - const location = headers.get('Location'); + // Digits + CHAR_0: 48, /* 0 */ + CHAR_9: 57, /* 9 */ - // HTTP fetch step 5.3 - let locationURL = null; - try { - locationURL = location === null ? null : new URL$1(location, request.url).toString(); - } catch (err) { - // error here can only be invalid URL in Location: header - // do not throw when options.redirect == manual - // let the user extract the errorneous redirect URL - if (request.redirect !== 'manual') { - reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, 'invalid-redirect')); - finalize(); - return; - } - } + // Alphabet chars. + CHAR_UPPERCASE_A: 65, /* A */ + CHAR_LOWERCASE_A: 97, /* a */ + CHAR_UPPERCASE_Z: 90, /* Z */ + CHAR_LOWERCASE_Z: 122, /* z */ - // HTTP fetch step 5.5 - switch (request.redirect) { - case 'error': - reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect')); - finalize(); - return; - case 'manual': - // node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL. - if (locationURL !== null) { - // handle corrupted header - try { - headers.set('Location', locationURL); - } catch (err) { - // istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request - reject(err); - } - } - break; - case 'follow': - // HTTP-redirect fetch step 2 - if (locationURL === null) { - break; - } - - // HTTP-redirect fetch step 5 - if (request.counter >= request.follow) { - reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect')); - finalize(); - return; - } - - // HTTP-redirect fetch step 6 (counter increment) - // Create a new Request object. - const requestOpts = { - headers: new Headers(request.headers), - follow: request.follow, - counter: request.counter + 1, - agent: request.agent, - compress: request.compress, - method: request.method, - body: request.body, - signal: request.signal, - timeout: request.timeout, - size: request.size - }; - - if (!isDomainOrSubdomain(request.url, locationURL) || !isSameProtocol(request.url, locationURL)) { - for (const name of ['authorization', 'www-authenticate', 'cookie', 'cookie2']) { - requestOpts.headers.delete(name); - } - } - - // HTTP-redirect fetch step 9 - if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) { - reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect')); - finalize(); - return; - } - - // HTTP-redirect fetch step 11 - if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') { - requestOpts.method = 'GET'; - requestOpts.body = undefined; - requestOpts.headers.delete('content-length'); - } - - // HTTP-redirect fetch step 15 - resolve(fetch(new Request(locationURL, requestOpts))); - finalize(); - return; - } - } + CHAR_LEFT_PARENTHESES: 40, /* ( */ + CHAR_RIGHT_PARENTHESES: 41, /* ) */ - // prepare response - res.once('end', function () { - if (signal) signal.removeEventListener('abort', abortAndFinalize); - }); - let body = res.pipe(new PassThrough$1()); - - const response_options = { - url: request.url, - status: res.statusCode, - statusText: res.statusMessage, - headers: headers, - size: request.size, - timeout: request.timeout, - counter: request.counter - }; + CHAR_ASTERISK: 42, /* * */ - // HTTP-network fetch step 12.1.1.3 - const codings = headers.get('Content-Encoding'); + // Non-alphabetic chars. + CHAR_AMPERSAND: 38, /* & */ + CHAR_AT: 64, /* @ */ + CHAR_BACKWARD_SLASH: 92, /* \ */ + CHAR_CARRIAGE_RETURN: 13, /* \r */ + CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */ + CHAR_COLON: 58, /* : */ + CHAR_COMMA: 44, /* , */ + CHAR_DOT: 46, /* . */ + CHAR_DOUBLE_QUOTE: 34, /* " */ + CHAR_EQUAL: 61, /* = */ + CHAR_EXCLAMATION_MARK: 33, /* ! */ + CHAR_FORM_FEED: 12, /* \f */ + CHAR_FORWARD_SLASH: 47, /* / */ + CHAR_GRAVE_ACCENT: 96, /* ` */ + CHAR_HASH: 35, /* # */ + CHAR_HYPHEN_MINUS: 45, /* - */ + CHAR_LEFT_ANGLE_BRACKET: 60, /* < */ + CHAR_LEFT_CURLY_BRACE: 123, /* { */ + CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */ + CHAR_LINE_FEED: 10, /* \n */ + CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */ + CHAR_PERCENT: 37, /* % */ + CHAR_PLUS: 43, /* + */ + CHAR_QUESTION_MARK: 63, /* ? */ + CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */ + CHAR_RIGHT_CURLY_BRACE: 125, /* } */ + CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */ + CHAR_SEMICOLON: 59, /* ; */ + CHAR_SINGLE_QUOTE: 39, /* ' */ + CHAR_SPACE: 32, /* */ + CHAR_TAB: 9, /* \t */ + CHAR_UNDERSCORE: 95, /* _ */ + CHAR_VERTICAL_LINE: 124, /* | */ + CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */ - // HTTP-network fetch step 12.1.1.4: handle content codings + SEP: path.sep, - // in following scenarios we ignore compression support - // 1. compression support is disabled - // 2. HEAD request - // 3. no Content-Encoding header - // 4. no content response (204) - // 5. content not modified response (304) - if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) { - response = new Response(body, response_options); - resolve(response); - return; - } + /** + * Create EXTGLOB_CHARS + */ - // For Node v6+ - // Be less strict when decoding compressed responses, since sometimes - // servers send slightly invalid responses that are still accepted - // by common browsers. - // Always using Z_SYNC_FLUSH is what cURL does. - const zlibOptions = { - flush: zlib.Z_SYNC_FLUSH, - finishFlush: zlib.Z_SYNC_FLUSH - }; + extglobChars(chars) { + return { + '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` }, + '?': { type: 'qmark', open: '(?:', close: ')?' }, + '+': { type: 'plus', open: '(?:', close: ')+' }, + '*': { type: 'star', open: '(?:', close: ')*' }, + '@': { type: 'at', open: '(?:', close: ')' } + }; + }, - // for gzip - if (codings == 'gzip' || codings == 'x-gzip') { - body = body.pipe(zlib.createGunzip(zlibOptions)); - response = new Response(body, response_options); - resolve(response); - return; - } + /** + * Create GLOB_CHARS + */ - // for deflate - if (codings == 'deflate' || codings == 'x-deflate') { - // handle the infamous raw deflate response from old servers - // a hack for old IIS and Apache servers - const raw = res.pipe(new PassThrough$1()); - raw.once('data', function (chunk) { - // see http://stackoverflow.com/questions/37519828 - if ((chunk[0] & 0x0F) === 0x08) { - body = body.pipe(zlib.createInflate()); - } else { - body = body.pipe(zlib.createInflateRaw()); - } - response = new Response(body, response_options); - resolve(response); - }); - raw.on('end', function () { - // some old IIS servers return zero-length OK deflate responses, so 'data' is never emitted. - if (!response) { - response = new Response(body, response_options); - resolve(response); - } - }); - return; - } + globChars(win32) { + return win32 === true ? WINDOWS_CHARS : POSIX_CHARS; + } +}; - // for br - if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') { - body = body.pipe(zlib.createBrotliDecompress()); - response = new Response(body, response_options); - resolve(response); - return; - } - // otherwise, use response as-is - response = new Response(body, response_options); - resolve(response); - }); +/***/ }), - writeToStream(req, request); - }); -} -function fixResponseChunkedTransferBadEnding(request, errorCallback) { - let socket; +/***/ 8265: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - request.on('socket', function (s) { - socket = s; - }); - request.on('response', function (response) { - const headers = response.headers; - - if (headers['transfer-encoding'] === 'chunked' && !headers['content-length']) { - response.once('close', function (hadError) { - // tests for socket presence, as in some situations the - // the 'socket' event is not triggered for the request - // (happens in deno), avoids `TypeError` - // if a data listener is still present we didn't end cleanly - const hasDataListener = socket && socket.listenerCount('data') > 0; - - if (hasDataListener && !hadError) { - const err = new Error('Premature close'); - err.code = 'ERR_STREAM_PREMATURE_CLOSE'; - errorCallback(err); - } - }); - } - }); -} -function destroyStream(stream, err) { - if (stream.destroy) { - stream.destroy(err); - } else { - // node < 8 - stream.emit('error', err); - stream.end(); - } -} +const constants = __nccwpck_require__(5595); +const utils = __nccwpck_require__(4059); /** - * Redirect code matching - * - * @param Number code Status code - * @return Boolean + * Constants */ -fetch.isRedirect = function (code) { - return code === 301 || code === 302 || code === 303 || code === 307 || code === 308; -}; -// expose Promise -fetch.Promise = global.Promise; +const { + MAX_LENGTH, + POSIX_REGEX_SOURCE, + REGEX_NON_SPECIAL_CHARS, + REGEX_SPECIAL_CHARS_BACKREF, + REPLACEMENTS +} = constants; -module.exports = exports = fetch; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = exports; -exports.Headers = Headers; -exports.Request = Request; -exports.Response = Response; -exports.FetchError = FetchError; -exports.AbortError = AbortError; +/** + * Helpers + */ +const expandRange = (args, options) => { + if (typeof options.expandRange === 'function') { + return options.expandRange(...args, options); + } -/***/ }), + args.sort(); + const value = `[${args.join('-')}]`; -/***/ 5560: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + try { + /* eslint-disable-next-line no-new */ + new RegExp(value); + } catch (ex) { + return args.map(v => utils.escapeRegex(v)).join('..'); + } -var wrappy = __nccwpck_require__(8264) -module.exports = wrappy(once) -module.exports.strict = wrappy(onceStrict) + return value; +}; -once.proto = once(function () { - Object.defineProperty(Function.prototype, 'once', { - value: function () { - return once(this) - }, - configurable: true - }) +/** + * Create the message for a syntax error + */ - Object.defineProperty(Function.prototype, 'onceStrict', { - value: function () { - return onceStrict(this) - }, - configurable: true - }) -}) +const syntaxError = (type, char) => { + return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`; +}; -function once (fn) { - var f = function () { - if (f.called) return f.value - f.called = true - return f.value = fn.apply(this, arguments) +/** + * Parse the given input string. + * @param {String} input + * @param {Object} options + * @return {Object} + */ + +const parse = (input, options) => { + if (typeof input !== 'string') { + throw new TypeError('Expected a string'); } - f.called = false - return f -} -function onceStrict (fn) { - var f = function () { - if (f.called) - throw new Error(f.onceError) - f.called = true - return f.value = fn.apply(this, arguments) + input = REPLACEMENTS[input] || input; + + const opts = { ...options }; + const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; + + let len = input.length; + if (len > max) { + throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`); } - var name = fn.name || 'Function wrapped with `once`' - f.onceError = name + " shouldn't be called more than once" - f.called = false - return f -} + const bos = { type: 'bos', value: '', output: opts.prepend || '' }; + const tokens = [bos]; -/***/ }), + const capture = opts.capture ? '' : '?:'; + const win32 = utils.isWindows(options); -/***/ 2766: -/***/ ((module) => { + // create constants based on platform, for windows or posix + const PLATFORM_CHARS = constants.globChars(win32); + const EXTGLOB_CHARS = constants.extglobChars(PLATFORM_CHARS); + const { + DOT_LITERAL, + PLUS_LITERAL, + SLASH_LITERAL, + ONE_CHAR, + DOTS_SLASH, + NO_DOT, + NO_DOT_SLASH, + NO_DOTS_SLASH, + QMARK, + QMARK_NO_DOT, + STAR, + START_ANCHOR + } = PLATFORM_CHARS; -module.exports = (promise, onFinally) => { - onFinally = onFinally || (() => {}); + const globstar = opts => { + return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`; + }; - return promise.then( - val => new Promise(resolve => { - resolve(onFinally()); - }).then(() => val), - err => new Promise(resolve => { - resolve(onFinally()); - }).then(() => { - throw err; - }) - ); -}; + const nodot = opts.dot ? '' : NO_DOT; + const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT; + let star = opts.bash === true ? globstar(opts) : STAR; + if (opts.capture) { + star = `(${star})`; + } -/***/ }), + // minimatch options support + if (typeof opts.noext === 'boolean') { + opts.noextglob = opts.noext; + } -/***/ 6459: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + const state = { + input, + index: -1, + start: 0, + dot: opts.dot === true, + consumed: '', + output: '', + prefix: '', + backtrack: false, + negated: false, + brackets: 0, + braces: 0, + parens: 0, + quotes: 0, + globstar: false, + tokens + }; + input = utils.removePrefix(input, state); + len = input.length; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const EventEmitter = __nccwpck_require__(301); -const p_timeout_1 = __nccwpck_require__(4802); -const priority_queue_1 = __nccwpck_require__(5905); -// eslint-disable-next-line @typescript-eslint/no-empty-function -const empty = () => { }; -const timeoutError = new p_timeout_1.TimeoutError(); -/** -Promise queue with concurrency control. -*/ -class PQueue extends EventEmitter { - constructor(options) { - var _a, _b, _c, _d; - super(); - this._intervalCount = 0; - this._intervalEnd = 0; - this._pendingCount = 0; - this._resolveEmpty = empty; - this._resolveIdle = empty; - // eslint-disable-next-line @typescript-eslint/consistent-type-assertions - options = Object.assign({ carryoverConcurrencyCount: false, intervalCap: Infinity, interval: 0, concurrency: Infinity, autoStart: true, queueClass: priority_queue_1.default }, options); - if (!(typeof options.intervalCap === 'number' && options.intervalCap >= 1)) { - throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(_b = (_a = options.intervalCap) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : ''}\` (${typeof options.intervalCap})`); - } - if (options.interval === undefined || !(Number.isFinite(options.interval) && options.interval >= 0)) { - throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(_d = (_c = options.interval) === null || _c === void 0 ? void 0 : _c.toString()) !== null && _d !== void 0 ? _d : ''}\` (${typeof options.interval})`); - } - this._carryoverConcurrencyCount = options.carryoverConcurrencyCount; - this._isIntervalIgnored = options.intervalCap === Infinity || options.interval === 0; - this._intervalCap = options.intervalCap; - this._interval = options.interval; - this._queue = new options.queueClass(); - this._queueClass = options.queueClass; - this.concurrency = options.concurrency; - this._timeout = options.timeout; - this._throwOnTimeout = options.throwOnTimeout === true; - this._isPaused = options.autoStart === false; - } - get _doesIntervalAllowAnother() { - return this._isIntervalIgnored || this._intervalCount < this._intervalCap; + const extglobs = []; + const braces = []; + const stack = []; + let prev = bos; + let value; + + /** + * Tokenizing helpers + */ + + const eos = () => state.index === len - 1; + const peek = state.peek = (n = 1) => input[state.index + n]; + const advance = state.advance = () => input[++state.index] || ''; + const remaining = () => input.slice(state.index + 1); + const consume = (value = '', num = 0) => { + state.consumed += value; + state.index += num; + }; + + const append = token => { + state.output += token.output != null ? token.output : token.value; + consume(token.value); + }; + + const negate = () => { + let count = 1; + + while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) { + advance(); + state.start++; + count++; } - get _doesConcurrentAllowAnother() { - return this._pendingCount < this._concurrency; + + if (count % 2 === 0) { + return false; } - _next() { - this._pendingCount--; - this._tryToStartAnother(); - this.emit('next'); + + state.negated = true; + state.start++; + return true; + }; + + const increment = type => { + state[type]++; + stack.push(type); + }; + + const decrement = type => { + state[type]--; + stack.pop(); + }; + + /** + * Push tokens onto the tokens array. This helper speeds up + * tokenizing by 1) helping us avoid backtracking as much as possible, + * and 2) helping us avoid creating extra tokens when consecutive + * characters are plain text. This improves performance and simplifies + * lookbehinds. + */ + + const push = tok => { + if (prev.type === 'globstar') { + const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace'); + const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren')); + + if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) { + state.output = state.output.slice(0, -prev.output.length); + prev.type = 'star'; + prev.value = '*'; + prev.output = star; + state.output += prev.output; + } } - _resolvePromises() { - this._resolveEmpty(); - this._resolveEmpty = empty; - if (this._pendingCount === 0) { - this._resolveIdle(); - this._resolveIdle = empty; - this.emit('idle'); - } + + if (extglobs.length && tok.type !== 'paren') { + extglobs[extglobs.length - 1].inner += tok.value; } - _onResumeInterval() { - this._onInterval(); - this._initializeIntervalIfNeeded(); - this._timeoutId = undefined; + + if (tok.value || tok.output) append(tok); + if (prev && prev.type === 'text' && tok.type === 'text') { + prev.value += tok.value; + prev.output = (prev.output || '') + tok.value; + return; } - _isIntervalPaused() { - const now = Date.now(); - if (this._intervalId === undefined) { - const delay = this._intervalEnd - now; - if (delay < 0) { - // Act as the interval was done - // We don't need to resume it here because it will be resumed on line 160 - this._intervalCount = (this._carryoverConcurrencyCount) ? this._pendingCount : 0; - } - else { - // Act as the interval is pending - if (this._timeoutId === undefined) { - this._timeoutId = setTimeout(() => { - this._onResumeInterval(); - }, delay); - } - return true; - } - } - return false; - } - _tryToStartAnother() { - if (this._queue.size === 0) { - // We can clear the interval ("pause") - // Because we can redo it later ("resume") - if (this._intervalId) { - clearInterval(this._intervalId); - } - this._intervalId = undefined; - this._resolvePromises(); - return false; - } - if (!this._isPaused) { - const canInitializeInterval = !this._isIntervalPaused(); - if (this._doesIntervalAllowAnother && this._doesConcurrentAllowAnother) { - const job = this._queue.dequeue(); - if (!job) { - return false; - } - this.emit('active'); - job(); - if (canInitializeInterval) { - this._initializeIntervalIfNeeded(); - } - return true; - } - } - return false; + + tok.prev = prev; + tokens.push(tok); + prev = tok; + }; + + const extglobOpen = (type, value) => { + const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' }; + + token.prev = prev; + token.parens = state.parens; + token.output = state.output; + const output = (opts.capture ? '(' : '') + token.open; + + increment('parens'); + push({ type, value, output: state.output ? '' : ONE_CHAR }); + push({ type: 'paren', extglob: true, value: advance(), output }); + extglobs.push(token); + }; + + const extglobClose = token => { + let output = token.close + (opts.capture ? ')' : ''); + let rest; + + if (token.type === 'negate') { + let extglobStar = star; + + if (token.inner && token.inner.length > 1 && token.inner.includes('/')) { + extglobStar = globstar(opts); + } + + if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) { + output = token.close = `)$))${extglobStar}`; + } + + if (token.inner.includes('*') && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) { + // Any non-magical string (`.ts`) or even nested expression (`.{ts,tsx}`) can follow after the closing parenthesis. + // In this case, we need to parse the string and use it in the output of the original pattern. + // Suitable patterns: `/!(*.d).ts`, `/!(*.d).{ts,tsx}`, `**/!(*-dbg).@(js)`. + // + // Disabling the `fastpaths` option due to a problem with parsing strings as `.ts` in the pattern like `**/!(*.d).ts`. + const expression = parse(rest, { ...options, fastpaths: false }).output; + + output = token.close = `)${expression})${extglobStar})`; + } + + if (token.prev.type === 'bos') { + state.negatedExtglob = true; + } } - _initializeIntervalIfNeeded() { - if (this._isIntervalIgnored || this._intervalId !== undefined) { - return; + + push({ type: 'paren', extglob: true, value, output }); + decrement('parens'); + }; + + /** + * Fast paths + */ + + if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) { + let backslashes = false; + + let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => { + if (first === '\\') { + backslashes = true; + return m; + } + + if (first === '?') { + if (esc) { + return esc + first + (rest ? QMARK.repeat(rest.length) : ''); } - this._intervalId = setInterval(() => { - this._onInterval(); - }, this._interval); - this._intervalEnd = Date.now() + this._interval; - } - _onInterval() { - if (this._intervalCount === 0 && this._pendingCount === 0 && this._intervalId) { - clearInterval(this._intervalId); - this._intervalId = undefined; + if (index === 0) { + return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : ''); } - this._intervalCount = this._carryoverConcurrencyCount ? this._pendingCount : 0; - this._processQueue(); - } - /** - Executes all queued functions until it reaches the limit. - */ - _processQueue() { - // eslint-disable-next-line no-empty - while (this._tryToStartAnother()) { } - } - get concurrency() { - return this._concurrency; - } - set concurrency(newConcurrency) { - if (!(typeof newConcurrency === 'number' && newConcurrency >= 1)) { - throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${newConcurrency}\` (${typeof newConcurrency})`); + return QMARK.repeat(chars.length); + } + + if (first === '.') { + return DOT_LITERAL.repeat(chars.length); + } + + if (first === '*') { + if (esc) { + return esc + first + (rest ? star : ''); } - this._concurrency = newConcurrency; - this._processQueue(); - } - /** - Adds a sync or async task to the queue. Always returns a promise. - */ - async add(fn, options = {}) { - return new Promise((resolve, reject) => { - const run = async () => { - this._pendingCount++; - this._intervalCount++; - try { - const operation = (this._timeout === undefined && options.timeout === undefined) ? fn() : p_timeout_1.default(Promise.resolve(fn()), (options.timeout === undefined ? this._timeout : options.timeout), () => { - if (options.throwOnTimeout === undefined ? this._throwOnTimeout : options.throwOnTimeout) { - reject(timeoutError); - } - return undefined; - }); - resolve(await operation); - } - catch (error) { - reject(error); - } - this._next(); - }; - this._queue.enqueue(run, options); - this._tryToStartAnother(); - this.emit('add'); + return star; + } + return esc ? m : `\\${m}`; + }); + + if (backslashes === true) { + if (opts.unescape === true) { + output = output.replace(/\\/g, ''); + } else { + output = output.replace(/\\+/g, m => { + return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : ''); }); + } } - /** - Same as `.add()`, but accepts an array of sync or async functions. - @returns A promise that resolves when all functions are resolved. - */ - async addAll(functions, options) { - return Promise.all(functions.map(async (function_) => this.add(function_, options))); - } - /** - Start (or resume) executing enqueued tasks within concurrency limit. No need to call this if queue is not paused (via `options.autoStart = false` or by `.pause()` method.) - */ - start() { - if (!this._isPaused) { - return this; - } - this._isPaused = false; - this._processQueue(); - return this; - } - /** - Put queue execution on hold. - */ - pause() { - this._isPaused = true; + if (output === input && opts.contains === true) { + state.output = input; + return state; } - /** - Clear the queue. - */ - clear() { - this._queue = new this._queueClass(); + + state.output = utils.wrapOutput(output, state, options); + return state; + } + + /** + * Tokenize input until we reach end-of-string + */ + + while (!eos()) { + value = advance(); + + if (value === '\u0000') { + continue; } + /** - Can be called multiple times. Useful if you for example add additional items at a later time. + * Escaped characters + */ - @returns A promise that settles when the queue becomes empty. - */ - async onEmpty() { - // Instantly resolve if the queue is empty - if (this._queue.size === 0) { - return; + if (value === '\\') { + const next = peek(); + + if (next === '/' && opts.bash !== true) { + continue; + } + + if (next === '.' || next === ';') { + continue; + } + + if (!next) { + value += '\\'; + push({ type: 'text', value }); + continue; + } + + // collapse slashes to reduce potential for exploits + const match = /^\\+/.exec(remaining()); + let slashes = 0; + + if (match && match[0].length > 2) { + slashes = match[0].length; + state.index += slashes; + if (slashes % 2 !== 0) { + value += '\\'; } - return new Promise(resolve => { - const existingResolve = this._resolveEmpty; - this._resolveEmpty = () => { - existingResolve(); - resolve(); - }; - }); + } + + if (opts.unescape === true) { + value = advance(); + } else { + value += advance(); + } + + if (state.brackets === 0) { + push({ type: 'text', value }); + continue; + } } + /** - The difference with `.onEmpty` is that `.onIdle` guarantees that all work from the queue has finished. `.onEmpty` merely signals that the queue is empty, but it could mean that some promises haven't completed yet. + * If we're inside a regex character class, continue + * until we reach the closing bracket. + */ - @returns A promise that settles when the queue becomes empty, and all promises have completed; `queue.size === 0 && queue.pending === 0`. - */ - async onIdle() { - // Instantly resolve if none pending and if nothing else is queued - if (this._pendingCount === 0 && this._queue.size === 0) { - return; + if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) { + if (opts.posix !== false && value === ':') { + const inner = prev.value.slice(1); + if (inner.includes('[')) { + prev.posix = true; + + if (inner.includes(':')) { + const idx = prev.value.lastIndexOf('['); + const pre = prev.value.slice(0, idx); + const rest = prev.value.slice(idx + 2); + const posix = POSIX_REGEX_SOURCE[rest]; + if (posix) { + prev.value = pre + posix; + state.backtrack = true; + advance(); + + if (!bos.output && tokens.indexOf(prev) === 1) { + bos.output = ONE_CHAR; + } + continue; + } + } } - return new Promise(resolve => { - const existingResolve = this._resolveIdle; - this._resolveIdle = () => { - existingResolve(); - resolve(); - }; - }); - } - /** - Size of the queue. - */ - get size() { - return this._queue.size; - } - /** - Size of the queue, filtered by the given options. + } - For example, this can be used to find the number of items remaining in the queue with a specific priority level. - */ - sizeBy(options) { - // eslint-disable-next-line unicorn/no-fn-reference-in-iterator - return this._queue.filter(options).length; + if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) { + value = `\\${value}`; + } + + if (value === ']' && (prev.value === '[' || prev.value === '[^')) { + value = `\\${value}`; + } + + if (opts.posix === true && value === '!' && prev.value === '[') { + value = '^'; + } + + prev.value += value; + append({ value }); + continue; } + /** - Number of pending promises. - */ - get pending() { - return this._pendingCount; + * If we're inside a quoted string, continue + * until we reach the closing double quote. + */ + + if (state.quotes === 1 && value !== '"') { + value = utils.escapeRegex(value); + prev.value += value; + append({ value }); + continue; } + /** - Whether the queue is currently paused. - */ - get isPaused() { - return this._isPaused; - } - get timeout() { - return this._timeout; + * Double quotes + */ + + if (value === '"') { + state.quotes = state.quotes === 1 ? 0 : 1; + if (opts.keepQuotes === true) { + push({ type: 'text', value }); + } + continue; } + /** - Set the timeout for future operations. - */ - set timeout(milliseconds) { - this._timeout = milliseconds; + * Parentheses + */ + + if (value === '(') { + increment('parens'); + push({ type: 'paren', value }); + continue; } -} -exports["default"] = PQueue; + if (value === ')') { + if (state.parens === 0 && opts.strictBrackets === true) { + throw new SyntaxError(syntaxError('opening', '(')); + } -/***/ }), + const extglob = extglobs[extglobs.length - 1]; + if (extglob && state.parens === extglob.parens + 1) { + extglobClose(extglobs.pop()); + continue; + } -/***/ 9015: -/***/ ((__unused_webpack_module, exports) => { + push({ type: 'paren', value, output: state.parens ? ')' : '\\)' }); + decrement('parens'); + continue; + } + /** + * Square brackets + */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -// Port of lower_bound from https://en.cppreference.com/w/cpp/algorithm/lower_bound -// Used to compute insertion index to keep queue sorted after insertion -function lowerBound(array, value, comparator) { - let first = 0; - let count = array.length; - while (count > 0) { - const step = (count / 2) | 0; - let it = first + step; - if (comparator(array[it], value) <= 0) { - first = ++it; - count -= step + 1; - } - else { - count = step; + if (value === '[') { + if (opts.nobracket === true || !remaining().includes(']')) { + if (opts.nobracket !== true && opts.strictBrackets === true) { + throw new SyntaxError(syntaxError('closing', ']')); } - } - return first; -} -exports["default"] = lowerBound; - -/***/ }), + value = `\\${value}`; + } else { + increment('brackets'); + } -/***/ 5905: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + push({ type: 'bracket', value }); + continue; + } + if (value === ']') { + if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) { + push({ type: 'text', value, output: `\\${value}` }); + continue; + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -const lower_bound_1 = __nccwpck_require__(9015); -class PriorityQueue { - constructor() { - this._queue = []; - } - enqueue(run, options) { - options = Object.assign({ priority: 0 }, options); - const element = { - priority: options.priority, - run - }; - if (this.size && this._queue[this.size - 1].priority >= options.priority) { - this._queue.push(element); - return; + if (state.brackets === 0) { + if (opts.strictBrackets === true) { + throw new SyntaxError(syntaxError('opening', '[')); } - const index = lower_bound_1.default(this._queue, element, (a, b) => b.priority - a.priority); - this._queue.splice(index, 0, element); - } - dequeue() { - const item = this._queue.shift(); - return item === null || item === void 0 ? void 0 : item.run; - } - filter(options) { - return this._queue.filter((element) => element.priority === options.priority).map((element) => element.run); - } - get size() { - return this._queue.length; - } -} -exports["default"] = PriorityQueue; + push({ type: 'text', value, output: `\\${value}` }); + continue; + } -/***/ }), + decrement('brackets'); -/***/ 301: -/***/ ((module) => { + const prevValue = prev.value.slice(1); + if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) { + value = `/${value}`; + } + prev.value += value; + append({ value }); + // when literal brackets are explicitly disabled + // assume we should match with a regex character class + if (opts.literalBrackets === false || utils.hasRegexChars(prevValue)) { + continue; + } -var has = Object.prototype.hasOwnProperty - , prefix = '~'; + const escaped = utils.escapeRegex(prev.value); + state.output = state.output.slice(0, -prev.value.length); -/** - * Constructor to create a storage for our `EE` objects. - * An `Events` instance is a plain object whose properties are event names. - * - * @constructor - * @private - */ -function Events() {} + // when literal brackets are explicitly enabled + // assume we should escape the brackets to match literal characters + if (opts.literalBrackets === true) { + state.output += escaped; + prev.value = escaped; + continue; + } -// -// We try to not inherit from `Object.prototype`. In some engines creating an -// instance in this way is faster than calling `Object.create(null)` directly. -// If `Object.create(null)` is not supported we prefix the event names with a -// character to make sure that the built-in object properties are not -// overridden or used as an attack vector. -// -if (Object.create) { - Events.prototype = Object.create(null); + // when the user specifies nothing, try to match both + prev.value = `(${capture}${escaped}|${prev.value})`; + state.output += prev.value; + continue; + } - // - // This hack is needed because the `__proto__` property is still inherited in - // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5. - // - if (!new Events().__proto__) prefix = false; -} + /** + * Braces + */ -/** - * Representation of a single event listener. - * - * @param {Function} fn The listener function. - * @param {*} context The context to invoke the listener with. - * @param {Boolean} [once=false] Specify if the listener is a one-time listener. - * @constructor - * @private - */ -function EE(fn, context, once) { - this.fn = fn; - this.context = context; - this.once = once || false; -} + if (value === '{' && opts.nobrace !== true) { + increment('braces'); -/** - * Add a listener for a given event. - * - * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. - * @param {(String|Symbol)} event The event name. - * @param {Function} fn The listener function. - * @param {*} context The context to invoke the listener with. - * @param {Boolean} once Specify if the listener is a one-time listener. - * @returns {EventEmitter} - * @private - */ -function addListener(emitter, event, fn, context, once) { - if (typeof fn !== 'function') { - throw new TypeError('The listener must be a function'); - } + const open = { + type: 'brace', + value, + output: '(', + outputIndex: state.output.length, + tokensIndex: state.tokens.length + }; - var listener = new EE(fn, context || emitter, once) - , evt = prefix ? prefix + event : event; + braces.push(open); + push(open); + continue; + } - if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++; - else if (!emitter._events[evt].fn) emitter._events[evt].push(listener); - else emitter._events[evt] = [emitter._events[evt], listener]; + if (value === '}') { + const brace = braces[braces.length - 1]; - return emitter; -} + if (opts.nobrace === true || !brace) { + push({ type: 'text', value, output: value }); + continue; + } -/** - * Clear event by name. - * - * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. - * @param {(String|Symbol)} evt The Event name. - * @private - */ -function clearEvent(emitter, evt) { - if (--emitter._eventsCount === 0) emitter._events = new Events(); - else delete emitter._events[evt]; -} + let output = ')'; -/** - * Minimal `EventEmitter` interface that is molded against the Node.js - * `EventEmitter` interface. - * - * @constructor - * @public - */ -function EventEmitter() { - this._events = new Events(); - this._eventsCount = 0; -} + if (brace.dots === true) { + const arr = tokens.slice(); + const range = []; -/** - * Return an array listing the events for which the emitter has registered - * listeners. - * - * @returns {Array} - * @public - */ -EventEmitter.prototype.eventNames = function eventNames() { - var names = [] - , events - , name; + for (let i = arr.length - 1; i >= 0; i--) { + tokens.pop(); + if (arr[i].type === 'brace') { + break; + } + if (arr[i].type !== 'dots') { + range.unshift(arr[i].value); + } + } - if (this._eventsCount === 0) return names; + output = expandRange(range, opts); + state.backtrack = true; + } - for (name in (events = this._events)) { - if (has.call(events, name)) names.push(prefix ? name.slice(1) : name); - } + if (brace.comma !== true && brace.dots !== true) { + const out = state.output.slice(0, brace.outputIndex); + const toks = state.tokens.slice(brace.tokensIndex); + brace.value = brace.output = '\\{'; + value = output = '\\}'; + state.output = out; + for (const t of toks) { + state.output += (t.output || t.value); + } + } - if (Object.getOwnPropertySymbols) { - return names.concat(Object.getOwnPropertySymbols(events)); - } + push({ type: 'brace', value, output }); + decrement('braces'); + braces.pop(); + continue; + } - return names; -}; + /** + * Pipes + */ -/** - * Return the listeners registered for a given event. - * - * @param {(String|Symbol)} event The event name. - * @returns {Array} The registered listeners. - * @public - */ -EventEmitter.prototype.listeners = function listeners(event) { - var evt = prefix ? prefix + event : event - , handlers = this._events[evt]; + if (value === '|') { + if (extglobs.length > 0) { + extglobs[extglobs.length - 1].conditions++; + } + push({ type: 'text', value }); + continue; + } - if (!handlers) return []; - if (handlers.fn) return [handlers.fn]; + /** + * Commas + */ - for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) { - ee[i] = handlers[i].fn; - } + if (value === ',') { + let output = value; - return ee; -}; + const brace = braces[braces.length - 1]; + if (brace && stack[stack.length - 1] === 'braces') { + brace.comma = true; + output = '|'; + } -/** - * Return the number of listeners listening to a given event. - * - * @param {(String|Symbol)} event The event name. - * @returns {Number} The number of listeners. - * @public - */ -EventEmitter.prototype.listenerCount = function listenerCount(event) { - var evt = prefix ? prefix + event : event - , listeners = this._events[evt]; + push({ type: 'comma', value, output }); + continue; + } - if (!listeners) return 0; - if (listeners.fn) return 1; - return listeners.length; -}; + /** + * Slashes + */ -/** - * Calls each of the listeners registered for a given event. - * - * @param {(String|Symbol)} event The event name. - * @returns {Boolean} `true` if the event had listeners, else `false`. - * @public - */ -EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { - var evt = prefix ? prefix + event : event; + if (value === '/') { + // if the beginning of the glob is "./", advance the start + // to the current index, and don't add the "./" characters + // to the state. This greatly simplifies lookbehinds when + // checking for BOS characters like "!" and "." (not "./") + if (prev.type === 'dot' && state.index === state.start + 1) { + state.start = state.index + 1; + state.consumed = ''; + state.output = ''; + tokens.pop(); + prev = bos; // reset "prev" to the first token + continue; + } - if (!this._events[evt]) return false; + push({ type: 'slash', value, output: SLASH_LITERAL }); + continue; + } - var listeners = this._events[evt] - , len = arguments.length - , args - , i; + /** + * Dots + */ - if (listeners.fn) { - if (listeners.once) this.removeListener(event, listeners.fn, undefined, true); + if (value === '.') { + if (state.braces > 0 && prev.type === 'dot') { + if (prev.value === '.') prev.output = DOT_LITERAL; + const brace = braces[braces.length - 1]; + prev.type = 'dots'; + prev.output += value; + prev.value += value; + brace.dots = true; + continue; + } - switch (len) { - case 1: return listeners.fn.call(listeners.context), true; - case 2: return listeners.fn.call(listeners.context, a1), true; - case 3: return listeners.fn.call(listeners.context, a1, a2), true; - case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; - case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; - case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; - } + if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') { + push({ type: 'text', value, output: DOT_LITERAL }); + continue; + } - for (i = 1, args = new Array(len -1); i < len; i++) { - args[i - 1] = arguments[i]; + push({ type: 'dot', value, output: DOT_LITERAL }); + continue; } - listeners.fn.apply(listeners.context, args); - } else { - var length = listeners.length - , j; + /** + * Question marks + */ - for (i = 0; i < length; i++) { - if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true); + if (value === '?') { + const isGroup = prev && prev.value === '('; + if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { + extglobOpen('qmark', value); + continue; + } - switch (len) { - case 1: listeners[i].fn.call(listeners[i].context); break; - case 2: listeners[i].fn.call(listeners[i].context, a1); break; - case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break; - case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break; - default: - if (!args) for (j = 1, args = new Array(len -1); j < len; j++) { - args[j - 1] = arguments[j]; - } + if (prev && prev.type === 'paren') { + const next = peek(); + let output = value; - listeners[i].fn.apply(listeners[i].context, args); - } - } - } + if (next === '<' && !utils.supportsLookbehinds()) { + throw new Error('Node.js v10 or higher is required for regex lookbehinds'); + } - return true; -}; + if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) { + output = `\\${value}`; + } -/** - * Add a listener for a given event. - * - * @param {(String|Symbol)} event The event name. - * @param {Function} fn The listener function. - * @param {*} [context=this] The context to invoke the listener with. - * @returns {EventEmitter} `this`. - * @public - */ -EventEmitter.prototype.on = function on(event, fn, context) { - return addListener(this, event, fn, context, false); -}; + push({ type: 'text', value, output }); + continue; + } -/** - * Add a one-time listener for a given event. - * - * @param {(String|Symbol)} event The event name. - * @param {Function} fn The listener function. - * @param {*} [context=this] The context to invoke the listener with. - * @returns {EventEmitter} `this`. - * @public - */ -EventEmitter.prototype.once = function once(event, fn, context) { - return addListener(this, event, fn, context, true); -}; + if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) { + push({ type: 'qmark', value, output: QMARK_NO_DOT }); + continue; + } -/** - * Remove the listeners of a given event. - * - * @param {(String|Symbol)} event The event name. - * @param {Function} fn Only remove the listeners that match this function. - * @param {*} context Only remove the listeners that have this context. - * @param {Boolean} once Only remove one-time listeners. - * @returns {EventEmitter} `this`. - * @public - */ -EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) { - var evt = prefix ? prefix + event : event; + push({ type: 'qmark', value, output: QMARK }); + continue; + } - if (!this._events[evt]) return this; - if (!fn) { - clearEvent(this, evt); - return this; - } + /** + * Exclamation + */ - var listeners = this._events[evt]; + if (value === '!') { + if (opts.noextglob !== true && peek() === '(') { + if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) { + extglobOpen('negate', value); + continue; + } + } - if (listeners.fn) { - if ( - listeners.fn === fn && - (!once || listeners.once) && - (!context || listeners.context === context) - ) { - clearEvent(this, evt); - } - } else { - for (var i = 0, events = [], length = listeners.length; i < length; i++) { - if ( - listeners[i].fn !== fn || - (once && !listeners[i].once) || - (context && listeners[i].context !== context) - ) { - events.push(listeners[i]); + if (opts.nonegate !== true && state.index === 0) { + negate(); + continue; } } - // - // Reset the array, or remove it completely if we have no more listeners. - // - if (events.length) this._events[evt] = events.length === 1 ? events[0] : events; - else clearEvent(this, evt); - } - - return this; -}; + /** + * Plus + */ -/** - * Remove all listeners, or those of the specified event. - * - * @param {(String|Symbol)} [event] The event name. - * @returns {EventEmitter} `this`. - * @public - */ -EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { - var evt; + if (value === '+') { + if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { + extglobOpen('plus', value); + continue; + } - if (event) { - evt = prefix ? prefix + event : event; - if (this._events[evt]) clearEvent(this, evt); - } else { - this._events = new Events(); - this._eventsCount = 0; - } + if ((prev && prev.value === '(') || opts.regex === false) { + push({ type: 'plus', value, output: PLUS_LITERAL }); + continue; + } - return this; -}; + if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) { + push({ type: 'plus', value }); + continue; + } -// -// Alias methods names because people roll like that. -// -EventEmitter.prototype.off = EventEmitter.prototype.removeListener; -EventEmitter.prototype.addListener = EventEmitter.prototype.on; + push({ type: 'plus', value: PLUS_LITERAL }); + continue; + } -// -// Expose the prefix. -// -EventEmitter.prefixed = prefix; + /** + * Plain text + */ -// -// Allow `EventEmitter` to be imported as module namespace. -// -EventEmitter.EventEmitter = EventEmitter; + if (value === '@') { + if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { + push({ type: 'at', extglob: true, value, output: '' }); + continue; + } -// -// Expose the module. -// -if (true) { - module.exports = EventEmitter; -} + push({ type: 'text', value }); + continue; + } + /** + * Plain text + */ -/***/ }), + if (value !== '*') { + if (value === '$' || value === '^') { + value = `\\${value}`; + } -/***/ 2103: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + const match = REGEX_NON_SPECIAL_CHARS.exec(remaining()); + if (match) { + value += match[0]; + state.index += match[0].length; + } + push({ type: 'text', value }); + continue; + } -const retry = __nccwpck_require__(5546); + /** + * Stars + */ -const networkErrorMsgs = [ - 'Failed to fetch', // Chrome - 'NetworkError when attempting to fetch resource.', // Firefox - 'The Internet connection appears to be offline.', // Safari - 'Network request failed' // `cross-fetch` -]; + if (prev && (prev.type === 'globstar' || prev.star === true)) { + prev.type = 'star'; + prev.star = true; + prev.value += value; + prev.output = star; + state.backtrack = true; + state.globstar = true; + consume(value); + continue; + } -class AbortError extends Error { - constructor(message) { - super(); - - if (message instanceof Error) { - this.originalError = message; - ({message} = message); - } else { - this.originalError = new Error(message); - this.originalError.stack = this.stack; - } - - this.name = 'AbortError'; - this.message = message; - } -} - -const decorateErrorWithCounts = (error, attemptNumber, options) => { - // Minus 1 from attemptNumber because the first attempt does not count as a retry - const retriesLeft = options.retries - (attemptNumber - 1); - - error.attemptNumber = attemptNumber; - error.retriesLeft = retriesLeft; - return error; -}; - -const isNetworkError = errorMessage => networkErrorMsgs.includes(errorMessage); - -const pRetry = (input, options) => new Promise((resolve, reject) => { - options = { - onFailedAttempt: () => {}, - retries: 10, - ...options - }; - - const operation = retry.operation(options); - - operation.attempt(async attemptNumber => { - try { - resolve(await input(attemptNumber)); - } catch (error) { - if (!(error instanceof Error)) { - reject(new TypeError(`Non-error was thrown: "${error}". You should only throw errors.`)); - return; - } - - if (error instanceof AbortError) { - operation.stop(); - reject(error.originalError); - } else if (error instanceof TypeError && !isNetworkError(error.message)) { - operation.stop(); - reject(error); - } else { - decorateErrorWithCounts(error, attemptNumber, options); - - try { - await options.onFailedAttempt(error); - } catch (error) { - reject(error); - return; - } - - if (!operation.retry(error)) { - reject(operation.mainError()); - } - } - } - }); -}); - -module.exports = pRetry; -// TODO: remove this in the next major version -module.exports["default"] = pRetry; + let rest = remaining(); + if (opts.noextglob !== true && /^\([^?]/.test(rest)) { + extglobOpen('star', value); + continue; + } -module.exports.AbortError = AbortError; + if (prev.type === 'star') { + if (opts.noglobstar === true) { + consume(value); + continue; + } + const prior = prev.prev; + const before = prior.prev; + const isStart = prior.type === 'slash' || prior.type === 'bos'; + const afterStar = before && (before.type === 'star' || before.type === 'globstar'); -/***/ }), + if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) { + push({ type: 'star', value, output: '' }); + continue; + } -/***/ 4802: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace'); + const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren'); + if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) { + push({ type: 'star', value, output: '' }); + continue; + } + // strip consecutive `/**/` + while (rest.slice(0, 3) === '/**') { + const after = input[state.index + 4]; + if (after && after !== '/') { + break; + } + rest = rest.slice(3); + consume('/**', 3); + } + if (prior.type === 'bos' && eos()) { + prev.type = 'globstar'; + prev.value += value; + prev.output = globstar(opts); + state.output = prev.output; + state.globstar = true; + consume(value); + continue; + } -const pFinally = __nccwpck_require__(2766); + if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) { + state.output = state.output.slice(0, -(prior.output + prev.output).length); + prior.output = `(?:${prior.output}`; -class TimeoutError extends Error { - constructor(message) { - super(message); - this.name = 'TimeoutError'; - } -} + prev.type = 'globstar'; + prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)'); + prev.value += value; + state.globstar = true; + state.output += prior.output + prev.output; + consume(value); + continue; + } -const pTimeout = (promise, milliseconds, fallback) => new Promise((resolve, reject) => { - if (typeof milliseconds !== 'number' || milliseconds < 0) { - throw new TypeError('Expected `milliseconds` to be a positive number'); - } + if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') { + const end = rest[1] !== void 0 ? '|$' : ''; - if (milliseconds === Infinity) { - resolve(promise); - return; - } + state.output = state.output.slice(0, -(prior.output + prev.output).length); + prior.output = `(?:${prior.output}`; - const timer = setTimeout(() => { - if (typeof fallback === 'function') { - try { - resolve(fallback()); - } catch (error) { - reject(error); - } + prev.type = 'globstar'; + prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`; + prev.value += value; - return; - } + state.output += prior.output + prev.output; + state.globstar = true; - const message = typeof fallback === 'string' ? fallback : `Promise timed out after ${milliseconds} milliseconds`; - const timeoutError = fallback instanceof Error ? fallback : new TimeoutError(message); + consume(value + advance()); - if (typeof promise.cancel === 'function') { - promise.cancel(); - } + push({ type: 'slash', value: '/', output: '' }); + continue; + } - reject(timeoutError); - }, milliseconds); + if (prior.type === 'bos' && rest[0] === '/') { + prev.type = 'globstar'; + prev.value += value; + prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`; + state.output = prev.output; + state.globstar = true; + consume(value + advance()); + push({ type: 'slash', value: '/', output: '' }); + continue; + } - // TODO: Use native `finally` keyword when targeting Node.js 10 - pFinally( - // eslint-disable-next-line promise/prefer-await-to-then - promise.then(resolve, reject), - () => { - clearTimeout(timer); - } - ); -}); + // remove single star from output + state.output = state.output.slice(0, -prev.output.length); -module.exports = pTimeout; -// TODO: Remove this for the next major release -module.exports["default"] = pTimeout; + // reset previous token to globstar + prev.type = 'globstar'; + prev.output = globstar(opts); + prev.value += value; -module.exports.TimeoutError = TimeoutError; + // reset output with globstar + state.output += prev.output; + state.globstar = true; + consume(value); + continue; + } + const token = { type: 'star', value, output: star }; -/***/ }), + if (opts.bash === true) { + token.output = '.*?'; + if (prev.type === 'bos' || prev.type === 'slash') { + token.output = nodot + token.output; + } + push(token); + continue; + } -/***/ 2673: -/***/ ((module) => { + if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) { + token.output = value; + push(token); + continue; + } -function _typeof(obj){"@babel/helpers - typeof";return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj},_typeof(obj)}function _createForOfIteratorHelper(o,allowArrayLike){var it=typeof Symbol!=="undefined"&&o[Symbol.iterator]||o["@@iterator"];if(!it){if(Array.isArray(o)||(it=_unsupportedIterableToArray(o))||allowArrayLike&&o&&typeof o.length==="number"){if(it)o=it;var i=0;var F=function F(){};return{s:F,n:function n(){if(i>=o.length)return{done:true};return{done:false,value:o[i++]}},e:function e(_e2){throw _e2},f:F}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var normalCompletion=true,didErr=false,err;return{s:function s(){it=it.call(o)},n:function n(){var step=it.next();normalCompletion=step.done;return step},e:function e(_e3){didErr=true;err=_e3},f:function f(){try{if(!normalCompletion&&it["return"]!=null)it["return"]()}finally{if(didErr)throw err}}}}function _defineProperty(obj,key,value){key=_toPropertyKey(key);if(key in obj){Object.defineProperty(obj,key,{value:value,enumerable:true,configurable:true,writable:true})}else{obj[key]=value}return obj}function _toPropertyKey(arg){var key=_toPrimitive(arg,"string");return _typeof(key)==="symbol"?key:String(key)}function _toPrimitive(input,hint){if(_typeof(input)!=="object"||input===null)return input;var prim=input[Symbol.toPrimitive];if(prim!==undefined){var res=prim.call(input,hint||"default");if(_typeof(res)!=="object")return res;throw new TypeError("@@toPrimitive must return a primitive value.")}return(hint==="string"?String:Number)(input)}function _slicedToArray(arr,i){return _arrayWithHoles(arr)||_iterableToArrayLimit(arr,i)||_unsupportedIterableToArray(arr,i)||_nonIterableRest()}function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _unsupportedIterableToArray(o,minLen){if(!o)return;if(typeof o==="string")return _arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);if(n==="Object"&&o.constructor)n=o.constructor.name;if(n==="Map"||n==="Set")return Array.from(o);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return _arrayLikeToArray(o,minLen)}function _arrayLikeToArray(arr,len){if(len==null||len>arr.length)len=arr.length;for(var i=0,arr2=new Array(len);i { + if (peek() !== '*') { + state.output += ONE_CHAR; + prev.output += ONE_CHAR; + } + } + push(token); + } + while (state.brackets > 0) { + if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']')); + state.output = utils.escapeLast(state.output, '['); + decrement('brackets'); + } -module.exports = __nccwpck_require__(8016); + while (state.parens > 0) { + if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')')); + state.output = utils.escapeLast(state.output, '('); + decrement('parens'); + } + while (state.braces > 0) { + if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}')); + state.output = utils.escapeLast(state.output, '{'); + decrement('braces'); + } -/***/ }), + if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) { + push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` }); + } -/***/ 5595: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // rebuild the output if we had to backtrack at any point + if (state.backtrack === true) { + state.output = ''; + for (const token of state.tokens) { + state.output += token.output != null ? token.output : token.value; + if (token.suffix) { + state.output += token.suffix; + } + } + } -const path = __nccwpck_require__(6928); -const WIN_SLASH = '\\\\/'; -const WIN_NO_SLASH = `[^${WIN_SLASH}]`; + return state; +}; /** - * Posix glob regex + * Fast paths for creating regular expressions for common glob patterns. + * This can significantly speed up processing and has very little downside + * impact when none of the fast paths match. */ -const DOT_LITERAL = '\\.'; -const PLUS_LITERAL = '\\+'; -const QMARK_LITERAL = '\\?'; -const SLASH_LITERAL = '\\/'; -const ONE_CHAR = '(?=.)'; -const QMARK = '[^/]'; -const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`; -const START_ANCHOR = `(?:^|${SLASH_LITERAL})`; -const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`; -const NO_DOT = `(?!${DOT_LITERAL})`; -const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`; -const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`; -const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`; -const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`; -const STAR = `${QMARK}*?`; - -const POSIX_CHARS = { - DOT_LITERAL, - PLUS_LITERAL, - QMARK_LITERAL, - SLASH_LITERAL, - ONE_CHAR, - QMARK, - END_ANCHOR, - DOTS_SLASH, - NO_DOT, - NO_DOTS, - NO_DOT_SLASH, - NO_DOTS_SLASH, - QMARK_NO_DOT, - STAR, - START_ANCHOR -}; +parse.fastpaths = (input, options) => { + const opts = { ...options }; + const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; + const len = input.length; + if (len > max) { + throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`); + } -/** - * Windows glob regex - */ + input = REPLACEMENTS[input] || input; + const win32 = utils.isWindows(options); -const WINDOWS_CHARS = { - ...POSIX_CHARS, + // create constants based on platform, for windows or posix + const { + DOT_LITERAL, + SLASH_LITERAL, + ONE_CHAR, + DOTS_SLASH, + NO_DOT, + NO_DOTS, + NO_DOTS_SLASH, + STAR, + START_ANCHOR + } = constants.globChars(win32); - SLASH_LITERAL: `[${WIN_SLASH}]`, - QMARK: WIN_NO_SLASH, - STAR: `${WIN_NO_SLASH}*?`, - DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`, - NO_DOT: `(?!${DOT_LITERAL})`, - NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, - NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`, - NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, - QMARK_NO_DOT: `[^.${WIN_SLASH}]`, - START_ANCHOR: `(?:^|[${WIN_SLASH}])`, - END_ANCHOR: `(?:[${WIN_SLASH}]|$)` -}; + const nodot = opts.dot ? NO_DOTS : NO_DOT; + const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT; + const capture = opts.capture ? '' : '?:'; + const state = { negated: false, prefix: '' }; + let star = opts.bash === true ? '.*?' : STAR; -/** - * POSIX Bracket Regex - */ + if (opts.capture) { + star = `(${star})`; + } -const POSIX_REGEX_SOURCE = { - alnum: 'a-zA-Z0-9', - alpha: 'a-zA-Z', - ascii: '\\x00-\\x7F', - blank: ' \\t', - cntrl: '\\x00-\\x1F\\x7F', - digit: '0-9', - graph: '\\x21-\\x7E', - lower: 'a-z', - print: '\\x20-\\x7E ', - punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~', - space: ' \\t\\r\\n\\v\\f', - upper: 'A-Z', - word: 'A-Za-z0-9_', - xdigit: 'A-Fa-f0-9' -}; + const globstar = opts => { + if (opts.noglobstar === true) return star; + return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`; + }; -module.exports = { - MAX_LENGTH: 1024 * 64, - POSIX_REGEX_SOURCE, + const create = str => { + switch (str) { + case '*': + return `${nodot}${ONE_CHAR}${star}`; - // regular expressions - REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g, - REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/, - REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/, - REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g, - REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g, - REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g, + case '.*': + return `${DOT_LITERAL}${ONE_CHAR}${star}`; - // Replace globs with equivalent patterns to reduce parsing time. - REPLACEMENTS: { - '***': '*', - '**/**': '**', - '**/**/**': '**' - }, + case '*.*': + return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`; - // Digits - CHAR_0: 48, /* 0 */ - CHAR_9: 57, /* 9 */ + case '*/*': + return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`; - // Alphabet chars. - CHAR_UPPERCASE_A: 65, /* A */ - CHAR_LOWERCASE_A: 97, /* a */ - CHAR_UPPERCASE_Z: 90, /* Z */ - CHAR_LOWERCASE_Z: 122, /* z */ + case '**': + return nodot + globstar(opts); - CHAR_LEFT_PARENTHESES: 40, /* ( */ - CHAR_RIGHT_PARENTHESES: 41, /* ) */ + case '**/*': + return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`; - CHAR_ASTERISK: 42, /* * */ + case '**/*.*': + return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`; - // Non-alphabetic chars. - CHAR_AMPERSAND: 38, /* & */ - CHAR_AT: 64, /* @ */ - CHAR_BACKWARD_SLASH: 92, /* \ */ - CHAR_CARRIAGE_RETURN: 13, /* \r */ - CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */ - CHAR_COLON: 58, /* : */ - CHAR_COMMA: 44, /* , */ - CHAR_DOT: 46, /* . */ - CHAR_DOUBLE_QUOTE: 34, /* " */ - CHAR_EQUAL: 61, /* = */ - CHAR_EXCLAMATION_MARK: 33, /* ! */ - CHAR_FORM_FEED: 12, /* \f */ - CHAR_FORWARD_SLASH: 47, /* / */ - CHAR_GRAVE_ACCENT: 96, /* ` */ - CHAR_HASH: 35, /* # */ - CHAR_HYPHEN_MINUS: 45, /* - */ - CHAR_LEFT_ANGLE_BRACKET: 60, /* < */ - CHAR_LEFT_CURLY_BRACE: 123, /* { */ - CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */ - CHAR_LINE_FEED: 10, /* \n */ - CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */ - CHAR_PERCENT: 37, /* % */ - CHAR_PLUS: 43, /* + */ - CHAR_QUESTION_MARK: 63, /* ? */ - CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */ - CHAR_RIGHT_CURLY_BRACE: 125, /* } */ - CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */ - CHAR_SEMICOLON: 59, /* ; */ - CHAR_SINGLE_QUOTE: 39, /* ' */ - CHAR_SPACE: 32, /* */ - CHAR_TAB: 9, /* \t */ - CHAR_UNDERSCORE: 95, /* _ */ - CHAR_VERTICAL_LINE: 124, /* | */ - CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */ + case '**/.*': + return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`; - SEP: path.sep, + default: { + const match = /^(.*?)\.(\w+)$/.exec(str); + if (!match) return; - /** - * Create EXTGLOB_CHARS - */ + const source = create(match[1]); + if (!source) return; - extglobChars(chars) { - return { - '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` }, - '?': { type: 'qmark', open: '(?:', close: ')?' }, - '+': { type: 'plus', open: '(?:', close: ')+' }, - '*': { type: 'star', open: '(?:', close: ')*' }, - '@': { type: 'at', open: '(?:', close: ')' } - }; - }, + return source + DOT_LITERAL + match[2]; + } + } + }; - /** - * Create GLOB_CHARS - */ + const output = utils.removePrefix(input, state); + let source = create(output); - globChars(win32) { - return win32 === true ? WINDOWS_CHARS : POSIX_CHARS; + if (source && opts.strictSlashes !== true) { + source += `${SLASH_LITERAL}?`; } + + return source; }; +module.exports = parse; + /***/ }), -/***/ 8265: +/***/ 8016: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -const constants = __nccwpck_require__(5595); +const path = __nccwpck_require__(6928); +const scan = __nccwpck_require__(1781); +const parse = __nccwpck_require__(8265); const utils = __nccwpck_require__(4059); +const constants = __nccwpck_require__(5595); +const isObject = val => val && typeof val === 'object' && !Array.isArray(val); /** - * Constants + * Creates a matcher function from one or more glob patterns. The + * returned function takes a string to match as its first argument, + * and returns true if the string is a match. The returned matcher + * function also takes a boolean as the second argument that, when true, + * returns an object with additional information. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch(glob[, options]); + * + * const isMatch = picomatch('*.!(*a)'); + * console.log(isMatch('a.a')); //=> false + * console.log(isMatch('a.b')); //=> true + * ``` + * @name picomatch + * @param {String|Array} `globs` One or more glob patterns. + * @param {Object=} `options` + * @return {Function=} Returns a matcher function. + * @api public */ -const { - MAX_LENGTH, - POSIX_REGEX_SOURCE, - REGEX_NON_SPECIAL_CHARS, - REGEX_SPECIAL_CHARS_BACKREF, - REPLACEMENTS -} = constants; +const picomatch = (glob, options, returnState = false) => { + if (Array.isArray(glob)) { + const fns = glob.map(input => picomatch(input, options, returnState)); + const arrayMatcher = str => { + for (const isMatch of fns) { + const state = isMatch(str); + if (state) return state; + } + return false; + }; + return arrayMatcher; + } -/** - * Helpers - */ + const isState = isObject(glob) && glob.tokens && glob.input; -const expandRange = (args, options) => { - if (typeof options.expandRange === 'function') { - return options.expandRange(...args, options); + if (glob === '' || (typeof glob !== 'string' && !isState)) { + throw new TypeError('Expected pattern to be a non-empty string'); } - args.sort(); - const value = `[${args.join('-')}]`; + const opts = options || {}; + const posix = utils.isWindows(options); + const regex = isState + ? picomatch.compileRe(glob, options) + : picomatch.makeRe(glob, options, false, true); - try { - /* eslint-disable-next-line no-new */ - new RegExp(value); - } catch (ex) { - return args.map(v => utils.escapeRegex(v)).join('..'); + const state = regex.state; + delete regex.state; + + let isIgnored = () => false; + if (opts.ignore) { + const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null }; + isIgnored = picomatch(opts.ignore, ignoreOpts, returnState); } - return value; -}; + const matcher = (input, returnObject = false) => { + const { isMatch, match, output } = picomatch.test(input, regex, options, { glob, posix }); + const result = { glob, state, regex, posix, input, output, match, isMatch }; -/** - * Create the message for a syntax error - */ + if (typeof opts.onResult === 'function') { + opts.onResult(result); + } -const syntaxError = (type, char) => { - return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`; + if (isMatch === false) { + result.isMatch = false; + return returnObject ? result : false; + } + + if (isIgnored(input)) { + if (typeof opts.onIgnore === 'function') { + opts.onIgnore(result); + } + result.isMatch = false; + return returnObject ? result : false; + } + + if (typeof opts.onMatch === 'function') { + opts.onMatch(result); + } + return returnObject ? result : true; + }; + + if (returnState) { + matcher.state = state; + } + + return matcher; }; /** - * Parse the given input string. - * @param {String} input - * @param {Object} options - * @return {Object} + * Test `input` with the given `regex`. This is used by the main + * `picomatch()` function to test the input string. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.test(input, regex[, options]); + * + * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/)); + * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' } + * ``` + * @param {String} `input` String to test. + * @param {RegExp} `regex` + * @return {Object} Returns an object with matching info. + * @api public */ -const parse = (input, options) => { +picomatch.test = (input, regex, options, { glob, posix } = {}) => { if (typeof input !== 'string') { - throw new TypeError('Expected a string'); + throw new TypeError('Expected input to be a string'); } - input = REPLACEMENTS[input] || input; - - const opts = { ...options }; - const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; - - let len = input.length; - if (len > max) { - throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`); + if (input === '') { + return { isMatch: false, output: '' }; } - const bos = { type: 'bos', value: '', output: opts.prepend || '' }; - const tokens = [bos]; - - const capture = opts.capture ? '' : '?:'; - const win32 = utils.isWindows(options); - - // create constants based on platform, for windows or posix - const PLATFORM_CHARS = constants.globChars(win32); - const EXTGLOB_CHARS = constants.extglobChars(PLATFORM_CHARS); - - const { - DOT_LITERAL, - PLUS_LITERAL, - SLASH_LITERAL, - ONE_CHAR, - DOTS_SLASH, - NO_DOT, - NO_DOT_SLASH, - NO_DOTS_SLASH, - QMARK, - QMARK_NO_DOT, - STAR, - START_ANCHOR - } = PLATFORM_CHARS; - - const globstar = opts => { - return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`; - }; - - const nodot = opts.dot ? '' : NO_DOT; - const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT; - let star = opts.bash === true ? globstar(opts) : STAR; + const opts = options || {}; + const format = opts.format || (posix ? utils.toPosixSlashes : null); + let match = input === glob; + let output = (match && format) ? format(input) : input; - if (opts.capture) { - star = `(${star})`; + if (match === false) { + output = format ? format(input) : input; + match = output === glob; } - // minimatch options support - if (typeof opts.noext === 'boolean') { - opts.noextglob = opts.noext; + if (match === false || opts.capture === true) { + if (opts.matchBase === true || opts.basename === true) { + match = picomatch.matchBase(input, regex, options, posix); + } else { + match = regex.exec(output); + } } - const state = { - input, - index: -1, - start: 0, - dot: opts.dot === true, - consumed: '', - output: '', - prefix: '', - backtrack: false, - negated: false, - brackets: 0, - braces: 0, - parens: 0, - quotes: 0, - globstar: false, - tokens - }; + return { isMatch: Boolean(match), match, output }; +}; - input = utils.removePrefix(input, state); - len = input.length; +/** + * Match the basename of a filepath. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.matchBase(input, glob[, options]); + * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true + * ``` + * @param {String} `input` String to test. + * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe). + * @return {Boolean} + * @api public + */ - const extglobs = []; - const braces = []; - const stack = []; - let prev = bos; - let value; +picomatch.matchBase = (input, glob, options, posix = utils.isWindows(options)) => { + const regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options); + return regex.test(path.basename(input)); +}; - /** - * Tokenizing helpers - */ +/** + * Returns true if **any** of the given glob `patterns` match the specified `string`. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.isMatch(string, patterns[, options]); + * + * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true + * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false + * ``` + * @param {String|Array} str The string to test. + * @param {String|Array} patterns One or more glob patterns to use for matching. + * @param {Object} [options] See available [options](#options). + * @return {Boolean} Returns true if any patterns match `str` + * @api public + */ - const eos = () => state.index === len - 1; - const peek = state.peek = (n = 1) => input[state.index + n]; - const advance = state.advance = () => input[++state.index] || ''; - const remaining = () => input.slice(state.index + 1); - const consume = (value = '', num = 0) => { - state.consumed += value; - state.index += num; - }; +picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str); - const append = token => { - state.output += token.output != null ? token.output : token.value; - consume(token.value); - }; +/** + * Parse a glob pattern to create the source string for a regular + * expression. + * + * ```js + * const picomatch = require('picomatch'); + * const result = picomatch.parse(pattern[, options]); + * ``` + * @param {String} `pattern` + * @param {Object} `options` + * @return {Object} Returns an object with useful properties and output to be used as a regex source string. + * @api public + */ - const negate = () => { - let count = 1; +picomatch.parse = (pattern, options) => { + if (Array.isArray(pattern)) return pattern.map(p => picomatch.parse(p, options)); + return parse(pattern, { ...options, fastpaths: false }); +}; - while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) { - advance(); - state.start++; - count++; - } +/** + * Scan a glob pattern to separate the pattern into segments. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.scan(input[, options]); + * + * const result = picomatch.scan('!./foo/*.js'); + * console.log(result); + * { prefix: '!./', + * input: '!./foo/*.js', + * start: 3, + * base: 'foo', + * glob: '*.js', + * isBrace: false, + * isBracket: false, + * isGlob: true, + * isExtglob: false, + * isGlobstar: false, + * negated: true } + * ``` + * @param {String} `input` Glob pattern to scan. + * @param {Object} `options` + * @return {Object} Returns an object with + * @api public + */ - if (count % 2 === 0) { - return false; - } +picomatch.scan = (input, options) => scan(input, options); - state.negated = true; - state.start++; - return true; - }; +/** + * Compile a regular expression from the `state` object returned by the + * [parse()](#parse) method. + * + * @param {Object} `state` + * @param {Object} `options` + * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser. + * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging. + * @return {RegExp} + * @api public + */ - const increment = type => { - state[type]++; - stack.push(type); - }; +picomatch.compileRe = (state, options, returnOutput = false, returnState = false) => { + if (returnOutput === true) { + return state.output; + } - const decrement = type => { - state[type]--; - stack.pop(); - }; + const opts = options || {}; + const prepend = opts.contains ? '' : '^'; + const append = opts.contains ? '' : '$'; - /** - * Push tokens onto the tokens array. This helper speeds up - * tokenizing by 1) helping us avoid backtracking as much as possible, - * and 2) helping us avoid creating extra tokens when consecutive - * characters are plain text. This improves performance and simplifies - * lookbehinds. - */ + let source = `${prepend}(?:${state.output})${append}`; + if (state && state.negated === true) { + source = `^(?!${source}).*$`; + } - const push = tok => { - if (prev.type === 'globstar') { - const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace'); - const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren')); + const regex = picomatch.toRegex(source, options); + if (returnState === true) { + regex.state = state; + } - if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) { - state.output = state.output.slice(0, -prev.output.length); - prev.type = 'star'; - prev.value = '*'; - prev.output = star; - state.output += prev.output; - } - } + return regex; +}; - if (extglobs.length && tok.type !== 'paren') { - extglobs[extglobs.length - 1].inner += tok.value; - } +/** + * Create a regular expression from a parsed glob pattern. + * + * ```js + * const picomatch = require('picomatch'); + * const state = picomatch.parse('*.js'); + * // picomatch.compileRe(state[, options]); + * + * console.log(picomatch.compileRe(state)); + * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ + * ``` + * @param {String} `state` The object returned from the `.parse` method. + * @param {Object} `options` + * @param {Boolean} `returnOutput` Implementors may use this argument to return the compiled output, instead of a regular expression. This is not exposed on the options to prevent end-users from mutating the result. + * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression. + * @return {RegExp} Returns a regex created from the given pattern. + * @api public + */ - if (tok.value || tok.output) append(tok); - if (prev && prev.type === 'text' && tok.type === 'text') { - prev.value += tok.value; - prev.output = (prev.output || '') + tok.value; - return; - } +picomatch.makeRe = (input, options = {}, returnOutput = false, returnState = false) => { + if (!input || typeof input !== 'string') { + throw new TypeError('Expected a non-empty string'); + } - tok.prev = prev; - tokens.push(tok); - prev = tok; - }; + let parsed = { negated: false, fastpaths: true }; - const extglobOpen = (type, value) => { - const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' }; + if (options.fastpaths !== false && (input[0] === '.' || input[0] === '*')) { + parsed.output = parse.fastpaths(input, options); + } - token.prev = prev; - token.parens = state.parens; - token.output = state.output; - const output = (opts.capture ? '(' : '') + token.open; + if (!parsed.output) { + parsed = parse(input, options); + } - increment('parens'); - push({ type, value, output: state.output ? '' : ONE_CHAR }); - push({ type: 'paren', extglob: true, value: advance(), output }); - extglobs.push(token); - }; + return picomatch.compileRe(parsed, options, returnOutput, returnState); +}; - const extglobClose = token => { - let output = token.close + (opts.capture ? ')' : ''); - let rest; +/** + * Create a regular expression from the given regex source string. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.toRegex(source[, options]); + * + * const { output } = picomatch.parse('*.js'); + * console.log(picomatch.toRegex(output)); + * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ + * ``` + * @param {String} `source` Regular expression source string. + * @param {Object} `options` + * @return {RegExp} + * @api public + */ - if (token.type === 'negate') { - let extglobStar = star; +picomatch.toRegex = (source, options) => { + try { + const opts = options || {}; + return new RegExp(source, opts.flags || (opts.nocase ? 'i' : '')); + } catch (err) { + if (options && options.debug === true) throw err; + return /$^/; + } +}; - if (token.inner && token.inner.length > 1 && token.inner.includes('/')) { - extglobStar = globstar(opts); - } +/** + * Picomatch constants. + * @return {Object} + */ - if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) { - output = token.close = `)$))${extglobStar}`; - } +picomatch.constants = constants; - if (token.inner.includes('*') && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) { - // Any non-magical string (`.ts`) or even nested expression (`.{ts,tsx}`) can follow after the closing parenthesis. - // In this case, we need to parse the string and use it in the output of the original pattern. - // Suitable patterns: `/!(*.d).ts`, `/!(*.d).{ts,tsx}`, `**/!(*-dbg).@(js)`. - // - // Disabling the `fastpaths` option due to a problem with parsing strings as `.ts` in the pattern like `**/!(*.d).ts`. - const expression = parse(rest, { ...options, fastpaths: false }).output; +/** + * Expose "picomatch" + */ - output = token.close = `)${expression})${extglobStar})`; - } +module.exports = picomatch; - if (token.prev.type === 'bos') { - state.negatedExtglob = true; - } - } - push({ type: 'paren', extglob: true, value, output }); - decrement('parens'); - }; +/***/ }), - /** - * Fast paths - */ +/***/ 1781: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) { - let backslashes = false; - let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => { - if (first === '\\') { - backslashes = true; - return m; - } - if (first === '?') { - if (esc) { - return esc + first + (rest ? QMARK.repeat(rest.length) : ''); - } - if (index === 0) { - return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : ''); - } - return QMARK.repeat(chars.length); - } - - if (first === '.') { - return DOT_LITERAL.repeat(chars.length); - } - - if (first === '*') { - if (esc) { - return esc + first + (rest ? star : ''); - } - return star; - } - return esc ? m : `\\${m}`; - }); - - if (backslashes === true) { - if (opts.unescape === true) { - output = output.replace(/\\/g, ''); - } else { - output = output.replace(/\\+/g, m => { - return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : ''); - }); - } - } +const utils = __nccwpck_require__(4059); +const { + CHAR_ASTERISK, /* * */ + CHAR_AT, /* @ */ + CHAR_BACKWARD_SLASH, /* \ */ + CHAR_COMMA, /* , */ + CHAR_DOT, /* . */ + CHAR_EXCLAMATION_MARK, /* ! */ + CHAR_FORWARD_SLASH, /* / */ + CHAR_LEFT_CURLY_BRACE, /* { */ + CHAR_LEFT_PARENTHESES, /* ( */ + CHAR_LEFT_SQUARE_BRACKET, /* [ */ + CHAR_PLUS, /* + */ + CHAR_QUESTION_MARK, /* ? */ + CHAR_RIGHT_CURLY_BRACE, /* } */ + CHAR_RIGHT_PARENTHESES, /* ) */ + CHAR_RIGHT_SQUARE_BRACKET /* ] */ +} = __nccwpck_require__(5595); - if (output === input && opts.contains === true) { - state.output = input; - return state; - } +const isPathSeparator = code => { + return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH; +}; - state.output = utils.wrapOutput(output, state, options); - return state; +const depth = token => { + if (token.isPrefix !== true) { + token.depth = token.isGlobstar ? Infinity : 1; } +}; - /** - * Tokenize input until we reach end-of-string - */ +/** + * Quickly scans a glob pattern and returns an object with a handful of + * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists), + * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not + * with `!(`) and `negatedExtglob` (true if the path starts with `!(`). + * + * ```js + * const pm = require('picomatch'); + * console.log(pm.scan('foo/bar/*.js')); + * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' } + * ``` + * @param {String} `str` + * @param {Object} `options` + * @return {Object} Returns an object with tokens and regex source string. + * @api public + */ - while (!eos()) { - value = advance(); +const scan = (input, options) => { + const opts = options || {}; - if (value === '\u0000') { - continue; - } + const length = input.length - 1; + const scanToEnd = opts.parts === true || opts.scanToEnd === true; + const slashes = []; + const tokens = []; + const parts = []; - /** - * Escaped characters - */ + let str = input; + let index = -1; + let start = 0; + let lastIndex = 0; + let isBrace = false; + let isBracket = false; + let isGlob = false; + let isExtglob = false; + let isGlobstar = false; + let braceEscaped = false; + let backslashes = false; + let negated = false; + let negatedExtglob = false; + let finished = false; + let braces = 0; + let prev; + let code; + let token = { value: '', depth: 0, isGlob: false }; - if (value === '\\') { - const next = peek(); + const eos = () => index >= length; + const peek = () => str.charCodeAt(index + 1); + const advance = () => { + prev = code; + return str.charCodeAt(++index); + }; - if (next === '/' && opts.bash !== true) { - continue; - } + while (index < length) { + code = advance(); + let next; - if (next === '.' || next === ';') { - continue; - } + if (code === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + code = advance(); - if (!next) { - value += '\\'; - push({ type: 'text', value }); - continue; + if (code === CHAR_LEFT_CURLY_BRACE) { + braceEscaped = true; } + continue; + } - // collapse slashes to reduce potential for exploits - const match = /^\\+/.exec(remaining()); - let slashes = 0; + if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) { + braces++; - if (match && match[0].length > 2) { - slashes = match[0].length; - state.index += slashes; - if (slashes % 2 !== 0) { - value += '\\'; + while (eos() !== true && (code = advance())) { + if (code === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + advance(); + continue; } - } - if (opts.unescape === true) { - value = advance(); - } else { - value += advance(); - } + if (code === CHAR_LEFT_CURLY_BRACE) { + braces++; + continue; + } - if (state.brackets === 0) { - push({ type: 'text', value }); - continue; - } - } + if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) { + isBrace = token.isBrace = true; + isGlob = token.isGlob = true; + finished = true; - /** - * If we're inside a regex character class, continue - * until we reach the closing bracket. - */ + if (scanToEnd === true) { + continue; + } - if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) { - if (opts.posix !== false && value === ':') { - const inner = prev.value.slice(1); - if (inner.includes('[')) { - prev.posix = true; + break; + } - if (inner.includes(':')) { - const idx = prev.value.lastIndexOf('['); - const pre = prev.value.slice(0, idx); - const rest = prev.value.slice(idx + 2); - const posix = POSIX_REGEX_SOURCE[rest]; - if (posix) { - prev.value = pre + posix; - state.backtrack = true; - advance(); + if (braceEscaped !== true && code === CHAR_COMMA) { + isBrace = token.isBrace = true; + isGlob = token.isGlob = true; + finished = true; - if (!bos.output && tokens.indexOf(prev) === 1) { - bos.output = ONE_CHAR; - } - continue; - } + if (scanToEnd === true) { + continue; } - } - } - if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) { - value = `\\${value}`; - } + break; + } - if (value === ']' && (prev.value === '[' || prev.value === '[^')) { - value = `\\${value}`; - } + if (code === CHAR_RIGHT_CURLY_BRACE) { + braces--; - if (opts.posix === true && value === '!' && prev.value === '[') { - value = '^'; + if (braces === 0) { + braceEscaped = false; + isBrace = token.isBrace = true; + finished = true; + break; + } + } } - prev.value += value; - append({ value }); - continue; - } - - /** - * If we're inside a quoted string, continue - * until we reach the closing double quote. - */ - - if (state.quotes === 1 && value !== '"') { - value = utils.escapeRegex(value); - prev.value += value; - append({ value }); - continue; - } - - /** - * Double quotes - */ - - if (value === '"') { - state.quotes = state.quotes === 1 ? 0 : 1; - if (opts.keepQuotes === true) { - push({ type: 'text', value }); + if (scanToEnd === true) { + continue; } - continue; - } - - /** - * Parentheses - */ - if (value === '(') { - increment('parens'); - push({ type: 'paren', value }); - continue; + break; } - if (value === ')') { - if (state.parens === 0 && opts.strictBrackets === true) { - throw new SyntaxError(syntaxError('opening', '(')); - } + if (code === CHAR_FORWARD_SLASH) { + slashes.push(index); + tokens.push(token); + token = { value: '', depth: 0, isGlob: false }; - const extglob = extglobs[extglobs.length - 1]; - if (extglob && state.parens === extglob.parens + 1) { - extglobClose(extglobs.pop()); + if (finished === true) continue; + if (prev === CHAR_DOT && index === (start + 1)) { + start += 2; continue; } - push({ type: 'paren', value, output: state.parens ? ')' : '\\)' }); - decrement('parens'); + lastIndex = index + 1; continue; } - /** - * Square brackets - */ + if (opts.noext !== true) { + const isExtglobChar = code === CHAR_PLUS + || code === CHAR_AT + || code === CHAR_ASTERISK + || code === CHAR_QUESTION_MARK + || code === CHAR_EXCLAMATION_MARK; - if (value === '[') { - if (opts.nobracket === true || !remaining().includes(']')) { - if (opts.nobracket !== true && opts.strictBrackets === true) { - throw new SyntaxError(syntaxError('closing', ']')); + if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) { + isGlob = token.isGlob = true; + isExtglob = token.isExtglob = true; + finished = true; + if (code === CHAR_EXCLAMATION_MARK && index === start) { + negatedExtglob = true; } - value = `\\${value}`; - } else { - increment('brackets'); - } - - push({ type: 'bracket', value }); - continue; - } + if (scanToEnd === true) { + while (eos() !== true && (code = advance())) { + if (code === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + code = advance(); + continue; + } - if (value === ']') { - if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) { - push({ type: 'text', value, output: `\\${value}` }); - continue; + if (code === CHAR_RIGHT_PARENTHESES) { + isGlob = token.isGlob = true; + finished = true; + break; + } + } + continue; + } + break; } + } - if (state.brackets === 0) { - if (opts.strictBrackets === true) { - throw new SyntaxError(syntaxError('opening', '[')); - } + if (code === CHAR_ASTERISK) { + if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true; + isGlob = token.isGlob = true; + finished = true; - push({ type: 'text', value, output: `\\${value}` }); + if (scanToEnd === true) { continue; } + break; + } - decrement('brackets'); + if (code === CHAR_QUESTION_MARK) { + isGlob = token.isGlob = true; + finished = true; - const prevValue = prev.value.slice(1); - if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) { - value = `/${value}`; + if (scanToEnd === true) { + continue; } + break; + } - prev.value += value; - append({ value }); + if (code === CHAR_LEFT_SQUARE_BRACKET) { + while (eos() !== true && (next = advance())) { + if (next === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + advance(); + continue; + } - // when literal brackets are explicitly disabled - // assume we should match with a regex character class - if (opts.literalBrackets === false || utils.hasRegexChars(prevValue)) { - continue; + if (next === CHAR_RIGHT_SQUARE_BRACKET) { + isBracket = token.isBracket = true; + isGlob = token.isGlob = true; + finished = true; + break; + } } - const escaped = utils.escapeRegex(prev.value); - state.output = state.output.slice(0, -prev.value.length); - - // when literal brackets are explicitly enabled - // assume we should escape the brackets to match literal characters - if (opts.literalBrackets === true) { - state.output += escaped; - prev.value = escaped; + if (scanToEnd === true) { continue; } - // when the user specifies nothing, try to match both - prev.value = `(${capture}${escaped}|${prev.value})`; - state.output += prev.value; - continue; + break; } - /** - * Braces - */ - - if (value === '{' && opts.nobrace !== true) { - increment('braces'); - - const open = { - type: 'brace', - value, - output: '(', - outputIndex: state.output.length, - tokensIndex: state.tokens.length - }; - - braces.push(open); - push(open); + if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) { + negated = token.negated = true; + start++; continue; } - if (value === '}') { - const brace = braces[braces.length - 1]; - - if (opts.nobrace === true || !brace) { - push({ type: 'text', value, output: value }); - continue; - } - - let output = ')'; + if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) { + isGlob = token.isGlob = true; - if (brace.dots === true) { - const arr = tokens.slice(); - const range = []; + if (scanToEnd === true) { + while (eos() !== true && (code = advance())) { + if (code === CHAR_LEFT_PARENTHESES) { + backslashes = token.backslashes = true; + code = advance(); + continue; + } - for (let i = arr.length - 1; i >= 0; i--) { - tokens.pop(); - if (arr[i].type === 'brace') { + if (code === CHAR_RIGHT_PARENTHESES) { + finished = true; break; } - if (arr[i].type !== 'dots') { - range.unshift(arr[i].value); - } - } - - output = expandRange(range, opts); - state.backtrack = true; - } - - if (brace.comma !== true && brace.dots !== true) { - const out = state.output.slice(0, brace.outputIndex); - const toks = state.tokens.slice(brace.tokensIndex); - brace.value = brace.output = '\\{'; - value = output = '\\}'; - state.output = out; - for (const t of toks) { - state.output += (t.output || t.value); } + continue; } - - push({ type: 'brace', value, output }); - decrement('braces'); - braces.pop(); - continue; + break; } - /** - * Pipes - */ + if (isGlob === true) { + finished = true; - if (value === '|') { - if (extglobs.length > 0) { - extglobs[extglobs.length - 1].conditions++; + if (scanToEnd === true) { + continue; } - push({ type: 'text', value }); - continue; + + break; } + } - /** - * Commas - */ + if (opts.noext === true) { + isExtglob = false; + isGlob = false; + } - if (value === ',') { - let output = value; + let base = str; + let prefix = ''; + let glob = ''; - const brace = braces[braces.length - 1]; - if (brace && stack[stack.length - 1] === 'braces') { - brace.comma = true; - output = '|'; - } + if (start > 0) { + prefix = str.slice(0, start); + str = str.slice(start); + lastIndex -= start; + } - push({ type: 'comma', value, output }); - continue; + if (base && isGlob === true && lastIndex > 0) { + base = str.slice(0, lastIndex); + glob = str.slice(lastIndex); + } else if (isGlob === true) { + base = ''; + glob = str; + } else { + base = str; + } + + if (base && base !== '' && base !== '/' && base !== str) { + if (isPathSeparator(base.charCodeAt(base.length - 1))) { + base = base.slice(0, -1); } + } - /** - * Slashes - */ + if (opts.unescape === true) { + if (glob) glob = utils.removeBackslashes(glob); - if (value === '/') { - // if the beginning of the glob is "./", advance the start - // to the current index, and don't add the "./" characters - // to the state. This greatly simplifies lookbehinds when - // checking for BOS characters like "!" and "." (not "./") - if (prev.type === 'dot' && state.index === state.start + 1) { - state.start = state.index + 1; - state.consumed = ''; - state.output = ''; - tokens.pop(); - prev = bos; // reset "prev" to the first token - continue; - } - - push({ type: 'slash', value, output: SLASH_LITERAL }); - continue; + if (base && backslashes === true) { + base = utils.removeBackslashes(base); } + } - /** - * Dots - */ - - if (value === '.') { - if (state.braces > 0 && prev.type === 'dot') { - if (prev.value === '.') prev.output = DOT_LITERAL; - const brace = braces[braces.length - 1]; - prev.type = 'dots'; - prev.output += value; - prev.value += value; - brace.dots = true; - continue; - } - - if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') { - push({ type: 'text', value, output: DOT_LITERAL }); - continue; - } + const state = { + prefix, + input, + start, + base, + glob, + isBrace, + isBracket, + isGlob, + isExtglob, + isGlobstar, + negated, + negatedExtglob + }; - push({ type: 'dot', value, output: DOT_LITERAL }); - continue; + if (opts.tokens === true) { + state.maxDepth = 0; + if (!isPathSeparator(code)) { + tokens.push(token); } + state.tokens = tokens; + } - /** - * Question marks - */ - - if (value === '?') { - const isGroup = prev && prev.value === '('; - if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { - extglobOpen('qmark', value); - continue; - } - - if (prev && prev.type === 'paren') { - const next = peek(); - let output = value; - - if (next === '<' && !utils.supportsLookbehinds()) { - throw new Error('Node.js v10 or higher is required for regex lookbehinds'); - } + if (opts.parts === true || opts.tokens === true) { + let prevIndex; - if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) { - output = `\\${value}`; + for (let idx = 0; idx < slashes.length; idx++) { + const n = prevIndex ? prevIndex + 1 : start; + const i = slashes[idx]; + const value = input.slice(n, i); + if (opts.tokens) { + if (idx === 0 && start !== 0) { + tokens[idx].isPrefix = true; + tokens[idx].value = prefix; + } else { + tokens[idx].value = value; } - - push({ type: 'text', value, output }); - continue; + depth(tokens[idx]); + state.maxDepth += tokens[idx].depth; } - - if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) { - push({ type: 'qmark', value, output: QMARK_NO_DOT }); - continue; + if (idx !== 0 || value !== '') { + parts.push(value); } - - push({ type: 'qmark', value, output: QMARK }); - continue; + prevIndex = i; } - /** - * Exclamation - */ - - if (value === '!') { - if (opts.noextglob !== true && peek() === '(') { - if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) { - extglobOpen('negate', value); - continue; - } - } + if (prevIndex && prevIndex + 1 < input.length) { + const value = input.slice(prevIndex + 1); + parts.push(value); - if (opts.nonegate !== true && state.index === 0) { - negate(); - continue; + if (opts.tokens) { + tokens[tokens.length - 1].value = value; + depth(tokens[tokens.length - 1]); + state.maxDepth += tokens[tokens.length - 1].depth; } } - /** - * Plus - */ + state.slashes = slashes; + state.parts = parts; + } - if (value === '+') { - if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { - extglobOpen('plus', value); - continue; - } + return state; +}; - if ((prev && prev.value === '(') || opts.regex === false) { - push({ type: 'plus', value, output: PLUS_LITERAL }); - continue; - } +module.exports = scan; - if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) { - push({ type: 'plus', value }); - continue; - } - push({ type: 'plus', value: PLUS_LITERAL }); - continue; - } +/***/ }), - /** - * Plain text - */ +/***/ 4059: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (value === '@') { - if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { - push({ type: 'at', extglob: true, value, output: '' }); - continue; - } - push({ type: 'text', value }); - continue; - } - /** - * Plain text - */ +const path = __nccwpck_require__(6928); +const win32 = process.platform === 'win32'; +const { + REGEX_BACKSLASH, + REGEX_REMOVE_BACKSLASH, + REGEX_SPECIAL_CHARS, + REGEX_SPECIAL_CHARS_GLOBAL +} = __nccwpck_require__(5595); - if (value !== '*') { - if (value === '$' || value === '^') { - value = `\\${value}`; - } +exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val); +exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str); +exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str); +exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1'); +exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/'); - const match = REGEX_NON_SPECIAL_CHARS.exec(remaining()); - if (match) { - value += match[0]; - state.index += match[0].length; - } +exports.removeBackslashes = str => { + return str.replace(REGEX_REMOVE_BACKSLASH, match => { + return match === '\\' ? '' : match; + }); +}; - push({ type: 'text', value }); - continue; - } +exports.supportsLookbehinds = () => { + const segs = process.version.slice(1).split('.').map(Number); + if (segs.length === 3 && segs[0] >= 9 || (segs[0] === 8 && segs[1] >= 10)) { + return true; + } + return false; +}; - /** - * Stars - */ +exports.isWindows = options => { + if (options && typeof options.windows === 'boolean') { + return options.windows; + } + return win32 === true || path.sep === '\\'; +}; - if (prev && (prev.type === 'globstar' || prev.star === true)) { - prev.type = 'star'; - prev.star = true; - prev.value += value; - prev.output = star; - state.backtrack = true; - state.globstar = true; - consume(value); - continue; - } +exports.escapeLast = (input, char, lastIdx) => { + const idx = input.lastIndexOf(char, lastIdx); + if (idx === -1) return input; + if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1); + return `${input.slice(0, idx)}\\${input.slice(idx)}`; +}; - let rest = remaining(); - if (opts.noextglob !== true && /^\([^?]/.test(rest)) { - extglobOpen('star', value); - continue; - } +exports.removePrefix = (input, state = {}) => { + let output = input; + if (output.startsWith('./')) { + output = output.slice(2); + state.prefix = './'; + } + return output; +}; - if (prev.type === 'star') { - if (opts.noglobstar === true) { - consume(value); - continue; - } +exports.wrapOutput = (input, state = {}, options = {}) => { + const prepend = options.contains ? '' : '^'; + const append = options.contains ? '' : '$'; - const prior = prev.prev; - const before = prior.prev; - const isStart = prior.type === 'slash' || prior.type === 'bos'; - const afterStar = before && (before.type === 'star' || before.type === 'globstar'); + let output = `${prepend}(?:${input})${append}`; + if (state.negated === true) { + output = `(?:^(?!${output}).*$)`; + } + return output; +}; - if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) { - push({ type: 'star', value, output: '' }); - continue; - } - const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace'); - const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren'); - if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) { - push({ type: 'star', value, output: '' }); - continue; - } +/***/ }), - // strip consecutive `/**/` - while (rest.slice(0, 3) === '/**') { - const after = input[state.index + 4]; - if (after && after !== '/') { - break; - } - rest = rest.slice(3); - consume('/**', 3); - } +/***/ 5546: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (prior.type === 'bos' && eos()) { - prev.type = 'globstar'; - prev.value += value; - prev.output = globstar(opts); - state.output = prev.output; - state.globstar = true; - consume(value); - continue; - } +module.exports = __nccwpck_require__(7084); - if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) { - state.output = state.output.slice(0, -(prior.output + prev.output).length); - prior.output = `(?:${prior.output}`; +/***/ }), - prev.type = 'globstar'; - prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)'); - prev.value += value; - state.globstar = true; - state.output += prior.output + prev.output; - consume(value); - continue; - } +/***/ 7084: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') { - const end = rest[1] !== void 0 ? '|$' : ''; +var RetryOperation = __nccwpck_require__(9538); - state.output = state.output.slice(0, -(prior.output + prev.output).length); - prior.output = `(?:${prior.output}`; +exports.operation = function(options) { + var timeouts = exports.timeouts(options); + return new RetryOperation(timeouts, { + forever: options && (options.forever || options.retries === Infinity), + unref: options && options.unref, + maxRetryTime: options && options.maxRetryTime + }); +}; - prev.type = 'globstar'; - prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`; - prev.value += value; +exports.timeouts = function(options) { + if (options instanceof Array) { + return [].concat(options); + } - state.output += prior.output + prev.output; - state.globstar = true; + var opts = { + retries: 10, + factor: 2, + minTimeout: 1 * 1000, + maxTimeout: Infinity, + randomize: false + }; + for (var key in options) { + opts[key] = options[key]; + } - consume(value + advance()); + if (opts.minTimeout > opts.maxTimeout) { + throw new Error('minTimeout is greater than maxTimeout'); + } - push({ type: 'slash', value: '/', output: '' }); - continue; - } + var timeouts = []; + for (var i = 0; i < opts.retries; i++) { + timeouts.push(this.createTimeout(i, opts)); + } - if (prior.type === 'bos' && rest[0] === '/') { - prev.type = 'globstar'; - prev.value += value; - prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`; - state.output = prev.output; - state.globstar = true; - consume(value + advance()); - push({ type: 'slash', value: '/', output: '' }); - continue; - } + if (options && options.forever && !timeouts.length) { + timeouts.push(this.createTimeout(i, opts)); + } - // remove single star from output - state.output = state.output.slice(0, -prev.output.length); + // sort the array numerically ascending + timeouts.sort(function(a,b) { + return a - b; + }); - // reset previous token to globstar - prev.type = 'globstar'; - prev.output = globstar(opts); - prev.value += value; + return timeouts; +}; - // reset output with globstar - state.output += prev.output; - state.globstar = true; - consume(value); - continue; - } +exports.createTimeout = function(attempt, opts) { + var random = (opts.randomize) + ? (Math.random() + 1) + : 1; - const token = { type: 'star', value, output: star }; + var timeout = Math.round(random * Math.max(opts.minTimeout, 1) * Math.pow(opts.factor, attempt)); + timeout = Math.min(timeout, opts.maxTimeout); - if (opts.bash === true) { - token.output = '.*?'; - if (prev.type === 'bos' || prev.type === 'slash') { - token.output = nodot + token.output; + return timeout; +}; + +exports.wrap = function(obj, options, methods) { + if (options instanceof Array) { + methods = options; + options = null; + } + + if (!methods) { + methods = []; + for (var key in obj) { + if (typeof obj[key] === 'function') { + methods.push(key); } - push(token); - continue; } + } - if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) { - token.output = value; - push(token); - continue; - } + for (var i = 0; i < methods.length; i++) { + var method = methods[i]; + var original = obj[method]; - if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') { - if (prev.type === 'dot') { - state.output += NO_DOT_SLASH; - prev.output += NO_DOT_SLASH; + obj[method] = function retryWrapper(original) { + var op = exports.operation(options); + var args = Array.prototype.slice.call(arguments, 1); + var callback = args.pop(); - } else if (opts.dot === true) { - state.output += NO_DOTS_SLASH; - prev.output += NO_DOTS_SLASH; + args.push(function(err) { + if (op.retry(err)) { + return; + } + if (err) { + arguments[0] = op.mainError(); + } + callback.apply(this, arguments); + }); - } else { - state.output += nodot; - prev.output += nodot; - } + op.attempt(function() { + original.apply(obj, args); + }); + }.bind(obj, original); + obj[method].options = options; + } +}; - if (peek() !== '*') { - state.output += ONE_CHAR; - prev.output += ONE_CHAR; - } - } - push(token); - } +/***/ }), - while (state.brackets > 0) { - if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']')); - state.output = utils.escapeLast(state.output, '['); - decrement('brackets'); - } +/***/ 9538: +/***/ ((module) => { - while (state.parens > 0) { - if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')')); - state.output = utils.escapeLast(state.output, '('); - decrement('parens'); +function RetryOperation(timeouts, options) { + // Compatibility for the old (timeouts, retryForever) signature + if (typeof options === 'boolean') { + options = { forever: options }; } - while (state.braces > 0) { - if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}')); - state.output = utils.escapeLast(state.output, '{'); - decrement('braces'); - } + this._originalTimeouts = JSON.parse(JSON.stringify(timeouts)); + this._timeouts = timeouts; + this._options = options || {}; + this._maxRetryTime = options && options.maxRetryTime || Infinity; + this._fn = null; + this._errors = []; + this._attempts = 1; + this._operationTimeout = null; + this._operationTimeoutCb = null; + this._timeout = null; + this._operationStart = null; + this._timer = null; - if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) { - push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` }); + if (this._options.forever) { + this._cachedTimeouts = this._timeouts.slice(0); } +} +module.exports = RetryOperation; - // rebuild the output if we had to backtrack at any point - if (state.backtrack === true) { - state.output = ''; +RetryOperation.prototype.reset = function() { + this._attempts = 1; + this._timeouts = this._originalTimeouts.slice(0); +} - for (const token of state.tokens) { - state.output += token.output != null ? token.output : token.value; +RetryOperation.prototype.stop = function() { + if (this._timeout) { + clearTimeout(this._timeout); + } + if (this._timer) { + clearTimeout(this._timer); + } - if (token.suffix) { - state.output += token.suffix; - } - } + this._timeouts = []; + this._cachedTimeouts = null; +}; + +RetryOperation.prototype.retry = function(err) { + if (this._timeout) { + clearTimeout(this._timeout); } - return state; -}; + if (!err) { + return false; + } + var currentTime = new Date().getTime(); + if (err && currentTime - this._operationStart >= this._maxRetryTime) { + this._errors.push(err); + this._errors.unshift(new Error('RetryOperation timeout occurred')); + return false; + } -/** - * Fast paths for creating regular expressions for common glob patterns. - * This can significantly speed up processing and has very little downside - * impact when none of the fast paths match. - */ + this._errors.push(err); -parse.fastpaths = (input, options) => { - const opts = { ...options }; - const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; - const len = input.length; - if (len > max) { - throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`); + var timeout = this._timeouts.shift(); + if (timeout === undefined) { + if (this._cachedTimeouts) { + // retry forever, only keep last error + this._errors.splice(0, this._errors.length - 1); + timeout = this._cachedTimeouts.slice(-1); + } else { + return false; + } } - input = REPLACEMENTS[input] || input; - const win32 = utils.isWindows(options); + var self = this; + this._timer = setTimeout(function() { + self._attempts++; - // create constants based on platform, for windows or posix - const { - DOT_LITERAL, - SLASH_LITERAL, - ONE_CHAR, - DOTS_SLASH, - NO_DOT, - NO_DOTS, - NO_DOTS_SLASH, - STAR, - START_ANCHOR - } = constants.globChars(win32); + if (self._operationTimeoutCb) { + self._timeout = setTimeout(function() { + self._operationTimeoutCb(self._attempts); + }, self._operationTimeout); - const nodot = opts.dot ? NO_DOTS : NO_DOT; - const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT; - const capture = opts.capture ? '' : '?:'; - const state = { negated: false, prefix: '' }; - let star = opts.bash === true ? '.*?' : STAR; + if (self._options.unref) { + self._timeout.unref(); + } + } - if (opts.capture) { - star = `(${star})`; + self._fn(self._attempts); + }, timeout); + + if (this._options.unref) { + this._timer.unref(); } - const globstar = opts => { - if (opts.noglobstar === true) return star; - return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`; - }; + return true; +}; - const create = str => { - switch (str) { - case '*': - return `${nodot}${ONE_CHAR}${star}`; +RetryOperation.prototype.attempt = function(fn, timeoutOps) { + this._fn = fn; - case '.*': - return `${DOT_LITERAL}${ONE_CHAR}${star}`; + if (timeoutOps) { + if (timeoutOps.timeout) { + this._operationTimeout = timeoutOps.timeout; + } + if (timeoutOps.cb) { + this._operationTimeoutCb = timeoutOps.cb; + } + } - case '*.*': - return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`; + var self = this; + if (this._operationTimeoutCb) { + this._timeout = setTimeout(function() { + self._operationTimeoutCb(); + }, self._operationTimeout); + } - case '*/*': - return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`; + this._operationStart = new Date().getTime(); - case '**': - return nodot + globstar(opts); + this._fn(this._attempts); +}; - case '**/*': - return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`; +RetryOperation.prototype.try = function(fn) { + console.log('Using RetryOperation.try() is deprecated'); + this.attempt(fn); +}; - case '**/*.*': - return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`; +RetryOperation.prototype.start = function(fn) { + console.log('Using RetryOperation.start() is deprecated'); + this.attempt(fn); +}; - case '**/.*': - return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`; +RetryOperation.prototype.start = RetryOperation.prototype.try; - default: { - const match = /^(.*?)\.(\w+)$/.exec(str); - if (!match) return; +RetryOperation.prototype.errors = function() { + return this._errors; +}; - const source = create(match[1]); - if (!source) return; +RetryOperation.prototype.attempts = function() { + return this._attempts; +}; - return source + DOT_LITERAL + match[2]; - } - } - }; +RetryOperation.prototype.mainError = function() { + if (this._errors.length === 0) { + return null; + } - const output = utils.removePrefix(input, state); - let source = create(output); + var counts = {}; + var mainError = null; + var mainErrorCount = 0; - if (source && opts.strictSlashes !== true) { - source += `${SLASH_LITERAL}?`; + for (var i = 0; i < this._errors.length; i++) { + var error = this._errors[i]; + var message = error.message; + var count = (counts[message] || 0) + 1; + + counts[message] = count; + + if (count >= mainErrorCount) { + mainError = error; + mainErrorCount = count; + } } - return source; + return mainError; }; -module.exports = parse; - /***/ }), -/***/ 8016: +/***/ 9379: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -const path = __nccwpck_require__(6928); -const scan = __nccwpck_require__(1781); -const parse = __nccwpck_require__(8265); -const utils = __nccwpck_require__(4059); -const constants = __nccwpck_require__(5595); -const isObject = val => val && typeof val === 'object' && !Array.isArray(val); - -/** - * Creates a matcher function from one or more glob patterns. The - * returned function takes a string to match as its first argument, - * and returns true if the string is a match. The returned matcher - * function also takes a boolean as the second argument that, when true, - * returns an object with additional information. - * - * ```js - * const picomatch = require('picomatch'); - * // picomatch(glob[, options]); - * - * const isMatch = picomatch('*.!(*a)'); - * console.log(isMatch('a.a')); //=> false - * console.log(isMatch('a.b')); //=> true - * ``` - * @name picomatch - * @param {String|Array} `globs` One or more glob patterns. - * @param {Object=} `options` - * @return {Function=} Returns a matcher function. - * @api public - */ - -const picomatch = (glob, options, returnState = false) => { - if (Array.isArray(glob)) { - const fns = glob.map(input => picomatch(input, options, returnState)); - const arrayMatcher = str => { - for (const isMatch of fns) { - const state = isMatch(str); - if (state) return state; - } - return false; - }; - return arrayMatcher; +const ANY = Symbol('SemVer ANY') +// hoisted class for cyclic dependency +class Comparator { + static get ANY () { + return ANY } - const isState = isObject(glob) && glob.tokens && glob.input; + constructor (comp, options) { + options = parseOptions(options) - if (glob === '' || (typeof glob !== 'string' && !isState)) { - throw new TypeError('Expected pattern to be a non-empty string'); - } + if (comp instanceof Comparator) { + if (comp.loose === !!options.loose) { + return comp + } else { + comp = comp.value + } + } - const opts = options || {}; - const posix = utils.isWindows(options); - const regex = isState - ? picomatch.compileRe(glob, options) - : picomatch.makeRe(glob, options, false, true); + comp = comp.trim().split(/\s+/).join(' ') + debug('comparator', comp, options) + this.options = options + this.loose = !!options.loose + this.parse(comp) - const state = regex.state; - delete regex.state; + if (this.semver === ANY) { + this.value = '' + } else { + this.value = this.operator + this.semver.version + } - let isIgnored = () => false; - if (opts.ignore) { - const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null }; - isIgnored = picomatch(opts.ignore, ignoreOpts, returnState); + debug('comp', this) } - const matcher = (input, returnObject = false) => { - const { isMatch, match, output } = picomatch.test(input, regex, options, { glob, posix }); - const result = { glob, state, regex, posix, input, output, match, isMatch }; - - if (typeof opts.onResult === 'function') { - opts.onResult(result); - } + parse (comp) { + const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR] + const m = comp.match(r) - if (isMatch === false) { - result.isMatch = false; - return returnObject ? result : false; + if (!m) { + throw new TypeError(`Invalid comparator: ${comp}`) } - if (isIgnored(input)) { - if (typeof opts.onIgnore === 'function') { - opts.onIgnore(result); - } - result.isMatch = false; - return returnObject ? result : false; + this.operator = m[1] !== undefined ? m[1] : '' + if (this.operator === '=') { + this.operator = '' } - if (typeof opts.onMatch === 'function') { - opts.onMatch(result); + // if it literally is just '>' or '' then allow anything. + if (!m[2]) { + this.semver = ANY + } else { + this.semver = new SemVer(m[2], this.options.loose) } - return returnObject ? result : true; - }; + } - if (returnState) { - matcher.state = state; + toString () { + return this.value } - return matcher; -}; + test (version) { + debug('Comparator.test', version, this.options.loose) -/** - * Test `input` with the given `regex`. This is used by the main - * `picomatch()` function to test the input string. - * - * ```js - * const picomatch = require('picomatch'); - * // picomatch.test(input, regex[, options]); - * - * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/)); - * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' } - * ``` - * @param {String} `input` String to test. - * @param {RegExp} `regex` - * @return {Object} Returns an object with matching info. - * @api public - */ + if (this.semver === ANY || version === ANY) { + return true + } -picomatch.test = (input, regex, options, { glob, posix } = {}) => { - if (typeof input !== 'string') { - throw new TypeError('Expected input to be a string'); - } + if (typeof version === 'string') { + try { + version = new SemVer(version, this.options) + } catch (er) { + return false + } + } - if (input === '') { - return { isMatch: false, output: '' }; + return cmp(version, this.operator, this.semver, this.options) } - const opts = options || {}; - const format = opts.format || (posix ? utils.toPosixSlashes : null); - let match = input === glob; - let output = (match && format) ? format(input) : input; - - if (match === false) { - output = format ? format(input) : input; - match = output === glob; - } + intersects (comp, options) { + if (!(comp instanceof Comparator)) { + throw new TypeError('a Comparator is required') + } - if (match === false || opts.capture === true) { - if (opts.matchBase === true || opts.basename === true) { - match = picomatch.matchBase(input, regex, options, posix); - } else { - match = regex.exec(output); + if (this.operator === '') { + if (this.value === '') { + return true + } + return new Range(comp.value, options).test(this.value) + } else if (comp.operator === '') { + if (comp.value === '') { + return true + } + return new Range(this.value, options).test(comp.semver) } - } - return { isMatch: Boolean(match), match, output }; -}; + options = parseOptions(options) -/** - * Match the basename of a filepath. - * - * ```js - * const picomatch = require('picomatch'); - * // picomatch.matchBase(input, glob[, options]); - * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true - * ``` - * @param {String} `input` String to test. - * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe). - * @return {Boolean} - * @api public - */ + // Special cases where nothing can possibly be lower + if (options.includePrerelease && + (this.value === '<0.0.0-0' || comp.value === '<0.0.0-0')) { + return false + } + if (!options.includePrerelease && + (this.value.startsWith('<0.0.0') || comp.value.startsWith('<0.0.0'))) { + return false + } -picomatch.matchBase = (input, glob, options, posix = utils.isWindows(options)) => { - const regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options); - return regex.test(path.basename(input)); -}; + // Same direction increasing (> or >=) + if (this.operator.startsWith('>') && comp.operator.startsWith('>')) { + return true + } + // Same direction decreasing (< or <=) + if (this.operator.startsWith('<') && comp.operator.startsWith('<')) { + return true + } + // same SemVer and both sides are inclusive (<= or >=) + if ( + (this.semver.version === comp.semver.version) && + this.operator.includes('=') && comp.operator.includes('=')) { + return true + } + // opposite directions less than + if (cmp(this.semver, '<', comp.semver, options) && + this.operator.startsWith('>') && comp.operator.startsWith('<')) { + return true + } + // opposite directions greater than + if (cmp(this.semver, '>', comp.semver, options) && + this.operator.startsWith('<') && comp.operator.startsWith('>')) { + return true + } + return false + } +} -/** - * Returns true if **any** of the given glob `patterns` match the specified `string`. - * - * ```js - * const picomatch = require('picomatch'); - * // picomatch.isMatch(string, patterns[, options]); - * - * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true - * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false - * ``` - * @param {String|Array} str The string to test. - * @param {String|Array} patterns One or more glob patterns to use for matching. - * @param {Object} [options] See available [options](#options). - * @return {Boolean} Returns true if any patterns match `str` - * @api public - */ +module.exports = Comparator -picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str); +const parseOptions = __nccwpck_require__(356) +const { safeRe: re, t } = __nccwpck_require__(5471) +const cmp = __nccwpck_require__(8646) +const debug = __nccwpck_require__(1159) +const SemVer = __nccwpck_require__(7163) +const Range = __nccwpck_require__(6782) -/** - * Parse a glob pattern to create the source string for a regular - * expression. - * - * ```js - * const picomatch = require('picomatch'); - * const result = picomatch.parse(pattern[, options]); - * ``` - * @param {String} `pattern` - * @param {Object} `options` - * @return {Object} Returns an object with useful properties and output to be used as a regex source string. - * @api public - */ -picomatch.parse = (pattern, options) => { - if (Array.isArray(pattern)) return pattern.map(p => picomatch.parse(p, options)); - return parse(pattern, { ...options, fastpaths: false }); -}; +/***/ }), -/** - * Scan a glob pattern to separate the pattern into segments. - * - * ```js - * const picomatch = require('picomatch'); - * // picomatch.scan(input[, options]); - * - * const result = picomatch.scan('!./foo/*.js'); - * console.log(result); - * { prefix: '!./', - * input: '!./foo/*.js', - * start: 3, - * base: 'foo', - * glob: '*.js', - * isBrace: false, - * isBracket: false, - * isGlob: true, - * isExtglob: false, - * isGlobstar: false, - * negated: true } - * ``` - * @param {String} `input` Glob pattern to scan. - * @param {Object} `options` - * @return {Object} Returns an object with - * @api public - */ +/***/ 6782: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -picomatch.scan = (input, options) => scan(input, options); -/** - * Compile a regular expression from the `state` object returned by the - * [parse()](#parse) method. - * - * @param {Object} `state` - * @param {Object} `options` - * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser. - * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging. - * @return {RegExp} - * @api public - */ -picomatch.compileRe = (state, options, returnOutput = false, returnState = false) => { - if (returnOutput === true) { - return state.output; - } +const SPACE_CHARACTERS = /\s+/g - const opts = options || {}; - const prepend = opts.contains ? '' : '^'; - const append = opts.contains ? '' : '$'; +// hoisted class for cyclic dependency +class Range { + constructor (range, options) { + options = parseOptions(options) - let source = `${prepend}(?:${state.output})${append}`; - if (state && state.negated === true) { - source = `^(?!${source}).*$`; - } + if (range instanceof Range) { + if ( + range.loose === !!options.loose && + range.includePrerelease === !!options.includePrerelease + ) { + return range + } else { + return new Range(range.raw, options) + } + } - const regex = picomatch.toRegex(source, options); - if (returnState === true) { - regex.state = state; - } + if (range instanceof Comparator) { + // just put it in the set and return + this.raw = range.value + this.set = [[range]] + this.formatted = undefined + return this + } - return regex; -}; + this.options = options + this.loose = !!options.loose + this.includePrerelease = !!options.includePrerelease -/** - * Create a regular expression from a parsed glob pattern. - * - * ```js - * const picomatch = require('picomatch'); - * const state = picomatch.parse('*.js'); - * // picomatch.compileRe(state[, options]); - * - * console.log(picomatch.compileRe(state)); - * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ - * ``` - * @param {String} `state` The object returned from the `.parse` method. - * @param {Object} `options` - * @param {Boolean} `returnOutput` Implementors may use this argument to return the compiled output, instead of a regular expression. This is not exposed on the options to prevent end-users from mutating the result. - * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression. - * @return {RegExp} Returns a regex created from the given pattern. - * @api public - */ + // First reduce all whitespace as much as possible so we do not have to rely + // on potentially slow regexes like \s*. This is then stored and used for + // future error messages as well. + this.raw = range.trim().replace(SPACE_CHARACTERS, ' ') -picomatch.makeRe = (input, options = {}, returnOutput = false, returnState = false) => { - if (!input || typeof input !== 'string') { - throw new TypeError('Expected a non-empty string'); - } + // First, split on || + this.set = this.raw + .split('||') + // map the range to a 2d array of comparators + .map(r => this.parseRange(r.trim())) + // throw out any comparator lists that are empty + // this generally means that it was not a valid range, which is allowed + // in loose mode, but will still throw if the WHOLE range is invalid. + .filter(c => c.length) - let parsed = { negated: false, fastpaths: true }; + if (!this.set.length) { + throw new TypeError(`Invalid SemVer Range: ${this.raw}`) + } - if (options.fastpaths !== false && (input[0] === '.' || input[0] === '*')) { - parsed.output = parse.fastpaths(input, options); - } + // if we have any that are not the null set, throw out null sets. + if (this.set.length > 1) { + // keep the first one, in case they're all null sets + const first = this.set[0] + this.set = this.set.filter(c => !isNullSet(c[0])) + if (this.set.length === 0) { + this.set = [first] + } else if (this.set.length > 1) { + // if we have any that are *, then the range is just * + for (const c of this.set) { + if (c.length === 1 && isAny(c[0])) { + this.set = [c] + break + } + } + } + } - if (!parsed.output) { - parsed = parse(input, options); + this.formatted = undefined } - return picomatch.compileRe(parsed, options, returnOutput, returnState); -}; - -/** - * Create a regular expression from the given regex source string. - * - * ```js - * const picomatch = require('picomatch'); - * // picomatch.toRegex(source[, options]); - * - * const { output } = picomatch.parse('*.js'); - * console.log(picomatch.toRegex(output)); - * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ - * ``` - * @param {String} `source` Regular expression source string. - * @param {Object} `options` - * @return {RegExp} - * @api public - */ - -picomatch.toRegex = (source, options) => { - try { - const opts = options || {}; - return new RegExp(source, opts.flags || (opts.nocase ? 'i' : '')); - } catch (err) { - if (options && options.debug === true) throw err; - return /$^/; + get range () { + if (this.formatted === undefined) { + this.formatted = '' + for (let i = 0; i < this.set.length; i++) { + if (i > 0) { + this.formatted += '||' + } + const comps = this.set[i] + for (let k = 0; k < comps.length; k++) { + if (k > 0) { + this.formatted += ' ' + } + this.formatted += comps[k].toString().trim() + } + } + } + return this.formatted } -}; -/** - * Picomatch constants. - * @return {Object} - */ + format () { + return this.range + } -picomatch.constants = constants; + toString () { + return this.range + } -/** - * Expose "picomatch" - */ + parseRange (range) { + // memoize range parsing for performance. + // this is a very hot path, and fully deterministic. + const memoOpts = + (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) | + (this.options.loose && FLAG_LOOSE) + const memoKey = memoOpts + ':' + range + const cached = cache.get(memoKey) + if (cached) { + return cached + } -module.exports = picomatch; + const loose = this.options.loose + // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` + const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE] + range = range.replace(hr, hyphenReplace(this.options.includePrerelease)) + debug('hyphen replace', range) + // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` + range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace) + debug('comparator trim', range) -/***/ }), + // `~ 1.2.3` => `~1.2.3` + range = range.replace(re[t.TILDETRIM], tildeTrimReplace) + debug('tilde trim', range) -/***/ 1781: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // `^ 1.2.3` => `^1.2.3` + range = range.replace(re[t.CARETTRIM], caretTrimReplace) + debug('caret trim', range) + // At this point, the range is completely trimmed and + // ready to be split into comparators. + let rangeList = range + .split(' ') + .map(comp => parseComparator(comp, this.options)) + .join(' ') + .split(/\s+/) + // >=0.0.0 is equivalent to * + .map(comp => replaceGTE0(comp, this.options)) -const utils = __nccwpck_require__(4059); -const { - CHAR_ASTERISK, /* * */ - CHAR_AT, /* @ */ - CHAR_BACKWARD_SLASH, /* \ */ - CHAR_COMMA, /* , */ - CHAR_DOT, /* . */ - CHAR_EXCLAMATION_MARK, /* ! */ - CHAR_FORWARD_SLASH, /* / */ - CHAR_LEFT_CURLY_BRACE, /* { */ - CHAR_LEFT_PARENTHESES, /* ( */ - CHAR_LEFT_SQUARE_BRACKET, /* [ */ - CHAR_PLUS, /* + */ - CHAR_QUESTION_MARK, /* ? */ - CHAR_RIGHT_CURLY_BRACE, /* } */ - CHAR_RIGHT_PARENTHESES, /* ) */ - CHAR_RIGHT_SQUARE_BRACKET /* ] */ -} = __nccwpck_require__(5595); + if (loose) { + // in loose mode, throw out any that are not valid comparators + rangeList = rangeList.filter(comp => { + debug('loose invalid filter', comp, this.options) + return !!comp.match(re[t.COMPARATORLOOSE]) + }) + } + debug('range list', rangeList) -const isPathSeparator = code => { - return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH; -}; + // if any comparators are the null set, then replace with JUST null set + // if more than one comparator, remove any * comparators + // also, don't include the same comparator more than once + const rangeMap = new Map() + const comparators = rangeList.map(comp => new Comparator(comp, this.options)) + for (const comp of comparators) { + if (isNullSet(comp)) { + return [comp] + } + rangeMap.set(comp.value, comp) + } + if (rangeMap.size > 1 && rangeMap.has('')) { + rangeMap.delete('') + } -const depth = token => { - if (token.isPrefix !== true) { - token.depth = token.isGlobstar ? Infinity : 1; + const result = [...rangeMap.values()] + cache.set(memoKey, result) + return result } -}; - -/** - * Quickly scans a glob pattern and returns an object with a handful of - * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists), - * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not - * with `!(`) and `negatedExtglob` (true if the path starts with `!(`). - * - * ```js - * const pm = require('picomatch'); - * console.log(pm.scan('foo/bar/*.js')); - * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' } - * ``` - * @param {String} `str` - * @param {Object} `options` - * @return {Object} Returns an object with tokens and regex source string. - * @api public - */ - -const scan = (input, options) => { - const opts = options || {}; - const length = input.length - 1; - const scanToEnd = opts.parts === true || opts.scanToEnd === true; - const slashes = []; - const tokens = []; - const parts = []; - - let str = input; - let index = -1; - let start = 0; - let lastIndex = 0; - let isBrace = false; - let isBracket = false; - let isGlob = false; - let isExtglob = false; - let isGlobstar = false; - let braceEscaped = false; - let backslashes = false; - let negated = false; - let negatedExtglob = false; - let finished = false; - let braces = 0; - let prev; - let code; - let token = { value: '', depth: 0, isGlob: false }; + intersects (range, options) { + if (!(range instanceof Range)) { + throw new TypeError('a Range is required') + } - const eos = () => index >= length; - const peek = () => str.charCodeAt(index + 1); - const advance = () => { - prev = code; - return str.charCodeAt(++index); - }; + return this.set.some((thisComparators) => { + return ( + isSatisfiable(thisComparators, options) && + range.set.some((rangeComparators) => { + return ( + isSatisfiable(rangeComparators, options) && + thisComparators.every((thisComparator) => { + return rangeComparators.every((rangeComparator) => { + return thisComparator.intersects(rangeComparator, options) + }) + }) + ) + }) + ) + }) + } - while (index < length) { - code = advance(); - let next; + // if ANY of the sets match ALL of its comparators, then pass + test (version) { + if (!version) { + return false + } - if (code === CHAR_BACKWARD_SLASH) { - backslashes = token.backslashes = true; - code = advance(); + if (typeof version === 'string') { + try { + version = new SemVer(version, this.options) + } catch (er) { + return false + } + } - if (code === CHAR_LEFT_CURLY_BRACE) { - braceEscaped = true; + for (let i = 0; i < this.set.length; i++) { + if (testSet(this.set[i], version, this.options)) { + return true } - continue; } + return false + } +} - if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) { - braces++; +module.exports = Range - while (eos() !== true && (code = advance())) { - if (code === CHAR_BACKWARD_SLASH) { - backslashes = token.backslashes = true; - advance(); - continue; - } +const LRU = __nccwpck_require__(1383) +const cache = new LRU() - if (code === CHAR_LEFT_CURLY_BRACE) { - braces++; - continue; - } +const parseOptions = __nccwpck_require__(356) +const Comparator = __nccwpck_require__(9379) +const debug = __nccwpck_require__(1159) +const SemVer = __nccwpck_require__(7163) +const { + safeRe: re, + t, + comparatorTrimReplace, + tildeTrimReplace, + caretTrimReplace, +} = __nccwpck_require__(5471) +const { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = __nccwpck_require__(5101) - if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) { - isBrace = token.isBrace = true; - isGlob = token.isGlob = true; - finished = true; +const isNullSet = c => c.value === '<0.0.0-0' +const isAny = c => c.value === '' - if (scanToEnd === true) { - continue; - } +// take a set of comparators and determine whether there +// exists a version which can satisfy it +const isSatisfiable = (comparators, options) => { + let result = true + const remainingComparators = comparators.slice() + let testComparator = remainingComparators.pop() - break; - } + while (result && remainingComparators.length) { + result = remainingComparators.every((otherComparator) => { + return testComparator.intersects(otherComparator, options) + }) - if (braceEscaped !== true && code === CHAR_COMMA) { - isBrace = token.isBrace = true; - isGlob = token.isGlob = true; - finished = true; + testComparator = remainingComparators.pop() + } - if (scanToEnd === true) { - continue; - } + return result +} - break; - } +// comprised of xranges, tildes, stars, and gtlt's at this point. +// already replaced the hyphen ranges +// turn into a set of JUST comparators. +const parseComparator = (comp, options) => { + debug('comp', comp, options) + comp = replaceCarets(comp, options) + debug('caret', comp) + comp = replaceTildes(comp, options) + debug('tildes', comp) + comp = replaceXRanges(comp, options) + debug('xrange', comp) + comp = replaceStars(comp, options) + debug('stars', comp) + return comp +} - if (code === CHAR_RIGHT_CURLY_BRACE) { - braces--; +const isX = id => !id || id.toLowerCase() === 'x' || id === '*' - if (braces === 0) { - braceEscaped = false; - isBrace = token.isBrace = true; - finished = true; - break; - } - } - } +// ~, ~> --> * (any, kinda silly) +// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0 +// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0 +// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0 +// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0 +// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0 +// ~0.0.1 --> >=0.0.1 <0.1.0-0 +const replaceTildes = (comp, options) => { + return comp + .trim() + .split(/\s+/) + .map((c) => replaceTilde(c, options)) + .join(' ') +} - if (scanToEnd === true) { - continue; - } +const replaceTilde = (comp, options) => { + const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE] + return comp.replace(r, (_, M, m, p, pr) => { + debug('tilde', comp, _, M, m, p, pr) + let ret - break; + if (isX(M)) { + ret = '' + } else if (isX(m)) { + ret = `>=${M}.0.0 <${+M + 1}.0.0-0` + } else if (isX(p)) { + // ~1.2 == >=1.2.0 <1.3.0-0 + ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0` + } else if (pr) { + debug('replaceTilde pr', pr) + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${+m + 1}.0-0` + } else { + // ~1.2.3 == >=1.2.3 <1.3.0-0 + ret = `>=${M}.${m}.${p + } <${M}.${+m + 1}.0-0` } - if (code === CHAR_FORWARD_SLASH) { - slashes.push(index); - tokens.push(token); - token = { value: '', depth: 0, isGlob: false }; - - if (finished === true) continue; - if (prev === CHAR_DOT && index === (start + 1)) { - start += 2; - continue; - } - - lastIndex = index + 1; - continue; - } + debug('tilde return', ret) + return ret + }) +} - if (opts.noext !== true) { - const isExtglobChar = code === CHAR_PLUS - || code === CHAR_AT - || code === CHAR_ASTERISK - || code === CHAR_QUESTION_MARK - || code === CHAR_EXCLAMATION_MARK; +// ^ --> * (any, kinda silly) +// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0 +// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0 +// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0 +// ^1.2.3 --> >=1.2.3 <2.0.0-0 +// ^1.2.0 --> >=1.2.0 <2.0.0-0 +// ^0.0.1 --> >=0.0.1 <0.0.2-0 +// ^0.1.0 --> >=0.1.0 <0.2.0-0 +const replaceCarets = (comp, options) => { + return comp + .trim() + .split(/\s+/) + .map((c) => replaceCaret(c, options)) + .join(' ') +} - if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) { - isGlob = token.isGlob = true; - isExtglob = token.isExtglob = true; - finished = true; - if (code === CHAR_EXCLAMATION_MARK && index === start) { - negatedExtglob = true; - } +const replaceCaret = (comp, options) => { + debug('caret', comp, options) + const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET] + const z = options.includePrerelease ? '-0' : '' + return comp.replace(r, (_, M, m, p, pr) => { + debug('caret', comp, _, M, m, p, pr) + let ret - if (scanToEnd === true) { - while (eos() !== true && (code = advance())) { - if (code === CHAR_BACKWARD_SLASH) { - backslashes = token.backslashes = true; - code = advance(); - continue; - } - - if (code === CHAR_RIGHT_PARENTHESES) { - isGlob = token.isGlob = true; - finished = true; - break; - } - } - continue; + if (isX(M)) { + ret = '' + } else if (isX(m)) { + ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0` + } else if (isX(p)) { + if (M === '0') { + ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0` + } else { + ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0` + } + } else if (pr) { + debug('replaceCaret pr', pr) + if (M === '0') { + if (m === '0') { + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${m}.${+p + 1}-0` + } else { + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${+m + 1}.0-0` } - break; + } else { + ret = `>=${M}.${m}.${p}-${pr + } <${+M + 1}.0.0-0` + } + } else { + debug('no pr') + if (M === '0') { + if (m === '0') { + ret = `>=${M}.${m}.${p + }${z} <${M}.${m}.${+p + 1}-0` + } else { + ret = `>=${M}.${m}.${p + }${z} <${M}.${+m + 1}.0-0` + } + } else { + ret = `>=${M}.${m}.${p + } <${+M + 1}.0.0-0` } } - if (code === CHAR_ASTERISK) { - if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true; - isGlob = token.isGlob = true; - finished = true; + debug('caret return', ret) + return ret + }) +} - if (scanToEnd === true) { - continue; - } - break; +const replaceXRanges = (comp, options) => { + debug('replaceXRanges', comp, options) + return comp + .split(/\s+/) + .map((c) => replaceXRange(c, options)) + .join(' ') +} + +const replaceXRange = (comp, options) => { + comp = comp.trim() + const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE] + return comp.replace(r, (ret, gtlt, M, m, p, pr) => { + debug('xRange', comp, ret, gtlt, M, m, p, pr) + const xM = isX(M) + const xm = xM || isX(m) + const xp = xm || isX(p) + const anyX = xp + + if (gtlt === '=' && anyX) { + gtlt = '' } - if (code === CHAR_QUESTION_MARK) { - isGlob = token.isGlob = true; - finished = true; + // if we're including prereleases in the match, then we need + // to fix this to -0, the lowest possible prerelease value + pr = options.includePrerelease ? '-0' : '' - if (scanToEnd === true) { - continue; + if (xM) { + if (gtlt === '>' || gtlt === '<') { + // nothing is allowed + ret = '<0.0.0-0' + } else { + // nothing is forbidden + ret = '*' } - break; - } + } else if (gtlt && anyX) { + // we know patch is an x, because we have any x at all. + // replace X with 0 + if (xm) { + m = 0 + } + p = 0 - if (code === CHAR_LEFT_SQUARE_BRACKET) { - while (eos() !== true && (next = advance())) { - if (next === CHAR_BACKWARD_SLASH) { - backslashes = token.backslashes = true; - advance(); - continue; + if (gtlt === '>') { + // >1 => >=2.0.0 + // >1.2 => >=1.3.0 + gtlt = '>=' + if (xm) { + M = +M + 1 + m = 0 + p = 0 + } else { + m = +m + 1 + p = 0 } - - if (next === CHAR_RIGHT_SQUARE_BRACKET) { - isBracket = token.isBracket = true; - isGlob = token.isGlob = true; - finished = true; - break; + } else if (gtlt === '<=') { + // <=0.7.x is actually <0.8.0, since any 0.7.x should + // pass. Similarly, <=7.x is actually <8.0.0, etc. + gtlt = '<' + if (xm) { + M = +M + 1 + } else { + m = +m + 1 } } - if (scanToEnd === true) { - continue; + if (gtlt === '<') { + pr = '-0' } - break; - } - - if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) { - negated = token.negated = true; - start++; - continue; + ret = `${gtlt + M}.${m}.${p}${pr}` + } else if (xm) { + ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0` + } else if (xp) { + ret = `>=${M}.${m}.0${pr + } <${M}.${+m + 1}.0-0` } - if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) { - isGlob = token.isGlob = true; - - if (scanToEnd === true) { - while (eos() !== true && (code = advance())) { - if (code === CHAR_LEFT_PARENTHESES) { - backslashes = token.backslashes = true; - code = advance(); - continue; - } + debug('xRange return', ret) - if (code === CHAR_RIGHT_PARENTHESES) { - finished = true; - break; - } - } - continue; - } - break; - } + return ret + }) +} - if (isGlob === true) { - finished = true; +// Because * is AND-ed with everything else in the comparator, +// and '' means "any version", just remove the *s entirely. +const replaceStars = (comp, options) => { + debug('replaceStars', comp, options) + // Looseness is ignored here. star is always as loose as it gets! + return comp + .trim() + .replace(re[t.STAR], '') +} - if (scanToEnd === true) { - continue; - } +const replaceGTE0 = (comp, options) => { + debug('replaceGTE0', comp, options) + return comp + .trim() + .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '') +} - break; - } +// This function is passed to string.replace(re[t.HYPHENRANGE]) +// M, m, patch, prerelease, build +// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 +// 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do +// 1.2 - 3.4 => >=1.2.0 <3.5.0-0 +// TODO build? +const hyphenReplace = incPr => ($0, + from, fM, fm, fp, fpr, fb, + to, tM, tm, tp, tpr) => { + if (isX(fM)) { + from = '' + } else if (isX(fm)) { + from = `>=${fM}.0.0${incPr ? '-0' : ''}` + } else if (isX(fp)) { + from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}` + } else if (fpr) { + from = `>=${from}` + } else { + from = `>=${from}${incPr ? '-0' : ''}` } - if (opts.noext === true) { - isExtglob = false; - isGlob = false; + if (isX(tM)) { + to = '' + } else if (isX(tm)) { + to = `<${+tM + 1}.0.0-0` + } else if (isX(tp)) { + to = `<${tM}.${+tm + 1}.0-0` + } else if (tpr) { + to = `<=${tM}.${tm}.${tp}-${tpr}` + } else if (incPr) { + to = `<${tM}.${tm}.${+tp + 1}-0` + } else { + to = `<=${to}` } - let base = str; - let prefix = ''; - let glob = ''; + return `${from} ${to}`.trim() +} - if (start > 0) { - prefix = str.slice(0, start); - str = str.slice(start); - lastIndex -= start; +const testSet = (set, version, options) => { + for (let i = 0; i < set.length; i++) { + if (!set[i].test(version)) { + return false + } } - if (base && isGlob === true && lastIndex > 0) { - base = str.slice(0, lastIndex); - glob = str.slice(lastIndex); - } else if (isGlob === true) { - base = ''; - glob = str; - } else { - base = str; - } + if (version.prerelease.length && !options.includePrerelease) { + // Find the set of versions that are allowed to have prereleases + // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 + // That should allow `1.2.3-pr.2` to pass. + // However, `1.2.4-alpha.notready` should NOT be allowed, + // even though it's within the range set by the comparators. + for (let i = 0; i < set.length; i++) { + debug(set[i].semver) + if (set[i].semver === Comparator.ANY) { + continue + } - if (base && base !== '' && base !== '/' && base !== str) { - if (isPathSeparator(base.charCodeAt(base.length - 1))) { - base = base.slice(0, -1); + if (set[i].semver.prerelease.length > 0) { + const allowed = set[i].semver + if (allowed.major === version.major && + allowed.minor === version.minor && + allowed.patch === version.patch) { + return true + } + } } + + // Version has a -pre, but it's not one of the ones we like. + return false } - if (opts.unescape === true) { - if (glob) glob = utils.removeBackslashes(glob); + return true +} - if (base && backslashes === true) { - base = utils.removeBackslashes(base); - } - } - const state = { - prefix, - input, - start, - base, - glob, - isBrace, - isBracket, - isGlob, - isExtglob, - isGlobstar, - negated, - negatedExtglob - }; +/***/ }), - if (opts.tokens === true) { - state.maxDepth = 0; - if (!isPathSeparator(code)) { - tokens.push(token); - } - state.tokens = tokens; - } +/***/ 7163: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (opts.parts === true || opts.tokens === true) { - let prevIndex; - for (let idx = 0; idx < slashes.length; idx++) { - const n = prevIndex ? prevIndex + 1 : start; - const i = slashes[idx]; - const value = input.slice(n, i); - if (opts.tokens) { - if (idx === 0 && start !== 0) { - tokens[idx].isPrefix = true; - tokens[idx].value = prefix; - } else { - tokens[idx].value = value; - } - depth(tokens[idx]); - state.maxDepth += tokens[idx].depth; - } - if (idx !== 0 || value !== '') { - parts.push(value); - } - prevIndex = i; - } - if (prevIndex && prevIndex + 1 < input.length) { - const value = input.slice(prevIndex + 1); - parts.push(value); +const debug = __nccwpck_require__(1159) +const { MAX_LENGTH, MAX_SAFE_INTEGER } = __nccwpck_require__(5101) +const { safeRe: re, t } = __nccwpck_require__(5471) - if (opts.tokens) { - tokens[tokens.length - 1].value = value; - depth(tokens[tokens.length - 1]); - state.maxDepth += tokens[tokens.length - 1].depth; +const parseOptions = __nccwpck_require__(356) +const { compareIdentifiers } = __nccwpck_require__(3348) +class SemVer { + constructor (version, options) { + options = parseOptions(options) + + if (version instanceof SemVer) { + if (version.loose === !!options.loose && + version.includePrerelease === !!options.includePrerelease) { + return version + } else { + version = version.version } + } else if (typeof version !== 'string') { + throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version}".`) } - state.slashes = slashes; - state.parts = parts; - } - - return state; -}; + if (version.length > MAX_LENGTH) { + throw new TypeError( + `version is longer than ${MAX_LENGTH} characters` + ) + } -module.exports = scan; + debug('SemVer', version, options) + this.options = options + this.loose = !!options.loose + // this isn't actually relevant for versions, but keep it so that we + // don't run into trouble passing this.options around. + this.includePrerelease = !!options.includePrerelease + const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]) -/***/ }), + if (!m) { + throw new TypeError(`Invalid Version: ${version}`) + } -/***/ 4059: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + this.raw = version + // these are actually numbers + this.major = +m[1] + this.minor = +m[2] + this.patch = +m[3] + if (this.major > MAX_SAFE_INTEGER || this.major < 0) { + throw new TypeError('Invalid major version') + } -const path = __nccwpck_require__(6928); -const win32 = process.platform === 'win32'; -const { - REGEX_BACKSLASH, - REGEX_REMOVE_BACKSLASH, - REGEX_SPECIAL_CHARS, - REGEX_SPECIAL_CHARS_GLOBAL -} = __nccwpck_require__(5595); + if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { + throw new TypeError('Invalid minor version') + } -exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val); -exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str); -exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str); -exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1'); -exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/'); + if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { + throw new TypeError('Invalid patch version') + } -exports.removeBackslashes = str => { - return str.replace(REGEX_REMOVE_BACKSLASH, match => { - return match === '\\' ? '' : match; - }); -}; + // numberify any prerelease numeric ids + if (!m[4]) { + this.prerelease = [] + } else { + this.prerelease = m[4].split('.').map((id) => { + if (/^[0-9]+$/.test(id)) { + const num = +id + if (num >= 0 && num < MAX_SAFE_INTEGER) { + return num + } + } + return id + }) + } -exports.supportsLookbehinds = () => { - const segs = process.version.slice(1).split('.').map(Number); - if (segs.length === 3 && segs[0] >= 9 || (segs[0] === 8 && segs[1] >= 10)) { - return true; + this.build = m[5] ? m[5].split('.') : [] + this.format() } - return false; -}; -exports.isWindows = options => { - if (options && typeof options.windows === 'boolean') { - return options.windows; + format () { + this.version = `${this.major}.${this.minor}.${this.patch}` + if (this.prerelease.length) { + this.version += `-${this.prerelease.join('.')}` + } + return this.version } - return win32 === true || path.sep === '\\'; -}; -exports.escapeLast = (input, char, lastIdx) => { - const idx = input.lastIndexOf(char, lastIdx); - if (idx === -1) return input; - if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1); - return `${input.slice(0, idx)}\\${input.slice(idx)}`; -}; - -exports.removePrefix = (input, state = {}) => { - let output = input; - if (output.startsWith('./')) { - output = output.slice(2); - state.prefix = './'; + toString () { + return this.version } - return output; -}; -exports.wrapOutput = (input, state = {}, options = {}) => { - const prepend = options.contains ? '' : '^'; - const append = options.contains ? '' : '$'; + compare (other) { + debug('SemVer.compare', this.version, this.options, other) + if (!(other instanceof SemVer)) { + if (typeof other === 'string' && other === this.version) { + return 0 + } + other = new SemVer(other, this.options) + } - let output = `${prepend}(?:${input})${append}`; - if (state.negated === true) { - output = `(?:^(?!${output}).*$)`; + if (other.version === this.version) { + return 0 + } + + return this.compareMain(other) || this.comparePre(other) } - return output; -}; + compareMain (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } -/***/ }), + return ( + compareIdentifiers(this.major, other.major) || + compareIdentifiers(this.minor, other.minor) || + compareIdentifiers(this.patch, other.patch) + ) + } -/***/ 5546: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + comparePre (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } -module.exports = __nccwpck_require__(7084); + // NOT having a prerelease is > having one + if (this.prerelease.length && !other.prerelease.length) { + return -1 + } else if (!this.prerelease.length && other.prerelease.length) { + return 1 + } else if (!this.prerelease.length && !other.prerelease.length) { + return 0 + } -/***/ }), - -/***/ 7084: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -var RetryOperation = __nccwpck_require__(9538); + let i = 0 + do { + const a = this.prerelease[i] + const b = other.prerelease[i] + debug('prerelease compare', i, a, b) + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) + } -exports.operation = function(options) { - var timeouts = exports.timeouts(options); - return new RetryOperation(timeouts, { - forever: options && (options.forever || options.retries === Infinity), - unref: options && options.unref, - maxRetryTime: options && options.maxRetryTime - }); -}; + compareBuild (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } -exports.timeouts = function(options) { - if (options instanceof Array) { - return [].concat(options); + let i = 0 + do { + const a = this.build[i] + const b = other.build[i] + debug('build compare', i, a, b) + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) } - var opts = { - retries: 10, - factor: 2, - minTimeout: 1 * 1000, - maxTimeout: Infinity, - randomize: false - }; - for (var key in options) { - opts[key] = options[key]; - } + // preminor will bump the version up to the next minor release, and immediately + // down to pre-release. premajor and prepatch work the same way. + inc (release, identifier, identifierBase) { + if (release.startsWith('pre')) { + if (!identifier && identifierBase === false) { + throw new Error('invalid increment argument: identifier is empty') + } + // Avoid an invalid semver results + if (identifier) { + const match = `-${identifier}`.match(this.options.loose ? re[t.PRERELEASELOOSE] : re[t.PRERELEASE]) + if (!match || match[1] !== identifier) { + throw new Error(`invalid identifier: ${identifier}`) + } + } + } - if (opts.minTimeout > opts.maxTimeout) { - throw new Error('minTimeout is greater than maxTimeout'); - } + switch (release) { + case 'premajor': + this.prerelease.length = 0 + this.patch = 0 + this.minor = 0 + this.major++ + this.inc('pre', identifier, identifierBase) + break + case 'preminor': + this.prerelease.length = 0 + this.patch = 0 + this.minor++ + this.inc('pre', identifier, identifierBase) + break + case 'prepatch': + // If this is already a prerelease, it will bump to the next version + // drop any prereleases that might already exist, since they are not + // relevant at this point. + this.prerelease.length = 0 + this.inc('patch', identifier, identifierBase) + this.inc('pre', identifier, identifierBase) + break + // If the input is a non-prerelease version, this acts the same as + // prepatch. + case 'prerelease': + if (this.prerelease.length === 0) { + this.inc('patch', identifier, identifierBase) + } + this.inc('pre', identifier, identifierBase) + break + case 'release': + if (this.prerelease.length === 0) { + throw new Error(`version ${this.raw} is not a prerelease`) + } + this.prerelease.length = 0 + break - var timeouts = []; - for (var i = 0; i < opts.retries; i++) { - timeouts.push(this.createTimeout(i, opts)); - } + case 'major': + // If this is a pre-major version, bump up to the same major version. + // Otherwise increment major. + // 1.0.0-5 bumps to 1.0.0 + // 1.1.0 bumps to 2.0.0 + if ( + this.minor !== 0 || + this.patch !== 0 || + this.prerelease.length === 0 + ) { + this.major++ + } + this.minor = 0 + this.patch = 0 + this.prerelease = [] + break + case 'minor': + // If this is a pre-minor version, bump up to the same minor version. + // Otherwise increment minor. + // 1.2.0-5 bumps to 1.2.0 + // 1.2.1 bumps to 1.3.0 + if (this.patch !== 0 || this.prerelease.length === 0) { + this.minor++ + } + this.patch = 0 + this.prerelease = [] + break + case 'patch': + // If this is not a pre-release version, it will increment the patch. + // If it is a pre-release it will bump up to the same patch version. + // 1.2.0-5 patches to 1.2.0 + // 1.2.0 patches to 1.2.1 + if (this.prerelease.length === 0) { + this.patch++ + } + this.prerelease = [] + break + // This probably shouldn't be used publicly. + // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. + case 'pre': { + const base = Number(identifierBase) ? 1 : 0 - if (options && options.forever && !timeouts.length) { - timeouts.push(this.createTimeout(i, opts)); + if (this.prerelease.length === 0) { + this.prerelease = [base] + } else { + let i = this.prerelease.length + while (--i >= 0) { + if (typeof this.prerelease[i] === 'number') { + this.prerelease[i]++ + i = -2 + } + } + if (i === -1) { + // didn't increment anything + if (identifier === this.prerelease.join('.') && identifierBase === false) { + throw new Error('invalid increment argument: identifier already exists') + } + this.prerelease.push(base) + } + } + if (identifier) { + // 1.2.0-beta.1 bumps to 1.2.0-beta.2, + // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 + let prerelease = [identifier, base] + if (identifierBase === false) { + prerelease = [identifier] + } + if (compareIdentifiers(this.prerelease[0], identifier) === 0) { + if (isNaN(this.prerelease[1])) { + this.prerelease = prerelease + } + } else { + this.prerelease = prerelease + } + } + break + } + default: + throw new Error(`invalid increment argument: ${release}`) + } + this.raw = this.format() + if (this.build.length) { + this.raw += `+${this.build.join('.')}` + } + return this } +} - // sort the array numerically ascending - timeouts.sort(function(a,b) { - return a - b; - }); +module.exports = SemVer - return timeouts; -}; -exports.createTimeout = function(attempt, opts) { - var random = (opts.randomize) - ? (Math.random() + 1) - : 1; +/***/ }), - var timeout = Math.round(random * Math.max(opts.minTimeout, 1) * Math.pow(opts.factor, attempt)); - timeout = Math.min(timeout, opts.maxTimeout); +/***/ 1799: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return timeout; -}; -exports.wrap = function(obj, options, methods) { - if (options instanceof Array) { - methods = options; - options = null; - } - if (!methods) { - methods = []; - for (var key in obj) { - if (typeof obj[key] === 'function') { - methods.push(key); - } - } - } +const parse = __nccwpck_require__(6353) +const clean = (version, options) => { + const s = parse(version.trim().replace(/^[=v]+/, ''), options) + return s ? s.version : null +} +module.exports = clean - for (var i = 0; i < methods.length; i++) { - var method = methods[i]; - var original = obj[method]; - obj[method] = function retryWrapper(original) { - var op = exports.operation(options); - var args = Array.prototype.slice.call(arguments, 1); - var callback = args.pop(); +/***/ }), - args.push(function(err) { - if (op.retry(err)) { - return; - } - if (err) { - arguments[0] = op.mainError(); - } - callback.apply(this, arguments); - }); +/***/ 8646: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - op.attempt(function() { - original.apply(obj, args); - }); - }.bind(obj, original); - obj[method].options = options; - } -}; -/***/ }), +const eq = __nccwpck_require__(5082) +const neq = __nccwpck_require__(4974) +const gt = __nccwpck_require__(6599) +const gte = __nccwpck_require__(1236) +const lt = __nccwpck_require__(3872) +const lte = __nccwpck_require__(6717) -/***/ 9538: -/***/ ((module) => { +const cmp = (a, op, b, loose) => { + switch (op) { + case '===': + if (typeof a === 'object') { + a = a.version + } + if (typeof b === 'object') { + b = b.version + } + return a === b -function RetryOperation(timeouts, options) { - // Compatibility for the old (timeouts, retryForever) signature - if (typeof options === 'boolean') { - options = { forever: options }; - } + case '!==': + if (typeof a === 'object') { + a = a.version + } + if (typeof b === 'object') { + b = b.version + } + return a !== b - this._originalTimeouts = JSON.parse(JSON.stringify(timeouts)); - this._timeouts = timeouts; - this._options = options || {}; - this._maxRetryTime = options && options.maxRetryTime || Infinity; - this._fn = null; - this._errors = []; - this._attempts = 1; - this._operationTimeout = null; - this._operationTimeoutCb = null; - this._timeout = null; - this._operationStart = null; - this._timer = null; + case '': + case '=': + case '==': + return eq(a, b, loose) - if (this._options.forever) { - this._cachedTimeouts = this._timeouts.slice(0); - } -} -module.exports = RetryOperation; + case '!=': + return neq(a, b, loose) -RetryOperation.prototype.reset = function() { - this._attempts = 1; - this._timeouts = this._originalTimeouts.slice(0); -} + case '>': + return gt(a, b, loose) -RetryOperation.prototype.stop = function() { - if (this._timeout) { - clearTimeout(this._timeout); - } - if (this._timer) { - clearTimeout(this._timer); - } + case '>=': + return gte(a, b, loose) - this._timeouts = []; - this._cachedTimeouts = null; -}; + case '<': + return lt(a, b, loose) -RetryOperation.prototype.retry = function(err) { - if (this._timeout) { - clearTimeout(this._timeout); - } + case '<=': + return lte(a, b, loose) - if (!err) { - return false; - } - var currentTime = new Date().getTime(); - if (err && currentTime - this._operationStart >= this._maxRetryTime) { - this._errors.push(err); - this._errors.unshift(new Error('RetryOperation timeout occurred')); - return false; + default: + throw new TypeError(`Invalid operator: ${op}`) } +} +module.exports = cmp - this._errors.push(err); - var timeout = this._timeouts.shift(); - if (timeout === undefined) { - if (this._cachedTimeouts) { - // retry forever, only keep last error - this._errors.splice(0, this._errors.length - 1); - timeout = this._cachedTimeouts.slice(-1); - } else { - return false; - } - } +/***/ }), - var self = this; - this._timer = setTimeout(function() { - self._attempts++; +/***/ 5385: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (self._operationTimeoutCb) { - self._timeout = setTimeout(function() { - self._operationTimeoutCb(self._attempts); - }, self._operationTimeout); - if (self._options.unref) { - self._timeout.unref(); - } - } - self._fn(self._attempts); - }, timeout); +const SemVer = __nccwpck_require__(7163) +const parse = __nccwpck_require__(6353) +const { safeRe: re, t } = __nccwpck_require__(5471) - if (this._options.unref) { - this._timer.unref(); +const coerce = (version, options) => { + if (version instanceof SemVer) { + return version } - return true; -}; + if (typeof version === 'number') { + version = String(version) + } -RetryOperation.prototype.attempt = function(fn, timeoutOps) { - this._fn = fn; + if (typeof version !== 'string') { + return null + } - if (timeoutOps) { - if (timeoutOps.timeout) { - this._operationTimeout = timeoutOps.timeout; - } - if (timeoutOps.cb) { - this._operationTimeoutCb = timeoutOps.cb; + options = options || {} + + let match = null + if (!options.rtl) { + match = version.match(options.includePrerelease ? re[t.COERCEFULL] : re[t.COERCE]) + } else { + // Find the right-most coercible string that does not share + // a terminus with a more left-ward coercible string. + // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' + // With includePrerelease option set, '1.2.3.4-rc' wants to coerce '2.3.4-rc', not '2.3.4' + // + // Walk through the string checking with a /g regexp + // Manually set the index so as to pick up overlapping matches. + // Stop when we get a match that ends at the string end, since no + // coercible string can be more right-ward without the same terminus. + const coerceRtlRegex = options.includePrerelease ? re[t.COERCERTLFULL] : re[t.COERCERTL] + let next + while ((next = coerceRtlRegex.exec(version)) && + (!match || match.index + match[0].length !== version.length) + ) { + if (!match || + next.index + next[0].length !== match.index + match[0].length) { + match = next + } + coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length } + // leave it in a clean state + coerceRtlRegex.lastIndex = -1 } - var self = this; - if (this._operationTimeoutCb) { - this._timeout = setTimeout(function() { - self._operationTimeoutCb(); - }, self._operationTimeout); + if (match === null) { + return null } - this._operationStart = new Date().getTime(); + const major = match[2] + const minor = match[3] || '0' + const patch = match[4] || '0' + const prerelease = options.includePrerelease && match[5] ? `-${match[5]}` : '' + const build = options.includePrerelease && match[6] ? `+${match[6]}` : '' - this._fn(this._attempts); -}; + return parse(`${major}.${minor}.${patch}${prerelease}${build}`, options) +} +module.exports = coerce -RetryOperation.prototype.try = function(fn) { - console.log('Using RetryOperation.try() is deprecated'); - this.attempt(fn); -}; -RetryOperation.prototype.start = function(fn) { - console.log('Using RetryOperation.start() is deprecated'); - this.attempt(fn); -}; +/***/ }), -RetryOperation.prototype.start = RetryOperation.prototype.try; +/***/ 7648: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -RetryOperation.prototype.errors = function() { - return this._errors; -}; -RetryOperation.prototype.attempts = function() { - return this._attempts; -}; -RetryOperation.prototype.mainError = function() { - if (this._errors.length === 0) { - return null; - } +const SemVer = __nccwpck_require__(7163) +const compareBuild = (a, b, loose) => { + const versionA = new SemVer(a, loose) + const versionB = new SemVer(b, loose) + return versionA.compare(versionB) || versionA.compareBuild(versionB) +} +module.exports = compareBuild - var counts = {}; - var mainError = null; - var mainErrorCount = 0; - for (var i = 0; i < this._errors.length; i++) { - var error = this._errors[i]; - var message = error.message; - var count = (counts[message] || 0) + 1; +/***/ }), - counts[message] = count; +/***/ 6874: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (count >= mainErrorCount) { - mainError = error; - mainErrorCount = count; - } - } - return mainError; -}; + +const compare = __nccwpck_require__(8469) +const compareLoose = (a, b) => compare(a, b, true) +module.exports = compareLoose /***/ }), -/***/ 9379: +/***/ 8469: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -const ANY = Symbol('SemVer ANY') -// hoisted class for cyclic dependency -class Comparator { - static get ANY () { - return ANY - } - constructor (comp, options) { - options = parseOptions(options) - if (comp instanceof Comparator) { - if (comp.loose === !!options.loose) { - return comp - } else { - comp = comp.value - } - } +const SemVer = __nccwpck_require__(7163) +const compare = (a, b, loose) => + new SemVer(a, loose).compare(new SemVer(b, loose)) - comp = comp.trim().split(/\s+/).join(' ') - debug('comparator', comp, options) - this.options = options - this.loose = !!options.loose - this.parse(comp) +module.exports = compare - if (this.semver === ANY) { - this.value = '' - } else { - this.value = this.operator + this.semver.version - } - debug('comp', this) - } +/***/ }), - parse (comp) { - const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR] - const m = comp.match(r) +/***/ 711: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (!m) { - throw new TypeError(`Invalid comparator: ${comp}`) - } - this.operator = m[1] !== undefined ? m[1] : '' - if (this.operator === '=') { - this.operator = '' - } - // if it literally is just '>' or '' then allow anything. - if (!m[2]) { - this.semver = ANY - } else { - this.semver = new SemVer(m[2], this.options.loose) - } - } +const parse = __nccwpck_require__(6353) - toString () { - return this.value +const diff = (version1, version2) => { + const v1 = parse(version1, null, true) + const v2 = parse(version2, null, true) + const comparison = v1.compare(v2) + + if (comparison === 0) { + return null } - test (version) { - debug('Comparator.test', version, this.options.loose) + const v1Higher = comparison > 0 + const highVersion = v1Higher ? v1 : v2 + const lowVersion = v1Higher ? v2 : v1 + const highHasPre = !!highVersion.prerelease.length + const lowHasPre = !!lowVersion.prerelease.length - if (this.semver === ANY || version === ANY) { - return true + if (lowHasPre && !highHasPre) { + // Going from prerelease -> no prerelease requires some special casing + + // If the low version has only a major, then it will always be a major + // Some examples: + // 1.0.0-1 -> 1.0.0 + // 1.0.0-1 -> 1.1.1 + // 1.0.0-1 -> 2.0.0 + if (!lowVersion.patch && !lowVersion.minor) { + return 'major' } - if (typeof version === 'string') { - try { - version = new SemVer(version, this.options) - } catch (er) { - return false + // If the main part has no difference + if (lowVersion.compareMain(highVersion) === 0) { + if (lowVersion.minor && !lowVersion.patch) { + return 'minor' } + return 'patch' } - - return cmp(version, this.operator, this.semver, this.options) } - intersects (comp, options) { - if (!(comp instanceof Comparator)) { - throw new TypeError('a Comparator is required') - } - - if (this.operator === '') { - if (this.value === '') { - return true - } - return new Range(comp.value, options).test(this.value) - } else if (comp.operator === '') { - if (comp.value === '') { - return true - } - return new Range(this.value, options).test(comp.semver) - } + // add the `pre` prefix if we are going to a prerelease version + const prefix = highHasPre ? 'pre' : '' - options = parseOptions(options) + if (v1.major !== v2.major) { + return prefix + 'major' + } - // Special cases where nothing can possibly be lower - if (options.includePrerelease && - (this.value === '<0.0.0-0' || comp.value === '<0.0.0-0')) { - return false - } - if (!options.includePrerelease && - (this.value.startsWith('<0.0.0') || comp.value.startsWith('<0.0.0'))) { - return false - } + if (v1.minor !== v2.minor) { + return prefix + 'minor' + } - // Same direction increasing (> or >=) - if (this.operator.startsWith('>') && comp.operator.startsWith('>')) { - return true - } - // Same direction decreasing (< or <=) - if (this.operator.startsWith('<') && comp.operator.startsWith('<')) { - return true - } - // same SemVer and both sides are inclusive (<= or >=) - if ( - (this.semver.version === comp.semver.version) && - this.operator.includes('=') && comp.operator.includes('=')) { - return true - } - // opposite directions less than - if (cmp(this.semver, '<', comp.semver, options) && - this.operator.startsWith('>') && comp.operator.startsWith('<')) { - return true - } - // opposite directions greater than - if (cmp(this.semver, '>', comp.semver, options) && - this.operator.startsWith('<') && comp.operator.startsWith('>')) { - return true - } - return false + if (v1.patch !== v2.patch) { + return prefix + 'patch' } + + // high and low are preleases + return 'prerelease' } -module.exports = Comparator +module.exports = diff + + +/***/ }), + +/***/ 5082: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + -const parseOptions = __nccwpck_require__(356) -const { safeRe: re, t } = __nccwpck_require__(5471) -const cmp = __nccwpck_require__(8646) -const debug = __nccwpck_require__(1159) -const SemVer = __nccwpck_require__(7163) -const Range = __nccwpck_require__(6782) + +const compare = __nccwpck_require__(8469) +const eq = (a, b, loose) => compare(a, b, loose) === 0 +module.exports = eq /***/ }), -/***/ 6782: +/***/ 6599: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -const SPACE_CHARACTERS = /\s+/g -// hoisted class for cyclic dependency -class Range { - constructor (range, options) { - options = parseOptions(options) - if (range instanceof Range) { - if ( - range.loose === !!options.loose && - range.includePrerelease === !!options.includePrerelease - ) { - return range - } else { - return new Range(range.raw, options) - } - } +const compare = __nccwpck_require__(8469) +const gt = (a, b, loose) => compare(a, b, loose) > 0 +module.exports = gt - if (range instanceof Comparator) { - // just put it in the set and return - this.raw = range.value - this.set = [[range]] - this.formatted = undefined - return this - } - this.options = options - this.loose = !!options.loose - this.includePrerelease = !!options.includePrerelease +/***/ }), - // First reduce all whitespace as much as possible so we do not have to rely - // on potentially slow regexes like \s*. This is then stored and used for - // future error messages as well. - this.raw = range.trim().replace(SPACE_CHARACTERS, ' ') +/***/ 1236: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // First, split on || - this.set = this.raw - .split('||') - // map the range to a 2d array of comparators - .map(r => this.parseRange(r.trim())) - // throw out any comparator lists that are empty - // this generally means that it was not a valid range, which is allowed - // in loose mode, but will still throw if the WHOLE range is invalid. - .filter(c => c.length) - if (!this.set.length) { - throw new TypeError(`Invalid SemVer Range: ${this.raw}`) - } - // if we have any that are not the null set, throw out null sets. - if (this.set.length > 1) { - // keep the first one, in case they're all null sets - const first = this.set[0] - this.set = this.set.filter(c => !isNullSet(c[0])) - if (this.set.length === 0) { - this.set = [first] - } else if (this.set.length > 1) { - // if we have any that are *, then the range is just * - for (const c of this.set) { - if (c.length === 1 && isAny(c[0])) { - this.set = [c] - break - } - } - } - } +const compare = __nccwpck_require__(8469) +const gte = (a, b, loose) => compare(a, b, loose) >= 0 +module.exports = gte - this.formatted = undefined - } - get range () { - if (this.formatted === undefined) { - this.formatted = '' - for (let i = 0; i < this.set.length; i++) { - if (i > 0) { - this.formatted += '||' - } - const comps = this.set[i] - for (let k = 0; k < comps.length; k++) { - if (k > 0) { - this.formatted += ' ' - } - this.formatted += comps[k].toString().trim() - } - } - } - return this.formatted - } +/***/ }), - format () { - return this.range +/***/ 2338: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const SemVer = __nccwpck_require__(7163) + +const inc = (version, release, options, identifier, identifierBase) => { + if (typeof (options) === 'string') { + identifierBase = identifier + identifier = options + options = undefined } - toString () { - return this.range + try { + return new SemVer( + version instanceof SemVer ? version.version : version, + options + ).inc(release, identifier, identifierBase).version + } catch (er) { + return null } +} +module.exports = inc - parseRange (range) { - // memoize range parsing for performance. - // this is a very hot path, and fully deterministic. - const memoOpts = - (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) | - (this.options.loose && FLAG_LOOSE) - const memoKey = memoOpts + ':' + range - const cached = cache.get(memoKey) - if (cached) { - return cached - } - const loose = this.options.loose - // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` - const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE] - range = range.replace(hr, hyphenReplace(this.options.includePrerelease)) - debug('hyphen replace', range) +/***/ }), - // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` - range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace) - debug('comparator trim', range) +/***/ 3872: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // `~ 1.2.3` => `~1.2.3` - range = range.replace(re[t.TILDETRIM], tildeTrimReplace) - debug('tilde trim', range) - // `^ 1.2.3` => `^1.2.3` - range = range.replace(re[t.CARETTRIM], caretTrimReplace) - debug('caret trim', range) - // At this point, the range is completely trimmed and - // ready to be split into comparators. +const compare = __nccwpck_require__(8469) +const lt = (a, b, loose) => compare(a, b, loose) < 0 +module.exports = lt - let rangeList = range - .split(' ') - .map(comp => parseComparator(comp, this.options)) - .join(' ') - .split(/\s+/) - // >=0.0.0 is equivalent to * - .map(comp => replaceGTE0(comp, this.options)) - if (loose) { - // in loose mode, throw out any that are not valid comparators - rangeList = rangeList.filter(comp => { - debug('loose invalid filter', comp, this.options) - return !!comp.match(re[t.COMPARATORLOOSE]) - }) - } - debug('range list', rangeList) +/***/ }), - // if any comparators are the null set, then replace with JUST null set - // if more than one comparator, remove any * comparators - // also, don't include the same comparator more than once - const rangeMap = new Map() - const comparators = rangeList.map(comp => new Comparator(comp, this.options)) - for (const comp of comparators) { - if (isNullSet(comp)) { - return [comp] - } - rangeMap.set(comp.value, comp) - } - if (rangeMap.size > 1 && rangeMap.has('')) { - rangeMap.delete('') - } +/***/ 6717: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - const result = [...rangeMap.values()] - cache.set(memoKey, result) - return result - } - intersects (range, options) { - if (!(range instanceof Range)) { - throw new TypeError('a Range is required') - } - return this.set.some((thisComparators) => { - return ( - isSatisfiable(thisComparators, options) && - range.set.some((rangeComparators) => { - return ( - isSatisfiable(rangeComparators, options) && - thisComparators.every((thisComparator) => { - return rangeComparators.every((rangeComparator) => { - return thisComparator.intersects(rangeComparator, options) - }) - }) - ) - }) - ) - }) - } +const compare = __nccwpck_require__(8469) +const lte = (a, b, loose) => compare(a, b, loose) <= 0 +module.exports = lte - // if ANY of the sets match ALL of its comparators, then pass - test (version) { - if (!version) { - return false - } - if (typeof version === 'string') { - try { - version = new SemVer(version, this.options) - } catch (er) { - return false - } - } +/***/ }), - for (let i = 0; i < this.set.length; i++) { - if (testSet(this.set[i], version, this.options)) { - return true - } - } - return false - } -} +/***/ 8511: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -module.exports = Range -const LRU = __nccwpck_require__(1383) -const cache = new LRU() -const parseOptions = __nccwpck_require__(356) -const Comparator = __nccwpck_require__(9379) -const debug = __nccwpck_require__(1159) const SemVer = __nccwpck_require__(7163) -const { - safeRe: re, - t, - comparatorTrimReplace, - tildeTrimReplace, - caretTrimReplace, -} = __nccwpck_require__(5471) -const { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = __nccwpck_require__(5101) +const major = (a, loose) => new SemVer(a, loose).major +module.exports = major -const isNullSet = c => c.value === '<0.0.0-0' -const isAny = c => c.value === '' -// take a set of comparators and determine whether there -// exists a version which can satisfy it -const isSatisfiable = (comparators, options) => { - let result = true - const remainingComparators = comparators.slice() - let testComparator = remainingComparators.pop() +/***/ }), - while (result && remainingComparators.length) { - result = remainingComparators.every((otherComparator) => { - return testComparator.intersects(otherComparator, options) - }) +/***/ 2603: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - testComparator = remainingComparators.pop() - } - return result -} -// comprised of xranges, tildes, stars, and gtlt's at this point. -// already replaced the hyphen ranges -// turn into a set of JUST comparators. -const parseComparator = (comp, options) => { - debug('comp', comp, options) - comp = replaceCarets(comp, options) - debug('caret', comp) - comp = replaceTildes(comp, options) - debug('tildes', comp) - comp = replaceXRanges(comp, options) - debug('xrange', comp) - comp = replaceStars(comp, options) - debug('stars', comp) - return comp -} +const SemVer = __nccwpck_require__(7163) +const minor = (a, loose) => new SemVer(a, loose).minor +module.exports = minor -const isX = id => !id || id.toLowerCase() === 'x' || id === '*' -// ~, ~> --> * (any, kinda silly) -// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0 -// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0 -// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0 -// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0 -// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0 -// ~0.0.1 --> >=0.0.1 <0.1.0-0 -const replaceTildes = (comp, options) => { - return comp - .trim() - .split(/\s+/) - .map((c) => replaceTilde(c, options)) - .join(' ') -} +/***/ }), -const replaceTilde = (comp, options) => { - const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE] - return comp.replace(r, (_, M, m, p, pr) => { - debug('tilde', comp, _, M, m, p, pr) - let ret +/***/ 4974: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (isX(M)) { - ret = '' - } else if (isX(m)) { - ret = `>=${M}.0.0 <${+M + 1}.0.0-0` - } else if (isX(p)) { - // ~1.2 == >=1.2.0 <1.3.0-0 - ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0` - } else if (pr) { - debug('replaceTilde pr', pr) - ret = `>=${M}.${m}.${p}-${pr - } <${M}.${+m + 1}.0-0` - } else { - // ~1.2.3 == >=1.2.3 <1.3.0-0 - ret = `>=${M}.${m}.${p - } <${M}.${+m + 1}.0-0` - } - debug('tilde return', ret) - return ret - }) -} -// ^ --> * (any, kinda silly) -// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0 -// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0 -// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0 -// ^1.2.3 --> >=1.2.3 <2.0.0-0 -// ^1.2.0 --> >=1.2.0 <2.0.0-0 -// ^0.0.1 --> >=0.0.1 <0.0.2-0 -// ^0.1.0 --> >=0.1.0 <0.2.0-0 -const replaceCarets = (comp, options) => { - return comp - .trim() - .split(/\s+/) - .map((c) => replaceCaret(c, options)) - .join(' ') -} +const compare = __nccwpck_require__(8469) +const neq = (a, b, loose) => compare(a, b, loose) !== 0 +module.exports = neq -const replaceCaret = (comp, options) => { - debug('caret', comp, options) - const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET] - const z = options.includePrerelease ? '-0' : '' - return comp.replace(r, (_, M, m, p, pr) => { - debug('caret', comp, _, M, m, p, pr) - let ret - if (isX(M)) { - ret = '' - } else if (isX(m)) { - ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0` - } else if (isX(p)) { - if (M === '0') { - ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0` - } else { - ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0` - } - } else if (pr) { - debug('replaceCaret pr', pr) - if (M === '0') { - if (m === '0') { - ret = `>=${M}.${m}.${p}-${pr - } <${M}.${m}.${+p + 1}-0` - } else { - ret = `>=${M}.${m}.${p}-${pr - } <${M}.${+m + 1}.0-0` - } - } else { - ret = `>=${M}.${m}.${p}-${pr - } <${+M + 1}.0.0-0` - } - } else { - debug('no pr') - if (M === '0') { - if (m === '0') { - ret = `>=${M}.${m}.${p - }${z} <${M}.${m}.${+p + 1}-0` - } else { - ret = `>=${M}.${m}.${p - }${z} <${M}.${+m + 1}.0-0` - } - } else { - ret = `>=${M}.${m}.${p - } <${+M + 1}.0.0-0` - } - } +/***/ }), - debug('caret return', ret) - return ret - }) -} +/***/ 6353: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -const replaceXRanges = (comp, options) => { - debug('replaceXRanges', comp, options) - return comp - .split(/\s+/) - .map((c) => replaceXRange(c, options)) - .join(' ') -} -const replaceXRange = (comp, options) => { - comp = comp.trim() - const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE] - return comp.replace(r, (ret, gtlt, M, m, p, pr) => { - debug('xRange', comp, ret, gtlt, M, m, p, pr) - const xM = isX(M) - const xm = xM || isX(m) - const xp = xm || isX(p) - const anyX = xp - if (gtlt === '=' && anyX) { - gtlt = '' +const SemVer = __nccwpck_require__(7163) +const parse = (version, options, throwErrors = false) => { + if (version instanceof SemVer) { + return version + } + try { + return new SemVer(version, options) + } catch (er) { + if (!throwErrors) { + return null } + throw er + } +} - // if we're including prereleases in the match, then we need - // to fix this to -0, the lowest possible prerelease value - pr = options.includePrerelease ? '-0' : '' - - if (xM) { - if (gtlt === '>' || gtlt === '<') { - // nothing is allowed - ret = '<0.0.0-0' - } else { - // nothing is forbidden - ret = '*' - } - } else if (gtlt && anyX) { - // we know patch is an x, because we have any x at all. - // replace X with 0 - if (xm) { - m = 0 - } - p = 0 - - if (gtlt === '>') { - // >1 => >=2.0.0 - // >1.2 => >=1.3.0 - gtlt = '>=' - if (xm) { - M = +M + 1 - m = 0 - p = 0 - } else { - m = +m + 1 - p = 0 - } - } else if (gtlt === '<=') { - // <=0.7.x is actually <0.8.0, since any 0.7.x should - // pass. Similarly, <=7.x is actually <8.0.0, etc. - gtlt = '<' - if (xm) { - M = +M + 1 - } else { - m = +m + 1 - } - } - - if (gtlt === '<') { - pr = '-0' - } - - ret = `${gtlt + M}.${m}.${p}${pr}` - } else if (xm) { - ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0` - } else if (xp) { - ret = `>=${M}.${m}.0${pr - } <${M}.${+m + 1}.0-0` - } +module.exports = parse - debug('xRange return', ret) - return ret - }) -} +/***/ }), -// Because * is AND-ed with everything else in the comparator, -// and '' means "any version", just remove the *s entirely. -const replaceStars = (comp, options) => { - debug('replaceStars', comp, options) - // Looseness is ignored here. star is always as loose as it gets! - return comp - .trim() - .replace(re[t.STAR], '') -} +/***/ 8756: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -const replaceGTE0 = (comp, options) => { - debug('replaceGTE0', comp, options) - return comp - .trim() - .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '') -} -// This function is passed to string.replace(re[t.HYPHENRANGE]) -// M, m, patch, prerelease, build -// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 -// 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do -// 1.2 - 3.4 => >=1.2.0 <3.5.0-0 -// TODO build? -const hyphenReplace = incPr => ($0, - from, fM, fm, fp, fpr, fb, - to, tM, tm, tp, tpr) => { - if (isX(fM)) { - from = '' - } else if (isX(fm)) { - from = `>=${fM}.0.0${incPr ? '-0' : ''}` - } else if (isX(fp)) { - from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}` - } else if (fpr) { - from = `>=${from}` - } else { - from = `>=${from}${incPr ? '-0' : ''}` - } - if (isX(tM)) { - to = '' - } else if (isX(tm)) { - to = `<${+tM + 1}.0.0-0` - } else if (isX(tp)) { - to = `<${tM}.${+tm + 1}.0-0` - } else if (tpr) { - to = `<=${tM}.${tm}.${tp}-${tpr}` - } else if (incPr) { - to = `<${tM}.${tm}.${+tp + 1}-0` - } else { - to = `<=${to}` - } +const SemVer = __nccwpck_require__(7163) +const patch = (a, loose) => new SemVer(a, loose).patch +module.exports = patch - return `${from} ${to}`.trim() -} -const testSet = (set, version, options) => { - for (let i = 0; i < set.length; i++) { - if (!set[i].test(version)) { - return false - } - } +/***/ }), - if (version.prerelease.length && !options.includePrerelease) { - // Find the set of versions that are allowed to have prereleases - // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 - // That should allow `1.2.3-pr.2` to pass. - // However, `1.2.4-alpha.notready` should NOT be allowed, - // even though it's within the range set by the comparators. - for (let i = 0; i < set.length; i++) { - debug(set[i].semver) - if (set[i].semver === Comparator.ANY) { - continue - } +/***/ 5714: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (set[i].semver.prerelease.length > 0) { - const allowed = set[i].semver - if (allowed.major === version.major && - allowed.minor === version.minor && - allowed.patch === version.patch) { - return true - } - } - } - // Version has a -pre, but it's not one of the ones we like. - return false - } - return true +const parse = __nccwpck_require__(6353) +const prerelease = (version, options) => { + const parsed = parse(version, options) + return (parsed && parsed.prerelease.length) ? parsed.prerelease : null } +module.exports = prerelease /***/ }), -/***/ 7163: +/***/ 2173: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -const debug = __nccwpck_require__(1159) -const { MAX_LENGTH, MAX_SAFE_INTEGER } = __nccwpck_require__(5101) -const { safeRe: re, t } = __nccwpck_require__(5471) -const parseOptions = __nccwpck_require__(356) -const { compareIdentifiers } = __nccwpck_require__(3348) -class SemVer { - constructor (version, options) { - options = parseOptions(options) - if (version instanceof SemVer) { - if (version.loose === !!options.loose && - version.includePrerelease === !!options.includePrerelease) { - return version - } else { - version = version.version - } - } else if (typeof version !== 'string') { - throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version}".`) - } +const compare = __nccwpck_require__(8469) +const rcompare = (a, b, loose) => compare(b, a, loose) +module.exports = rcompare - if (version.length > MAX_LENGTH) { - throw new TypeError( - `version is longer than ${MAX_LENGTH} characters` - ) - } - debug('SemVer', version, options) - this.options = options - this.loose = !!options.loose - // this isn't actually relevant for versions, but keep it so that we - // don't run into trouble passing this.options around. - this.includePrerelease = !!options.includePrerelease +/***/ }), - const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]) +/***/ 7192: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (!m) { - throw new TypeError(`Invalid Version: ${version}`) - } - this.raw = version - // these are actually numbers - this.major = +m[1] - this.minor = +m[2] - this.patch = +m[3] +const compareBuild = __nccwpck_require__(7648) +const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)) +module.exports = rsort - if (this.major > MAX_SAFE_INTEGER || this.major < 0) { - throw new TypeError('Invalid major version') - } - if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { - throw new TypeError('Invalid minor version') - } +/***/ }), - if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { - throw new TypeError('Invalid patch version') - } +/***/ 8011: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // numberify any prerelease numeric ids - if (!m[4]) { - this.prerelease = [] - } else { - this.prerelease = m[4].split('.').map((id) => { - if (/^[0-9]+$/.test(id)) { - const num = +id - if (num >= 0 && num < MAX_SAFE_INTEGER) { - return num - } - } - return id - }) - } - this.build = m[5] ? m[5].split('.') : [] - this.format() - } - format () { - this.version = `${this.major}.${this.minor}.${this.patch}` - if (this.prerelease.length) { - this.version += `-${this.prerelease.join('.')}` - } - return this.version +const Range = __nccwpck_require__(6782) +const satisfies = (version, range, options) => { + try { + range = new Range(range, options) + } catch (er) { + return false } + return range.test(version) +} +module.exports = satisfies - toString () { - return this.version - } - compare (other) { - debug('SemVer.compare', this.version, this.options, other) - if (!(other instanceof SemVer)) { - if (typeof other === 'string' && other === this.version) { - return 0 - } - other = new SemVer(other, this.options) - } +/***/ }), - if (other.version === this.version) { - return 0 - } +/***/ 9872: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return this.compareMain(other) || this.comparePre(other) - } - compareMain (other) { - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options) - } - return ( - compareIdentifiers(this.major, other.major) || - compareIdentifiers(this.minor, other.minor) || - compareIdentifiers(this.patch, other.patch) - ) - } +const compareBuild = __nccwpck_require__(7648) +const sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose)) +module.exports = sort - comparePre (other) { - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options) - } - // NOT having a prerelease is > having one - if (this.prerelease.length && !other.prerelease.length) { - return -1 - } else if (!this.prerelease.length && other.prerelease.length) { - return 1 - } else if (!this.prerelease.length && !other.prerelease.length) { - return 0 - } +/***/ }), - let i = 0 - do { - const a = this.prerelease[i] - const b = other.prerelease[i] - debug('prerelease compare', i, a, b) - if (a === undefined && b === undefined) { - return 0 - } else if (b === undefined) { - return 1 - } else if (a === undefined) { - return -1 - } else if (a === b) { - continue - } else { - return compareIdentifiers(a, b) - } - } while (++i) - } +/***/ 8780: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - compareBuild (other) { - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options) - } - let i = 0 - do { - const a = this.build[i] - const b = other.build[i] - debug('build compare', i, a, b) - if (a === undefined && b === undefined) { - return 0 - } else if (b === undefined) { - return 1 - } else if (a === undefined) { - return -1 - } else if (a === b) { - continue - } else { - return compareIdentifiers(a, b) - } - } while (++i) - } - // preminor will bump the version up to the next minor release, and immediately - // down to pre-release. premajor and prepatch work the same way. - inc (release, identifier, identifierBase) { - switch (release) { - case 'premajor': - this.prerelease.length = 0 - this.patch = 0 - this.minor = 0 - this.major++ - this.inc('pre', identifier, identifierBase) - break - case 'preminor': - this.prerelease.length = 0 - this.patch = 0 - this.minor++ - this.inc('pre', identifier, identifierBase) - break - case 'prepatch': - // If this is already a prerelease, it will bump to the next version - // drop any prereleases that might already exist, since they are not - // relevant at this point. - this.prerelease.length = 0 - this.inc('patch', identifier, identifierBase) - this.inc('pre', identifier, identifierBase) - break - // If the input is a non-prerelease version, this acts the same as - // prepatch. - case 'prerelease': - if (this.prerelease.length === 0) { - this.inc('patch', identifier, identifierBase) - } - this.inc('pre', identifier, identifierBase) - break +const parse = __nccwpck_require__(6353) +const valid = (version, options) => { + const v = parse(version, options) + return v ? v.version : null +} +module.exports = valid - case 'major': - // If this is a pre-major version, bump up to the same major version. - // Otherwise increment major. - // 1.0.0-5 bumps to 1.0.0 - // 1.1.0 bumps to 2.0.0 - if ( - this.minor !== 0 || - this.patch !== 0 || - this.prerelease.length === 0 - ) { - this.major++ - } - this.minor = 0 - this.patch = 0 - this.prerelease = [] - break - case 'minor': - // If this is a pre-minor version, bump up to the same minor version. - // Otherwise increment minor. - // 1.2.0-5 bumps to 1.2.0 - // 1.2.1 bumps to 1.3.0 - if (this.patch !== 0 || this.prerelease.length === 0) { - this.minor++ - } - this.patch = 0 - this.prerelease = [] - break - case 'patch': - // If this is not a pre-release version, it will increment the patch. - // If it is a pre-release it will bump up to the same patch version. - // 1.2.0-5 patches to 1.2.0 - // 1.2.0 patches to 1.2.1 - if (this.prerelease.length === 0) { - this.patch++ - } - this.prerelease = [] - break - // This probably shouldn't be used publicly. - // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. - case 'pre': { - const base = Number(identifierBase) ? 1 : 0 - if (!identifier && identifierBase === false) { - throw new Error('invalid increment argument: identifier is empty') - } +/***/ }), - if (this.prerelease.length === 0) { - this.prerelease = [base] - } else { - let i = this.prerelease.length - while (--i >= 0) { - if (typeof this.prerelease[i] === 'number') { - this.prerelease[i]++ - i = -2 - } - } - if (i === -1) { - // didn't increment anything - if (identifier === this.prerelease.join('.') && identifierBase === false) { - throw new Error('invalid increment argument: identifier already exists') - } - this.prerelease.push(base) - } - } - if (identifier) { - // 1.2.0-beta.1 bumps to 1.2.0-beta.2, - // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 - let prerelease = [identifier, base] - if (identifierBase === false) { - prerelease = [identifier] - } - if (compareIdentifiers(this.prerelease[0], identifier) === 0) { - if (isNaN(this.prerelease[1])) { - this.prerelease = prerelease - } - } else { - this.prerelease = prerelease - } - } - break - } - default: - throw new Error(`invalid increment argument: ${release}`) - } - this.raw = this.format() - if (this.build.length) { - this.raw += `+${this.build.join('.')}` - } - return this - } -} - -module.exports = SemVer - - -/***/ }), - -/***/ 1799: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const parse = __nccwpck_require__(6353) -const clean = (version, options) => { - const s = parse(version.trim().replace(/^[=v]+/, ''), options) - return s ? s.version : null -} -module.exports = clean - - -/***/ }), - -/***/ 8646: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const eq = __nccwpck_require__(5082) -const neq = __nccwpck_require__(4974) -const gt = __nccwpck_require__(6599) -const gte = __nccwpck_require__(1236) -const lt = __nccwpck_require__(3872) -const lte = __nccwpck_require__(6717) - -const cmp = (a, op, b, loose) => { - switch (op) { - case '===': - if (typeof a === 'object') { - a = a.version - } - if (typeof b === 'object') { - b = b.version - } - return a === b - - case '!==': - if (typeof a === 'object') { - a = a.version - } - if (typeof b === 'object') { - b = b.version - } - return a !== b - - case '': - case '=': - case '==': - return eq(a, b, loose) - - case '!=': - return neq(a, b, loose) - - case '>': - return gt(a, b, loose) - - case '>=': - return gte(a, b, loose) - - case '<': - return lt(a, b, loose) - - case '<=': - return lte(a, b, loose) - - default: - throw new TypeError(`Invalid operator: ${op}`) - } -} -module.exports = cmp - - -/***/ }), - -/***/ 5385: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const SemVer = __nccwpck_require__(7163) -const parse = __nccwpck_require__(6353) -const { safeRe: re, t } = __nccwpck_require__(5471) - -const coerce = (version, options) => { - if (version instanceof SemVer) { - return version - } - - if (typeof version === 'number') { - version = String(version) - } - - if (typeof version !== 'string') { - return null - } - - options = options || {} - - let match = null - if (!options.rtl) { - match = version.match(options.includePrerelease ? re[t.COERCEFULL] : re[t.COERCE]) - } else { - // Find the right-most coercible string that does not share - // a terminus with a more left-ward coercible string. - // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' - // With includePrerelease option set, '1.2.3.4-rc' wants to coerce '2.3.4-rc', not '2.3.4' - // - // Walk through the string checking with a /g regexp - // Manually set the index so as to pick up overlapping matches. - // Stop when we get a match that ends at the string end, since no - // coercible string can be more right-ward without the same terminus. - const coerceRtlRegex = options.includePrerelease ? re[t.COERCERTLFULL] : re[t.COERCERTL] - let next - while ((next = coerceRtlRegex.exec(version)) && - (!match || match.index + match[0].length !== version.length) - ) { - if (!match || - next.index + next[0].length !== match.index + match[0].length) { - match = next - } - coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length - } - // leave it in a clean state - coerceRtlRegex.lastIndex = -1 - } - - if (match === null) { - return null - } - - const major = match[2] - const minor = match[3] || '0' - const patch = match[4] || '0' - const prerelease = options.includePrerelease && match[5] ? `-${match[5]}` : '' - const build = options.includePrerelease && match[6] ? `+${match[6]}` : '' - - return parse(`${major}.${minor}.${patch}${prerelease}${build}`, options) -} -module.exports = coerce - - -/***/ }), - -/***/ 7648: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const SemVer = __nccwpck_require__(7163) -const compareBuild = (a, b, loose) => { - const versionA = new SemVer(a, loose) - const versionB = new SemVer(b, loose) - return versionA.compare(versionB) || versionA.compareBuild(versionB) -} -module.exports = compareBuild - - -/***/ }), - -/***/ 6874: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const compare = __nccwpck_require__(8469) -const compareLoose = (a, b) => compare(a, b, true) -module.exports = compareLoose - - -/***/ }), - -/***/ 8469: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const SemVer = __nccwpck_require__(7163) -const compare = (a, b, loose) => - new SemVer(a, loose).compare(new SemVer(b, loose)) - -module.exports = compare - - -/***/ }), - -/***/ 711: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const parse = __nccwpck_require__(6353) - -const diff = (version1, version2) => { - const v1 = parse(version1, null, true) - const v2 = parse(version2, null, true) - const comparison = v1.compare(v2) - - if (comparison === 0) { - return null - } - - const v1Higher = comparison > 0 - const highVersion = v1Higher ? v1 : v2 - const lowVersion = v1Higher ? v2 : v1 - const highHasPre = !!highVersion.prerelease.length - const lowHasPre = !!lowVersion.prerelease.length - - if (lowHasPre && !highHasPre) { - // Going from prerelease -> no prerelease requires some special casing - - // If the low version has only a major, then it will always be a major - // Some examples: - // 1.0.0-1 -> 1.0.0 - // 1.0.0-1 -> 1.1.1 - // 1.0.0-1 -> 2.0.0 - if (!lowVersion.patch && !lowVersion.minor) { - return 'major' - } - - // Otherwise it can be determined by checking the high version - - if (highVersion.patch) { - // anything higher than a patch bump would result in the wrong version - return 'patch' - } - - if (highVersion.minor) { - // anything higher than a minor bump would result in the wrong version - return 'minor' - } - - // bumping major/minor/patch all have same result - return 'major' - } - - // add the `pre` prefix if we are going to a prerelease version - const prefix = highHasPre ? 'pre' : '' - - if (v1.major !== v2.major) { - return prefix + 'major' - } - - if (v1.minor !== v2.minor) { - return prefix + 'minor' - } - - if (v1.patch !== v2.patch) { - return prefix + 'patch' - } - - // high and low are preleases - return 'prerelease' -} - -module.exports = diff - - -/***/ }), - -/***/ 5082: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const compare = __nccwpck_require__(8469) -const eq = (a, b, loose) => compare(a, b, loose) === 0 -module.exports = eq - - -/***/ }), - -/***/ 6599: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const compare = __nccwpck_require__(8469) -const gt = (a, b, loose) => compare(a, b, loose) > 0 -module.exports = gt - - -/***/ }), - -/***/ 1236: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const compare = __nccwpck_require__(8469) -const gte = (a, b, loose) => compare(a, b, loose) >= 0 -module.exports = gte - - -/***/ }), - -/***/ 2338: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const SemVer = __nccwpck_require__(7163) - -const inc = (version, release, options, identifier, identifierBase) => { - if (typeof (options) === 'string') { - identifierBase = identifier - identifier = options - options = undefined - } - - try { - return new SemVer( - version instanceof SemVer ? version.version : version, - options - ).inc(release, identifier, identifierBase).version - } catch (er) { - return null - } -} -module.exports = inc - - -/***/ }), - -/***/ 3872: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const compare = __nccwpck_require__(8469) -const lt = (a, b, loose) => compare(a, b, loose) < 0 -module.exports = lt - - -/***/ }), - -/***/ 6717: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const compare = __nccwpck_require__(8469) -const lte = (a, b, loose) => compare(a, b, loose) <= 0 -module.exports = lte - - -/***/ }), - -/***/ 8511: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const SemVer = __nccwpck_require__(7163) -const major = (a, loose) => new SemVer(a, loose).major -module.exports = major - - -/***/ }), - -/***/ 2603: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const SemVer = __nccwpck_require__(7163) -const minor = (a, loose) => new SemVer(a, loose).minor -module.exports = minor - - -/***/ }), - -/***/ 4974: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const compare = __nccwpck_require__(8469) -const neq = (a, b, loose) => compare(a, b, loose) !== 0 -module.exports = neq - - -/***/ }), - -/***/ 6353: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const SemVer = __nccwpck_require__(7163) -const parse = (version, options, throwErrors = false) => { - if (version instanceof SemVer) { - return version - } - try { - return new SemVer(version, options) - } catch (er) { - if (!throwErrors) { - return null - } - throw er - } -} - -module.exports = parse - - -/***/ }), - -/***/ 8756: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const SemVer = __nccwpck_require__(7163) -const patch = (a, loose) => new SemVer(a, loose).patch -module.exports = patch - - -/***/ }), - -/***/ 5714: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const parse = __nccwpck_require__(6353) -const prerelease = (version, options) => { - const parsed = parse(version, options) - return (parsed && parsed.prerelease.length) ? parsed.prerelease : null -} -module.exports = prerelease - - -/***/ }), - -/***/ 2173: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const compare = __nccwpck_require__(8469) -const rcompare = (a, b, loose) => compare(b, a, loose) -module.exports = rcompare - - -/***/ }), - -/***/ 7192: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const compareBuild = __nccwpck_require__(7648) -const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)) -module.exports = rsort - - -/***/ }), - -/***/ 8011: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const Range = __nccwpck_require__(6782) -const satisfies = (version, range, options) => { - try { - range = new Range(range, options) - } catch (er) { - return false - } - return range.test(version) -} -module.exports = satisfies - - -/***/ }), - -/***/ 9872: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const compareBuild = __nccwpck_require__(7648) -const sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose)) -module.exports = sort - - -/***/ }), - -/***/ 8780: +/***/ 2088: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -const parse = __nccwpck_require__(6353) -const valid = (version, options) => { - const v = parse(version, options) - return v ? v.version : null -} -module.exports = valid - -/***/ }), - -/***/ 2088: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { // just pre-load all the stuff that index.js lazily exports const internalRe = __nccwpck_require__(5471) @@ -34624,6 +31180,8 @@ module.exports = { /***/ 5101: /***/ ((module) => { + + // Note: this is the semver.org version of the spec that it implements // Not necessarily the package version of this code. const SEMVER_SPEC_VERSION = '2.0.0' @@ -34666,6 +31224,8 @@ module.exports = { /***/ 1159: /***/ ((module) => { + + const debug = ( typeof process === 'object' && process.env && @@ -34682,6 +31242,8 @@ module.exports = debug /***/ 3348: /***/ ((module) => { + + const numeric = /^[0-9]+$/ const compareIdentifiers = (a, b) => { const anum = numeric.test(a) @@ -34712,6 +31274,8 @@ module.exports = { /***/ 1383: /***/ ((module) => { + + class LRUCache { constructor () { this.max = 1000 @@ -34759,6 +31323,8 @@ module.exports = LRUCache /***/ 356: /***/ ((module) => { + + // parse out just the options we care about const looseOption = Object.freeze({ loose: true }) const emptyOpts = Object.freeze({ }) @@ -34781,6 +31347,8 @@ module.exports = parseOptions /***/ 5471: /***/ ((module, exports, __nccwpck_require__) => { + + const { MAX_SAFE_COMPONENT_LENGTH, MAX_SAFE_BUILD_LENGTH, @@ -34793,6 +31361,7 @@ exports = module.exports = {} const re = exports.re = [] const safeRe = exports.safeRe = [] const src = exports.src = [] +const safeSrc = exports.safeSrc = [] const t = exports.t = {} let R = 0 @@ -34825,6 +31394,7 @@ const createToken = (name, value, isGlobal) => { debug(name, index, value) t[name] = index src[index] = value + safeSrc[index] = safe re[index] = new RegExp(value, isGlobal ? 'g' : undefined) safeRe[index] = new RegExp(safe, isGlobal ? 'g' : undefined) } @@ -34857,12 +31427,14 @@ createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + // ## Pre-release Version Identifier // A numeric identifier, or a non-numeric identifier. +// Non-numberic identifiers include numberic identifiers but can be longer. +// Therefore non-numberic identifiers must go first. -createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER] -}|${src[t.NONNUMERICIDENTIFIER]})`) +createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NONNUMERICIDENTIFIER] +}|${src[t.NUMERICIDENTIFIER]})`) -createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE] -}|${src[t.NONNUMERICIDENTIFIER]})`) +createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NONNUMERICIDENTIFIER] +}|${src[t.NUMERICIDENTIFIERLOOSE]})`) // ## Pre-release Version // Hyphen, followed by one or more dot-separated pre-release version @@ -35005,6 +31577,8 @@ createToken('GTE0PRE', '^\\s*>=\\s*0\\.0\\.0-0\\s*$') /***/ 2276: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + // Determine if version is greater than all the versions possible in the range. const outside = __nccwpck_require__(280) const gtr = (version, range, options) => outside(version, range, '>', options) @@ -35016,6 +31590,8 @@ module.exports = gtr /***/ 3465: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + const Range = __nccwpck_require__(6782) const intersects = (r1, r2, options) => { r1 = new Range(r1, options) @@ -35030,6 +31606,8 @@ module.exports = intersects /***/ 5213: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + const outside = __nccwpck_require__(280) // Determine if version is less than all the versions possible in the range const ltr = (version, range, options) => outside(version, range, '<', options) @@ -35041,6 +31619,8 @@ module.exports = ltr /***/ 5574: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + const SemVer = __nccwpck_require__(7163) const Range = __nccwpck_require__(6782) @@ -35073,6 +31653,8 @@ module.exports = maxSatisfying /***/ 8595: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + const SemVer = __nccwpck_require__(7163) const Range = __nccwpck_require__(6782) const minSatisfying = (versions, range, options) => { @@ -35104,6 +31686,8 @@ module.exports = minSatisfying /***/ 1866: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + const SemVer = __nccwpck_require__(7163) const Range = __nccwpck_require__(6782) const gt = __nccwpck_require__(6599) @@ -35172,6 +31756,8 @@ module.exports = minVersion /***/ 280: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + const SemVer = __nccwpck_require__(7163) const Comparator = __nccwpck_require__(9379) const { ANY } = Comparator @@ -35259,6 +31845,8 @@ module.exports = outside /***/ 2028: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + // given a set of versions and a range, create a "simplified" range // that includes the same versions that the original range does // If the original range is shorter than the simplified one, return that. @@ -35313,6 +31901,8 @@ module.exports = (versions, range, options) => { /***/ 1489: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + const Range = __nccwpck_require__(6782) const Comparator = __nccwpck_require__(9379) const { ANY } = Comparator @@ -35567,6 +32157,8 @@ module.exports = subset /***/ 4750: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + const Range = __nccwpck_require__(6782) // Mostly just for testing and legacy API reasons @@ -35582,6 +32174,8 @@ module.exports = toComparators /***/ 4737: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + const Range = __nccwpck_require__(6782) const validRange = (range, options) => { try { @@ -35890,206 +32484,6 @@ toRegexRange.clearCache = () => (toRegexRange.cache = {}); module.exports = toRegexRange; -/***/ }), - -/***/ 1552: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -var punycode = __nccwpck_require__(4876); -var mappingTable = __nccwpck_require__(2472); - -var PROCESSING_OPTIONS = { - TRANSITIONAL: 0, - NONTRANSITIONAL: 1 -}; - -function normalize(str) { // fix bug in v8 - return str.split('\u0000').map(function (s) { return s.normalize('NFC'); }).join('\u0000'); -} - -function findStatus(val) { - var start = 0; - var end = mappingTable.length - 1; - - while (start <= end) { - var mid = Math.floor((start + end) / 2); - - var target = mappingTable[mid]; - if (target[0][0] <= val && target[0][1] >= val) { - return target; - } else if (target[0][0] > val) { - end = mid - 1; - } else { - start = mid + 1; - } - } - - return null; -} - -var regexAstralSymbols = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g; - -function countSymbols(string) { - return string - // replace every surrogate pair with a BMP symbol - .replace(regexAstralSymbols, '_') - // then get the length - .length; -} - -function mapChars(domain_name, useSTD3, processing_option) { - var hasError = false; - var processed = ""; - - var len = countSymbols(domain_name); - for (var i = 0; i < len; ++i) { - var codePoint = domain_name.codePointAt(i); - var status = findStatus(codePoint); - - switch (status[1]) { - case "disallowed": - hasError = true; - processed += String.fromCodePoint(codePoint); - break; - case "ignored": - break; - case "mapped": - processed += String.fromCodePoint.apply(String, status[2]); - break; - case "deviation": - if (processing_option === PROCESSING_OPTIONS.TRANSITIONAL) { - processed += String.fromCodePoint.apply(String, status[2]); - } else { - processed += String.fromCodePoint(codePoint); - } - break; - case "valid": - processed += String.fromCodePoint(codePoint); - break; - case "disallowed_STD3_mapped": - if (useSTD3) { - hasError = true; - processed += String.fromCodePoint(codePoint); - } else { - processed += String.fromCodePoint.apply(String, status[2]); - } - break; - case "disallowed_STD3_valid": - if (useSTD3) { - hasError = true; - } - - processed += String.fromCodePoint(codePoint); - break; - } - } - - return { - string: processed, - error: hasError - }; -} - -var combiningMarksRegex = /[\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08E4-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B62\u0B63\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C00-\u0C03\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0D01-\u0D03\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D82\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F\u109A-\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u180B-\u180D\u18A9\u1920-\u192B\u1930-\u193B\u19B0-\u19C0\u19C8\u19C9\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B04\u1B34-\u1B44\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BE6-\u1BF3\u1C24-\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF2-\u1CF4\u1CF8\u1CF9\u1DC0-\u1DF5\u1DFC-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA880\uA881\uA8B4-\uA8C4\uA8E0-\uA8F1\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9E5\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2D]|\uD800[\uDDFD\uDEE0\uDF76-\uDF7A]|\uD802[\uDE01-\uDE03\uDE05\uDE06\uDE0C-\uDE0F\uDE38-\uDE3A\uDE3F\uDEE5\uDEE6]|\uD804[\uDC00-\uDC02\uDC38-\uDC46\uDC7F-\uDC82\uDCB0-\uDCBA\uDD00-\uDD02\uDD27-\uDD34\uDD73\uDD80-\uDD82\uDDB3-\uDDC0\uDE2C-\uDE37\uDEDF-\uDEEA\uDF01-\uDF03\uDF3C\uDF3E-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF57\uDF62\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDCB0-\uDCC3\uDDAF-\uDDB5\uDDB8-\uDDC0\uDE30-\uDE40\uDEAB-\uDEB7]|\uD81A[\uDEF0-\uDEF4\uDF30-\uDF36]|\uD81B[\uDF51-\uDF7E\uDF8F-\uDF92]|\uD82F[\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD83A[\uDCD0-\uDCD6]|\uDB40[\uDD00-\uDDEF]/; - -function validateLabel(label, processing_option) { - if (label.substr(0, 4) === "xn--") { - label = punycode.toUnicode(label); - processing_option = PROCESSING_OPTIONS.NONTRANSITIONAL; - } - - var error = false; - - if (normalize(label) !== label || - (label[3] === "-" && label[4] === "-") || - label[0] === "-" || label[label.length - 1] === "-" || - label.indexOf(".") !== -1 || - label.search(combiningMarksRegex) === 0) { - error = true; - } - - var len = countSymbols(label); - for (var i = 0; i < len; ++i) { - var status = findStatus(label.codePointAt(i)); - if ((processing === PROCESSING_OPTIONS.TRANSITIONAL && status[1] !== "valid") || - (processing === PROCESSING_OPTIONS.NONTRANSITIONAL && - status[1] !== "valid" && status[1] !== "deviation")) { - error = true; - break; - } - } - - return { - label: label, - error: error - }; -} - -function processing(domain_name, useSTD3, processing_option) { - var result = mapChars(domain_name, useSTD3, processing_option); - result.string = normalize(result.string); - - var labels = result.string.split("."); - for (var i = 0; i < labels.length; ++i) { - try { - var validation = validateLabel(labels[i]); - labels[i] = validation.label; - result.error = result.error || validation.error; - } catch(e) { - result.error = true; - } - } - - return { - string: labels.join("."), - error: result.error - }; -} - -module.exports.toASCII = function(domain_name, useSTD3, processing_option, verifyDnsLength) { - var result = processing(domain_name, useSTD3, processing_option); - var labels = result.string.split("."); - labels = labels.map(function(l) { - try { - return punycode.toASCII(l); - } catch(e) { - result.error = true; - return l; - } - }); - - if (verifyDnsLength) { - var total = labels.slice(0, labels.length - 1).join(".").length; - if (total.length > 253 || total.length === 0) { - result.error = true; - } - - for (var i=0; i < labels.length; ++i) { - if (labels.length > 63 || labels.length === 0) { - result.error = true; - break; - } - } - } - - if (result.error) return null; - return labels.join("."); -}; - -module.exports.toUnicode = function(domain_name, useSTD3) { - var result = processing(domain_name, useSTD3, PROCESSING_OPTIONS.NONTRANSITIONAL); - - return { - domain: result.string, - error: result.error - }; -}; - -module.exports.PROCESSING_OPTIONS = PROCESSING_OPTIONS; - - /***/ }), /***/ 770: @@ -59403,1961 +55797,6 @@ function version(uuid) { } var _default = exports["default"] = version; -/***/ }), - -/***/ 7125: -/***/ ((module) => { - - - -var conversions = {}; -module.exports = conversions; - -function sign(x) { - return x < 0 ? -1 : 1; -} - -function evenRound(x) { - // Round x to the nearest integer, choosing the even integer if it lies halfway between two. - if ((x % 1) === 0.5 && (x & 1) === 0) { // [even number].5; round down (i.e. floor) - return Math.floor(x); - } else { - return Math.round(x); - } -} - -function createNumberConversion(bitLength, typeOpts) { - if (!typeOpts.unsigned) { - --bitLength; - } - const lowerBound = typeOpts.unsigned ? 0 : -Math.pow(2, bitLength); - const upperBound = Math.pow(2, bitLength) - 1; - - const moduloVal = typeOpts.moduloBitLength ? Math.pow(2, typeOpts.moduloBitLength) : Math.pow(2, bitLength); - const moduloBound = typeOpts.moduloBitLength ? Math.pow(2, typeOpts.moduloBitLength - 1) : Math.pow(2, bitLength - 1); - - return function(V, opts) { - if (!opts) opts = {}; - - let x = +V; - - if (opts.enforceRange) { - if (!Number.isFinite(x)) { - throw new TypeError("Argument is not a finite number"); - } - - x = sign(x) * Math.floor(Math.abs(x)); - if (x < lowerBound || x > upperBound) { - throw new TypeError("Argument is not in byte range"); - } - - return x; - } - - if (!isNaN(x) && opts.clamp) { - x = evenRound(x); - - if (x < lowerBound) x = lowerBound; - if (x > upperBound) x = upperBound; - return x; - } - - if (!Number.isFinite(x) || x === 0) { - return 0; - } - - x = sign(x) * Math.floor(Math.abs(x)); - x = x % moduloVal; - - if (!typeOpts.unsigned && x >= moduloBound) { - return x - moduloVal; - } else if (typeOpts.unsigned) { - if (x < 0) { - x += moduloVal; - } else if (x === -0) { // don't return negative zero - return 0; - } - } - - return x; - } -} - -conversions["void"] = function () { - return undefined; -}; - -conversions["boolean"] = function (val) { - return !!val; -}; - -conversions["byte"] = createNumberConversion(8, { unsigned: false }); -conversions["octet"] = createNumberConversion(8, { unsigned: true }); - -conversions["short"] = createNumberConversion(16, { unsigned: false }); -conversions["unsigned short"] = createNumberConversion(16, { unsigned: true }); - -conversions["long"] = createNumberConversion(32, { unsigned: false }); -conversions["unsigned long"] = createNumberConversion(32, { unsigned: true }); - -conversions["long long"] = createNumberConversion(32, { unsigned: false, moduloBitLength: 64 }); -conversions["unsigned long long"] = createNumberConversion(32, { unsigned: true, moduloBitLength: 64 }); - -conversions["double"] = function (V) { - const x = +V; - - if (!Number.isFinite(x)) { - throw new TypeError("Argument is not a finite floating-point value"); - } - - return x; -}; - -conversions["unrestricted double"] = function (V) { - const x = +V; - - if (isNaN(x)) { - throw new TypeError("Argument is NaN"); - } - - return x; -}; - -// not quite valid, but good enough for JS -conversions["float"] = conversions["double"]; -conversions["unrestricted float"] = conversions["unrestricted double"]; - -conversions["DOMString"] = function (V, opts) { - if (!opts) opts = {}; - - if (opts.treatNullAsEmptyString && V === null) { - return ""; - } - - return String(V); -}; - -conversions["ByteString"] = function (V, opts) { - const x = String(V); - let c = undefined; - for (let i = 0; (c = x.codePointAt(i)) !== undefined; ++i) { - if (c > 255) { - throw new TypeError("Argument is not a valid bytestring"); - } - } - - return x; -}; - -conversions["USVString"] = function (V) { - const S = String(V); - const n = S.length; - const U = []; - for (let i = 0; i < n; ++i) { - const c = S.charCodeAt(i); - if (c < 0xD800 || c > 0xDFFF) { - U.push(String.fromCodePoint(c)); - } else if (0xDC00 <= c && c <= 0xDFFF) { - U.push(String.fromCodePoint(0xFFFD)); - } else { - if (i === n - 1) { - U.push(String.fromCodePoint(0xFFFD)); - } else { - const d = S.charCodeAt(i + 1); - if (0xDC00 <= d && d <= 0xDFFF) { - const a = c & 0x3FF; - const b = d & 0x3FF; - U.push(String.fromCodePoint((2 << 15) + (2 << 9) * a + b)); - ++i; - } else { - U.push(String.fromCodePoint(0xFFFD)); - } - } - } - } - - return U.join(''); -}; - -conversions["Date"] = function (V, opts) { - if (!(V instanceof Date)) { - throw new TypeError("Argument is not a Date object"); - } - if (isNaN(V)) { - return undefined; - } - - return V; -}; - -conversions["RegExp"] = function (V, opts) { - if (!(V instanceof RegExp)) { - V = new RegExp(V); - } - - return V; -}; - - -/***/ }), - -/***/ 3184: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - -const usm = __nccwpck_require__(905); - -exports.implementation = class URLImpl { - constructor(constructorArgs) { - const url = constructorArgs[0]; - const base = constructorArgs[1]; - - let parsedBase = null; - if (base !== undefined) { - parsedBase = usm.basicURLParse(base); - if (parsedBase === "failure") { - throw new TypeError("Invalid base URL"); - } - } - - const parsedURL = usm.basicURLParse(url, { baseURL: parsedBase }); - if (parsedURL === "failure") { - throw new TypeError("Invalid URL"); - } - - this._url = parsedURL; - - // TODO: query stuff - } - - get href() { - return usm.serializeURL(this._url); - } - - set href(v) { - const parsedURL = usm.basicURLParse(v); - if (parsedURL === "failure") { - throw new TypeError("Invalid URL"); - } - - this._url = parsedURL; - } - - get origin() { - return usm.serializeURLOrigin(this._url); - } - - get protocol() { - return this._url.scheme + ":"; - } - - set protocol(v) { - usm.basicURLParse(v + ":", { url: this._url, stateOverride: "scheme start" }); - } - - get username() { - return this._url.username; - } - - set username(v) { - if (usm.cannotHaveAUsernamePasswordPort(this._url)) { - return; - } - - usm.setTheUsername(this._url, v); - } - - get password() { - return this._url.password; - } - - set password(v) { - if (usm.cannotHaveAUsernamePasswordPort(this._url)) { - return; - } - - usm.setThePassword(this._url, v); - } - - get host() { - const url = this._url; - - if (url.host === null) { - return ""; - } - - if (url.port === null) { - return usm.serializeHost(url.host); - } - - return usm.serializeHost(url.host) + ":" + usm.serializeInteger(url.port); - } - - set host(v) { - if (this._url.cannotBeABaseURL) { - return; - } - - usm.basicURLParse(v, { url: this._url, stateOverride: "host" }); - } - - get hostname() { - if (this._url.host === null) { - return ""; - } - - return usm.serializeHost(this._url.host); - } - - set hostname(v) { - if (this._url.cannotBeABaseURL) { - return; - } - - usm.basicURLParse(v, { url: this._url, stateOverride: "hostname" }); - } - - get port() { - if (this._url.port === null) { - return ""; - } - - return usm.serializeInteger(this._url.port); - } - - set port(v) { - if (usm.cannotHaveAUsernamePasswordPort(this._url)) { - return; - } - - if (v === "") { - this._url.port = null; - } else { - usm.basicURLParse(v, { url: this._url, stateOverride: "port" }); - } - } - - get pathname() { - if (this._url.cannotBeABaseURL) { - return this._url.path[0]; - } - - if (this._url.path.length === 0) { - return ""; - } - - return "/" + this._url.path.join("/"); - } - - set pathname(v) { - if (this._url.cannotBeABaseURL) { - return; - } - - this._url.path = []; - usm.basicURLParse(v, { url: this._url, stateOverride: "path start" }); - } - - get search() { - if (this._url.query === null || this._url.query === "") { - return ""; - } - - return "?" + this._url.query; - } - - set search(v) { - // TODO: query stuff - - const url = this._url; - - if (v === "") { - url.query = null; - return; - } - - const input = v[0] === "?" ? v.substring(1) : v; - url.query = ""; - usm.basicURLParse(input, { url, stateOverride: "query" }); - } - - get hash() { - if (this._url.fragment === null || this._url.fragment === "") { - return ""; - } - - return "#" + this._url.fragment; - } - - set hash(v) { - if (v === "") { - this._url.fragment = null; - return; - } - - const input = v[0] === "#" ? v.substring(1) : v; - this._url.fragment = ""; - usm.basicURLParse(input, { url: this._url, stateOverride: "fragment" }); - } - - toJSON() { - return this.href; - } -}; - - -/***/ }), - -/***/ 6633: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const conversions = __nccwpck_require__(7125); -const utils = __nccwpck_require__(9857); -const Impl = __nccwpck_require__(3184); - -const impl = utils.implSymbol; - -function URL(url) { - if (!this || this[impl] || !(this instanceof URL)) { - throw new TypeError("Failed to construct 'URL': Please use the 'new' operator, this DOM object constructor cannot be called as a function."); - } - if (arguments.length < 1) { - throw new TypeError("Failed to construct 'URL': 1 argument required, but only " + arguments.length + " present."); - } - const args = []; - for (let i = 0; i < arguments.length && i < 2; ++i) { - args[i] = arguments[i]; - } - args[0] = conversions["USVString"](args[0]); - if (args[1] !== undefined) { - args[1] = conversions["USVString"](args[1]); - } - - module.exports.setup(this, args); -} - -URL.prototype.toJSON = function toJSON() { - if (!this || !module.exports.is(this)) { - throw new TypeError("Illegal invocation"); - } - const args = []; - for (let i = 0; i < arguments.length && i < 0; ++i) { - args[i] = arguments[i]; - } - return this[impl].toJSON.apply(this[impl], args); -}; -Object.defineProperty(URL.prototype, "href", { - get() { - return this[impl].href; - }, - set(V) { - V = conversions["USVString"](V); - this[impl].href = V; - }, - enumerable: true, - configurable: true -}); - -URL.prototype.toString = function () { - if (!this || !module.exports.is(this)) { - throw new TypeError("Illegal invocation"); - } - return this.href; -}; - -Object.defineProperty(URL.prototype, "origin", { - get() { - return this[impl].origin; - }, - enumerable: true, - configurable: true -}); - -Object.defineProperty(URL.prototype, "protocol", { - get() { - return this[impl].protocol; - }, - set(V) { - V = conversions["USVString"](V); - this[impl].protocol = V; - }, - enumerable: true, - configurable: true -}); - -Object.defineProperty(URL.prototype, "username", { - get() { - return this[impl].username; - }, - set(V) { - V = conversions["USVString"](V); - this[impl].username = V; - }, - enumerable: true, - configurable: true -}); - -Object.defineProperty(URL.prototype, "password", { - get() { - return this[impl].password; - }, - set(V) { - V = conversions["USVString"](V); - this[impl].password = V; - }, - enumerable: true, - configurable: true -}); - -Object.defineProperty(URL.prototype, "host", { - get() { - return this[impl].host; - }, - set(V) { - V = conversions["USVString"](V); - this[impl].host = V; - }, - enumerable: true, - configurable: true -}); - -Object.defineProperty(URL.prototype, "hostname", { - get() { - return this[impl].hostname; - }, - set(V) { - V = conversions["USVString"](V); - this[impl].hostname = V; - }, - enumerable: true, - configurable: true -}); - -Object.defineProperty(URL.prototype, "port", { - get() { - return this[impl].port; - }, - set(V) { - V = conversions["USVString"](V); - this[impl].port = V; - }, - enumerable: true, - configurable: true -}); - -Object.defineProperty(URL.prototype, "pathname", { - get() { - return this[impl].pathname; - }, - set(V) { - V = conversions["USVString"](V); - this[impl].pathname = V; - }, - enumerable: true, - configurable: true -}); - -Object.defineProperty(URL.prototype, "search", { - get() { - return this[impl].search; - }, - set(V) { - V = conversions["USVString"](V); - this[impl].search = V; - }, - enumerable: true, - configurable: true -}); - -Object.defineProperty(URL.prototype, "hash", { - get() { - return this[impl].hash; - }, - set(V) { - V = conversions["USVString"](V); - this[impl].hash = V; - }, - enumerable: true, - configurable: true -}); - - -module.exports = { - is(obj) { - return !!obj && obj[impl] instanceof Impl.implementation; - }, - create(constructorArgs, privateData) { - let obj = Object.create(URL.prototype); - this.setup(obj, constructorArgs, privateData); - return obj; - }, - setup(obj, constructorArgs, privateData) { - if (!privateData) privateData = {}; - privateData.wrapper = obj; - - obj[impl] = new Impl.implementation(constructorArgs, privateData); - obj[impl][utils.wrapperSymbol] = obj; - }, - interface: URL, - expose: { - Window: { URL: URL }, - Worker: { URL: URL } - } -}; - - - -/***/ }), - -/***/ 2686: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -exports.URL = __nccwpck_require__(6633)["interface"]; -exports.serializeURL = __nccwpck_require__(905).serializeURL; -exports.serializeURLOrigin = __nccwpck_require__(905).serializeURLOrigin; -exports.basicURLParse = __nccwpck_require__(905).basicURLParse; -exports.setTheUsername = __nccwpck_require__(905).setTheUsername; -exports.setThePassword = __nccwpck_require__(905).setThePassword; -exports.serializeHost = __nccwpck_require__(905).serializeHost; -exports.serializeInteger = __nccwpck_require__(905).serializeInteger; -exports.parseURL = __nccwpck_require__(905).parseURL; - - -/***/ }), - -/***/ 905: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - -const punycode = __nccwpck_require__(4876); -const tr46 = __nccwpck_require__(1552); - -const specialSchemes = { - ftp: 21, - file: null, - gopher: 70, - http: 80, - https: 443, - ws: 80, - wss: 443 -}; - -const failure = Symbol("failure"); - -function countSymbols(str) { - return punycode.ucs2.decode(str).length; -} - -function at(input, idx) { - const c = input[idx]; - return isNaN(c) ? undefined : String.fromCodePoint(c); -} - -function isASCIIDigit(c) { - return c >= 0x30 && c <= 0x39; -} - -function isASCIIAlpha(c) { - return (c >= 0x41 && c <= 0x5A) || (c >= 0x61 && c <= 0x7A); -} - -function isASCIIAlphanumeric(c) { - return isASCIIAlpha(c) || isASCIIDigit(c); -} - -function isASCIIHex(c) { - return isASCIIDigit(c) || (c >= 0x41 && c <= 0x46) || (c >= 0x61 && c <= 0x66); -} - -function isSingleDot(buffer) { - return buffer === "." || buffer.toLowerCase() === "%2e"; -} - -function isDoubleDot(buffer) { - buffer = buffer.toLowerCase(); - return buffer === ".." || buffer === "%2e." || buffer === ".%2e" || buffer === "%2e%2e"; -} - -function isWindowsDriveLetterCodePoints(cp1, cp2) { - return isASCIIAlpha(cp1) && (cp2 === 58 || cp2 === 124); -} - -function isWindowsDriveLetterString(string) { - return string.length === 2 && isASCIIAlpha(string.codePointAt(0)) && (string[1] === ":" || string[1] === "|"); -} - -function isNormalizedWindowsDriveLetterString(string) { - return string.length === 2 && isASCIIAlpha(string.codePointAt(0)) && string[1] === ":"; -} - -function containsForbiddenHostCodePoint(string) { - return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|%|\/|:|\?|@|\[|\\|\]/) !== -1; -} - -function containsForbiddenHostCodePointExcludingPercent(string) { - return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|\/|:|\?|@|\[|\\|\]/) !== -1; -} - -function isSpecialScheme(scheme) { - return specialSchemes[scheme] !== undefined; -} - -function isSpecial(url) { - return isSpecialScheme(url.scheme); -} - -function defaultPort(scheme) { - return specialSchemes[scheme]; -} - -function percentEncode(c) { - let hex = c.toString(16).toUpperCase(); - if (hex.length === 1) { - hex = "0" + hex; - } - - return "%" + hex; -} - -function utf8PercentEncode(c) { - const buf = new Buffer(c); - - let str = ""; - - for (let i = 0; i < buf.length; ++i) { - str += percentEncode(buf[i]); - } - - return str; -} - -function utf8PercentDecode(str) { - const input = new Buffer(str); - const output = []; - for (let i = 0; i < input.length; ++i) { - if (input[i] !== 37) { - output.push(input[i]); - } else if (input[i] === 37 && isASCIIHex(input[i + 1]) && isASCIIHex(input[i + 2])) { - output.push(parseInt(input.slice(i + 1, i + 3).toString(), 16)); - i += 2; - } else { - output.push(input[i]); - } - } - return new Buffer(output).toString(); -} - -function isC0ControlPercentEncode(c) { - return c <= 0x1F || c > 0x7E; -} - -const extraPathPercentEncodeSet = new Set([32, 34, 35, 60, 62, 63, 96, 123, 125]); -function isPathPercentEncode(c) { - return isC0ControlPercentEncode(c) || extraPathPercentEncodeSet.has(c); -} - -const extraUserinfoPercentEncodeSet = - new Set([47, 58, 59, 61, 64, 91, 92, 93, 94, 124]); -function isUserinfoPercentEncode(c) { - return isPathPercentEncode(c) || extraUserinfoPercentEncodeSet.has(c); -} - -function percentEncodeChar(c, encodeSetPredicate) { - const cStr = String.fromCodePoint(c); - - if (encodeSetPredicate(c)) { - return utf8PercentEncode(cStr); - } - - return cStr; -} - -function parseIPv4Number(input) { - let R = 10; - - if (input.length >= 2 && input.charAt(0) === "0" && input.charAt(1).toLowerCase() === "x") { - input = input.substring(2); - R = 16; - } else if (input.length >= 2 && input.charAt(0) === "0") { - input = input.substring(1); - R = 8; - } - - if (input === "") { - return 0; - } - - const regex = R === 10 ? /[^0-9]/ : (R === 16 ? /[^0-9A-Fa-f]/ : /[^0-7]/); - if (regex.test(input)) { - return failure; - } - - return parseInt(input, R); -} - -function parseIPv4(input) { - const parts = input.split("."); - if (parts[parts.length - 1] === "") { - if (parts.length > 1) { - parts.pop(); - } - } - - if (parts.length > 4) { - return input; - } - - const numbers = []; - for (const part of parts) { - if (part === "") { - return input; - } - const n = parseIPv4Number(part); - if (n === failure) { - return input; - } - - numbers.push(n); - } - - for (let i = 0; i < numbers.length - 1; ++i) { - if (numbers[i] > 255) { - return failure; - } - } - if (numbers[numbers.length - 1] >= Math.pow(256, 5 - numbers.length)) { - return failure; - } - - let ipv4 = numbers.pop(); - let counter = 0; - - for (const n of numbers) { - ipv4 += n * Math.pow(256, 3 - counter); - ++counter; - } - - return ipv4; -} - -function serializeIPv4(address) { - let output = ""; - let n = address; - - for (let i = 1; i <= 4; ++i) { - output = String(n % 256) + output; - if (i !== 4) { - output = "." + output; - } - n = Math.floor(n / 256); - } - - return output; -} - -function parseIPv6(input) { - const address = [0, 0, 0, 0, 0, 0, 0, 0]; - let pieceIndex = 0; - let compress = null; - let pointer = 0; - - input = punycode.ucs2.decode(input); - - if (input[pointer] === 58) { - if (input[pointer + 1] !== 58) { - return failure; - } - - pointer += 2; - ++pieceIndex; - compress = pieceIndex; - } - - while (pointer < input.length) { - if (pieceIndex === 8) { - return failure; - } - - if (input[pointer] === 58) { - if (compress !== null) { - return failure; - } - ++pointer; - ++pieceIndex; - compress = pieceIndex; - continue; - } - - let value = 0; - let length = 0; - - while (length < 4 && isASCIIHex(input[pointer])) { - value = value * 0x10 + parseInt(at(input, pointer), 16); - ++pointer; - ++length; - } - - if (input[pointer] === 46) { - if (length === 0) { - return failure; - } - - pointer -= length; - - if (pieceIndex > 6) { - return failure; - } - - let numbersSeen = 0; - - while (input[pointer] !== undefined) { - let ipv4Piece = null; - - if (numbersSeen > 0) { - if (input[pointer] === 46 && numbersSeen < 4) { - ++pointer; - } else { - return failure; - } - } - - if (!isASCIIDigit(input[pointer])) { - return failure; - } - - while (isASCIIDigit(input[pointer])) { - const number = parseInt(at(input, pointer)); - if (ipv4Piece === null) { - ipv4Piece = number; - } else if (ipv4Piece === 0) { - return failure; - } else { - ipv4Piece = ipv4Piece * 10 + number; - } - if (ipv4Piece > 255) { - return failure; - } - ++pointer; - } - - address[pieceIndex] = address[pieceIndex] * 0x100 + ipv4Piece; - - ++numbersSeen; - - if (numbersSeen === 2 || numbersSeen === 4) { - ++pieceIndex; - } - } - - if (numbersSeen !== 4) { - return failure; - } - - break; - } else if (input[pointer] === 58) { - ++pointer; - if (input[pointer] === undefined) { - return failure; - } - } else if (input[pointer] !== undefined) { - return failure; - } - - address[pieceIndex] = value; - ++pieceIndex; - } - - if (compress !== null) { - let swaps = pieceIndex - compress; - pieceIndex = 7; - while (pieceIndex !== 0 && swaps > 0) { - const temp = address[compress + swaps - 1]; - address[compress + swaps - 1] = address[pieceIndex]; - address[pieceIndex] = temp; - --pieceIndex; - --swaps; - } - } else if (compress === null && pieceIndex !== 8) { - return failure; - } - - return address; -} - -function serializeIPv6(address) { - let output = ""; - const seqResult = findLongestZeroSequence(address); - const compress = seqResult.idx; - let ignore0 = false; - - for (let pieceIndex = 0; pieceIndex <= 7; ++pieceIndex) { - if (ignore0 && address[pieceIndex] === 0) { - continue; - } else if (ignore0) { - ignore0 = false; - } - - if (compress === pieceIndex) { - const separator = pieceIndex === 0 ? "::" : ":"; - output += separator; - ignore0 = true; - continue; - } - - output += address[pieceIndex].toString(16); - - if (pieceIndex !== 7) { - output += ":"; - } - } - - return output; -} - -function parseHost(input, isSpecialArg) { - if (input[0] === "[") { - if (input[input.length - 1] !== "]") { - return failure; - } - - return parseIPv6(input.substring(1, input.length - 1)); - } - - if (!isSpecialArg) { - return parseOpaqueHost(input); - } - - const domain = utf8PercentDecode(input); - const asciiDomain = tr46.toASCII(domain, false, tr46.PROCESSING_OPTIONS.NONTRANSITIONAL, false); - if (asciiDomain === null) { - return failure; - } - - if (containsForbiddenHostCodePoint(asciiDomain)) { - return failure; - } - - const ipv4Host = parseIPv4(asciiDomain); - if (typeof ipv4Host === "number" || ipv4Host === failure) { - return ipv4Host; - } - - return asciiDomain; -} - -function parseOpaqueHost(input) { - if (containsForbiddenHostCodePointExcludingPercent(input)) { - return failure; - } - - let output = ""; - const decoded = punycode.ucs2.decode(input); - for (let i = 0; i < decoded.length; ++i) { - output += percentEncodeChar(decoded[i], isC0ControlPercentEncode); - } - return output; -} - -function findLongestZeroSequence(arr) { - let maxIdx = null; - let maxLen = 1; // only find elements > 1 - let currStart = null; - let currLen = 0; - - for (let i = 0; i < arr.length; ++i) { - if (arr[i] !== 0) { - if (currLen > maxLen) { - maxIdx = currStart; - maxLen = currLen; - } - - currStart = null; - currLen = 0; - } else { - if (currStart === null) { - currStart = i; - } - ++currLen; - } - } - - // if trailing zeros - if (currLen > maxLen) { - maxIdx = currStart; - maxLen = currLen; - } - - return { - idx: maxIdx, - len: maxLen - }; -} - -function serializeHost(host) { - if (typeof host === "number") { - return serializeIPv4(host); - } - - // IPv6 serializer - if (host instanceof Array) { - return "[" + serializeIPv6(host) + "]"; - } - - return host; -} - -function trimControlChars(url) { - return url.replace(/^[\u0000-\u001F\u0020]+|[\u0000-\u001F\u0020]+$/g, ""); -} - -function trimTabAndNewline(url) { - return url.replace(/\u0009|\u000A|\u000D/g, ""); -} - -function shortenPath(url) { - const path = url.path; - if (path.length === 0) { - return; - } - if (url.scheme === "file" && path.length === 1 && isNormalizedWindowsDriveLetter(path[0])) { - return; - } - - path.pop(); -} - -function includesCredentials(url) { - return url.username !== "" || url.password !== ""; -} - -function cannotHaveAUsernamePasswordPort(url) { - return url.host === null || url.host === "" || url.cannotBeABaseURL || url.scheme === "file"; -} - -function isNormalizedWindowsDriveLetter(string) { - return /^[A-Za-z]:$/.test(string); -} - -function URLStateMachine(input, base, encodingOverride, url, stateOverride) { - this.pointer = 0; - this.input = input; - this.base = base || null; - this.encodingOverride = encodingOverride || "utf-8"; - this.stateOverride = stateOverride; - this.url = url; - this.failure = false; - this.parseError = false; - - if (!this.url) { - this.url = { - scheme: "", - username: "", - password: "", - host: null, - port: null, - path: [], - query: null, - fragment: null, - - cannotBeABaseURL: false - }; - - const res = trimControlChars(this.input); - if (res !== this.input) { - this.parseError = true; - } - this.input = res; - } - - const res = trimTabAndNewline(this.input); - if (res !== this.input) { - this.parseError = true; - } - this.input = res; - - this.state = stateOverride || "scheme start"; - - this.buffer = ""; - this.atFlag = false; - this.arrFlag = false; - this.passwordTokenSeenFlag = false; - - this.input = punycode.ucs2.decode(this.input); - - for (; this.pointer <= this.input.length; ++this.pointer) { - const c = this.input[this.pointer]; - const cStr = isNaN(c) ? undefined : String.fromCodePoint(c); - - // exec state machine - const ret = this["parse " + this.state](c, cStr); - if (!ret) { - break; // terminate algorithm - } else if (ret === failure) { - this.failure = true; - break; - } - } -} - -URLStateMachine.prototype["parse scheme start"] = function parseSchemeStart(c, cStr) { - if (isASCIIAlpha(c)) { - this.buffer += cStr.toLowerCase(); - this.state = "scheme"; - } else if (!this.stateOverride) { - this.state = "no scheme"; - --this.pointer; - } else { - this.parseError = true; - return failure; - } - - return true; -}; - -URLStateMachine.prototype["parse scheme"] = function parseScheme(c, cStr) { - if (isASCIIAlphanumeric(c) || c === 43 || c === 45 || c === 46) { - this.buffer += cStr.toLowerCase(); - } else if (c === 58) { - if (this.stateOverride) { - if (isSpecial(this.url) && !isSpecialScheme(this.buffer)) { - return false; - } - - if (!isSpecial(this.url) && isSpecialScheme(this.buffer)) { - return false; - } - - if ((includesCredentials(this.url) || this.url.port !== null) && this.buffer === "file") { - return false; - } - - if (this.url.scheme === "file" && (this.url.host === "" || this.url.host === null)) { - return false; - } - } - this.url.scheme = this.buffer; - this.buffer = ""; - if (this.stateOverride) { - return false; - } - if (this.url.scheme === "file") { - if (this.input[this.pointer + 1] !== 47 || this.input[this.pointer + 2] !== 47) { - this.parseError = true; - } - this.state = "file"; - } else if (isSpecial(this.url) && this.base !== null && this.base.scheme === this.url.scheme) { - this.state = "special relative or authority"; - } else if (isSpecial(this.url)) { - this.state = "special authority slashes"; - } else if (this.input[this.pointer + 1] === 47) { - this.state = "path or authority"; - ++this.pointer; - } else { - this.url.cannotBeABaseURL = true; - this.url.path.push(""); - this.state = "cannot-be-a-base-URL path"; - } - } else if (!this.stateOverride) { - this.buffer = ""; - this.state = "no scheme"; - this.pointer = -1; - } else { - this.parseError = true; - return failure; - } - - return true; -}; - -URLStateMachine.prototype["parse no scheme"] = function parseNoScheme(c) { - if (this.base === null || (this.base.cannotBeABaseURL && c !== 35)) { - return failure; - } else if (this.base.cannotBeABaseURL && c === 35) { - this.url.scheme = this.base.scheme; - this.url.path = this.base.path.slice(); - this.url.query = this.base.query; - this.url.fragment = ""; - this.url.cannotBeABaseURL = true; - this.state = "fragment"; - } else if (this.base.scheme === "file") { - this.state = "file"; - --this.pointer; - } else { - this.state = "relative"; - --this.pointer; - } - - return true; -}; - -URLStateMachine.prototype["parse special relative or authority"] = function parseSpecialRelativeOrAuthority(c) { - if (c === 47 && this.input[this.pointer + 1] === 47) { - this.state = "special authority ignore slashes"; - ++this.pointer; - } else { - this.parseError = true; - this.state = "relative"; - --this.pointer; - } - - return true; -}; - -URLStateMachine.prototype["parse path or authority"] = function parsePathOrAuthority(c) { - if (c === 47) { - this.state = "authority"; - } else { - this.state = "path"; - --this.pointer; - } - - return true; -}; - -URLStateMachine.prototype["parse relative"] = function parseRelative(c) { - this.url.scheme = this.base.scheme; - if (isNaN(c)) { - this.url.username = this.base.username; - this.url.password = this.base.password; - this.url.host = this.base.host; - this.url.port = this.base.port; - this.url.path = this.base.path.slice(); - this.url.query = this.base.query; - } else if (c === 47) { - this.state = "relative slash"; - } else if (c === 63) { - this.url.username = this.base.username; - this.url.password = this.base.password; - this.url.host = this.base.host; - this.url.port = this.base.port; - this.url.path = this.base.path.slice(); - this.url.query = ""; - this.state = "query"; - } else if (c === 35) { - this.url.username = this.base.username; - this.url.password = this.base.password; - this.url.host = this.base.host; - this.url.port = this.base.port; - this.url.path = this.base.path.slice(); - this.url.query = this.base.query; - this.url.fragment = ""; - this.state = "fragment"; - } else if (isSpecial(this.url) && c === 92) { - this.parseError = true; - this.state = "relative slash"; - } else { - this.url.username = this.base.username; - this.url.password = this.base.password; - this.url.host = this.base.host; - this.url.port = this.base.port; - this.url.path = this.base.path.slice(0, this.base.path.length - 1); - - this.state = "path"; - --this.pointer; - } - - return true; -}; - -URLStateMachine.prototype["parse relative slash"] = function parseRelativeSlash(c) { - if (isSpecial(this.url) && (c === 47 || c === 92)) { - if (c === 92) { - this.parseError = true; - } - this.state = "special authority ignore slashes"; - } else if (c === 47) { - this.state = "authority"; - } else { - this.url.username = this.base.username; - this.url.password = this.base.password; - this.url.host = this.base.host; - this.url.port = this.base.port; - this.state = "path"; - --this.pointer; - } - - return true; -}; - -URLStateMachine.prototype["parse special authority slashes"] = function parseSpecialAuthoritySlashes(c) { - if (c === 47 && this.input[this.pointer + 1] === 47) { - this.state = "special authority ignore slashes"; - ++this.pointer; - } else { - this.parseError = true; - this.state = "special authority ignore slashes"; - --this.pointer; - } - - return true; -}; - -URLStateMachine.prototype["parse special authority ignore slashes"] = function parseSpecialAuthorityIgnoreSlashes(c) { - if (c !== 47 && c !== 92) { - this.state = "authority"; - --this.pointer; - } else { - this.parseError = true; - } - - return true; -}; - -URLStateMachine.prototype["parse authority"] = function parseAuthority(c, cStr) { - if (c === 64) { - this.parseError = true; - if (this.atFlag) { - this.buffer = "%40" + this.buffer; - } - this.atFlag = true; - - // careful, this is based on buffer and has its own pointer (this.pointer != pointer) and inner chars - const len = countSymbols(this.buffer); - for (let pointer = 0; pointer < len; ++pointer) { - const codePoint = this.buffer.codePointAt(pointer); - - if (codePoint === 58 && !this.passwordTokenSeenFlag) { - this.passwordTokenSeenFlag = true; - continue; - } - const encodedCodePoints = percentEncodeChar(codePoint, isUserinfoPercentEncode); - if (this.passwordTokenSeenFlag) { - this.url.password += encodedCodePoints; - } else { - this.url.username += encodedCodePoints; - } - } - this.buffer = ""; - } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || - (isSpecial(this.url) && c === 92)) { - if (this.atFlag && this.buffer === "") { - this.parseError = true; - return failure; - } - this.pointer -= countSymbols(this.buffer) + 1; - this.buffer = ""; - this.state = "host"; - } else { - this.buffer += cStr; - } - - return true; -}; - -URLStateMachine.prototype["parse hostname"] = -URLStateMachine.prototype["parse host"] = function parseHostName(c, cStr) { - if (this.stateOverride && this.url.scheme === "file") { - --this.pointer; - this.state = "file host"; - } else if (c === 58 && !this.arrFlag) { - if (this.buffer === "") { - this.parseError = true; - return failure; - } - - const host = parseHost(this.buffer, isSpecial(this.url)); - if (host === failure) { - return failure; - } - - this.url.host = host; - this.buffer = ""; - this.state = "port"; - if (this.stateOverride === "hostname") { - return false; - } - } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || - (isSpecial(this.url) && c === 92)) { - --this.pointer; - if (isSpecial(this.url) && this.buffer === "") { - this.parseError = true; - return failure; - } else if (this.stateOverride && this.buffer === "" && - (includesCredentials(this.url) || this.url.port !== null)) { - this.parseError = true; - return false; - } - - const host = parseHost(this.buffer, isSpecial(this.url)); - if (host === failure) { - return failure; - } - - this.url.host = host; - this.buffer = ""; - this.state = "path start"; - if (this.stateOverride) { - return false; - } - } else { - if (c === 91) { - this.arrFlag = true; - } else if (c === 93) { - this.arrFlag = false; - } - this.buffer += cStr; - } - - return true; -}; - -URLStateMachine.prototype["parse port"] = function parsePort(c, cStr) { - if (isASCIIDigit(c)) { - this.buffer += cStr; - } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || - (isSpecial(this.url) && c === 92) || - this.stateOverride) { - if (this.buffer !== "") { - const port = parseInt(this.buffer); - if (port > Math.pow(2, 16) - 1) { - this.parseError = true; - return failure; - } - this.url.port = port === defaultPort(this.url.scheme) ? null : port; - this.buffer = ""; - } - if (this.stateOverride) { - return false; - } - this.state = "path start"; - --this.pointer; - } else { - this.parseError = true; - return failure; - } - - return true; -}; - -const fileOtherwiseCodePoints = new Set([47, 92, 63, 35]); - -URLStateMachine.prototype["parse file"] = function parseFile(c) { - this.url.scheme = "file"; - - if (c === 47 || c === 92) { - if (c === 92) { - this.parseError = true; - } - this.state = "file slash"; - } else if (this.base !== null && this.base.scheme === "file") { - if (isNaN(c)) { - this.url.host = this.base.host; - this.url.path = this.base.path.slice(); - this.url.query = this.base.query; - } else if (c === 63) { - this.url.host = this.base.host; - this.url.path = this.base.path.slice(); - this.url.query = ""; - this.state = "query"; - } else if (c === 35) { - this.url.host = this.base.host; - this.url.path = this.base.path.slice(); - this.url.query = this.base.query; - this.url.fragment = ""; - this.state = "fragment"; - } else { - if (this.input.length - this.pointer - 1 === 0 || // remaining consists of 0 code points - !isWindowsDriveLetterCodePoints(c, this.input[this.pointer + 1]) || - (this.input.length - this.pointer - 1 >= 2 && // remaining has at least 2 code points - !fileOtherwiseCodePoints.has(this.input[this.pointer + 2]))) { - this.url.host = this.base.host; - this.url.path = this.base.path.slice(); - shortenPath(this.url); - } else { - this.parseError = true; - } - - this.state = "path"; - --this.pointer; - } - } else { - this.state = "path"; - --this.pointer; - } - - return true; -}; - -URLStateMachine.prototype["parse file slash"] = function parseFileSlash(c) { - if (c === 47 || c === 92) { - if (c === 92) { - this.parseError = true; - } - this.state = "file host"; - } else { - if (this.base !== null && this.base.scheme === "file") { - if (isNormalizedWindowsDriveLetterString(this.base.path[0])) { - this.url.path.push(this.base.path[0]); - } else { - this.url.host = this.base.host; - } - } - this.state = "path"; - --this.pointer; - } - - return true; -}; - -URLStateMachine.prototype["parse file host"] = function parseFileHost(c, cStr) { - if (isNaN(c) || c === 47 || c === 92 || c === 63 || c === 35) { - --this.pointer; - if (!this.stateOverride && isWindowsDriveLetterString(this.buffer)) { - this.parseError = true; - this.state = "path"; - } else if (this.buffer === "") { - this.url.host = ""; - if (this.stateOverride) { - return false; - } - this.state = "path start"; - } else { - let host = parseHost(this.buffer, isSpecial(this.url)); - if (host === failure) { - return failure; - } - if (host === "localhost") { - host = ""; - } - this.url.host = host; - - if (this.stateOverride) { - return false; - } - - this.buffer = ""; - this.state = "path start"; - } - } else { - this.buffer += cStr; - } - - return true; -}; - -URLStateMachine.prototype["parse path start"] = function parsePathStart(c) { - if (isSpecial(this.url)) { - if (c === 92) { - this.parseError = true; - } - this.state = "path"; - - if (c !== 47 && c !== 92) { - --this.pointer; - } - } else if (!this.stateOverride && c === 63) { - this.url.query = ""; - this.state = "query"; - } else if (!this.stateOverride && c === 35) { - this.url.fragment = ""; - this.state = "fragment"; - } else if (c !== undefined) { - this.state = "path"; - if (c !== 47) { - --this.pointer; - } - } - - return true; -}; - -URLStateMachine.prototype["parse path"] = function parsePath(c) { - if (isNaN(c) || c === 47 || (isSpecial(this.url) && c === 92) || - (!this.stateOverride && (c === 63 || c === 35))) { - if (isSpecial(this.url) && c === 92) { - this.parseError = true; - } - - if (isDoubleDot(this.buffer)) { - shortenPath(this.url); - if (c !== 47 && !(isSpecial(this.url) && c === 92)) { - this.url.path.push(""); - } - } else if (isSingleDot(this.buffer) && c !== 47 && - !(isSpecial(this.url) && c === 92)) { - this.url.path.push(""); - } else if (!isSingleDot(this.buffer)) { - if (this.url.scheme === "file" && this.url.path.length === 0 && isWindowsDriveLetterString(this.buffer)) { - if (this.url.host !== "" && this.url.host !== null) { - this.parseError = true; - this.url.host = ""; - } - this.buffer = this.buffer[0] + ":"; - } - this.url.path.push(this.buffer); - } - this.buffer = ""; - if (this.url.scheme === "file" && (c === undefined || c === 63 || c === 35)) { - while (this.url.path.length > 1 && this.url.path[0] === "") { - this.parseError = true; - this.url.path.shift(); - } - } - if (c === 63) { - this.url.query = ""; - this.state = "query"; - } - if (c === 35) { - this.url.fragment = ""; - this.state = "fragment"; - } - } else { - // TODO: If c is not a URL code point and not "%", parse error. - - if (c === 37 && - (!isASCIIHex(this.input[this.pointer + 1]) || - !isASCIIHex(this.input[this.pointer + 2]))) { - this.parseError = true; - } - - this.buffer += percentEncodeChar(c, isPathPercentEncode); - } - - return true; -}; - -URLStateMachine.prototype["parse cannot-be-a-base-URL path"] = function parseCannotBeABaseURLPath(c) { - if (c === 63) { - this.url.query = ""; - this.state = "query"; - } else if (c === 35) { - this.url.fragment = ""; - this.state = "fragment"; - } else { - // TODO: Add: not a URL code point - if (!isNaN(c) && c !== 37) { - this.parseError = true; - } - - if (c === 37 && - (!isASCIIHex(this.input[this.pointer + 1]) || - !isASCIIHex(this.input[this.pointer + 2]))) { - this.parseError = true; - } - - if (!isNaN(c)) { - this.url.path[0] = this.url.path[0] + percentEncodeChar(c, isC0ControlPercentEncode); - } - } - - return true; -}; - -URLStateMachine.prototype["parse query"] = function parseQuery(c, cStr) { - if (isNaN(c) || (!this.stateOverride && c === 35)) { - if (!isSpecial(this.url) || this.url.scheme === "ws" || this.url.scheme === "wss") { - this.encodingOverride = "utf-8"; - } - - const buffer = new Buffer(this.buffer); // TODO: Use encoding override instead - for (let i = 0; i < buffer.length; ++i) { - if (buffer[i] < 0x21 || buffer[i] > 0x7E || buffer[i] === 0x22 || buffer[i] === 0x23 || - buffer[i] === 0x3C || buffer[i] === 0x3E) { - this.url.query += percentEncode(buffer[i]); - } else { - this.url.query += String.fromCodePoint(buffer[i]); - } - } - - this.buffer = ""; - if (c === 35) { - this.url.fragment = ""; - this.state = "fragment"; - } - } else { - // TODO: If c is not a URL code point and not "%", parse error. - if (c === 37 && - (!isASCIIHex(this.input[this.pointer + 1]) || - !isASCIIHex(this.input[this.pointer + 2]))) { - this.parseError = true; - } - - this.buffer += cStr; - } - - return true; -}; - -URLStateMachine.prototype["parse fragment"] = function parseFragment(c) { - if (isNaN(c)) { // do nothing - } else if (c === 0x0) { - this.parseError = true; - } else { - // TODO: If c is not a URL code point and not "%", parse error. - if (c === 37 && - (!isASCIIHex(this.input[this.pointer + 1]) || - !isASCIIHex(this.input[this.pointer + 2]))) { - this.parseError = true; - } - - this.url.fragment += percentEncodeChar(c, isC0ControlPercentEncode); - } - - return true; -}; - -function serializeURL(url, excludeFragment) { - let output = url.scheme + ":"; - if (url.host !== null) { - output += "//"; - - if (url.username !== "" || url.password !== "") { - output += url.username; - if (url.password !== "") { - output += ":" + url.password; - } - output += "@"; - } - - output += serializeHost(url.host); - - if (url.port !== null) { - output += ":" + url.port; - } - } else if (url.host === null && url.scheme === "file") { - output += "//"; - } - - if (url.cannotBeABaseURL) { - output += url.path[0]; - } else { - for (const string of url.path) { - output += "/" + string; - } - } - - if (url.query !== null) { - output += "?" + url.query; - } - - if (!excludeFragment && url.fragment !== null) { - output += "#" + url.fragment; - } - - return output; -} - -function serializeOrigin(tuple) { - let result = tuple.scheme + "://"; - result += serializeHost(tuple.host); - - if (tuple.port !== null) { - result += ":" + tuple.port; - } - - return result; -} - -module.exports.serializeURL = serializeURL; - -module.exports.serializeURLOrigin = function (url) { - // https://url.spec.whatwg.org/#concept-url-origin - switch (url.scheme) { - case "blob": - try { - return module.exports.serializeURLOrigin(module.exports.parseURL(url.path[0])); - } catch (e) { - // serializing an opaque origin returns "null" - return "null"; - } - case "ftp": - case "gopher": - case "http": - case "https": - case "ws": - case "wss": - return serializeOrigin({ - scheme: url.scheme, - host: url.host, - port: url.port - }); - case "file": - // spec says "exercise to the reader", chrome says "file://" - return "file://"; - default: - // serializing an opaque origin returns "null" - return "null"; - } -}; - -module.exports.basicURLParse = function (input, options) { - if (options === undefined) { - options = {}; - } - - const usm = new URLStateMachine(input, options.baseURL, options.encodingOverride, options.url, options.stateOverride); - if (usm.failure) { - return "failure"; - } - - return usm.url; -}; - -module.exports.setTheUsername = function (url, username) { - url.username = ""; - const decoded = punycode.ucs2.decode(username); - for (let i = 0; i < decoded.length; ++i) { - url.username += percentEncodeChar(decoded[i], isUserinfoPercentEncode); - } -}; - -module.exports.setThePassword = function (url, password) { - url.password = ""; - const decoded = punycode.ucs2.decode(password); - for (let i = 0; i < decoded.length; ++i) { - url.password += percentEncodeChar(decoded[i], isUserinfoPercentEncode); - } -}; - -module.exports.serializeHost = serializeHost; - -module.exports.cannotHaveAUsernamePasswordPort = cannotHaveAUsernamePasswordPort; - -module.exports.serializeInteger = function (integer) { - return String(integer); -}; - -module.exports.parseURL = function (input, options) { - if (options === undefined) { - options = {}; - } - - // We don't handle blobs, so this just delegates: - return module.exports.basicURLParse(input, { baseURL: options.baseURL, encodingOverride: options.encodingOverride }); -}; - - -/***/ }), - -/***/ 9857: -/***/ ((module) => { - - - -module.exports.mixin = function mixin(target, source) { - const keys = Object.getOwnPropertyNames(source); - for (let i = 0; i < keys.length; ++i) { - Object.defineProperty(target, keys[i], Object.getOwnPropertyDescriptor(source, keys[i])); - } -}; - -module.exports.wrapperSymbol = Symbol("wrapper"); -module.exports.implSymbol = Symbol("impl"); - -module.exports.wrapperForImpl = function (impl) { - return impl[module.exports.wrapperSymbol]; -}; - -module.exports.implForWrapper = function (wrapper) { - return wrapper[module.exports.implSymbol]; -}; - - - /***/ }), /***/ 8264: @@ -61400,6924 +55839,6990 @@ function wrappy (fn, cb) { /***/ }), -/***/ 3176: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ZodError = exports.quotelessJson = exports.ZodIssueCode = void 0; -const util_1 = __nccwpck_require__(8771); -exports.ZodIssueCode = util_1.util.arrayToEnum([ - "invalid_type", - "invalid_literal", - "custom", - "invalid_union", - "invalid_union_discriminator", - "invalid_enum_value", - "unrecognized_keys", - "invalid_arguments", - "invalid_return_type", - "invalid_date", - "invalid_string", - "too_small", - "too_big", - "invalid_intersection_types", - "not_multiple_of", - "not_finite", -]); -const quotelessJson = (obj) => { - const json = JSON.stringify(obj, null, 2); - return json.replace(/"([^"]+)":/g, "$1:"); -}; -exports.quotelessJson = quotelessJson; -class ZodError extends Error { - get errors() { - return this.issues; - } - constructor(issues) { - super(); - this.issues = []; - this.addIssue = (sub) => { - this.issues = [...this.issues, sub]; - }; - this.addIssues = (subs = []) => { - this.issues = [...this.issues, ...subs]; - }; - const actualProto = new.target.prototype; - if (Object.setPrototypeOf) { - // eslint-disable-next-line ban/ban - Object.setPrototypeOf(this, actualProto); - } - else { - this.__proto__ = actualProto; - } - this.name = "ZodError"; - this.issues = issues; - } - format(_mapper) { - const mapper = _mapper || - function (issue) { - return issue.message; - }; - const fieldErrors = { _errors: [] }; - const processError = (error) => { - for (const issue of error.issues) { - if (issue.code === "invalid_union") { - issue.unionErrors.map(processError); - } - else if (issue.code === "invalid_return_type") { - processError(issue.returnTypeError); - } - else if (issue.code === "invalid_arguments") { - processError(issue.argumentsError); - } - else if (issue.path.length === 0) { - fieldErrors._errors.push(mapper(issue)); - } - else { - let curr = fieldErrors; - let i = 0; - while (i < issue.path.length) { - const el = issue.path[i]; - const terminal = i === issue.path.length - 1; - if (!terminal) { - curr[el] = curr[el] || { _errors: [] }; - // if (typeof el === "string") { - // curr[el] = curr[el] || { _errors: [] }; - // } else if (typeof el === "number") { - // const errorArray: any = []; - // errorArray._errors = []; - // curr[el] = curr[el] || errorArray; - // } - } - else { - curr[el] = curr[el] || { _errors: [] }; - curr[el]._errors.push(mapper(issue)); - } - curr = curr[el]; - i++; - } - } - } - }; - processError(this); - return fieldErrors; - } - static assert(value) { - if (!(value instanceof ZodError)) { - throw new Error(`Not a ZodError: ${value}`); - } - } - toString() { - return this.message; - } - get message() { - return JSON.stringify(this.issues, util_1.util.jsonStringifyReplacer, 2); - } - get isEmpty() { - return this.issues.length === 0; - } - flatten(mapper = (issue) => issue.message) { - const fieldErrors = {}; - const formErrors = []; - for (const sub of this.issues) { - if (sub.path.length > 0) { - fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; - fieldErrors[sub.path[0]].push(mapper(sub)); - } - else { - formErrors.push(mapper(sub)); - } - } - return { formErrors, fieldErrors }; - } - get formErrors() { - return this.flatten(); - } -} -exports.ZodError = ZodError; -ZodError.create = (issues) => { - const error = new ZodError(issues); - return error; -}; +/***/ 2613: +/***/ ((module) => { +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("assert"); /***/ }), -/***/ 5918: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - - -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getErrorMap = exports.setErrorMap = exports.defaultErrorMap = void 0; -const en_1 = __importDefault(__nccwpck_require__(9294)); -exports.defaultErrorMap = en_1.default; -let overrideErrorMap = en_1.default; -function setErrorMap(map) { - overrideErrorMap = map; -} -exports.setErrorMap = setErrorMap; -function getErrorMap() { - return overrideErrorMap; -} -exports.getErrorMap = getErrorMap; +/***/ 290: +/***/ ((module) => { +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("async_hooks"); /***/ }), -/***/ 9746: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __exportStar = (this && this.__exportStar) || function(m, exports) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -__exportStar(__nccwpck_require__(5918), exports); -__exportStar(__nccwpck_require__(4640), exports); -__exportStar(__nccwpck_require__(5935), exports); -__exportStar(__nccwpck_require__(8771), exports); -__exportStar(__nccwpck_require__(5128), exports); -__exportStar(__nccwpck_require__(3176), exports); +/***/ 181: +/***/ ((module) => { +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("buffer"); /***/ }), -/***/ 189: -/***/ ((__unused_webpack_module, exports) => { +/***/ 5317: +/***/ ((module) => { +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("child_process"); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.errorUtil = void 0; -var errorUtil; -(function (errorUtil) { - errorUtil.errToObj = (message) => typeof message === "string" ? { message } : message || {}; - errorUtil.toString = (message) => typeof message === "string" ? message : message === null || message === void 0 ? void 0 : message.message; -})(errorUtil || (exports.errorUtil = errorUtil = {})); +/***/ }), + +/***/ 4236: +/***/ ((module) => { +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("console"); /***/ }), -/***/ 4640: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/***/ 6982: +/***/ ((module) => { +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("crypto"); -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.isAsync = exports.isValid = exports.isDirty = exports.isAborted = exports.OK = exports.DIRTY = exports.INVALID = exports.ParseStatus = exports.addIssueToContext = exports.EMPTY_PATH = exports.makeIssue = void 0; -const errors_1 = __nccwpck_require__(5918); -const en_1 = __importDefault(__nccwpck_require__(9294)); -const makeIssue = (params) => { - const { data, path, errorMaps, issueData } = params; - const fullPath = [...path, ...(issueData.path || [])]; - const fullIssue = { - ...issueData, - path: fullPath, - }; - if (issueData.message !== undefined) { - return { - ...issueData, - path: fullPath, - message: issueData.message, - }; - } - let errorMessage = ""; - const maps = errorMaps - .filter((m) => !!m) - .slice() - .reverse(); - for (const map of maps) { - errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message; - } - return { - ...issueData, - path: fullPath, - message: errorMessage, - }; -}; -exports.makeIssue = makeIssue; -exports.EMPTY_PATH = []; -function addIssueToContext(ctx, issueData) { - const overrideMap = (0, errors_1.getErrorMap)(); - const issue = (0, exports.makeIssue)({ - issueData: issueData, - data: ctx.data, - path: ctx.path, - errorMaps: [ - ctx.common.contextualErrorMap, // contextual error map is first priority - ctx.schemaErrorMap, // then schema-bound map if available - overrideMap, // then global override map - overrideMap === en_1.default ? undefined : en_1.default, // then global default map - ].filter((x) => !!x), - }); - ctx.common.issues.push(issue); -} -exports.addIssueToContext = addIssueToContext; -class ParseStatus { - constructor() { - this.value = "valid"; - } - dirty() { - if (this.value === "valid") - this.value = "dirty"; - } - abort() { - if (this.value !== "aborted") - this.value = "aborted"; - } - static mergeArray(status, results) { - const arrayValue = []; - for (const s of results) { - if (s.status === "aborted") - return exports.INVALID; - if (s.status === "dirty") - status.dirty(); - arrayValue.push(s.value); - } - return { status: status.value, value: arrayValue }; - } - static async mergeObjectAsync(status, pairs) { - const syncPairs = []; - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - syncPairs.push({ - key, - value, - }); - } - return ParseStatus.mergeObjectSync(status, syncPairs); - } - static mergeObjectSync(status, pairs) { - const finalObject = {}; - for (const pair of pairs) { - const { key, value } = pair; - if (key.status === "aborted") - return exports.INVALID; - if (value.status === "aborted") - return exports.INVALID; - if (key.status === "dirty") - status.dirty(); - if (value.status === "dirty") - status.dirty(); - if (key.value !== "__proto__" && - (typeof value.value !== "undefined" || pair.alwaysSet)) { - finalObject[key.value] = value.value; - } - } - return { status: status.value, value: finalObject }; - } -} -exports.ParseStatus = ParseStatus; -exports.INVALID = Object.freeze({ - status: "aborted", -}); -const DIRTY = (value) => ({ status: "dirty", value }); -exports.DIRTY = DIRTY; -const OK = (value) => ({ status: "valid", value }); -exports.OK = OK; -const isAborted = (x) => x.status === "aborted"; -exports.isAborted = isAborted; -const isDirty = (x) => x.status === "dirty"; -exports.isDirty = isDirty; -const isValid = (x) => x.status === "valid"; -exports.isValid = isValid; -const isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise; -exports.isAsync = isAsync; +/***/ }), + +/***/ 1637: +/***/ ((module) => { +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("diagnostics_channel"); /***/ }), -/***/ 5935: -/***/ ((__unused_webpack_module, exports) => { +/***/ 4434: +/***/ ((module) => { +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("events"); -Object.defineProperty(exports, "__esModule", ({ value: true })); +/***/ }), + +/***/ 9896: +/***/ ((module) => { +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("fs"); /***/ }), -/***/ 8771: -/***/ ((__unused_webpack_module, exports) => { +/***/ 8611: +/***/ ((module) => { +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("http"); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getParsedType = exports.ZodParsedType = exports.objectUtil = exports.util = void 0; -var util; -(function (util) { - util.assertEqual = (val) => val; - function assertIs(_arg) { } - util.assertIs = assertIs; - function assertNever(_x) { - throw new Error(); - } - util.assertNever = assertNever; - util.arrayToEnum = (items) => { - const obj = {}; - for (const item of items) { - obj[item] = item; - } - return obj; - }; - util.getValidEnumValues = (obj) => { - const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number"); - const filtered = {}; - for (const k of validKeys) { - filtered[k] = obj[k]; - } - return util.objectValues(filtered); - }; - util.objectValues = (obj) => { - return util.objectKeys(obj).map(function (e) { - return obj[e]; - }); - }; - util.objectKeys = typeof Object.keys === "function" // eslint-disable-line ban/ban - ? (obj) => Object.keys(obj) // eslint-disable-line ban/ban - : (object) => { - const keys = []; - for (const key in object) { - if (Object.prototype.hasOwnProperty.call(object, key)) { - keys.push(key); - } - } - return keys; - }; - util.find = (arr, checker) => { - for (const item of arr) { - if (checker(item)) - return item; - } - return undefined; - }; - util.isInteger = typeof Number.isInteger === "function" - ? (val) => Number.isInteger(val) // eslint-disable-line ban/ban - : (val) => typeof val === "number" && isFinite(val) && Math.floor(val) === val; - function joinValues(array, separator = " | ") { - return array - .map((val) => (typeof val === "string" ? `'${val}'` : val)) - .join(separator); - } - util.joinValues = joinValues; - util.jsonStringifyReplacer = (_, value) => { - if (typeof value === "bigint") { - return value.toString(); - } - return value; - }; -})(util || (exports.util = util = {})); -var objectUtil; -(function (objectUtil) { - objectUtil.mergeShapes = (first, second) => { - return { - ...first, - ...second, // second overwrites first - }; - }; -})(objectUtil || (exports.objectUtil = objectUtil = {})); -exports.ZodParsedType = util.arrayToEnum([ - "string", - "nan", - "number", - "integer", - "float", - "boolean", - "date", - "bigint", - "symbol", - "function", - "undefined", - "null", - "array", - "object", - "unknown", - "promise", - "void", - "never", - "map", - "set", -]); -const getParsedType = (data) => { - const t = typeof data; - switch (t) { - case "undefined": - return exports.ZodParsedType.undefined; - case "string": - return exports.ZodParsedType.string; - case "number": - return isNaN(data) ? exports.ZodParsedType.nan : exports.ZodParsedType.number; - case "boolean": - return exports.ZodParsedType.boolean; - case "function": - return exports.ZodParsedType.function; - case "bigint": - return exports.ZodParsedType.bigint; - case "symbol": - return exports.ZodParsedType.symbol; - case "object": - if (Array.isArray(data)) { - return exports.ZodParsedType.array; - } - if (data === null) { - return exports.ZodParsedType.null; - } - if (data.then && - typeof data.then === "function" && - data.catch && - typeof data.catch === "function") { - return exports.ZodParsedType.promise; - } - if (typeof Map !== "undefined" && data instanceof Map) { - return exports.ZodParsedType.map; - } - if (typeof Set !== "undefined" && data instanceof Set) { - return exports.ZodParsedType.set; - } - if (typeof Date !== "undefined" && data instanceof Date) { - return exports.ZodParsedType.date; - } - return exports.ZodParsedType.object; - default: - return exports.ZodParsedType.unknown; - } -}; -exports.getParsedType = getParsedType; +/***/ }), + +/***/ 5675: +/***/ ((module) => { +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("http2"); /***/ }), -/***/ 4809: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/***/ 5692: +/***/ ((module) => { +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("https"); -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __exportStar = (this && this.__exportStar) || function(m, exports) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.z = void 0; -const z = __importStar(__nccwpck_require__(9746)); -exports.z = z; -__exportStar(__nccwpck_require__(9746), exports); -exports["default"] = z; +/***/ }), +/***/ 9278: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("net"); /***/ }), -/***/ 9294: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 7598: +/***/ ((module) => { +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:crypto"); -Object.defineProperty(exports, "__esModule", ({ value: true })); -const util_1 = __nccwpck_require__(8771); -const ZodError_1 = __nccwpck_require__(3176); -const errorMap = (issue, _ctx) => { - let message; - switch (issue.code) { - case ZodError_1.ZodIssueCode.invalid_type: - if (issue.received === util_1.ZodParsedType.undefined) { - message = "Required"; - } - else { - message = `Expected ${issue.expected}, received ${issue.received}`; - } - break; - case ZodError_1.ZodIssueCode.invalid_literal: - message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util_1.util.jsonStringifyReplacer)}`; - break; - case ZodError_1.ZodIssueCode.unrecognized_keys: - message = `Unrecognized key(s) in object: ${util_1.util.joinValues(issue.keys, ", ")}`; - break; - case ZodError_1.ZodIssueCode.invalid_union: - message = `Invalid input`; - break; - case ZodError_1.ZodIssueCode.invalid_union_discriminator: - message = `Invalid discriminator value. Expected ${util_1.util.joinValues(issue.options)}`; - break; - case ZodError_1.ZodIssueCode.invalid_enum_value: - message = `Invalid enum value. Expected ${util_1.util.joinValues(issue.options)}, received '${issue.received}'`; - break; - case ZodError_1.ZodIssueCode.invalid_arguments: - message = `Invalid function arguments`; - break; - case ZodError_1.ZodIssueCode.invalid_return_type: - message = `Invalid function return type`; - break; - case ZodError_1.ZodIssueCode.invalid_date: - message = `Invalid date`; - break; - case ZodError_1.ZodIssueCode.invalid_string: - if (typeof issue.validation === "object") { - if ("includes" in issue.validation) { - message = `Invalid input: must include "${issue.validation.includes}"`; - if (typeof issue.validation.position === "number") { - message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`; - } - } - else if ("startsWith" in issue.validation) { - message = `Invalid input: must start with "${issue.validation.startsWith}"`; - } - else if ("endsWith" in issue.validation) { - message = `Invalid input: must end with "${issue.validation.endsWith}"`; - } - else { - util_1.util.assertNever(issue.validation); - } - } - else if (issue.validation !== "regex") { - message = `Invalid ${issue.validation}`; - } - else { - message = "Invalid"; - } - break; - case ZodError_1.ZodIssueCode.too_small: - if (issue.type === "array") - message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`; - else if (issue.type === "string") - message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`; - else if (issue.type === "number") - message = `Number must be ${issue.exact - ? `exactly equal to ` - : issue.inclusive - ? `greater than or equal to ` - : `greater than `}${issue.minimum}`; - else if (issue.type === "date") - message = `Date must be ${issue.exact - ? `exactly equal to ` - : issue.inclusive - ? `greater than or equal to ` - : `greater than `}${new Date(Number(issue.minimum))}`; - else - message = "Invalid input"; - break; - case ZodError_1.ZodIssueCode.too_big: - if (issue.type === "array") - message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`; - else if (issue.type === "string") - message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`; - else if (issue.type === "number") - message = `Number must be ${issue.exact - ? `exactly` - : issue.inclusive - ? `less than or equal to` - : `less than`} ${issue.maximum}`; - else if (issue.type === "bigint") - message = `BigInt must be ${issue.exact - ? `exactly` - : issue.inclusive - ? `less than or equal to` - : `less than`} ${issue.maximum}`; - else if (issue.type === "date") - message = `Date must be ${issue.exact - ? `exactly` - : issue.inclusive - ? `smaller than or equal to` - : `smaller than`} ${new Date(Number(issue.maximum))}`; - else - message = "Invalid input"; - break; - case ZodError_1.ZodIssueCode.custom: - message = `Invalid input`; - break; - case ZodError_1.ZodIssueCode.invalid_intersection_types: - message = `Intersection results could not be merged`; - break; - case ZodError_1.ZodIssueCode.not_multiple_of: - message = `Number must be a multiple of ${issue.multipleOf}`; - break; - case ZodError_1.ZodIssueCode.not_finite: - message = "Number must be finite"; - break; - default: - message = _ctx.defaultError; - util_1.util.assertNever(issue); - } - return { message }; -}; -exports["default"] = errorMap; +/***/ }), + +/***/ 8474: +/***/ ((module) => { +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:events"); /***/ }), -/***/ 5128: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/***/ 7075: +/***/ ((module) => { +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:stream"); -var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); -}; -var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { - if (kind === "m") throw new TypeError("Private method is not writable"); - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); - return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; -}; -var _ZodEnum_cache, _ZodNativeEnum_cache; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.boolean = exports.bigint = exports.array = exports.any = exports.coerce = exports.ZodFirstPartyTypeKind = exports.late = exports.ZodSchema = exports.Schema = exports.custom = exports.ZodReadonly = exports.ZodPipeline = exports.ZodBranded = exports.BRAND = exports.ZodNaN = exports.ZodCatch = exports.ZodDefault = exports.ZodNullable = exports.ZodOptional = exports.ZodTransformer = exports.ZodEffects = exports.ZodPromise = exports.ZodNativeEnum = exports.ZodEnum = exports.ZodLiteral = exports.ZodLazy = exports.ZodFunction = exports.ZodSet = exports.ZodMap = exports.ZodRecord = exports.ZodTuple = exports.ZodIntersection = exports.ZodDiscriminatedUnion = exports.ZodUnion = exports.ZodObject = exports.ZodArray = exports.ZodVoid = exports.ZodNever = exports.ZodUnknown = exports.ZodAny = exports.ZodNull = exports.ZodUndefined = exports.ZodSymbol = exports.ZodDate = exports.ZodBoolean = exports.ZodBigInt = exports.ZodNumber = exports.ZodString = exports.datetimeRegex = exports.ZodType = void 0; -exports.NEVER = exports["void"] = exports.unknown = exports.union = exports.undefined = exports.tuple = exports.transformer = exports.symbol = exports.string = exports.strictObject = exports.set = exports.record = exports.promise = exports.preprocess = exports.pipeline = exports.ostring = exports.optional = exports.onumber = exports.oboolean = exports.object = exports.number = exports.nullable = exports["null"] = exports.never = exports.nativeEnum = exports.nan = exports.map = exports.literal = exports.lazy = exports.intersection = exports["instanceof"] = exports["function"] = exports["enum"] = exports.effect = exports.discriminatedUnion = exports.date = void 0; -const errors_1 = __nccwpck_require__(5918); -const errorUtil_1 = __nccwpck_require__(189); -const parseUtil_1 = __nccwpck_require__(4640); -const util_1 = __nccwpck_require__(8771); -const ZodError_1 = __nccwpck_require__(3176); -class ParseInputLazyPath { - constructor(parent, value, path, key) { - this._cachedPath = []; - this.parent = parent; - this.data = value; - this._path = path; - this._key = key; - } - get path() { - if (!this._cachedPath.length) { - if (this._key instanceof Array) { - this._cachedPath.push(...this._path, ...this._key); - } - else { - this._cachedPath.push(...this._path, this._key); - } - } - return this._cachedPath; - } +/***/ }), + +/***/ 7975: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:util"); + +/***/ }), + +/***/ 857: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("os"); + +/***/ }), + +/***/ 6928: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("path"); + +/***/ }), + +/***/ 2987: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("perf_hooks"); + +/***/ }), + +/***/ 3480: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("querystring"); + +/***/ }), + +/***/ 2203: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("stream"); + +/***/ }), + +/***/ 3774: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("stream/web"); + +/***/ }), + +/***/ 3193: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("string_decoder"); + +/***/ }), + +/***/ 3557: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("timers"); + +/***/ }), + +/***/ 4756: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("tls"); + +/***/ }), + +/***/ 7016: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("url"); + +/***/ }), + +/***/ 9023: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("util"); + +/***/ }), + +/***/ 8253: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("util/types"); + +/***/ }), + +/***/ 8167: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("worker_threads"); + +/***/ }), + +/***/ 3106: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("zlib"); + +/***/ }), + +/***/ 7182: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const WritableStream = (__nccwpck_require__(7075).Writable) +const inherits = (__nccwpck_require__(7975).inherits) + +const StreamSearch = __nccwpck_require__(4136) + +const PartStream = __nccwpck_require__(612) +const HeaderParser = __nccwpck_require__(2271) + +const DASH = 45 +const B_ONEDASH = Buffer.from('-') +const B_CRLF = Buffer.from('\r\n') +const EMPTY_FN = function () {} + +function Dicer (cfg) { + if (!(this instanceof Dicer)) { return new Dicer(cfg) } + WritableStream.call(this, cfg) + + if (!cfg || (!cfg.headerFirst && typeof cfg.boundary !== 'string')) { throw new TypeError('Boundary required') } + + if (typeof cfg.boundary === 'string') { this.setBoundary(cfg.boundary) } else { this._bparser = undefined } + + this._headerFirst = cfg.headerFirst + + this._dashes = 0 + this._parts = 0 + this._finished = false + this._realFinish = false + this._isPreamble = true + this._justMatched = false + this._firstWrite = true + this._inHeader = true + this._part = undefined + this._cb = undefined + this._ignoreData = false + this._partOpts = { highWaterMark: cfg.partHwm } + this._pause = false + + const self = this + this._hparser = new HeaderParser(cfg) + this._hparser.on('header', function (header) { + self._inHeader = false + self._part.emit('header', header) + }) } -const handleResult = (ctx, result) => { - if ((0, parseUtil_1.isValid)(result)) { - return { success: true, data: result.value }; - } - else { - if (!ctx.common.issues.length) { - throw new Error("Validation failed but no issues detected."); +inherits(Dicer, WritableStream) + +Dicer.prototype.emit = function (ev) { + if (ev === 'finish' && !this._realFinish) { + if (!this._finished) { + const self = this + process.nextTick(function () { + self.emit('error', new Error('Unexpected end of multipart data')) + if (self._part && !self._ignoreData) { + const type = (self._isPreamble ? 'Preamble' : 'Part') + self._part.emit('error', new Error(type + ' terminated early due to unexpected end of multipart data')) + self._part.push(null) + process.nextTick(function () { + self._realFinish = true + self.emit('finish') + self._realFinish = false + }) + return } - return { - success: false, - get error() { - if (this._error) - return this._error; - const error = new ZodError_1.ZodError(ctx.common.issues); - this._error = error; - return this._error; - }, - }; - } -}; -function processCreateParams(params) { - if (!params) - return {}; - const { errorMap, invalid_type_error, required_error, description } = params; - if (errorMap && (invalid_type_error || required_error)) { - throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); + self._realFinish = true + self.emit('finish') + self._realFinish = false + }) } - if (errorMap) - return { errorMap: errorMap, description }; - const customMap = (iss, ctx) => { - var _a, _b; - const { message } = params; - if (iss.code === "invalid_enum_value") { - return { message: message !== null && message !== void 0 ? message : ctx.defaultError }; - } - if (typeof ctx.data === "undefined") { - return { message: (_a = message !== null && message !== void 0 ? message : required_error) !== null && _a !== void 0 ? _a : ctx.defaultError }; - } - if (iss.code !== "invalid_type") - return { message: ctx.defaultError }; - return { message: (_b = message !== null && message !== void 0 ? message : invalid_type_error) !== null && _b !== void 0 ? _b : ctx.defaultError }; - }; - return { errorMap: customMap, description }; + } else { WritableStream.prototype.emit.apply(this, arguments) } } -class ZodType { - get description() { - return this._def.description; - } - _getType(input) { - return (0, util_1.getParsedType)(input.data); - } - _getOrReturnCtx(input, ctx) { - return (ctx || { - common: input.parent.common, - data: input.data, - parsedType: (0, util_1.getParsedType)(input.data), - schemaErrorMap: this._def.errorMap, - path: input.path, - parent: input.parent, - }); + +Dicer.prototype._write = function (data, encoding, cb) { + // ignore unexpected data (e.g. extra trailer data after finished) + if (!this._hparser && !this._bparser) { return cb() } + + if (this._headerFirst && this._isPreamble) { + if (!this._part) { + this._part = new PartStream(this._partOpts) + if (this.listenerCount('preamble') !== 0) { this.emit('preamble', this._part) } else { this._ignore() } } - _processInputParams(input) { - return { - status: new parseUtil_1.ParseStatus(), - ctx: { - common: input.parent.common, - data: input.data, - parsedType: (0, util_1.getParsedType)(input.data), - schemaErrorMap: this._def.errorMap, - path: input.path, - parent: input.parent, - }, - }; + const r = this._hparser.push(data) + if (!this._inHeader && r !== undefined && r < data.length) { data = data.slice(r) } else { return cb() } + } + + // allows for "easier" testing + if (this._firstWrite) { + this._bparser.push(B_CRLF) + this._firstWrite = false + } + + this._bparser.push(data) + + if (this._pause) { this._cb = cb } else { cb() } +} + +Dicer.prototype.reset = function () { + this._part = undefined + this._bparser = undefined + this._hparser = undefined +} + +Dicer.prototype.setBoundary = function (boundary) { + const self = this + this._bparser = new StreamSearch('\r\n--' + boundary) + this._bparser.on('info', function (isMatch, data, start, end) { + self._oninfo(isMatch, data, start, end) + }) +} + +Dicer.prototype._ignore = function () { + if (this._part && !this._ignoreData) { + this._ignoreData = true + this._part.on('error', EMPTY_FN) + // we must perform some kind of read on the stream even though we are + // ignoring the data, otherwise node's Readable stream will not emit 'end' + // after pushing null to the stream + this._part.resume() + } +} + +Dicer.prototype._oninfo = function (isMatch, data, start, end) { + let buf; const self = this; let i = 0; let r; let shouldWriteMore = true + + if (!this._part && this._justMatched && data) { + while (this._dashes < 2 && (start + i) < end) { + if (data[start + i] === DASH) { + ++i + ++this._dashes + } else { + if (this._dashes) { buf = B_ONEDASH } + this._dashes = 0 + break + } } - _parseSync(input) { - const result = this._parse(input); - if ((0, parseUtil_1.isAsync)(result)) { - throw new Error("Synchronous parse encountered promise."); - } - return result; + if (this._dashes === 2) { + if ((start + i) < end && this.listenerCount('trailer') !== 0) { this.emit('trailer', data.slice(start + i, end)) } + this.reset() + this._finished = true + // no more parts will be added + if (self._parts === 0) { + self._realFinish = true + self.emit('finish') + self._realFinish = false + } } - _parseAsync(input) { - const result = this._parse(input); - return Promise.resolve(result); + if (this._dashes) { return } + } + if (this._justMatched) { this._justMatched = false } + if (!this._part) { + this._part = new PartStream(this._partOpts) + this._part._read = function (n) { + self._unpause() } - parse(data, params) { - const result = this.safeParse(data, params); - if (result.success) - return result.data; - throw result.error; + if (this._isPreamble && this.listenerCount('preamble') !== 0) { + this.emit('preamble', this._part) + } else if (this._isPreamble !== true && this.listenerCount('part') !== 0) { + this.emit('part', this._part) + } else { + this._ignore() } - safeParse(data, params) { - var _a; - const ctx = { - common: { - issues: [], - async: (_a = params === null || params === void 0 ? void 0 : params.async) !== null && _a !== void 0 ? _a : false, - contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap, - }, - path: (params === null || params === void 0 ? void 0 : params.path) || [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: (0, util_1.getParsedType)(data), - }; - const result = this._parseSync({ data, path: ctx.path, parent: ctx }); - return handleResult(ctx, result); + if (!this._isPreamble) { this._inHeader = true } + } + if (data && start < end && !this._ignoreData) { + if (this._isPreamble || !this._inHeader) { + if (buf) { shouldWriteMore = this._part.push(buf) } + shouldWriteMore = this._part.push(data.slice(start, end)) + if (!shouldWriteMore) { this._pause = true } + } else if (!this._isPreamble && this._inHeader) { + if (buf) { this._hparser.push(buf) } + r = this._hparser.push(data.slice(start, end)) + if (!this._inHeader && r !== undefined && r < end) { this._oninfo(false, data, start + r, end) } } - "~validate"(data) { - var _a, _b; - const ctx = { - common: { - issues: [], - async: !!this["~standard"].async, - }, - path: [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: (0, util_1.getParsedType)(data), - }; - if (!this["~standard"].async) { - try { - const result = this._parseSync({ data, path: [], parent: ctx }); - return (0, parseUtil_1.isValid)(result) - ? { - value: result.value, - } - : { - issues: ctx.common.issues, - }; + } + if (isMatch) { + this._hparser.reset() + if (this._isPreamble) { this._isPreamble = false } else { + if (start !== end) { + ++this._parts + this._part.on('end', function () { + if (--self._parts === 0) { + if (self._finished) { + self._realFinish = true + self.emit('finish') + self._realFinish = false + } else { + self._unpause() } - catch (err) { - if ((_b = (_a = err === null || err === void 0 ? void 0 : err.message) === null || _a === void 0 ? void 0 : _a.toLowerCase()) === null || _b === void 0 ? void 0 : _b.includes("encountered")) { - this["~standard"].async = true; - } - ctx.common = { - issues: [], - async: true, - }; - } - } - return this._parseAsync({ data, path: [], parent: ctx }).then((result) => (0, parseUtil_1.isValid)(result) - ? { - value: result.value, - } - : { - issues: ctx.common.issues, - }); - } - async parseAsync(data, params) { - const result = await this.safeParseAsync(data, params); - if (result.success) - return result.data; - throw result.error; - } - async safeParseAsync(data, params) { - const ctx = { - common: { - issues: [], - contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap, - async: true, - }, - path: (params === null || params === void 0 ? void 0 : params.path) || [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: (0, util_1.getParsedType)(data), - }; - const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }); - const result = await ((0, parseUtil_1.isAsync)(maybeAsyncResult) - ? maybeAsyncResult - : Promise.resolve(maybeAsyncResult)); - return handleResult(ctx, result); - } - refine(check, message) { - const getIssueProperties = (val) => { - if (typeof message === "string" || typeof message === "undefined") { - return { message }; - } - else if (typeof message === "function") { - return message(val); - } - else { - return message; - } - }; - return this._refinement((val, ctx) => { - const result = check(val); - const setError = () => ctx.addIssue({ - code: ZodError_1.ZodIssueCode.custom, - ...getIssueProperties(val), - }); - if (typeof Promise !== "undefined" && result instanceof Promise) { - return result.then((data) => { - if (!data) { - setError(); - return false; - } - else { - return true; - } - }); - } - if (!result) { - setError(); - return false; - } - else { - return true; - } - }); - } - refinement(check, refinementData) { - return this._refinement((val, ctx) => { - if (!check(val)) { - ctx.addIssue(typeof refinementData === "function" - ? refinementData(val, ctx) - : refinementData); - return false; - } - else { - return true; - } - }); - } - _refinement(refinement) { - return new ZodEffects({ - schema: this, - typeName: ZodFirstPartyTypeKind.ZodEffects, - effect: { type: "refinement", refinement }, - }); - } - superRefine(refinement) { - return this._refinement(refinement); - } - constructor(def) { - /** Alias of safeParseAsync */ - this.spa = this.safeParseAsync; - this._def = def; - this.parse = this.parse.bind(this); - this.safeParse = this.safeParse.bind(this); - this.parseAsync = this.parseAsync.bind(this); - this.safeParseAsync = this.safeParseAsync.bind(this); - this.spa = this.spa.bind(this); - this.refine = this.refine.bind(this); - this.refinement = this.refinement.bind(this); - this.superRefine = this.superRefine.bind(this); - this.optional = this.optional.bind(this); - this.nullable = this.nullable.bind(this); - this.nullish = this.nullish.bind(this); - this.array = this.array.bind(this); - this.promise = this.promise.bind(this); - this.or = this.or.bind(this); - this.and = this.and.bind(this); - this.transform = this.transform.bind(this); - this.brand = this.brand.bind(this); - this.default = this.default.bind(this); - this.catch = this.catch.bind(this); - this.describe = this.describe.bind(this); - this.pipe = this.pipe.bind(this); - this.readonly = this.readonly.bind(this); - this.isNullable = this.isNullable.bind(this); - this.isOptional = this.isOptional.bind(this); - this["~standard"] = { - version: 1, - vendor: "zod", - validate: (data) => this["~validate"](data), - }; - } - optional() { - return ZodOptional.create(this, this._def); - } - nullable() { - return ZodNullable.create(this, this._def); - } - nullish() { - return this.nullable().optional(); - } - array() { - return ZodArray.create(this); - } - promise() { - return ZodPromise.create(this, this._def); - } - or(option) { - return ZodUnion.create([this, option], this._def); - } - and(incoming) { - return ZodIntersection.create(this, incoming, this._def); - } - transform(transform) { - return new ZodEffects({ - ...processCreateParams(this._def), - schema: this, - typeName: ZodFirstPartyTypeKind.ZodEffects, - effect: { type: "transform", transform }, - }); - } - default(def) { - const defaultValueFunc = typeof def === "function" ? def : () => def; - return new ZodDefault({ - ...processCreateParams(this._def), - innerType: this, - defaultValue: defaultValueFunc, - typeName: ZodFirstPartyTypeKind.ZodDefault, - }); - } - brand() { - return new ZodBranded({ - typeName: ZodFirstPartyTypeKind.ZodBranded, - type: this, - ...processCreateParams(this._def), - }); - } - catch(def) { - const catchValueFunc = typeof def === "function" ? def : () => def; - return new ZodCatch({ - ...processCreateParams(this._def), - innerType: this, - catchValue: catchValueFunc, - typeName: ZodFirstPartyTypeKind.ZodCatch, - }); - } - describe(description) { - const This = this.constructor; - return new This({ - ...this._def, - description, - }); - } - pipe(target) { - return ZodPipeline.create(this, target); - } - readonly() { - return ZodReadonly.create(this); - } - isOptional() { - return this.safeParse(undefined).success; - } - isNullable() { - return this.safeParse(null).success; + } + }) + } } + this._part.push(null) + this._part = undefined + this._ignoreData = false + this._justMatched = true + this._dashes = 0 + } } -exports.ZodType = ZodType; -exports.Schema = ZodType; -exports.ZodSchema = ZodType; -const cuidRegex = /^c[^\s-]{8,}$/i; -const cuid2Regex = /^[0-9a-z]+$/; -const ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i; -// const uuidRegex = -// /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i; -const uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i; -const nanoidRegex = /^[a-z0-9_-]{21}$/i; -const jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/; -const durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; -// from https://stackoverflow.com/a/46181/1550155 -// old version: too slow, didn't support unicode -// const emailRegex = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i; -//old email regex -// const emailRegex = /^(([^<>()[\].,;:\s@"]+(\.[^<>()[\].,;:\s@"]+)*)|(".+"))@((?!-)([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{1,})[^-<>()[\].,;:\s@"]$/i; -// eslint-disable-next-line -// const emailRegex = -// /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\])|(\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\.[A-Za-z]{2,})+))$/; -// const emailRegex = -// /^[a-zA-Z0-9\.\!\#\$\%\&\'\*\+\/\=\?\^\_\`\{\|\}\~\-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; -// const emailRegex = -// /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$/i; -const emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; -// const emailRegex = -// /^[a-z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\.[a-z0-9\-]+)*$/i; -// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression -const _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; -let emojiRegex; -// faster, simpler, safer -const ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; -const ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/; -// const ipv6Regex = -// /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/; -const ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/; -const ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; -// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript -const base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; -// https://base64.guru/standards/base64url -const base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/; -// simple -// const dateRegexSource = `\\d{4}-\\d{2}-\\d{2}`; -// no leap year validation -// const dateRegexSource = `\\d{4}-((0[13578]|10|12)-31|(0[13-9]|1[0-2])-30|(0[1-9]|1[0-2])-(0[1-9]|1\\d|2\\d))`; -// with leap year validation -const dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`; -const dateRegex = new RegExp(`^${dateRegexSource}$`); -function timeRegexSource(args) { - let secondsRegexSource = `[0-5]\\d`; - if (args.precision) { - secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`; - } - else if (args.precision == null) { - secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`; + +Dicer.prototype._unpause = function () { + if (!this._pause) { return } + + this._pause = false + if (this._cb) { + const cb = this._cb + this._cb = undefined + cb() + } +} + +module.exports = Dicer + + +/***/ }), + +/***/ 2271: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const EventEmitter = (__nccwpck_require__(8474).EventEmitter) +const inherits = (__nccwpck_require__(7975).inherits) +const getLimit = __nccwpck_require__(2393) + +const StreamSearch = __nccwpck_require__(4136) + +const B_DCRLF = Buffer.from('\r\n\r\n') +const RE_CRLF = /\r\n/g +const RE_HDR = /^([^:]+):[ \t]?([\x00-\xFF]+)?$/ // eslint-disable-line no-control-regex + +function HeaderParser (cfg) { + EventEmitter.call(this) + + cfg = cfg || {} + const self = this + this.nread = 0 + this.maxed = false + this.npairs = 0 + this.maxHeaderPairs = getLimit(cfg, 'maxHeaderPairs', 2000) + this.maxHeaderSize = getLimit(cfg, 'maxHeaderSize', 80 * 1024) + this.buffer = '' + this.header = {} + this.finished = false + this.ss = new StreamSearch(B_DCRLF) + this.ss.on('info', function (isMatch, data, start, end) { + if (data && !self.maxed) { + if (self.nread + end - start >= self.maxHeaderSize) { + end = self.maxHeaderSize - self.nread + start + self.nread = self.maxHeaderSize + self.maxed = true + } else { self.nread += (end - start) } + + self.buffer += data.toString('binary', start, end) } - const secondsQuantifier = args.precision ? "+" : "?"; // require seconds if precision is nonzero - return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`; + if (isMatch) { self._finish() } + }) } -function timeRegex(args) { - return new RegExp(`^${timeRegexSource(args)}$`); +inherits(HeaderParser, EventEmitter) + +HeaderParser.prototype.push = function (data) { + const r = this.ss.push(data) + if (this.finished) { return r } } -// Adapted from https://stackoverflow.com/a/3143231 -function datetimeRegex(args) { - let regex = `${dateRegexSource}T${timeRegexSource(args)}`; - const opts = []; - opts.push(args.local ? `Z?` : `Z`); - if (args.offset) - opts.push(`([+-]\\d{2}:?\\d{2})`); - regex = `${regex}(${opts.join("|")})`; - return new RegExp(`^${regex}$`); + +HeaderParser.prototype.reset = function () { + this.finished = false + this.buffer = '' + this.header = {} + this.ss.reset() } -exports.datetimeRegex = datetimeRegex; -function isValidIP(ip, version) { - if ((version === "v4" || !version) && ipv4Regex.test(ip)) { - return true; - } - if ((version === "v6" || !version) && ipv6Regex.test(ip)) { - return true; - } - return false; + +HeaderParser.prototype._finish = function () { + if (this.buffer) { this._parseHeader() } + this.ss.matches = this.ss.maxMatches + const header = this.header + this.header = {} + this.buffer = '' + this.finished = true + this.nread = this.npairs = 0 + this.maxed = false + this.emit('header', header) } -function isValidJWT(jwt, alg) { - if (!jwtRegex.test(jwt)) - return false; - try { - const [header] = jwt.split("."); - // Convert base64url to base64 - const base64 = header - .replace(/-/g, "+") - .replace(/_/g, "/") - .padEnd(header.length + ((4 - (header.length % 4)) % 4), "="); - const decoded = JSON.parse(atob(base64)); - if (typeof decoded !== "object" || decoded === null) - return false; - if (!decoded.typ || !decoded.alg) - return false; - if (alg && decoded.alg !== alg) - return false; - return true; + +HeaderParser.prototype._parseHeader = function () { + if (this.npairs === this.maxHeaderPairs) { return } + + const lines = this.buffer.split(RE_CRLF) + const len = lines.length + let m, h + + for (var i = 0; i < len; ++i) { // eslint-disable-line no-var + if (lines[i].length === 0) { continue } + if (lines[i][0] === '\t' || lines[i][0] === ' ') { + // folded header content + // RFC2822 says to just remove the CRLF and not the whitespace following + // it, so we follow the RFC and include the leading whitespace ... + if (h) { + this.header[h][this.header[h].length - 1] += lines[i] + continue + } } - catch (_a) { - return false; + + const posColon = lines[i].indexOf(':') + if ( + posColon === -1 || + posColon === 0 + ) { + return } + m = RE_HDR.exec(lines[i]) + h = m[1].toLowerCase() + this.header[h] = this.header[h] || [] + this.header[h].push((m[2] || '')) + if (++this.npairs === this.maxHeaderPairs) { break } + } } -function isValidCidr(ip, version) { - if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) { - return true; - } - if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) { - return true; - } - return false; + +module.exports = HeaderParser + + +/***/ }), + +/***/ 612: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const inherits = (__nccwpck_require__(7975).inherits) +const ReadableStream = (__nccwpck_require__(7075).Readable) + +function PartStream (opts) { + ReadableStream.call(this, opts) } -class ZodString extends ZodType { - _parse(input) { - if (this._def.coerce) { - input.data = String(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== util_1.ZodParsedType.string) { - const ctx = this._getOrReturnCtx(input); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.string, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - const status = new parseUtil_1.ParseStatus(); - let ctx = undefined; - for (const check of this._def.checks) { - if (check.kind === "min") { - if (input.data.length < check.value) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_small, - minimum: check.value, - type: "string", - inclusive: true, - exact: false, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "max") { - if (input.data.length > check.value) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_big, - maximum: check.value, - type: "string", - inclusive: true, - exact: false, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "length") { - const tooBig = input.data.length > check.value; - const tooSmall = input.data.length < check.value; - if (tooBig || tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - if (tooBig) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_big, - maximum: check.value, - type: "string", - inclusive: true, - exact: true, - message: check.message, - }); - } - else if (tooSmall) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_small, - minimum: check.value, - type: "string", - inclusive: true, - exact: true, - message: check.message, - }); - } - status.dirty(); - } - } - else if (check.kind === "email") { - if (!emailRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - validation: "email", - code: ZodError_1.ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "emoji") { - if (!emojiRegex) { - emojiRegex = new RegExp(_emojiRegex, "u"); - } - if (!emojiRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - validation: "emoji", - code: ZodError_1.ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); +inherits(PartStream, ReadableStream) + +PartStream.prototype._read = function (n) {} + +module.exports = PartStream + + +/***/ }), + +/***/ 4136: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +/** + * Copyright Brian White. All rights reserved. + * + * @see https://github.com/mscdex/streamsearch + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + * + * Based heavily on the Streaming Boyer-Moore-Horspool C++ implementation + * by Hongli Lai at: https://github.com/FooBarWidget/boyer-moore-horspool + */ +const EventEmitter = (__nccwpck_require__(8474).EventEmitter) +const inherits = (__nccwpck_require__(7975).inherits) + +function SBMH (needle) { + if (typeof needle === 'string') { + needle = Buffer.from(needle) + } + + if (!Buffer.isBuffer(needle)) { + throw new TypeError('The needle has to be a String or a Buffer.') + } + + const needleLength = needle.length + + if (needleLength === 0) { + throw new Error('The needle cannot be an empty String/Buffer.') + } + + if (needleLength > 256) { + throw new Error('The needle cannot have a length bigger than 256.') + } + + this.maxMatches = Infinity + this.matches = 0 + + this._occ = new Array(256) + .fill(needleLength) // Initialize occurrence table. + this._lookbehind_size = 0 + this._needle = needle + this._bufpos = 0 + + this._lookbehind = Buffer.alloc(needleLength) + + // Populate occurrence table with analysis of the needle, + // ignoring last letter. + for (var i = 0; i < needleLength - 1; ++i) { // eslint-disable-line no-var + this._occ[needle[i]] = needleLength - 1 - i + } +} +inherits(SBMH, EventEmitter) + +SBMH.prototype.reset = function () { + this._lookbehind_size = 0 + this.matches = 0 + this._bufpos = 0 +} + +SBMH.prototype.push = function (chunk, pos) { + if (!Buffer.isBuffer(chunk)) { + chunk = Buffer.from(chunk, 'binary') + } + const chlen = chunk.length + this._bufpos = pos || 0 + let r + while (r !== chlen && this.matches < this.maxMatches) { r = this._sbmh_feed(chunk) } + return r +} + +SBMH.prototype._sbmh_feed = function (data) { + const len = data.length + const needle = this._needle + const needleLength = needle.length + const lastNeedleChar = needle[needleLength - 1] + + // Positive: points to a position in `data` + // pos == 3 points to data[3] + // Negative: points to a position in the lookbehind buffer + // pos == -2 points to lookbehind[lookbehind_size - 2] + let pos = -this._lookbehind_size + let ch + + if (pos < 0) { + // Lookbehind buffer is not empty. Perform Boyer-Moore-Horspool + // search with character lookup code that considers both the + // lookbehind buffer and the current round's haystack data. + // + // Loop until + // there is a match. + // or until + // we've moved past the position that requires the + // lookbehind buffer. In this case we switch to the + // optimized loop. + // or until + // the character to look at lies outside the haystack. + while (pos < 0 && pos <= len - needleLength) { + ch = this._sbmh_lookup_char(data, pos + needleLength - 1) + + if ( + ch === lastNeedleChar && + this._sbmh_memcmp(data, pos, needleLength - 1) + ) { + this._lookbehind_size = 0 + ++this.matches + this.emit('info', true) + + return (this._bufpos = pos + needleLength) + } + pos += this._occ[ch] + } + + // No match. + + if (pos < 0) { + // There's too few data for Boyer-Moore-Horspool to run, + // so let's use a different algorithm to skip as much as + // we can. + // Forward pos until + // the trailing part of lookbehind + data + // looks like the beginning of the needle + // or until + // pos == 0 + while (pos < 0 && !this._sbmh_memcmp(data, pos, len - pos)) { ++pos } + } + + if (pos >= 0) { + // Discard lookbehind buffer. + this.emit('info', false, this._lookbehind, 0, this._lookbehind_size) + this._lookbehind_size = 0 + } else { + // Cut off part of the lookbehind buffer that has + // been processed and append the entire haystack + // into it. + const bytesToCutOff = this._lookbehind_size + pos + if (bytesToCutOff > 0) { + // The cut off data is guaranteed not to contain the needle. + this.emit('info', false, this._lookbehind, 0, bytesToCutOff) + } + + this._lookbehind.copy(this._lookbehind, 0, bytesToCutOff, + this._lookbehind_size - bytesToCutOff) + this._lookbehind_size -= bytesToCutOff + + data.copy(this._lookbehind, this._lookbehind_size) + this._lookbehind_size += len + + this._bufpos = len + return len + } + } + + pos += (pos >= 0) * this._bufpos + + // Lookbehind buffer is now empty. We only need to check if the + // needle is in the haystack. + if (data.indexOf(needle, pos) !== -1) { + pos = data.indexOf(needle, pos) + ++this.matches + if (pos > 0) { this.emit('info', true, data, this._bufpos, pos) } else { this.emit('info', true) } + + return (this._bufpos = pos + needleLength) + } else { + pos = len - needleLength + } + + // There was no match. If there's trailing haystack data that we cannot + // match yet using the Boyer-Moore-Horspool algorithm (because the trailing + // data is less than the needle size) then match using a modified + // algorithm that starts matching from the beginning instead of the end. + // Whatever trailing data is left after running this algorithm is added to + // the lookbehind buffer. + while ( + pos < len && + ( + data[pos] !== needle[0] || + ( + (Buffer.compare( + data.subarray(pos, pos + len - pos), + needle.subarray(0, len - pos) + ) !== 0) + ) + ) + ) { + ++pos + } + if (pos < len) { + data.copy(this._lookbehind, 0, pos, pos + (len - pos)) + this._lookbehind_size = len - pos + } + + // Everything until pos is guaranteed not to contain needle data. + if (pos > 0) { this.emit('info', false, data, this._bufpos, pos < len ? pos : len) } + + this._bufpos = len + return len +} + +SBMH.prototype._sbmh_lookup_char = function (data, pos) { + return (pos < 0) + ? this._lookbehind[this._lookbehind_size + pos] + : data[pos] +} + +SBMH.prototype._sbmh_memcmp = function (data, pos, len) { + for (var i = 0; i < len; ++i) { // eslint-disable-line no-var + if (this._sbmh_lookup_char(data, pos + i) !== this._needle[i]) { return false } + } + return true +} + +module.exports = SBMH + + +/***/ }), + +/***/ 9581: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const WritableStream = (__nccwpck_require__(7075).Writable) +const { inherits } = __nccwpck_require__(7975) +const Dicer = __nccwpck_require__(7182) + +const MultipartParser = __nccwpck_require__(1192) +const UrlencodedParser = __nccwpck_require__(855) +const parseParams = __nccwpck_require__(8929) + +function Busboy (opts) { + if (!(this instanceof Busboy)) { return new Busboy(opts) } + + if (typeof opts !== 'object') { + throw new TypeError('Busboy expected an options-Object.') + } + if (typeof opts.headers !== 'object') { + throw new TypeError('Busboy expected an options-Object with headers-attribute.') + } + if (typeof opts.headers['content-type'] !== 'string') { + throw new TypeError('Missing Content-Type-header.') + } + + const { + headers, + ...streamOptions + } = opts + + this.opts = { + autoDestroy: false, + ...streamOptions + } + WritableStream.call(this, this.opts) + + this._done = false + this._parser = this.getParserByHeaders(headers) + this._finished = false +} +inherits(Busboy, WritableStream) + +Busboy.prototype.emit = function (ev) { + if (ev === 'finish') { + if (!this._done) { + this._parser?.end() + return + } else if (this._finished) { + return + } + this._finished = true + } + WritableStream.prototype.emit.apply(this, arguments) +} + +Busboy.prototype.getParserByHeaders = function (headers) { + const parsed = parseParams(headers['content-type']) + + const cfg = { + defCharset: this.opts.defCharset, + fileHwm: this.opts.fileHwm, + headers, + highWaterMark: this.opts.highWaterMark, + isPartAFile: this.opts.isPartAFile, + limits: this.opts.limits, + parsedConType: parsed, + preservePath: this.opts.preservePath + } + + if (MultipartParser.detect.test(parsed[0])) { + return new MultipartParser(this, cfg) + } + if (UrlencodedParser.detect.test(parsed[0])) { + return new UrlencodedParser(this, cfg) + } + throw new Error('Unsupported Content-Type.') +} + +Busboy.prototype._write = function (chunk, encoding, cb) { + this._parser.write(chunk, cb) +} + +module.exports = Busboy +module.exports["default"] = Busboy +module.exports.Busboy = Busboy + +module.exports.Dicer = Dicer + + +/***/ }), + +/***/ 1192: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +// TODO: +// * support 1 nested multipart level +// (see second multipart example here: +// http://www.w3.org/TR/html401/interact/forms.html#didx-multipartform-data) +// * support limits.fieldNameSize +// -- this will require modifications to utils.parseParams + +const { Readable } = __nccwpck_require__(7075) +const { inherits } = __nccwpck_require__(7975) + +const Dicer = __nccwpck_require__(7182) + +const parseParams = __nccwpck_require__(8929) +const decodeText = __nccwpck_require__(2747) +const basename = __nccwpck_require__(692) +const getLimit = __nccwpck_require__(2393) + +const RE_BOUNDARY = /^boundary$/i +const RE_FIELD = /^form-data$/i +const RE_CHARSET = /^charset$/i +const RE_FILENAME = /^filename$/i +const RE_NAME = /^name$/i + +Multipart.detect = /^multipart\/form-data/i +function Multipart (boy, cfg) { + let i + let len + const self = this + let boundary + const limits = cfg.limits + const isPartAFile = cfg.isPartAFile || ((fieldName, contentType, fileName) => (contentType === 'application/octet-stream' || fileName !== undefined)) + const parsedConType = cfg.parsedConType || [] + const defCharset = cfg.defCharset || 'utf8' + const preservePath = cfg.preservePath + const fileOpts = { highWaterMark: cfg.fileHwm } + + for (i = 0, len = parsedConType.length; i < len; ++i) { + if (Array.isArray(parsedConType[i]) && + RE_BOUNDARY.test(parsedConType[i][0])) { + boundary = parsedConType[i][1] + break + } + } + + function checkFinished () { + if (nends === 0 && finished && !boy._done) { + finished = false + self.end() + } + } + + if (typeof boundary !== 'string') { throw new Error('Multipart: Boundary not found') } + + const fieldSizeLimit = getLimit(limits, 'fieldSize', 1 * 1024 * 1024) + const fileSizeLimit = getLimit(limits, 'fileSize', Infinity) + const filesLimit = getLimit(limits, 'files', Infinity) + const fieldsLimit = getLimit(limits, 'fields', Infinity) + const partsLimit = getLimit(limits, 'parts', Infinity) + const headerPairsLimit = getLimit(limits, 'headerPairs', 2000) + const headerSizeLimit = getLimit(limits, 'headerSize', 80 * 1024) + + let nfiles = 0 + let nfields = 0 + let nends = 0 + let curFile + let curField + let finished = false + + this._needDrain = false + this._pause = false + this._cb = undefined + this._nparts = 0 + this._boy = boy + + const parserCfg = { + boundary, + maxHeaderPairs: headerPairsLimit, + maxHeaderSize: headerSizeLimit, + partHwm: fileOpts.highWaterMark, + highWaterMark: cfg.highWaterMark + } + + this.parser = new Dicer(parserCfg) + this.parser.on('drain', function () { + self._needDrain = false + if (self._cb && !self._pause) { + const cb = self._cb + self._cb = undefined + cb() + } + }).on('part', function onPart (part) { + if (++self._nparts > partsLimit) { + self.parser.removeListener('part', onPart) + self.parser.on('part', skipPart) + boy.hitPartsLimit = true + boy.emit('partsLimit') + return skipPart(part) + } + + // hack because streams2 _always_ doesn't emit 'end' until nextTick, so let + // us emit 'end' early since we know the part has ended if we are already + // seeing the next part + if (curField) { + const field = curField + field.emit('end') + field.removeAllListeners('end') + } + + part.on('header', function (header) { + let contype + let fieldname + let parsed + let charset + let encoding + let filename + let nsize = 0 + + if (header['content-type']) { + parsed = parseParams(header['content-type'][0]) + if (parsed[0]) { + contype = parsed[0].toLowerCase() + for (i = 0, len = parsed.length; i < len; ++i) { + if (RE_CHARSET.test(parsed[i][0])) { + charset = parsed[i][1].toLowerCase() + break + } + } + } + } + + if (contype === undefined) { contype = 'text/plain' } + if (charset === undefined) { charset = defCharset } + + if (header['content-disposition']) { + parsed = parseParams(header['content-disposition'][0]) + if (!RE_FIELD.test(parsed[0])) { return skipPart(part) } + for (i = 0, len = parsed.length; i < len; ++i) { + if (RE_NAME.test(parsed[i][0])) { + fieldname = parsed[i][1] + } else if (RE_FILENAME.test(parsed[i][0])) { + filename = parsed[i][1] + if (!preservePath) { filename = basename(filename) } + } + } + } else { return skipPart(part) } + + if (header['content-transfer-encoding']) { encoding = header['content-transfer-encoding'][0].toLowerCase() } else { encoding = '7bit' } + + let onData, + onEnd + + if (isPartAFile(fieldname, contype, filename)) { + // file/binary field + if (nfiles === filesLimit) { + if (!boy.hitFilesLimit) { + boy.hitFilesLimit = true + boy.emit('filesLimit') + } + return skipPart(part) + } + + ++nfiles + + if (boy.listenerCount('file') === 0) { + self.parser._ignore() + return + } + + ++nends + const file = new FileStream(fileOpts) + curFile = file + file.on('end', function () { + --nends + self._pause = false + checkFinished() + if (self._cb && !self._needDrain) { + const cb = self._cb + self._cb = undefined + cb() + } + }) + file._read = function (n) { + if (!self._pause) { return } + self._pause = false + if (self._cb && !self._needDrain) { + const cb = self._cb + self._cb = undefined + cb() + } + } + boy.emit('file', fieldname, file, filename, encoding, contype) + + onData = function (data) { + if ((nsize += data.length) > fileSizeLimit) { + const extralen = fileSizeLimit - nsize + data.length + if (extralen > 0) { file.push(data.slice(0, extralen)) } + file.truncated = true + file.bytesRead = fileSizeLimit + part.removeAllListeners('data') + file.emit('limit') + return + } else if (!file.push(data)) { self._pause = true } + + file.bytesRead = nsize + } + + onEnd = function () { + curFile = undefined + file.push(null) + } + } else { + // non-file field + if (nfields === fieldsLimit) { + if (!boy.hitFieldsLimit) { + boy.hitFieldsLimit = true + boy.emit('fieldsLimit') + } + return skipPart(part) + } + + ++nfields + ++nends + let buffer = '' + let truncated = false + curField = part + + onData = function (data) { + if ((nsize += data.length) > fieldSizeLimit) { + const extralen = (fieldSizeLimit - (nsize - data.length)) + buffer += data.toString('binary', 0, extralen) + truncated = true + part.removeAllListeners('data') + } else { buffer += data.toString('binary') } + } + + onEnd = function () { + curField = undefined + if (buffer.length) { buffer = decodeText(buffer, 'binary', charset) } + boy.emit('field', fieldname, buffer, false, truncated, encoding, contype) + --nends + checkFinished() + } + } + + /* As of node@2efe4ab761666 (v0.10.29+/v0.11.14+), busboy had become + broken. Streams2/streams3 is a huge black box of confusion, but + somehow overriding the sync state seems to fix things again (and still + seems to work for previous node versions). + */ + part._readableState.sync = false + + part.on('data', onData) + part.on('end', onEnd) + }).on('error', function (err) { + if (curFile) { curFile.emit('error', err) } + }) + }).on('error', function (err) { + boy.emit('error', err) + }).on('finish', function () { + finished = true + checkFinished() + }) +} + +Multipart.prototype.write = function (chunk, cb) { + const r = this.parser.write(chunk) + if (r && !this._pause) { + cb() + } else { + this._needDrain = !r + this._cb = cb + } +} + +Multipart.prototype.end = function () { + const self = this + + if (self.parser.writable) { + self.parser.end() + } else if (!self._boy._done) { + process.nextTick(function () { + self._boy._done = true + self._boy.emit('finish') + }) + } +} + +function skipPart (part) { + part.resume() +} + +function FileStream (opts) { + Readable.call(this, opts) + + this.bytesRead = 0 + + this.truncated = false +} + +inherits(FileStream, Readable) + +FileStream.prototype._read = function (n) {} + +module.exports = Multipart + + +/***/ }), + +/***/ 855: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const Decoder = __nccwpck_require__(1496) +const decodeText = __nccwpck_require__(2747) +const getLimit = __nccwpck_require__(2393) + +const RE_CHARSET = /^charset$/i + +UrlEncoded.detect = /^application\/x-www-form-urlencoded/i +function UrlEncoded (boy, cfg) { + const limits = cfg.limits + const parsedConType = cfg.parsedConType + this.boy = boy + + this.fieldSizeLimit = getLimit(limits, 'fieldSize', 1 * 1024 * 1024) + this.fieldNameSizeLimit = getLimit(limits, 'fieldNameSize', 100) + this.fieldsLimit = getLimit(limits, 'fields', Infinity) + + let charset + for (var i = 0, len = parsedConType.length; i < len; ++i) { // eslint-disable-line no-var + if (Array.isArray(parsedConType[i]) && + RE_CHARSET.test(parsedConType[i][0])) { + charset = parsedConType[i][1].toLowerCase() + break + } + } + + if (charset === undefined) { charset = cfg.defCharset || 'utf8' } + + this.decoder = new Decoder() + this.charset = charset + this._fields = 0 + this._state = 'key' + this._checkingBytes = true + this._bytesKey = 0 + this._bytesVal = 0 + this._key = '' + this._val = '' + this._keyTrunc = false + this._valTrunc = false + this._hitLimit = false +} + +UrlEncoded.prototype.write = function (data, cb) { + if (this._fields === this.fieldsLimit) { + if (!this.boy.hitFieldsLimit) { + this.boy.hitFieldsLimit = true + this.boy.emit('fieldsLimit') + } + return cb() + } + + let idxeq; let idxamp; let i; let p = 0; const len = data.length + + while (p < len) { + if (this._state === 'key') { + idxeq = idxamp = undefined + for (i = p; i < len; ++i) { + if (!this._checkingBytes) { ++p } + if (data[i] === 0x3D/* = */) { + idxeq = i + break + } else if (data[i] === 0x26/* & */) { + idxamp = i + break + } + if (this._checkingBytes && this._bytesKey === this.fieldNameSizeLimit) { + this._hitLimit = true + break + } else if (this._checkingBytes) { ++this._bytesKey } + } + + if (idxeq !== undefined) { + // key with assignment + if (idxeq > p) { this._key += this.decoder.write(data.toString('binary', p, idxeq)) } + this._state = 'val' + + this._hitLimit = false + this._checkingBytes = true + this._val = '' + this._bytesVal = 0 + this._valTrunc = false + this.decoder.reset() + + p = idxeq + 1 + } else if (idxamp !== undefined) { + // key with no assignment + ++this._fields + let key; const keyTrunc = this._keyTrunc + if (idxamp > p) { key = (this._key += this.decoder.write(data.toString('binary', p, idxamp))) } else { key = this._key } + + this._hitLimit = false + this._checkingBytes = true + this._key = '' + this._bytesKey = 0 + this._keyTrunc = false + this.decoder.reset() + + if (key.length) { + this.boy.emit('field', decodeText(key, 'binary', this.charset), + '', + keyTrunc, + false) + } + + p = idxamp + 1 + if (this._fields === this.fieldsLimit) { return cb() } + } else if (this._hitLimit) { + // we may not have hit the actual limit if there are encoded bytes... + if (i > p) { this._key += this.decoder.write(data.toString('binary', p, i)) } + p = i + if ((this._bytesKey = this._key.length) === this.fieldNameSizeLimit) { + // yep, we actually did hit the limit + this._checkingBytes = false + this._keyTrunc = true + } + } else { + if (p < len) { this._key += this.decoder.write(data.toString('binary', p)) } + p = len + } + } else { + idxamp = undefined + for (i = p; i < len; ++i) { + if (!this._checkingBytes) { ++p } + if (data[i] === 0x26/* & */) { + idxamp = i + break + } + if (this._checkingBytes && this._bytesVal === this.fieldSizeLimit) { + this._hitLimit = true + break + } else if (this._checkingBytes) { ++this._bytesVal } + } + + if (idxamp !== undefined) { + ++this._fields + if (idxamp > p) { this._val += this.decoder.write(data.toString('binary', p, idxamp)) } + this.boy.emit('field', decodeText(this._key, 'binary', this.charset), + decodeText(this._val, 'binary', this.charset), + this._keyTrunc, + this._valTrunc) + this._state = 'key' + + this._hitLimit = false + this._checkingBytes = true + this._key = '' + this._bytesKey = 0 + this._keyTrunc = false + this.decoder.reset() + + p = idxamp + 1 + if (this._fields === this.fieldsLimit) { return cb() } + } else if (this._hitLimit) { + // we may not have hit the actual limit if there are encoded bytes... + if (i > p) { this._val += this.decoder.write(data.toString('binary', p, i)) } + p = i + if ((this._val === '' && this.fieldSizeLimit === 0) || + (this._bytesVal = this._val.length) === this.fieldSizeLimit) { + // yep, we actually did hit the limit + this._checkingBytes = false + this._valTrunc = true + } + } else { + if (p < len) { this._val += this.decoder.write(data.toString('binary', p)) } + p = len + } + } + } + cb() +} + +UrlEncoded.prototype.end = function () { + if (this.boy._done) { return } + + if (this._state === 'key' && this._key.length > 0) { + this.boy.emit('field', decodeText(this._key, 'binary', this.charset), + '', + this._keyTrunc, + false) + } else if (this._state === 'val') { + this.boy.emit('field', decodeText(this._key, 'binary', this.charset), + decodeText(this._val, 'binary', this.charset), + this._keyTrunc, + this._valTrunc) + } + this.boy._done = true + this.boy.emit('finish') +} + +module.exports = UrlEncoded + + +/***/ }), + +/***/ 1496: +/***/ ((module) => { + + + +const RE_PLUS = /\+/g + +const HEX = [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, + 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 +] + +function Decoder () { + this.buffer = undefined +} +Decoder.prototype.write = function (str) { + // Replace '+' with ' ' before decoding + str = str.replace(RE_PLUS, ' ') + let res = '' + let i = 0; let p = 0; const len = str.length + for (; i < len; ++i) { + if (this.buffer !== undefined) { + if (!HEX[str.charCodeAt(i)]) { + res += '%' + this.buffer + this.buffer = undefined + --i // retry character + } else { + this.buffer += str[i] + ++p + if (this.buffer.length === 2) { + res += String.fromCharCode(parseInt(this.buffer, 16)) + this.buffer = undefined + } + } + } else if (str[i] === '%') { + if (i > p) { + res += str.substring(p, i) + p = i + } + this.buffer = '' + ++p + } + } + if (p < len && this.buffer === undefined) { res += str.substring(p) } + return res +} +Decoder.prototype.reset = function () { + this.buffer = undefined +} + +module.exports = Decoder + + +/***/ }), + +/***/ 692: +/***/ ((module) => { + + + +module.exports = function basename (path) { + if (typeof path !== 'string') { return '' } + for (var i = path.length - 1; i >= 0; --i) { // eslint-disable-line no-var + switch (path.charCodeAt(i)) { + case 0x2F: // '/' + case 0x5C: // '\' + path = path.slice(i + 1) + return (path === '..' || path === '.' ? '' : path) + } + } + return (path === '..' || path === '.' ? '' : path) +} + + +/***/ }), + +/***/ 2747: +/***/ (function(module) { + + + +// Node has always utf-8 +const utf8Decoder = new TextDecoder('utf-8') +const textDecoders = new Map([ + ['utf-8', utf8Decoder], + ['utf8', utf8Decoder] +]) + +function getDecoder (charset) { + let lc + while (true) { + switch (charset) { + case 'utf-8': + case 'utf8': + return decoders.utf8 + case 'latin1': + case 'ascii': // TODO: Make these a separate, strict decoder? + case 'us-ascii': + case 'iso-8859-1': + case 'iso8859-1': + case 'iso88591': + case 'iso_8859-1': + case 'windows-1252': + case 'iso_8859-1:1987': + case 'cp1252': + case 'x-cp1252': + return decoders.latin1 + case 'utf16le': + case 'utf-16le': + case 'ucs2': + case 'ucs-2': + return decoders.utf16le + case 'base64': + return decoders.base64 + default: + if (lc === undefined) { + lc = true + charset = charset.toLowerCase() + continue + } + return decoders.other.bind(charset) + } + } +} + +const decoders = { + utf8: (data, sourceEncoding) => { + if (data.length === 0) { + return '' + } + if (typeof data === 'string') { + data = Buffer.from(data, sourceEncoding) + } + return data.utf8Slice(0, data.length) + }, + + latin1: (data, sourceEncoding) => { + if (data.length === 0) { + return '' + } + if (typeof data === 'string') { + return data + } + return data.latin1Slice(0, data.length) + }, + + utf16le: (data, sourceEncoding) => { + if (data.length === 0) { + return '' + } + if (typeof data === 'string') { + data = Buffer.from(data, sourceEncoding) + } + return data.ucs2Slice(0, data.length) + }, + + base64: (data, sourceEncoding) => { + if (data.length === 0) { + return '' + } + if (typeof data === 'string') { + data = Buffer.from(data, sourceEncoding) + } + return data.base64Slice(0, data.length) + }, + + other: (data, sourceEncoding) => { + if (data.length === 0) { + return '' + } + if (typeof data === 'string') { + data = Buffer.from(data, sourceEncoding) + } + + if (textDecoders.has(this.toString())) { + try { + return textDecoders.get(this).decode(data) + } catch {} + } + return typeof data === 'string' + ? data + : data.toString() + } +} + +function decodeText (text, sourceEncoding, destEncoding) { + if (text) { + return getDecoder(destEncoding)(text, sourceEncoding) + } + return text +} + +module.exports = decodeText + + +/***/ }), + +/***/ 2393: +/***/ ((module) => { + + + +module.exports = function getLimit (limits, name, defaultLimit) { + if ( + !limits || + limits[name] === undefined || + limits[name] === null + ) { return defaultLimit } + + if ( + typeof limits[name] !== 'number' || + isNaN(limits[name]) + ) { throw new TypeError('Limit ' + name + ' is not a valid number') } + + return limits[name] +} + + +/***/ }), + +/***/ 8929: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +/* eslint-disable object-property-newline */ + + +const decodeText = __nccwpck_require__(2747) + +const RE_ENCODED = /%[a-fA-F0-9][a-fA-F0-9]/g + +const EncodedLookup = { + '%00': '\x00', '%01': '\x01', '%02': '\x02', '%03': '\x03', '%04': '\x04', + '%05': '\x05', '%06': '\x06', '%07': '\x07', '%08': '\x08', '%09': '\x09', + '%0a': '\x0a', '%0A': '\x0a', '%0b': '\x0b', '%0B': '\x0b', '%0c': '\x0c', + '%0C': '\x0c', '%0d': '\x0d', '%0D': '\x0d', '%0e': '\x0e', '%0E': '\x0e', + '%0f': '\x0f', '%0F': '\x0f', '%10': '\x10', '%11': '\x11', '%12': '\x12', + '%13': '\x13', '%14': '\x14', '%15': '\x15', '%16': '\x16', '%17': '\x17', + '%18': '\x18', '%19': '\x19', '%1a': '\x1a', '%1A': '\x1a', '%1b': '\x1b', + '%1B': '\x1b', '%1c': '\x1c', '%1C': '\x1c', '%1d': '\x1d', '%1D': '\x1d', + '%1e': '\x1e', '%1E': '\x1e', '%1f': '\x1f', '%1F': '\x1f', '%20': '\x20', + '%21': '\x21', '%22': '\x22', '%23': '\x23', '%24': '\x24', '%25': '\x25', + '%26': '\x26', '%27': '\x27', '%28': '\x28', '%29': '\x29', '%2a': '\x2a', + '%2A': '\x2a', '%2b': '\x2b', '%2B': '\x2b', '%2c': '\x2c', '%2C': '\x2c', + '%2d': '\x2d', '%2D': '\x2d', '%2e': '\x2e', '%2E': '\x2e', '%2f': '\x2f', + '%2F': '\x2f', '%30': '\x30', '%31': '\x31', '%32': '\x32', '%33': '\x33', + '%34': '\x34', '%35': '\x35', '%36': '\x36', '%37': '\x37', '%38': '\x38', + '%39': '\x39', '%3a': '\x3a', '%3A': '\x3a', '%3b': '\x3b', '%3B': '\x3b', + '%3c': '\x3c', '%3C': '\x3c', '%3d': '\x3d', '%3D': '\x3d', '%3e': '\x3e', + '%3E': '\x3e', '%3f': '\x3f', '%3F': '\x3f', '%40': '\x40', '%41': '\x41', + '%42': '\x42', '%43': '\x43', '%44': '\x44', '%45': '\x45', '%46': '\x46', + '%47': '\x47', '%48': '\x48', '%49': '\x49', '%4a': '\x4a', '%4A': '\x4a', + '%4b': '\x4b', '%4B': '\x4b', '%4c': '\x4c', '%4C': '\x4c', '%4d': '\x4d', + '%4D': '\x4d', '%4e': '\x4e', '%4E': '\x4e', '%4f': '\x4f', '%4F': '\x4f', + '%50': '\x50', '%51': '\x51', '%52': '\x52', '%53': '\x53', '%54': '\x54', + '%55': '\x55', '%56': '\x56', '%57': '\x57', '%58': '\x58', '%59': '\x59', + '%5a': '\x5a', '%5A': '\x5a', '%5b': '\x5b', '%5B': '\x5b', '%5c': '\x5c', + '%5C': '\x5c', '%5d': '\x5d', '%5D': '\x5d', '%5e': '\x5e', '%5E': '\x5e', + '%5f': '\x5f', '%5F': '\x5f', '%60': '\x60', '%61': '\x61', '%62': '\x62', + '%63': '\x63', '%64': '\x64', '%65': '\x65', '%66': '\x66', '%67': '\x67', + '%68': '\x68', '%69': '\x69', '%6a': '\x6a', '%6A': '\x6a', '%6b': '\x6b', + '%6B': '\x6b', '%6c': '\x6c', '%6C': '\x6c', '%6d': '\x6d', '%6D': '\x6d', + '%6e': '\x6e', '%6E': '\x6e', '%6f': '\x6f', '%6F': '\x6f', '%70': '\x70', + '%71': '\x71', '%72': '\x72', '%73': '\x73', '%74': '\x74', '%75': '\x75', + '%76': '\x76', '%77': '\x77', '%78': '\x78', '%79': '\x79', '%7a': '\x7a', + '%7A': '\x7a', '%7b': '\x7b', '%7B': '\x7b', '%7c': '\x7c', '%7C': '\x7c', + '%7d': '\x7d', '%7D': '\x7d', '%7e': '\x7e', '%7E': '\x7e', '%7f': '\x7f', + '%7F': '\x7f', '%80': '\x80', '%81': '\x81', '%82': '\x82', '%83': '\x83', + '%84': '\x84', '%85': '\x85', '%86': '\x86', '%87': '\x87', '%88': '\x88', + '%89': '\x89', '%8a': '\x8a', '%8A': '\x8a', '%8b': '\x8b', '%8B': '\x8b', + '%8c': '\x8c', '%8C': '\x8c', '%8d': '\x8d', '%8D': '\x8d', '%8e': '\x8e', + '%8E': '\x8e', '%8f': '\x8f', '%8F': '\x8f', '%90': '\x90', '%91': '\x91', + '%92': '\x92', '%93': '\x93', '%94': '\x94', '%95': '\x95', '%96': '\x96', + '%97': '\x97', '%98': '\x98', '%99': '\x99', '%9a': '\x9a', '%9A': '\x9a', + '%9b': '\x9b', '%9B': '\x9b', '%9c': '\x9c', '%9C': '\x9c', '%9d': '\x9d', + '%9D': '\x9d', '%9e': '\x9e', '%9E': '\x9e', '%9f': '\x9f', '%9F': '\x9f', + '%a0': '\xa0', '%A0': '\xa0', '%a1': '\xa1', '%A1': '\xa1', '%a2': '\xa2', + '%A2': '\xa2', '%a3': '\xa3', '%A3': '\xa3', '%a4': '\xa4', '%A4': '\xa4', + '%a5': '\xa5', '%A5': '\xa5', '%a6': '\xa6', '%A6': '\xa6', '%a7': '\xa7', + '%A7': '\xa7', '%a8': '\xa8', '%A8': '\xa8', '%a9': '\xa9', '%A9': '\xa9', + '%aa': '\xaa', '%Aa': '\xaa', '%aA': '\xaa', '%AA': '\xaa', '%ab': '\xab', + '%Ab': '\xab', '%aB': '\xab', '%AB': '\xab', '%ac': '\xac', '%Ac': '\xac', + '%aC': '\xac', '%AC': '\xac', '%ad': '\xad', '%Ad': '\xad', '%aD': '\xad', + '%AD': '\xad', '%ae': '\xae', '%Ae': '\xae', '%aE': '\xae', '%AE': '\xae', + '%af': '\xaf', '%Af': '\xaf', '%aF': '\xaf', '%AF': '\xaf', '%b0': '\xb0', + '%B0': '\xb0', '%b1': '\xb1', '%B1': '\xb1', '%b2': '\xb2', '%B2': '\xb2', + '%b3': '\xb3', '%B3': '\xb3', '%b4': '\xb4', '%B4': '\xb4', '%b5': '\xb5', + '%B5': '\xb5', '%b6': '\xb6', '%B6': '\xb6', '%b7': '\xb7', '%B7': '\xb7', + '%b8': '\xb8', '%B8': '\xb8', '%b9': '\xb9', '%B9': '\xb9', '%ba': '\xba', + '%Ba': '\xba', '%bA': '\xba', '%BA': '\xba', '%bb': '\xbb', '%Bb': '\xbb', + '%bB': '\xbb', '%BB': '\xbb', '%bc': '\xbc', '%Bc': '\xbc', '%bC': '\xbc', + '%BC': '\xbc', '%bd': '\xbd', '%Bd': '\xbd', '%bD': '\xbd', '%BD': '\xbd', + '%be': '\xbe', '%Be': '\xbe', '%bE': '\xbe', '%BE': '\xbe', '%bf': '\xbf', + '%Bf': '\xbf', '%bF': '\xbf', '%BF': '\xbf', '%c0': '\xc0', '%C0': '\xc0', + '%c1': '\xc1', '%C1': '\xc1', '%c2': '\xc2', '%C2': '\xc2', '%c3': '\xc3', + '%C3': '\xc3', '%c4': '\xc4', '%C4': '\xc4', '%c5': '\xc5', '%C5': '\xc5', + '%c6': '\xc6', '%C6': '\xc6', '%c7': '\xc7', '%C7': '\xc7', '%c8': '\xc8', + '%C8': '\xc8', '%c9': '\xc9', '%C9': '\xc9', '%ca': '\xca', '%Ca': '\xca', + '%cA': '\xca', '%CA': '\xca', '%cb': '\xcb', '%Cb': '\xcb', '%cB': '\xcb', + '%CB': '\xcb', '%cc': '\xcc', '%Cc': '\xcc', '%cC': '\xcc', '%CC': '\xcc', + '%cd': '\xcd', '%Cd': '\xcd', '%cD': '\xcd', '%CD': '\xcd', '%ce': '\xce', + '%Ce': '\xce', '%cE': '\xce', '%CE': '\xce', '%cf': '\xcf', '%Cf': '\xcf', + '%cF': '\xcf', '%CF': '\xcf', '%d0': '\xd0', '%D0': '\xd0', '%d1': '\xd1', + '%D1': '\xd1', '%d2': '\xd2', '%D2': '\xd2', '%d3': '\xd3', '%D3': '\xd3', + '%d4': '\xd4', '%D4': '\xd4', '%d5': '\xd5', '%D5': '\xd5', '%d6': '\xd6', + '%D6': '\xd6', '%d7': '\xd7', '%D7': '\xd7', '%d8': '\xd8', '%D8': '\xd8', + '%d9': '\xd9', '%D9': '\xd9', '%da': '\xda', '%Da': '\xda', '%dA': '\xda', + '%DA': '\xda', '%db': '\xdb', '%Db': '\xdb', '%dB': '\xdb', '%DB': '\xdb', + '%dc': '\xdc', '%Dc': '\xdc', '%dC': '\xdc', '%DC': '\xdc', '%dd': '\xdd', + '%Dd': '\xdd', '%dD': '\xdd', '%DD': '\xdd', '%de': '\xde', '%De': '\xde', + '%dE': '\xde', '%DE': '\xde', '%df': '\xdf', '%Df': '\xdf', '%dF': '\xdf', + '%DF': '\xdf', '%e0': '\xe0', '%E0': '\xe0', '%e1': '\xe1', '%E1': '\xe1', + '%e2': '\xe2', '%E2': '\xe2', '%e3': '\xe3', '%E3': '\xe3', '%e4': '\xe4', + '%E4': '\xe4', '%e5': '\xe5', '%E5': '\xe5', '%e6': '\xe6', '%E6': '\xe6', + '%e7': '\xe7', '%E7': '\xe7', '%e8': '\xe8', '%E8': '\xe8', '%e9': '\xe9', + '%E9': '\xe9', '%ea': '\xea', '%Ea': '\xea', '%eA': '\xea', '%EA': '\xea', + '%eb': '\xeb', '%Eb': '\xeb', '%eB': '\xeb', '%EB': '\xeb', '%ec': '\xec', + '%Ec': '\xec', '%eC': '\xec', '%EC': '\xec', '%ed': '\xed', '%Ed': '\xed', + '%eD': '\xed', '%ED': '\xed', '%ee': '\xee', '%Ee': '\xee', '%eE': '\xee', + '%EE': '\xee', '%ef': '\xef', '%Ef': '\xef', '%eF': '\xef', '%EF': '\xef', + '%f0': '\xf0', '%F0': '\xf0', '%f1': '\xf1', '%F1': '\xf1', '%f2': '\xf2', + '%F2': '\xf2', '%f3': '\xf3', '%F3': '\xf3', '%f4': '\xf4', '%F4': '\xf4', + '%f5': '\xf5', '%F5': '\xf5', '%f6': '\xf6', '%F6': '\xf6', '%f7': '\xf7', + '%F7': '\xf7', '%f8': '\xf8', '%F8': '\xf8', '%f9': '\xf9', '%F9': '\xf9', + '%fa': '\xfa', '%Fa': '\xfa', '%fA': '\xfa', '%FA': '\xfa', '%fb': '\xfb', + '%Fb': '\xfb', '%fB': '\xfb', '%FB': '\xfb', '%fc': '\xfc', '%Fc': '\xfc', + '%fC': '\xfc', '%FC': '\xfc', '%fd': '\xfd', '%Fd': '\xfd', '%fD': '\xfd', + '%FD': '\xfd', '%fe': '\xfe', '%Fe': '\xfe', '%fE': '\xfe', '%FE': '\xfe', + '%ff': '\xff', '%Ff': '\xff', '%fF': '\xff', '%FF': '\xff' +} + +function encodedReplacer (match) { + return EncodedLookup[match] +} + +const STATE_KEY = 0 +const STATE_VALUE = 1 +const STATE_CHARSET = 2 +const STATE_LANG = 3 + +function parseParams (str) { + const res = [] + let state = STATE_KEY + let charset = '' + let inquote = false + let escaping = false + let p = 0 + let tmp = '' + const len = str.length + + for (var i = 0; i < len; ++i) { // eslint-disable-line no-var + const char = str[i] + if (char === '\\' && inquote) { + if (escaping) { escaping = false } else { + escaping = true + continue + } + } else if (char === '"') { + if (!escaping) { + if (inquote) { + inquote = false + state = STATE_KEY + } else { inquote = true } + continue + } else { escaping = false } + } else { + if (escaping && inquote) { tmp += '\\' } + escaping = false + if ((state === STATE_CHARSET || state === STATE_LANG) && char === "'") { + if (state === STATE_CHARSET) { + state = STATE_LANG + charset = tmp.substring(1) + } else { state = STATE_VALUE } + tmp = '' + continue + } else if (state === STATE_KEY && + (char === '*' || char === '=') && + res.length) { + state = char === '*' + ? STATE_CHARSET + : STATE_VALUE + res[p] = [tmp, undefined] + tmp = '' + continue + } else if (!inquote && char === ';') { + state = STATE_KEY + if (charset) { + if (tmp.length) { + tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer), + 'binary', + charset) + } + charset = '' + } else if (tmp.length) { + tmp = decodeText(tmp, 'binary', 'utf8') + } + if (res[p] === undefined) { res[p] = tmp } else { res[p][1] = tmp } + tmp = '' + ++p + continue + } else if (!inquote && (char === ' ' || char === '\t')) { continue } + } + tmp += char + } + if (charset && tmp.length) { + tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer), + 'binary', + charset) + } else if (tmp) { + tmp = decodeText(tmp, 'binary', 'utf8') + } + + if (res[p] === undefined) { + if (tmp) { res[p] = tmp } + } else { res[p][1] = tmp } + + return res +} + +module.exports = parseParams + + +/***/ }), + +/***/ 2046: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const index_js_1 = __importDefault(__nccwpck_require__(1059)); +__exportStar(__nccwpck_require__(1059), exports); +exports["default"] = index_js_1.default; + + +/***/ }), + +/***/ 2111: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ZodError = exports.quotelessJson = exports.ZodIssueCode = void 0; +const util_js_1 = __nccwpck_require__(3304); +exports.ZodIssueCode = util_js_1.util.arrayToEnum([ + "invalid_type", + "invalid_literal", + "custom", + "invalid_union", + "invalid_union_discriminator", + "invalid_enum_value", + "unrecognized_keys", + "invalid_arguments", + "invalid_return_type", + "invalid_date", + "invalid_string", + "too_small", + "too_big", + "invalid_intersection_types", + "not_multiple_of", + "not_finite", +]); +const quotelessJson = (obj) => { + const json = JSON.stringify(obj, null, 2); + return json.replace(/"([^"]+)":/g, "$1:"); +}; +exports.quotelessJson = quotelessJson; +class ZodError extends Error { + get errors() { + return this.issues; + } + constructor(issues) { + super(); + this.issues = []; + this.addIssue = (sub) => { + this.issues = [...this.issues, sub]; + }; + this.addIssues = (subs = []) => { + this.issues = [...this.issues, ...subs]; + }; + const actualProto = new.target.prototype; + if (Object.setPrototypeOf) { + // eslint-disable-next-line ban/ban + Object.setPrototypeOf(this, actualProto); + } + else { + this.__proto__ = actualProto; + } + this.name = "ZodError"; + this.issues = issues; + } + format(_mapper) { + const mapper = _mapper || + function (issue) { + return issue.message; + }; + const fieldErrors = { _errors: [] }; + const processError = (error) => { + for (const issue of error.issues) { + if (issue.code === "invalid_union") { + issue.unionErrors.map(processError); } - } - else if (check.kind === "uuid") { - if (!uuidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - validation: "uuid", - code: ZodError_1.ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); + else if (issue.code === "invalid_return_type") { + processError(issue.returnTypeError); } - } - else if (check.kind === "nanoid") { - if (!nanoidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - validation: "nanoid", - code: ZodError_1.ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); + else if (issue.code === "invalid_arguments") { + processError(issue.argumentsError); + } + else if (issue.path.length === 0) { + fieldErrors._errors.push(mapper(issue)); + } + else { + let curr = fieldErrors; + let i = 0; + while (i < issue.path.length) { + const el = issue.path[i]; + const terminal = i === issue.path.length - 1; + if (!terminal) { + curr[el] = curr[el] || { _errors: [] }; + // if (typeof el === "string") { + // curr[el] = curr[el] || { _errors: [] }; + // } else if (typeof el === "number") { + // const errorArray: any = []; + // errorArray._errors = []; + // curr[el] = curr[el] || errorArray; + // } + } + else { + curr[el] = curr[el] || { _errors: [] }; + curr[el]._errors.push(mapper(issue)); + } + curr = curr[el]; + i++; + } } } - else if (check.kind === "cuid") { - if (!cuidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - validation: "cuid", - code: ZodError_1.ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); + }; + processError(this); + return fieldErrors; + } + static assert(value) { + if (!(value instanceof ZodError)) { + throw new Error(`Not a ZodError: ${value}`); + } + } + toString() { + return this.message; + } + get message() { + return JSON.stringify(this.issues, util_js_1.util.jsonStringifyReplacer, 2); + } + get isEmpty() { + return this.issues.length === 0; + } + flatten(mapper = (issue) => issue.message) { + const fieldErrors = {}; + const formErrors = []; + for (const sub of this.issues) { + if (sub.path.length > 0) { + fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; + fieldErrors[sub.path[0]].push(mapper(sub)); + } + else { + formErrors.push(mapper(sub)); + } + } + return { formErrors, fieldErrors }; + } + get formErrors() { + return this.flatten(); + } +} +exports.ZodError = ZodError; +ZodError.create = (issues) => { + const error = new ZodError(issues); + return error; +}; + + +/***/ }), + +/***/ 7665: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.defaultErrorMap = void 0; +exports.setErrorMap = setErrorMap; +exports.getErrorMap = getErrorMap; +const en_js_1 = __importDefault(__nccwpck_require__(2929)); +exports.defaultErrorMap = en_js_1.default; +let overrideErrorMap = en_js_1.default; +function setErrorMap(map) { + overrideErrorMap = map; +} +function getErrorMap() { + return overrideErrorMap; +} + + +/***/ }), + +/***/ 8101: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +__exportStar(__nccwpck_require__(7665), exports); +__exportStar(__nccwpck_require__(937), exports); +__exportStar(__nccwpck_require__(6822), exports); +__exportStar(__nccwpck_require__(3304), exports); +__exportStar(__nccwpck_require__(4741), exports); +__exportStar(__nccwpck_require__(2111), exports); + + +/***/ }), + +/***/ 1344: +/***/ ((__unused_webpack_module, exports) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.errorUtil = void 0; +var errorUtil; +(function (errorUtil) { + errorUtil.errToObj = (message) => typeof message === "string" ? { message } : message || {}; + // biome-ignore lint: + errorUtil.toString = (message) => typeof message === "string" ? message : message?.message; +})(errorUtil || (exports.errorUtil = errorUtil = {})); + + +/***/ }), + +/***/ 937: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.isAsync = exports.isValid = exports.isDirty = exports.isAborted = exports.OK = exports.DIRTY = exports.INVALID = exports.ParseStatus = exports.EMPTY_PATH = exports.makeIssue = void 0; +exports.addIssueToContext = addIssueToContext; +const errors_js_1 = __nccwpck_require__(7665); +const en_js_1 = __importDefault(__nccwpck_require__(2929)); +const makeIssue = (params) => { + const { data, path, errorMaps, issueData } = params; + const fullPath = [...path, ...(issueData.path || [])]; + const fullIssue = { + ...issueData, + path: fullPath, + }; + if (issueData.message !== undefined) { + return { + ...issueData, + path: fullPath, + message: issueData.message, + }; + } + let errorMessage = ""; + const maps = errorMaps + .filter((m) => !!m) + .slice() + .reverse(); + for (const map of maps) { + errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message; + } + return { + ...issueData, + path: fullPath, + message: errorMessage, + }; +}; +exports.makeIssue = makeIssue; +exports.EMPTY_PATH = []; +function addIssueToContext(ctx, issueData) { + const overrideMap = (0, errors_js_1.getErrorMap)(); + const issue = (0, exports.makeIssue)({ + issueData: issueData, + data: ctx.data, + path: ctx.path, + errorMaps: [ + ctx.common.contextualErrorMap, // contextual error map is first priority + ctx.schemaErrorMap, // then schema-bound map if available + overrideMap, // then global override map + overrideMap === en_js_1.default ? undefined : en_js_1.default, // then global default map + ].filter((x) => !!x), + }); + ctx.common.issues.push(issue); +} +class ParseStatus { + constructor() { + this.value = "valid"; + } + dirty() { + if (this.value === "valid") + this.value = "dirty"; + } + abort() { + if (this.value !== "aborted") + this.value = "aborted"; + } + static mergeArray(status, results) { + const arrayValue = []; + for (const s of results) { + if (s.status === "aborted") + return exports.INVALID; + if (s.status === "dirty") + status.dirty(); + arrayValue.push(s.value); + } + return { status: status.value, value: arrayValue }; + } + static async mergeObjectAsync(status, pairs) { + const syncPairs = []; + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + syncPairs.push({ + key, + value, + }); + } + return ParseStatus.mergeObjectSync(status, syncPairs); + } + static mergeObjectSync(status, pairs) { + const finalObject = {}; + for (const pair of pairs) { + const { key, value } = pair; + if (key.status === "aborted") + return exports.INVALID; + if (value.status === "aborted") + return exports.INVALID; + if (key.status === "dirty") + status.dirty(); + if (value.status === "dirty") + status.dirty(); + if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) { + finalObject[key.value] = value.value; + } + } + return { status: status.value, value: finalObject }; + } +} +exports.ParseStatus = ParseStatus; +exports.INVALID = Object.freeze({ + status: "aborted", +}); +const DIRTY = (value) => ({ status: "dirty", value }); +exports.DIRTY = DIRTY; +const OK = (value) => ({ status: "valid", value }); +exports.OK = OK; +const isAborted = (x) => x.status === "aborted"; +exports.isAborted = isAborted; +const isDirty = (x) => x.status === "dirty"; +exports.isDirty = isDirty; +const isValid = (x) => x.status === "valid"; +exports.isValid = isValid; +const isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise; +exports.isAsync = isAsync; + + +/***/ }), + +/***/ 6822: +/***/ ((__unused_webpack_module, exports) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + + +/***/ }), + +/***/ 3304: +/***/ ((__unused_webpack_module, exports) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getParsedType = exports.ZodParsedType = exports.objectUtil = exports.util = void 0; +var util; +(function (util) { + util.assertEqual = (_) => { }; + function assertIs(_arg) { } + util.assertIs = assertIs; + function assertNever(_x) { + throw new Error(); + } + util.assertNever = assertNever; + util.arrayToEnum = (items) => { + const obj = {}; + for (const item of items) { + obj[item] = item; + } + return obj; + }; + util.getValidEnumValues = (obj) => { + const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number"); + const filtered = {}; + for (const k of validKeys) { + filtered[k] = obj[k]; + } + return util.objectValues(filtered); + }; + util.objectValues = (obj) => { + return util.objectKeys(obj).map(function (e) { + return obj[e]; + }); + }; + util.objectKeys = typeof Object.keys === "function" // eslint-disable-line ban/ban + ? (obj) => Object.keys(obj) // eslint-disable-line ban/ban + : (object) => { + const keys = []; + for (const key in object) { + if (Object.prototype.hasOwnProperty.call(object, key)) { + keys.push(key); } } - else if (check.kind === "cuid2") { - if (!cuid2Regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - validation: "cuid2", - code: ZodError_1.ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } + return keys; + }; + util.find = (arr, checker) => { + for (const item of arr) { + if (checker(item)) + return item; + } + return undefined; + }; + util.isInteger = typeof Number.isInteger === "function" + ? (val) => Number.isInteger(val) // eslint-disable-line ban/ban + : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val; + function joinValues(array, separator = " | ") { + return array.map((val) => (typeof val === "string" ? `'${val}'` : val)).join(separator); + } + util.joinValues = joinValues; + util.jsonStringifyReplacer = (_, value) => { + if (typeof value === "bigint") { + return value.toString(); + } + return value; + }; +})(util || (exports.util = util = {})); +var objectUtil; +(function (objectUtil) { + objectUtil.mergeShapes = (first, second) => { + return { + ...first, + ...second, // second overwrites first + }; + }; +})(objectUtil || (exports.objectUtil = objectUtil = {})); +exports.ZodParsedType = util.arrayToEnum([ + "string", + "nan", + "number", + "integer", + "float", + "boolean", + "date", + "bigint", + "symbol", + "function", + "undefined", + "null", + "array", + "object", + "unknown", + "promise", + "void", + "never", + "map", + "set", +]); +const getParsedType = (data) => { + const t = typeof data; + switch (t) { + case "undefined": + return exports.ZodParsedType.undefined; + case "string": + return exports.ZodParsedType.string; + case "number": + return Number.isNaN(data) ? exports.ZodParsedType.nan : exports.ZodParsedType.number; + case "boolean": + return exports.ZodParsedType.boolean; + case "function": + return exports.ZodParsedType.function; + case "bigint": + return exports.ZodParsedType.bigint; + case "symbol": + return exports.ZodParsedType.symbol; + case "object": + if (Array.isArray(data)) { + return exports.ZodParsedType.array; } - else if (check.kind === "ulid") { - if (!ulidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - validation: "ulid", - code: ZodError_1.ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } + if (data === null) { + return exports.ZodParsedType.null; } - else if (check.kind === "url") { - try { - new URL(input.data); - } - catch (_a) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - validation: "url", - code: ZodError_1.ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } + if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { + return exports.ZodParsedType.promise; } - else if (check.kind === "regex") { - check.regex.lastIndex = 0; - const testResult = check.regex.test(input.data); - if (!testResult) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - validation: "regex", - code: ZodError_1.ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } + if (typeof Map !== "undefined" && data instanceof Map) { + return exports.ZodParsedType.map; } - else if (check.kind === "trim") { - input.data = input.data.trim(); + if (typeof Set !== "undefined" && data instanceof Set) { + return exports.ZodParsedType.set; } - else if (check.kind === "includes") { - if (!input.data.includes(check.value, check.position)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_string, - validation: { includes: check.value, position: check.position }, - message: check.message, - }); - status.dirty(); - } + if (typeof Date !== "undefined" && data instanceof Date) { + return exports.ZodParsedType.date; } - else if (check.kind === "toLowerCase") { - input.data = input.data.toLowerCase(); + return exports.ZodParsedType.object; + default: + return exports.ZodParsedType.unknown; + } +}; +exports.getParsedType = getParsedType; + + +/***/ }), + +/***/ 1059: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.z = void 0; +const z = __importStar(__nccwpck_require__(8101)); +exports.z = z; +__exportStar(__nccwpck_require__(8101), exports); +exports["default"] = z; + + +/***/ }), + +/***/ 2929: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const ZodError_js_1 = __nccwpck_require__(2111); +const util_js_1 = __nccwpck_require__(3304); +const errorMap = (issue, _ctx) => { + let message; + switch (issue.code) { + case ZodError_js_1.ZodIssueCode.invalid_type: + if (issue.received === util_js_1.ZodParsedType.undefined) { + message = "Required"; } - else if (check.kind === "toUpperCase") { - input.data = input.data.toUpperCase(); + else { + message = `Expected ${issue.expected}, received ${issue.received}`; } - else if (check.kind === "startsWith") { - if (!input.data.startsWith(check.value)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_string, - validation: { startsWith: check.value }, - message: check.message, - }); - status.dirty(); + break; + case ZodError_js_1.ZodIssueCode.invalid_literal: + message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util_js_1.util.jsonStringifyReplacer)}`; + break; + case ZodError_js_1.ZodIssueCode.unrecognized_keys: + message = `Unrecognized key(s) in object: ${util_js_1.util.joinValues(issue.keys, ", ")}`; + break; + case ZodError_js_1.ZodIssueCode.invalid_union: + message = `Invalid input`; + break; + case ZodError_js_1.ZodIssueCode.invalid_union_discriminator: + message = `Invalid discriminator value. Expected ${util_js_1.util.joinValues(issue.options)}`; + break; + case ZodError_js_1.ZodIssueCode.invalid_enum_value: + message = `Invalid enum value. Expected ${util_js_1.util.joinValues(issue.options)}, received '${issue.received}'`; + break; + case ZodError_js_1.ZodIssueCode.invalid_arguments: + message = `Invalid function arguments`; + break; + case ZodError_js_1.ZodIssueCode.invalid_return_type: + message = `Invalid function return type`; + break; + case ZodError_js_1.ZodIssueCode.invalid_date: + message = `Invalid date`; + break; + case ZodError_js_1.ZodIssueCode.invalid_string: + if (typeof issue.validation === "object") { + if ("includes" in issue.validation) { + message = `Invalid input: must include "${issue.validation.includes}"`; + if (typeof issue.validation.position === "number") { + message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`; + } } - } - else if (check.kind === "endsWith") { - if (!input.data.endsWith(check.value)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_string, - validation: { endsWith: check.value }, - message: check.message, - }); - status.dirty(); + else if ("startsWith" in issue.validation) { + message = `Invalid input: must start with "${issue.validation.startsWith}"`; } - } - else if (check.kind === "datetime") { - const regex = datetimeRegex(check); - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_string, - validation: "datetime", - message: check.message, - }); - status.dirty(); + else if ("endsWith" in issue.validation) { + message = `Invalid input: must end with "${issue.validation.endsWith}"`; } - } - else if (check.kind === "date") { - const regex = dateRegex; - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_string, - validation: "date", - message: check.message, - }); - status.dirty(); + else { + util_js_1.util.assertNever(issue.validation); } } - else if (check.kind === "time") { - const regex = timeRegex(check); - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_string, - validation: "time", - message: check.message, - }); - status.dirty(); - } + else if (issue.validation !== "regex") { + message = `Invalid ${issue.validation}`; } - else if (check.kind === "duration") { - if (!durationRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - validation: "duration", - code: ZodError_1.ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } + else { + message = "Invalid"; } - else if (check.kind === "ip") { - if (!isValidIP(input.data, check.version)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - validation: "ip", - code: ZodError_1.ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } + break; + case ZodError_js_1.ZodIssueCode.too_small: + if (issue.type === "array") + message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`; + else if (issue.type === "string") + message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`; + else if (issue.type === "number") + message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`; + else if (issue.type === "date") + message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`; + else + message = "Invalid input"; + break; + case ZodError_js_1.ZodIssueCode.too_big: + if (issue.type === "array") + message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`; + else if (issue.type === "string") + message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`; + else if (issue.type === "number") + message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; + else if (issue.type === "bigint") + message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; + else if (issue.type === "date") + message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`; + else + message = "Invalid input"; + break; + case ZodError_js_1.ZodIssueCode.custom: + message = `Invalid input`; + break; + case ZodError_js_1.ZodIssueCode.invalid_intersection_types: + message = `Intersection results could not be merged`; + break; + case ZodError_js_1.ZodIssueCode.not_multiple_of: + message = `Number must be a multiple of ${issue.multipleOf}`; + break; + case ZodError_js_1.ZodIssueCode.not_finite: + message = "Number must be finite"; + break; + default: + message = _ctx.defaultError; + util_js_1.util.assertNever(issue); + } + return { message }; +}; +exports["default"] = errorMap; + + +/***/ }), + +/***/ 4741: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.discriminatedUnion = exports.date = exports.boolean = exports.bigint = exports.array = exports.any = exports.coerce = exports.ZodFirstPartyTypeKind = exports.late = exports.ZodSchema = exports.Schema = exports.ZodReadonly = exports.ZodPipeline = exports.ZodBranded = exports.BRAND = exports.ZodNaN = exports.ZodCatch = exports.ZodDefault = exports.ZodNullable = exports.ZodOptional = exports.ZodTransformer = exports.ZodEffects = exports.ZodPromise = exports.ZodNativeEnum = exports.ZodEnum = exports.ZodLiteral = exports.ZodLazy = exports.ZodFunction = exports.ZodSet = exports.ZodMap = exports.ZodRecord = exports.ZodTuple = exports.ZodIntersection = exports.ZodDiscriminatedUnion = exports.ZodUnion = exports.ZodObject = exports.ZodArray = exports.ZodVoid = exports.ZodNever = exports.ZodUnknown = exports.ZodAny = exports.ZodNull = exports.ZodUndefined = exports.ZodSymbol = exports.ZodDate = exports.ZodBoolean = exports.ZodBigInt = exports.ZodNumber = exports.ZodString = exports.ZodType = void 0; +exports.NEVER = exports["void"] = exports.unknown = exports.union = exports.undefined = exports.tuple = exports.transformer = exports.symbol = exports.string = exports.strictObject = exports.set = exports.record = exports.promise = exports.preprocess = exports.pipeline = exports.ostring = exports.optional = exports.onumber = exports.oboolean = exports.object = exports.number = exports.nullable = exports["null"] = exports.never = exports.nativeEnum = exports.nan = exports.map = exports.literal = exports.lazy = exports.intersection = exports["instanceof"] = exports["function"] = exports["enum"] = exports.effect = void 0; +exports.datetimeRegex = datetimeRegex; +exports.custom = custom; +const ZodError_js_1 = __nccwpck_require__(2111); +const errors_js_1 = __nccwpck_require__(7665); +const errorUtil_js_1 = __nccwpck_require__(1344); +const parseUtil_js_1 = __nccwpck_require__(937); +const util_js_1 = __nccwpck_require__(3304); +class ParseInputLazyPath { + constructor(parent, value, path, key) { + this._cachedPath = []; + this.parent = parent; + this.data = value; + this._path = path; + this._key = key; + } + get path() { + if (!this._cachedPath.length) { + if (Array.isArray(this._key)) { + this._cachedPath.push(...this._path, ...this._key); } - else if (check.kind === "jwt") { - if (!isValidJWT(input.data, check.alg)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - validation: "jwt", - code: ZodError_1.ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } + else { + this._cachedPath.push(...this._path, this._key); } - else if (check.kind === "cidr") { - if (!isValidCidr(input.data, check.version)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - validation: "cidr", - code: ZodError_1.ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); + } + return this._cachedPath; + } +} +const handleResult = (ctx, result) => { + if ((0, parseUtil_js_1.isValid)(result)) { + return { success: true, data: result.value }; + } + else { + if (!ctx.common.issues.length) { + throw new Error("Validation failed but no issues detected."); + } + return { + success: false, + get error() { + if (this._error) + return this._error; + const error = new ZodError_js_1.ZodError(ctx.common.issues); + this._error = error; + return this._error; + }, + }; + } +}; +function processCreateParams(params) { + if (!params) + return {}; + const { errorMap, invalid_type_error, required_error, description } = params; + if (errorMap && (invalid_type_error || required_error)) { + throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); + } + if (errorMap) + return { errorMap: errorMap, description }; + const customMap = (iss, ctx) => { + const { message } = params; + if (iss.code === "invalid_enum_value") { + return { message: message ?? ctx.defaultError }; + } + if (typeof ctx.data === "undefined") { + return { message: message ?? required_error ?? ctx.defaultError }; + } + if (iss.code !== "invalid_type") + return { message: ctx.defaultError }; + return { message: message ?? invalid_type_error ?? ctx.defaultError }; + }; + return { errorMap: customMap, description }; +} +class ZodType { + get description() { + return this._def.description; + } + _getType(input) { + return (0, util_js_1.getParsedType)(input.data); + } + _getOrReturnCtx(input, ctx) { + return (ctx || { + common: input.parent.common, + data: input.data, + parsedType: (0, util_js_1.getParsedType)(input.data), + schemaErrorMap: this._def.errorMap, + path: input.path, + parent: input.parent, + }); + } + _processInputParams(input) { + return { + status: new parseUtil_js_1.ParseStatus(), + ctx: { + common: input.parent.common, + data: input.data, + parsedType: (0, util_js_1.getParsedType)(input.data), + schemaErrorMap: this._def.errorMap, + path: input.path, + parent: input.parent, + }, + }; + } + _parseSync(input) { + const result = this._parse(input); + if ((0, parseUtil_js_1.isAsync)(result)) { + throw new Error("Synchronous parse encountered promise."); + } + return result; + } + _parseAsync(input) { + const result = this._parse(input); + return Promise.resolve(result); + } + parse(data, params) { + const result = this.safeParse(data, params); + if (result.success) + return result.data; + throw result.error; + } + safeParse(data, params) { + const ctx = { + common: { + issues: [], + async: params?.async ?? false, + contextualErrorMap: params?.errorMap, + }, + path: params?.path || [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: (0, util_js_1.getParsedType)(data), + }; + const result = this._parseSync({ data, path: ctx.path, parent: ctx }); + return handleResult(ctx, result); + } + "~validate"(data) { + const ctx = { + common: { + issues: [], + async: !!this["~standard"].async, + }, + path: [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: (0, util_js_1.getParsedType)(data), + }; + if (!this["~standard"].async) { + try { + const result = this._parseSync({ data, path: [], parent: ctx }); + return (0, parseUtil_js_1.isValid)(result) + ? { + value: result.value, + } + : { + issues: ctx.common.issues, + }; + } + catch (err) { + if (err?.message?.toLowerCase()?.includes("encountered")) { + this["~standard"].async = true; } + ctx.common = { + issues: [], + async: true, + }; + } + } + return this._parseAsync({ data, path: [], parent: ctx }).then((result) => (0, parseUtil_js_1.isValid)(result) + ? { + value: result.value, + } + : { + issues: ctx.common.issues, + }); + } + async parseAsync(data, params) { + const result = await this.safeParseAsync(data, params); + if (result.success) + return result.data; + throw result.error; + } + async safeParseAsync(data, params) { + const ctx = { + common: { + issues: [], + contextualErrorMap: params?.errorMap, + async: true, + }, + path: params?.path || [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: (0, util_js_1.getParsedType)(data), + }; + const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }); + const result = await ((0, parseUtil_js_1.isAsync)(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult)); + return handleResult(ctx, result); + } + refine(check, message) { + const getIssueProperties = (val) => { + if (typeof message === "string" || typeof message === "undefined") { + return { message }; + } + else if (typeof message === "function") { + return message(val); } - else if (check.kind === "base64") { - if (!base64Regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - validation: "base64", - code: ZodError_1.ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } + else { + return message; } - else if (check.kind === "base64url") { - if (!base64urlRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - validation: "base64url", - code: ZodError_1.ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } + }; + return this._refinement((val, ctx) => { + const result = check(val); + const setError = () => ctx.addIssue({ + code: ZodError_js_1.ZodIssueCode.custom, + ...getIssueProperties(val), + }); + if (typeof Promise !== "undefined" && result instanceof Promise) { + return result.then((data) => { + if (!data) { + setError(); + return false; + } + else { + return true; + } + }); + } + if (!result) { + setError(); + return false; } else { - util_1.util.assertNever(check); + return true; } - } - return { status: status.value, value: input.data }; - } - _regex(regex, validation, message) { - return this.refinement((data) => regex.test(data), { - validation, - code: ZodError_1.ZodIssueCode.invalid_string, - ...errorUtil_1.errorUtil.errToObj(message), }); } - _addCheck(check) { - return new ZodString({ - ...this._def, - checks: [...this._def.checks, check], + refinement(check, refinementData) { + return this._refinement((val, ctx) => { + if (!check(val)) { + ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData); + return false; + } + else { + return true; + } }); } - email(message) { - return this._addCheck({ kind: "email", ...errorUtil_1.errorUtil.errToObj(message) }); - } - url(message) { - return this._addCheck({ kind: "url", ...errorUtil_1.errorUtil.errToObj(message) }); - } - emoji(message) { - return this._addCheck({ kind: "emoji", ...errorUtil_1.errorUtil.errToObj(message) }); - } - uuid(message) { - return this._addCheck({ kind: "uuid", ...errorUtil_1.errorUtil.errToObj(message) }); - } - nanoid(message) { - return this._addCheck({ kind: "nanoid", ...errorUtil_1.errorUtil.errToObj(message) }); - } - cuid(message) { - return this._addCheck({ kind: "cuid", ...errorUtil_1.errorUtil.errToObj(message) }); - } - cuid2(message) { - return this._addCheck({ kind: "cuid2", ...errorUtil_1.errorUtil.errToObj(message) }); - } - ulid(message) { - return this._addCheck({ kind: "ulid", ...errorUtil_1.errorUtil.errToObj(message) }); - } - base64(message) { - return this._addCheck({ kind: "base64", ...errorUtil_1.errorUtil.errToObj(message) }); - } - base64url(message) { - // base64url encoding is a modification of base64 that can safely be used in URLs and filenames - return this._addCheck({ - kind: "base64url", - ...errorUtil_1.errorUtil.errToObj(message), + _refinement(refinement) { + return new ZodEffects({ + schema: this, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect: { type: "refinement", refinement }, }); } - jwt(options) { - return this._addCheck({ kind: "jwt", ...errorUtil_1.errorUtil.errToObj(options) }); - } - ip(options) { - return this._addCheck({ kind: "ip", ...errorUtil_1.errorUtil.errToObj(options) }); - } - cidr(options) { - return this._addCheck({ kind: "cidr", ...errorUtil_1.errorUtil.errToObj(options) }); - } - datetime(options) { - var _a, _b; - if (typeof options === "string") { - return this._addCheck({ - kind: "datetime", - precision: null, - offset: false, - local: false, - message: options, - }); - } - return this._addCheck({ - kind: "datetime", - precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision, - offset: (_a = options === null || options === void 0 ? void 0 : options.offset) !== null && _a !== void 0 ? _a : false, - local: (_b = options === null || options === void 0 ? void 0 : options.local) !== null && _b !== void 0 ? _b : false, - ...errorUtil_1.errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message), - }); + superRefine(refinement) { + return this._refinement(refinement); } - date(message) { - return this._addCheck({ kind: "date", message }); + constructor(def) { + /** Alias of safeParseAsync */ + this.spa = this.safeParseAsync; + this._def = def; + this.parse = this.parse.bind(this); + this.safeParse = this.safeParse.bind(this); + this.parseAsync = this.parseAsync.bind(this); + this.safeParseAsync = this.safeParseAsync.bind(this); + this.spa = this.spa.bind(this); + this.refine = this.refine.bind(this); + this.refinement = this.refinement.bind(this); + this.superRefine = this.superRefine.bind(this); + this.optional = this.optional.bind(this); + this.nullable = this.nullable.bind(this); + this.nullish = this.nullish.bind(this); + this.array = this.array.bind(this); + this.promise = this.promise.bind(this); + this.or = this.or.bind(this); + this.and = this.and.bind(this); + this.transform = this.transform.bind(this); + this.brand = this.brand.bind(this); + this.default = this.default.bind(this); + this.catch = this.catch.bind(this); + this.describe = this.describe.bind(this); + this.pipe = this.pipe.bind(this); + this.readonly = this.readonly.bind(this); + this.isNullable = this.isNullable.bind(this); + this.isOptional = this.isOptional.bind(this); + this["~standard"] = { + version: 1, + vendor: "zod", + validate: (data) => this["~validate"](data), + }; } - time(options) { - if (typeof options === "string") { - return this._addCheck({ - kind: "time", - precision: null, - message: options, - }); - } - return this._addCheck({ - kind: "time", - precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision, - ...errorUtil_1.errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message), - }); + optional() { + return ZodOptional.create(this, this._def); } - duration(message) { - return this._addCheck({ kind: "duration", ...errorUtil_1.errorUtil.errToObj(message) }); + nullable() { + return ZodNullable.create(this, this._def); } - regex(regex, message) { - return this._addCheck({ - kind: "regex", - regex: regex, - ...errorUtil_1.errorUtil.errToObj(message), - }); + nullish() { + return this.nullable().optional(); } - includes(value, options) { - return this._addCheck({ - kind: "includes", - value: value, - position: options === null || options === void 0 ? void 0 : options.position, - ...errorUtil_1.errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message), - }); + array() { + return ZodArray.create(this); } - startsWith(value, message) { - return this._addCheck({ - kind: "startsWith", - value: value, - ...errorUtil_1.errorUtil.errToObj(message), - }); + promise() { + return ZodPromise.create(this, this._def); } - endsWith(value, message) { - return this._addCheck({ - kind: "endsWith", - value: value, - ...errorUtil_1.errorUtil.errToObj(message), - }); + or(option) { + return ZodUnion.create([this, option], this._def); } - min(minLength, message) { - return this._addCheck({ - kind: "min", - value: minLength, - ...errorUtil_1.errorUtil.errToObj(message), - }); + and(incoming) { + return ZodIntersection.create(this, incoming, this._def); } - max(maxLength, message) { - return this._addCheck({ - kind: "max", - value: maxLength, - ...errorUtil_1.errorUtil.errToObj(message), + transform(transform) { + return new ZodEffects({ + ...processCreateParams(this._def), + schema: this, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect: { type: "transform", transform }, }); } - length(len, message) { - return this._addCheck({ - kind: "length", - value: len, - ...errorUtil_1.errorUtil.errToObj(message), + default(def) { + const defaultValueFunc = typeof def === "function" ? def : () => def; + return new ZodDefault({ + ...processCreateParams(this._def), + innerType: this, + defaultValue: defaultValueFunc, + typeName: ZodFirstPartyTypeKind.ZodDefault, }); } - /** - * Equivalent to `.min(1)` - */ - nonempty(message) { - return this.min(1, errorUtil_1.errorUtil.errToObj(message)); - } - trim() { - return new ZodString({ - ...this._def, - checks: [...this._def.checks, { kind: "trim" }], + brand() { + return new ZodBranded({ + typeName: ZodFirstPartyTypeKind.ZodBranded, + type: this, + ...processCreateParams(this._def), }); } - toLowerCase() { - return new ZodString({ - ...this._def, - checks: [...this._def.checks, { kind: "toLowerCase" }], + catch(def) { + const catchValueFunc = typeof def === "function" ? def : () => def; + return new ZodCatch({ + ...processCreateParams(this._def), + innerType: this, + catchValue: catchValueFunc, + typeName: ZodFirstPartyTypeKind.ZodCatch, }); } - toUpperCase() { - return new ZodString({ + describe(description) { + const This = this.constructor; + return new This({ ...this._def, - checks: [...this._def.checks, { kind: "toUpperCase" }], + description, }); } - get isDatetime() { - return !!this._def.checks.find((ch) => ch.kind === "datetime"); - } - get isDate() { - return !!this._def.checks.find((ch) => ch.kind === "date"); - } - get isTime() { - return !!this._def.checks.find((ch) => ch.kind === "time"); - } - get isDuration() { - return !!this._def.checks.find((ch) => ch.kind === "duration"); - } - get isEmail() { - return !!this._def.checks.find((ch) => ch.kind === "email"); - } - get isURL() { - return !!this._def.checks.find((ch) => ch.kind === "url"); - } - get isEmoji() { - return !!this._def.checks.find((ch) => ch.kind === "emoji"); + pipe(target) { + return ZodPipeline.create(this, target); } - get isUUID() { - return !!this._def.checks.find((ch) => ch.kind === "uuid"); + readonly() { + return ZodReadonly.create(this); } - get isNANOID() { - return !!this._def.checks.find((ch) => ch.kind === "nanoid"); + isOptional() { + return this.safeParse(undefined).success; } - get isCUID() { - return !!this._def.checks.find((ch) => ch.kind === "cuid"); + isNullable() { + return this.safeParse(null).success; } - get isCUID2() { - return !!this._def.checks.find((ch) => ch.kind === "cuid2"); +} +exports.ZodType = ZodType; +exports.Schema = ZodType; +exports.ZodSchema = ZodType; +const cuidRegex = /^c[^\s-]{8,}$/i; +const cuid2Regex = /^[0-9a-z]+$/; +const ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i; +// const uuidRegex = +// /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i; +const uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i; +const nanoidRegex = /^[a-z0-9_-]{21}$/i; +const jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/; +const durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; +// from https://stackoverflow.com/a/46181/1550155 +// old version: too slow, didn't support unicode +// const emailRegex = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i; +//old email regex +// const emailRegex = /^(([^<>()[\].,;:\s@"]+(\.[^<>()[\].,;:\s@"]+)*)|(".+"))@((?!-)([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{1,})[^-<>()[\].,;:\s@"]$/i; +// eslint-disable-next-line +// const emailRegex = +// /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\])|(\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\.[A-Za-z]{2,})+))$/; +// const emailRegex = +// /^[a-zA-Z0-9\.\!\#\$\%\&\'\*\+\/\=\?\^\_\`\{\|\}\~\-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; +// const emailRegex = +// /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$/i; +const emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; +// const emailRegex = +// /^[a-z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\.[a-z0-9\-]+)*$/i; +// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression +const _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; +let emojiRegex; +// faster, simpler, safer +const ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; +const ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/; +// const ipv6Regex = +// /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/; +const ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/; +const ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; +// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript +const base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; +// https://base64.guru/standards/base64url +const base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/; +// simple +// const dateRegexSource = `\\d{4}-\\d{2}-\\d{2}`; +// no leap year validation +// const dateRegexSource = `\\d{4}-((0[13578]|10|12)-31|(0[13-9]|1[0-2])-30|(0[1-9]|1[0-2])-(0[1-9]|1\\d|2\\d))`; +// with leap year validation +const dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`; +const dateRegex = new RegExp(`^${dateRegexSource}$`); +function timeRegexSource(args) { + let secondsRegexSource = `[0-5]\\d`; + if (args.precision) { + secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`; } - get isULID() { - return !!this._def.checks.find((ch) => ch.kind === "ulid"); + else if (args.precision == null) { + secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`; } - get isIP() { - return !!this._def.checks.find((ch) => ch.kind === "ip"); + const secondsQuantifier = args.precision ? "+" : "?"; // require seconds if precision is nonzero + return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`; +} +function timeRegex(args) { + return new RegExp(`^${timeRegexSource(args)}$`); +} +// Adapted from https://stackoverflow.com/a/3143231 +function datetimeRegex(args) { + let regex = `${dateRegexSource}T${timeRegexSource(args)}`; + const opts = []; + opts.push(args.local ? `Z?` : `Z`); + if (args.offset) + opts.push(`([+-]\\d{2}:?\\d{2})`); + regex = `${regex}(${opts.join("|")})`; + return new RegExp(`^${regex}$`); +} +function isValidIP(ip, version) { + if ((version === "v4" || !version) && ipv4Regex.test(ip)) { + return true; } - get isCIDR() { - return !!this._def.checks.find((ch) => ch.kind === "cidr"); + if ((version === "v6" || !version) && ipv6Regex.test(ip)) { + return true; } - get isBase64() { - return !!this._def.checks.find((ch) => ch.kind === "base64"); + return false; +} +function isValidJWT(jwt, alg) { + if (!jwtRegex.test(jwt)) + return false; + try { + const [header] = jwt.split("."); + // Convert base64url to base64 + const base64 = header + .replace(/-/g, "+") + .replace(/_/g, "/") + .padEnd(header.length + ((4 - (header.length % 4)) % 4), "="); + const decoded = JSON.parse(atob(base64)); + if (typeof decoded !== "object" || decoded === null) + return false; + if ("typ" in decoded && decoded?.typ !== "JWT") + return false; + if (!decoded.alg) + return false; + if (alg && decoded.alg !== alg) + return false; + return true; } - get isBase64url() { - // base64url encoding is a modification of base64 that can safely be used in URLs and filenames - return !!this._def.checks.find((ch) => ch.kind === "base64url"); + catch { + return false; } - get minLength() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min; +} +function isValidCidr(ip, version) { + if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) { + return true; } - get maxLength() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max; + if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) { + return true; } + return false; } -exports.ZodString = ZodString; -ZodString.create = (params) => { - var _a; - return new ZodString({ - checks: [], - typeName: ZodFirstPartyTypeKind.ZodString, - coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false, - ...processCreateParams(params), - }); -}; -// https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034 -function floatSafeRemainder(val, step) { - const valDecCount = (val.toString().split(".")[1] || "").length; - const stepDecCount = (step.toString().split(".")[1] || "").length; - const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; - const valInt = parseInt(val.toFixed(decCount).replace(".", "")); - const stepInt = parseInt(step.toFixed(decCount).replace(".", "")); - return (valInt % stepInt) / Math.pow(10, decCount); -} -class ZodNumber extends ZodType { - constructor() { - super(...arguments); - this.min = this.gte; - this.max = this.lte; - this.step = this.multipleOf; - } +class ZodString extends ZodType { _parse(input) { if (this._def.coerce) { - input.data = Number(input.data); + input.data = String(input.data); } const parsedType = this._getType(input); - if (parsedType !== util_1.ZodParsedType.number) { + if (parsedType !== util_js_1.ZodParsedType.string) { const ctx = this._getOrReturnCtx(input); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.number, + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.string, received: ctx.parsedType, }); - return parseUtil_1.INVALID; + return parseUtil_js_1.INVALID; } + const status = new parseUtil_js_1.ParseStatus(); let ctx = undefined; - const status = new parseUtil_1.ParseStatus(); for (const check of this._def.checks) { - if (check.kind === "int") { - if (!util_1.util.isInteger(input.data)) { + if (check.kind === "min") { + if (input.data.length < check.value) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.too_small, + minimum: check.value, + type: "string", + inclusive: true, + exact: false, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "max") { + if (input.data.length > check.value) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.too_big, + maximum: check.value, + type: "string", + inclusive: true, + exact: false, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "length") { + const tooBig = input.data.length > check.value; + const tooSmall = input.data.length < check.value; + if (tooBig || tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + if (tooBig) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.too_big, + maximum: check.value, + type: "string", + inclusive: true, + exact: true, + message: check.message, + }); + } + else if (tooSmall) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.too_small, + minimum: check.value, + type: "string", + inclusive: true, + exact: true, + message: check.message, + }); + } + status.dirty(); + } + } + else if (check.kind === "email") { + if (!emailRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + validation: "email", + code: ZodError_js_1.ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "emoji") { + if (!emojiRegex) { + emojiRegex = new RegExp(_emojiRegex, "u"); + } + if (!emojiRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + validation: "emoji", + code: ZodError_js_1.ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "uuid") { + if (!uuidRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: "integer", - received: "float", + (0, parseUtil_js_1.addIssueToContext)(ctx, { + validation: "uuid", + code: ZodError_js_1.ZodIssueCode.invalid_string, message: check.message, }); status.dirty(); } } - else if (check.kind === "min") { - const tooSmall = check.inclusive - ? input.data < check.value - : input.data <= check.value; - if (tooSmall) { + else if (check.kind === "nanoid") { + if (!nanoidRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_small, - minimum: check.value, - type: "number", - inclusive: check.inclusive, - exact: false, + (0, parseUtil_js_1.addIssueToContext)(ctx, { + validation: "nanoid", + code: ZodError_js_1.ZodIssueCode.invalid_string, message: check.message, }); status.dirty(); } } - else if (check.kind === "max") { - const tooBig = check.inclusive - ? input.data > check.value - : input.data >= check.value; - if (tooBig) { + else if (check.kind === "cuid") { + if (!cuidRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_big, - maximum: check.value, - type: "number", - inclusive: check.inclusive, - exact: false, + (0, parseUtil_js_1.addIssueToContext)(ctx, { + validation: "cuid", + code: ZodError_js_1.ZodIssueCode.invalid_string, message: check.message, }); status.dirty(); } } - else if (check.kind === "multipleOf") { - if (floatSafeRemainder(input.data, check.value) !== 0) { + else if (check.kind === "cuid2") { + if (!cuid2Regex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.not_multiple_of, - multipleOf: check.value, + (0, parseUtil_js_1.addIssueToContext)(ctx, { + validation: "cuid2", + code: ZodError_js_1.ZodIssueCode.invalid_string, message: check.message, }); status.dirty(); } } - else if (check.kind === "finite") { - if (!Number.isFinite(input.data)) { + else if (check.kind === "ulid") { + if (!ulidRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.not_finite, + (0, parseUtil_js_1.addIssueToContext)(ctx, { + validation: "ulid", + code: ZodError_js_1.ZodIssueCode.invalid_string, message: check.message, }); status.dirty(); } } - else { - util_1.util.assertNever(check); + else if (check.kind === "url") { + try { + new URL(input.data); + } + catch { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + validation: "url", + code: ZodError_js_1.ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } } - } - return { status: status.value, value: input.data }; - } - gte(value, message) { - return this.setLimit("min", value, true, errorUtil_1.errorUtil.toString(message)); - } - gt(value, message) { - return this.setLimit("min", value, false, errorUtil_1.errorUtil.toString(message)); - } - lte(value, message) { - return this.setLimit("max", value, true, errorUtil_1.errorUtil.toString(message)); - } - lt(value, message) { - return this.setLimit("max", value, false, errorUtil_1.errorUtil.toString(message)); - } - setLimit(kind, value, inclusive, message) { - return new ZodNumber({ - ...this._def, - checks: [ - ...this._def.checks, - { - kind, - value, - inclusive, - message: errorUtil_1.errorUtil.toString(message), - }, - ], - }); - } - _addCheck(check) { - return new ZodNumber({ - ...this._def, - checks: [...this._def.checks, check], - }); - } - int(message) { - return this._addCheck({ - kind: "int", - message: errorUtil_1.errorUtil.toString(message), - }); - } - positive(message) { - return this._addCheck({ - kind: "min", - value: 0, - inclusive: false, - message: errorUtil_1.errorUtil.toString(message), - }); - } - negative(message) { - return this._addCheck({ - kind: "max", - value: 0, - inclusive: false, - message: errorUtil_1.errorUtil.toString(message), - }); - } - nonpositive(message) { - return this._addCheck({ - kind: "max", - value: 0, - inclusive: true, - message: errorUtil_1.errorUtil.toString(message), - }); - } - nonnegative(message) { - return this._addCheck({ - kind: "min", - value: 0, - inclusive: true, - message: errorUtil_1.errorUtil.toString(message), - }); - } - multipleOf(value, message) { - return this._addCheck({ - kind: "multipleOf", - value: value, - message: errorUtil_1.errorUtil.toString(message), - }); - } - finite(message) { - return this._addCheck({ - kind: "finite", - message: errorUtil_1.errorUtil.toString(message), - }); - } - safe(message) { - return this._addCheck({ - kind: "min", - inclusive: true, - value: Number.MIN_SAFE_INTEGER, - message: errorUtil_1.errorUtil.toString(message), - })._addCheck({ - kind: "max", - inclusive: true, - value: Number.MAX_SAFE_INTEGER, - message: errorUtil_1.errorUtil.toString(message), - }); - } - get minValue() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; + else if (check.kind === "regex") { + check.regex.lastIndex = 0; + const testResult = check.regex.test(input.data); + if (!testResult) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + validation: "regex", + code: ZodError_js_1.ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } } - } - return min; - } - get maxValue() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; + else if (check.kind === "trim") { + input.data = input.data.trim(); } - } - return max; - } - get isInt() { - return !!this._def.checks.find((ch) => ch.kind === "int" || - (ch.kind === "multipleOf" && util_1.util.isInteger(ch.value))); - } - get isFinite() { - let max = null, min = null; - for (const ch of this._def.checks) { - if (ch.kind === "finite" || - ch.kind === "int" || - ch.kind === "multipleOf") { - return true; + else if (check.kind === "includes") { + if (!input.data.includes(check.value, check.position)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_string, + validation: { includes: check.value, position: check.position }, + message: check.message, + }); + status.dirty(); + } } - else if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; + else if (check.kind === "toLowerCase") { + input.data = input.data.toLowerCase(); } - else if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; + else if (check.kind === "toUpperCase") { + input.data = input.data.toUpperCase(); } - } - return Number.isFinite(min) && Number.isFinite(max); - } -} -exports.ZodNumber = ZodNumber; -ZodNumber.create = (params) => { - return new ZodNumber({ - checks: [], - typeName: ZodFirstPartyTypeKind.ZodNumber, - coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, - ...processCreateParams(params), - }); -}; -class ZodBigInt extends ZodType { - constructor() { - super(...arguments); - this.min = this.gte; - this.max = this.lte; - } - _parse(input) { - if (this._def.coerce) { - try { - input.data = BigInt(input.data); + else if (check.kind === "startsWith") { + if (!input.data.startsWith(check.value)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_string, + validation: { startsWith: check.value }, + message: check.message, + }); + status.dirty(); + } } - catch (_a) { - return this._getInvalidInput(input); + else if (check.kind === "endsWith") { + if (!input.data.endsWith(check.value)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_string, + validation: { endsWith: check.value }, + message: check.message, + }); + status.dirty(); + } } - } - const parsedType = this._getType(input); - if (parsedType !== util_1.ZodParsedType.bigint) { - return this._getInvalidInput(input); - } - let ctx = undefined; - const status = new parseUtil_1.ParseStatus(); - for (const check of this._def.checks) { - if (check.kind === "min") { - const tooSmall = check.inclusive - ? input.data < check.value - : input.data <= check.value; - if (tooSmall) { + else if (check.kind === "datetime") { + const regex = datetimeRegex(check); + if (!regex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_small, - type: "bigint", - minimum: check.value, - inclusive: check.inclusive, + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_string, + validation: "datetime", message: check.message, }); status.dirty(); } } - else if (check.kind === "max") { - const tooBig = check.inclusive - ? input.data > check.value - : input.data >= check.value; - if (tooBig) { + else if (check.kind === "date") { + const regex = dateRegex; + if (!regex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_big, - type: "bigint", - maximum: check.value, - inclusive: check.inclusive, + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_string, + validation: "date", message: check.message, }); status.dirty(); } } - else if (check.kind === "multipleOf") { - if (input.data % check.value !== BigInt(0)) { + else if (check.kind === "time") { + const regex = timeRegex(check); + if (!regex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.not_multiple_of, - multipleOf: check.value, + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_string, + validation: "time", message: check.message, }); status.dirty(); } } - else { - util_1.util.assertNever(check); + else if (check.kind === "duration") { + if (!durationRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + validation: "duration", + code: ZodError_js_1.ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } } - } - return { status: status.value, value: input.data }; - } - _getInvalidInput(input) { - const ctx = this._getOrReturnCtx(input); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.bigint, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - gte(value, message) { - return this.setLimit("min", value, true, errorUtil_1.errorUtil.toString(message)); - } - gt(value, message) { - return this.setLimit("min", value, false, errorUtil_1.errorUtil.toString(message)); - } - lte(value, message) { - return this.setLimit("max", value, true, errorUtil_1.errorUtil.toString(message)); - } - lt(value, message) { - return this.setLimit("max", value, false, errorUtil_1.errorUtil.toString(message)); - } - setLimit(kind, value, inclusive, message) { - return new ZodBigInt({ - ...this._def, - checks: [ - ...this._def.checks, - { - kind, - value, - inclusive, - message: errorUtil_1.errorUtil.toString(message), - }, - ], - }); - } - _addCheck(check) { - return new ZodBigInt({ - ...this._def, - checks: [...this._def.checks, check], - }); - } - positive(message) { - return this._addCheck({ - kind: "min", - value: BigInt(0), - inclusive: false, - message: errorUtil_1.errorUtil.toString(message), - }); - } - negative(message) { - return this._addCheck({ - kind: "max", - value: BigInt(0), - inclusive: false, - message: errorUtil_1.errorUtil.toString(message), - }); - } - nonpositive(message) { - return this._addCheck({ - kind: "max", - value: BigInt(0), - inclusive: true, - message: errorUtil_1.errorUtil.toString(message), - }); - } - nonnegative(message) { - return this._addCheck({ - kind: "min", - value: BigInt(0), - inclusive: true, - message: errorUtil_1.errorUtil.toString(message), - }); - } - multipleOf(value, message) { - return this._addCheck({ - kind: "multipleOf", - value, - message: errorUtil_1.errorUtil.toString(message), - }); - } - get minValue() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; + else if (check.kind === "ip") { + if (!isValidIP(input.data, check.version)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + validation: "ip", + code: ZodError_js_1.ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } } - } - return min; - } - get maxValue() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; + else if (check.kind === "jwt") { + if (!isValidJWT(input.data, check.alg)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + validation: "jwt", + code: ZodError_js_1.ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } } - } - return max; - } -} -exports.ZodBigInt = ZodBigInt; -ZodBigInt.create = (params) => { - var _a; - return new ZodBigInt({ - checks: [], - typeName: ZodFirstPartyTypeKind.ZodBigInt, - coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false, - ...processCreateParams(params), - }); -}; -class ZodBoolean extends ZodType { - _parse(input) { - if (this._def.coerce) { - input.data = Boolean(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== util_1.ZodParsedType.boolean) { - const ctx = this._getOrReturnCtx(input); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.boolean, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - return (0, parseUtil_1.OK)(input.data); - } -} -exports.ZodBoolean = ZodBoolean; -ZodBoolean.create = (params) => { - return new ZodBoolean({ - typeName: ZodFirstPartyTypeKind.ZodBoolean, - coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, - ...processCreateParams(params), - }); -}; -class ZodDate extends ZodType { - _parse(input) { - if (this._def.coerce) { - input.data = new Date(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== util_1.ZodParsedType.date) { - const ctx = this._getOrReturnCtx(input); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.date, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - if (isNaN(input.data.getTime())) { - const ctx = this._getOrReturnCtx(input); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_date, - }); - return parseUtil_1.INVALID; - } - const status = new parseUtil_1.ParseStatus(); - let ctx = undefined; - for (const check of this._def.checks) { - if (check.kind === "min") { - if (input.data.getTime() < check.value) { + else if (check.kind === "cidr") { + if (!isValidCidr(input.data, check.version)) { ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_small, + (0, parseUtil_js_1.addIssueToContext)(ctx, { + validation: "cidr", + code: ZodError_js_1.ZodIssueCode.invalid_string, message: check.message, - inclusive: true, - exact: false, - minimum: check.value, - type: "date", }); status.dirty(); } } - else if (check.kind === "max") { - if (input.data.getTime() > check.value) { + else if (check.kind === "base64") { + if (!base64Regex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_big, + (0, parseUtil_js_1.addIssueToContext)(ctx, { + validation: "base64", + code: ZodError_js_1.ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "base64url") { + if (!base64urlRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + validation: "base64url", + code: ZodError_js_1.ZodIssueCode.invalid_string, message: check.message, - inclusive: true, - exact: false, - maximum: check.value, - type: "date", }); status.dirty(); } } else { - util_1.util.assertNever(check); + util_js_1.util.assertNever(check); } } - return { - status: status.value, - value: new Date(input.data.getTime()), - }; + return { status: status.value, value: input.data }; + } + _regex(regex, validation, message) { + return this.refinement((data) => regex.test(data), { + validation, + code: ZodError_js_1.ZodIssueCode.invalid_string, + ...errorUtil_js_1.errorUtil.errToObj(message), + }); } _addCheck(check) { - return new ZodDate({ + return new ZodString({ ...this._def, checks: [...this._def.checks, check], }); } - min(minDate, message) { - return this._addCheck({ - kind: "min", - value: minDate.getTime(), - message: errorUtil_1.errorUtil.toString(message), - }); - } - max(maxDate, message) { - return this._addCheck({ - kind: "max", - value: maxDate.getTime(), - message: errorUtil_1.errorUtil.toString(message), - }); - } - get minDate() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min != null ? new Date(min) : null; - } - get maxDate() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max != null ? new Date(max) : null; + email(message) { + return this._addCheck({ kind: "email", ...errorUtil_js_1.errorUtil.errToObj(message) }); } -} -exports.ZodDate = ZodDate; -ZodDate.create = (params) => { - return new ZodDate({ - checks: [], - coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, - typeName: ZodFirstPartyTypeKind.ZodDate, - ...processCreateParams(params), - }); -}; -class ZodSymbol extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== util_1.ZodParsedType.symbol) { - const ctx = this._getOrReturnCtx(input); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.symbol, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - return (0, parseUtil_1.OK)(input.data); + url(message) { + return this._addCheck({ kind: "url", ...errorUtil_js_1.errorUtil.errToObj(message) }); } -} -exports.ZodSymbol = ZodSymbol; -ZodSymbol.create = (params) => { - return new ZodSymbol({ - typeName: ZodFirstPartyTypeKind.ZodSymbol, - ...processCreateParams(params), - }); -}; -class ZodUndefined extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== util_1.ZodParsedType.undefined) { - const ctx = this._getOrReturnCtx(input); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.undefined, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - return (0, parseUtil_1.OK)(input.data); + emoji(message) { + return this._addCheck({ kind: "emoji", ...errorUtil_js_1.errorUtil.errToObj(message) }); } -} -exports.ZodUndefined = ZodUndefined; -ZodUndefined.create = (params) => { - return new ZodUndefined({ - typeName: ZodFirstPartyTypeKind.ZodUndefined, - ...processCreateParams(params), - }); -}; -class ZodNull extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== util_1.ZodParsedType.null) { - const ctx = this._getOrReturnCtx(input); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.null, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - return (0, parseUtil_1.OK)(input.data); + uuid(message) { + return this._addCheck({ kind: "uuid", ...errorUtil_js_1.errorUtil.errToObj(message) }); } -} -exports.ZodNull = ZodNull; -ZodNull.create = (params) => { - return new ZodNull({ - typeName: ZodFirstPartyTypeKind.ZodNull, - ...processCreateParams(params), - }); -}; -class ZodAny extends ZodType { - constructor() { - super(...arguments); - // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject. - this._any = true; + nanoid(message) { + return this._addCheck({ kind: "nanoid", ...errorUtil_js_1.errorUtil.errToObj(message) }); } - _parse(input) { - return (0, parseUtil_1.OK)(input.data); + cuid(message) { + return this._addCheck({ kind: "cuid", ...errorUtil_js_1.errorUtil.errToObj(message) }); } -} -exports.ZodAny = ZodAny; -ZodAny.create = (params) => { - return new ZodAny({ - typeName: ZodFirstPartyTypeKind.ZodAny, - ...processCreateParams(params), - }); -}; -class ZodUnknown extends ZodType { - constructor() { - super(...arguments); - // required - this._unknown = true; + cuid2(message) { + return this._addCheck({ kind: "cuid2", ...errorUtil_js_1.errorUtil.errToObj(message) }); } - _parse(input) { - return (0, parseUtil_1.OK)(input.data); + ulid(message) { + return this._addCheck({ kind: "ulid", ...errorUtil_js_1.errorUtil.errToObj(message) }); } -} -exports.ZodUnknown = ZodUnknown; -ZodUnknown.create = (params) => { - return new ZodUnknown({ - typeName: ZodFirstPartyTypeKind.ZodUnknown, - ...processCreateParams(params), - }); -}; -class ZodNever extends ZodType { - _parse(input) { - const ctx = this._getOrReturnCtx(input); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.never, - received: ctx.parsedType, + base64(message) { + return this._addCheck({ kind: "base64", ...errorUtil_js_1.errorUtil.errToObj(message) }); + } + base64url(message) { + // base64url encoding is a modification of base64 that can safely be used in URLs and filenames + return this._addCheck({ + kind: "base64url", + ...errorUtil_js_1.errorUtil.errToObj(message), }); - return parseUtil_1.INVALID; } -} -exports.ZodNever = ZodNever; -ZodNever.create = (params) => { - return new ZodNever({ - typeName: ZodFirstPartyTypeKind.ZodNever, - ...processCreateParams(params), - }); -}; -class ZodVoid extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== util_1.ZodParsedType.undefined) { - const ctx = this._getOrReturnCtx(input); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.void, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - return (0, parseUtil_1.OK)(input.data); + jwt(options) { + return this._addCheck({ kind: "jwt", ...errorUtil_js_1.errorUtil.errToObj(options) }); } -} -exports.ZodVoid = ZodVoid; -ZodVoid.create = (params) => { - return new ZodVoid({ - typeName: ZodFirstPartyTypeKind.ZodVoid, - ...processCreateParams(params), - }); -}; -class ZodArray extends ZodType { - _parse(input) { - const { ctx, status } = this._processInputParams(input); - const def = this._def; - if (ctx.parsedType !== util_1.ZodParsedType.array) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.array, - received: ctx.parsedType, + ip(options) { + return this._addCheck({ kind: "ip", ...errorUtil_js_1.errorUtil.errToObj(options) }); + } + cidr(options) { + return this._addCheck({ kind: "cidr", ...errorUtil_js_1.errorUtil.errToObj(options) }); + } + datetime(options) { + if (typeof options === "string") { + return this._addCheck({ + kind: "datetime", + precision: null, + offset: false, + local: false, + message: options, }); - return parseUtil_1.INVALID; - } - if (def.exactLength !== null) { - const tooBig = ctx.data.length > def.exactLength.value; - const tooSmall = ctx.data.length < def.exactLength.value; - if (tooBig || tooSmall) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: tooBig ? ZodError_1.ZodIssueCode.too_big : ZodError_1.ZodIssueCode.too_small, - minimum: (tooSmall ? def.exactLength.value : undefined), - maximum: (tooBig ? def.exactLength.value : undefined), - type: "array", - inclusive: true, - exact: true, - message: def.exactLength.message, - }); - status.dirty(); - } - } - if (def.minLength !== null) { - if (ctx.data.length < def.minLength.value) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_small, - minimum: def.minLength.value, - type: "array", - inclusive: true, - exact: false, - message: def.minLength.message, - }); - status.dirty(); - } - } - if (def.maxLength !== null) { - if (ctx.data.length > def.maxLength.value) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_big, - maximum: def.maxLength.value, - type: "array", - inclusive: true, - exact: false, - message: def.maxLength.message, - }); - status.dirty(); - } } - if (ctx.common.async) { - return Promise.all([...ctx.data].map((item, i) => { - return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i)); - })).then((result) => { - return parseUtil_1.ParseStatus.mergeArray(status, result); + return this._addCheck({ + kind: "datetime", + precision: typeof options?.precision === "undefined" ? null : options?.precision, + offset: options?.offset ?? false, + local: options?.local ?? false, + ...errorUtil_js_1.errorUtil.errToObj(options?.message), + }); + } + date(message) { + return this._addCheck({ kind: "date", message }); + } + time(options) { + if (typeof options === "string") { + return this._addCheck({ + kind: "time", + precision: null, + message: options, }); } - const result = [...ctx.data].map((item, i) => { - return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i)); + return this._addCheck({ + kind: "time", + precision: typeof options?.precision === "undefined" ? null : options?.precision, + ...errorUtil_js_1.errorUtil.errToObj(options?.message), }); - return parseUtil_1.ParseStatus.mergeArray(status, result); } - get element() { - return this._def.type; + duration(message) { + return this._addCheck({ kind: "duration", ...errorUtil_js_1.errorUtil.errToObj(message) }); + } + regex(regex, message) { + return this._addCheck({ + kind: "regex", + regex: regex, + ...errorUtil_js_1.errorUtil.errToObj(message), + }); + } + includes(value, options) { + return this._addCheck({ + kind: "includes", + value: value, + position: options?.position, + ...errorUtil_js_1.errorUtil.errToObj(options?.message), + }); + } + startsWith(value, message) { + return this._addCheck({ + kind: "startsWith", + value: value, + ...errorUtil_js_1.errorUtil.errToObj(message), + }); + } + endsWith(value, message) { + return this._addCheck({ + kind: "endsWith", + value: value, + ...errorUtil_js_1.errorUtil.errToObj(message), + }); } min(minLength, message) { - return new ZodArray({ - ...this._def, - minLength: { value: minLength, message: errorUtil_1.errorUtil.toString(message) }, + return this._addCheck({ + kind: "min", + value: minLength, + ...errorUtil_js_1.errorUtil.errToObj(message), }); } max(maxLength, message) { - return new ZodArray({ - ...this._def, - maxLength: { value: maxLength, message: errorUtil_1.errorUtil.toString(message) }, + return this._addCheck({ + kind: "max", + value: maxLength, + ...errorUtil_js_1.errorUtil.errToObj(message), }); } length(len, message) { - return new ZodArray({ - ...this._def, - exactLength: { value: len, message: errorUtil_1.errorUtil.toString(message) }, + return this._addCheck({ + kind: "length", + value: len, + ...errorUtil_js_1.errorUtil.errToObj(message), }); } + /** + * Equivalent to `.min(1)` + */ nonempty(message) { - return this.min(1, message); + return this.min(1, errorUtil_js_1.errorUtil.errToObj(message)); } -} -exports.ZodArray = ZodArray; -ZodArray.create = (schema, params) => { - return new ZodArray({ - type: schema, - minLength: null, - maxLength: null, - exactLength: null, - typeName: ZodFirstPartyTypeKind.ZodArray, - ...processCreateParams(params), - }); -}; -function deepPartialify(schema) { - if (schema instanceof ZodObject) { - const newShape = {}; - for (const key in schema.shape) { - const fieldSchema = schema.shape[key]; - newShape[key] = ZodOptional.create(deepPartialify(fieldSchema)); - } - return new ZodObject({ - ...schema._def, - shape: () => newShape, + trim() { + return new ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "trim" }], }); } - else if (schema instanceof ZodArray) { - return new ZodArray({ - ...schema._def, - type: deepPartialify(schema.element), + toLowerCase() { + return new ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "toLowerCase" }], }); } - else if (schema instanceof ZodOptional) { - return ZodOptional.create(deepPartialify(schema.unwrap())); + toUpperCase() { + return new ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "toUpperCase" }], + }); } - else if (schema instanceof ZodNullable) { - return ZodNullable.create(deepPartialify(schema.unwrap())); + get isDatetime() { + return !!this._def.checks.find((ch) => ch.kind === "datetime"); } - else if (schema instanceof ZodTuple) { - return ZodTuple.create(schema.items.map((item) => deepPartialify(item))); + get isDate() { + return !!this._def.checks.find((ch) => ch.kind === "date"); } - else { - return schema; + get isTime() { + return !!this._def.checks.find((ch) => ch.kind === "time"); + } + get isDuration() { + return !!this._def.checks.find((ch) => ch.kind === "duration"); + } + get isEmail() { + return !!this._def.checks.find((ch) => ch.kind === "email"); + } + get isURL() { + return !!this._def.checks.find((ch) => ch.kind === "url"); + } + get isEmoji() { + return !!this._def.checks.find((ch) => ch.kind === "emoji"); + } + get isUUID() { + return !!this._def.checks.find((ch) => ch.kind === "uuid"); + } + get isNANOID() { + return !!this._def.checks.find((ch) => ch.kind === "nanoid"); + } + get isCUID() { + return !!this._def.checks.find((ch) => ch.kind === "cuid"); + } + get isCUID2() { + return !!this._def.checks.find((ch) => ch.kind === "cuid2"); + } + get isULID() { + return !!this._def.checks.find((ch) => ch.kind === "ulid"); + } + get isIP() { + return !!this._def.checks.find((ch) => ch.kind === "ip"); + } + get isCIDR() { + return !!this._def.checks.find((ch) => ch.kind === "cidr"); + } + get isBase64() { + return !!this._def.checks.find((ch) => ch.kind === "base64"); + } + get isBase64url() { + // base64url encoding is a modification of base64 that can safely be used in URLs and filenames + return !!this._def.checks.find((ch) => ch.kind === "base64url"); + } + get minLength() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min; + } + get maxLength() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; } } -class ZodObject extends ZodType { +exports.ZodString = ZodString; +ZodString.create = (params) => { + return new ZodString({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodString, + coerce: params?.coerce ?? false, + ...processCreateParams(params), + }); +}; +// https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034 +function floatSafeRemainder(val, step) { + const valDecCount = (val.toString().split(".")[1] || "").length; + const stepDecCount = (step.toString().split(".")[1] || "").length; + const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; + const valInt = Number.parseInt(val.toFixed(decCount).replace(".", "")); + const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", "")); + return (valInt % stepInt) / 10 ** decCount; +} +class ZodNumber extends ZodType { constructor() { super(...arguments); - this._cached = null; - /** - * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped. - * If you want to pass through unknown properties, use `.passthrough()` instead. - */ - this.nonstrict = this.passthrough; - // extend< - // Augmentation extends ZodRawShape, - // NewOutput extends util.flatten<{ - // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation - // ? Augmentation[k]["_output"] - // : k extends keyof Output - // ? Output[k] - // : never; - // }>, - // NewInput extends util.flatten<{ - // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation - // ? Augmentation[k]["_input"] - // : k extends keyof Input - // ? Input[k] - // : never; - // }> - // >( - // augmentation: Augmentation - // ): ZodObject< - // extendShape, - // UnknownKeys, - // Catchall, - // NewOutput, - // NewInput - // > { - // return new ZodObject({ - // ...this._def, - // shape: () => ({ - // ...this._def.shape(), - // ...augmentation, - // }), - // }) as any; - // } - /** - * @deprecated Use `.extend` instead - * */ - this.augment = this.extend; - } - _getCached() { - if (this._cached !== null) - return this._cached; - const shape = this._def.shape(); - const keys = util_1.util.objectKeys(shape); - return (this._cached = { shape, keys }); + this.min = this.gte; + this.max = this.lte; + this.step = this.multipleOf; } _parse(input) { + if (this._def.coerce) { + input.data = Number(input.data); + } const parsedType = this._getType(input); - if (parsedType !== util_1.ZodParsedType.object) { + if (parsedType !== util_js_1.ZodParsedType.number) { const ctx = this._getOrReturnCtx(input); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.object, + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.number, received: ctx.parsedType, }); - return parseUtil_1.INVALID; + return parseUtil_js_1.INVALID; } - const { status, ctx } = this._processInputParams(input); - const { shape, keys: shapeKeys } = this._getCached(); - const extraKeys = []; - if (!(this._def.catchall instanceof ZodNever && - this._def.unknownKeys === "strip")) { - for (const key in ctx.data) { - if (!shapeKeys.includes(key)) { - extraKeys.push(key); + let ctx = undefined; + const status = new parseUtil_js_1.ParseStatus(); + for (const check of this._def.checks) { + if (check.kind === "int") { + if (!util_js_1.util.isInteger(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: "integer", + received: "float", + message: check.message, + }); + status.dirty(); } } - } - const pairs = []; - for (const key of shapeKeys) { - const keyValidator = shape[key]; - const value = ctx.data[key]; - pairs.push({ - key: { status: "valid", value: key }, - value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), - alwaysSet: key in ctx.data, - }); - } - if (this._def.catchall instanceof ZodNever) { - const unknownKeys = this._def.unknownKeys; - if (unknownKeys === "passthrough") { - for (const key of extraKeys) { - pairs.push({ - key: { status: "valid", value: key }, - value: { status: "valid", value: ctx.data[key] }, + else if (check.kind === "min") { + const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; + if (tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.too_small, + minimum: check.value, + type: "number", + inclusive: check.inclusive, + exact: false, + message: check.message, }); + status.dirty(); } } - else if (unknownKeys === "strict") { - if (extraKeys.length > 0) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.unrecognized_keys, - keys: extraKeys, + else if (check.kind === "max") { + const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; + if (tooBig) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.too_big, + maximum: check.value, + type: "number", + inclusive: check.inclusive, + exact: false, + message: check.message, }); status.dirty(); } } - else if (unknownKeys === "strip") { - } - else { - throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); - } - } - else { - // run catchall validation - const catchall = this._def.catchall; - for (const key of extraKeys) { - const value = ctx.data[key]; - pairs.push({ - key: { status: "valid", value: key }, - value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value) - ), - alwaysSet: key in ctx.data, - }); - } - } - if (ctx.common.async) { - return Promise.resolve() - .then(async () => { - const syncPairs = []; - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - syncPairs.push({ - key, - value, - alwaysSet: pair.alwaysSet, + else if (check.kind === "multipleOf") { + if (floatSafeRemainder(input.data, check.value) !== 0) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.not_multiple_of, + multipleOf: check.value, + message: check.message, }); + status.dirty(); } - return syncPairs; - }) - .then((syncPairs) => { - return parseUtil_1.ParseStatus.mergeObjectSync(status, syncPairs); - }); - } - else { - return parseUtil_1.ParseStatus.mergeObjectSync(status, pairs); - } - } - get shape() { - return this._def.shape(); - } - strict(message) { - errorUtil_1.errorUtil.errToObj; - return new ZodObject({ - ...this._def, - unknownKeys: "strict", - ...(message !== undefined - ? { - errorMap: (issue, ctx) => { - var _a, _b, _c, _d; - const defaultError = (_c = (_b = (_a = this._def).errorMap) === null || _b === void 0 ? void 0 : _b.call(_a, issue, ctx).message) !== null && _c !== void 0 ? _c : ctx.defaultError; - if (issue.code === "unrecognized_keys") - return { - message: (_d = errorUtil_1.errorUtil.errToObj(message).message) !== null && _d !== void 0 ? _d : defaultError, - }; - return { - message: defaultError, - }; - }, + } + else if (check.kind === "finite") { + if (!Number.isFinite(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.not_finite, + message: check.message, + }); + status.dirty(); } - : {}), - }); + } + else { + util_js_1.util.assertNever(check); + } + } + return { status: status.value, value: input.data }; } - strip() { - return new ZodObject({ - ...this._def, - unknownKeys: "strip", - }); + gte(value, message) { + return this.setLimit("min", value, true, errorUtil_js_1.errorUtil.toString(message)); } - passthrough() { - return new ZodObject({ + gt(value, message) { + return this.setLimit("min", value, false, errorUtil_js_1.errorUtil.toString(message)); + } + lte(value, message) { + return this.setLimit("max", value, true, errorUtil_js_1.errorUtil.toString(message)); + } + lt(value, message) { + return this.setLimit("max", value, false, errorUtil_js_1.errorUtil.toString(message)); + } + setLimit(kind, value, inclusive, message) { + return new ZodNumber({ ...this._def, - unknownKeys: "passthrough", + checks: [ + ...this._def.checks, + { + kind, + value, + inclusive, + message: errorUtil_js_1.errorUtil.toString(message), + }, + ], }); } - // const AugmentFactory = - // (def: Def) => - // ( - // augmentation: Augmentation - // ): ZodObject< - // extendShape, Augmentation>, - // Def["unknownKeys"], - // Def["catchall"] - // > => { - // return new ZodObject({ - // ...def, - // shape: () => ({ - // ...def.shape(), - // ...augmentation, - // }), - // }) as any; - // }; - extend(augmentation) { - return new ZodObject({ + _addCheck(check) { + return new ZodNumber({ ...this._def, - shape: () => ({ - ...this._def.shape(), - ...augmentation, - }), + checks: [...this._def.checks, check], }); } - /** - * Prior to zod@1.0.12 there was a bug in the - * inferred type of merged objects. Please - * upgrade if you are experiencing issues. - */ - merge(merging) { - const merged = new ZodObject({ - unknownKeys: merging._def.unknownKeys, - catchall: merging._def.catchall, - shape: () => ({ - ...this._def.shape(), - ...merging._def.shape(), - }), - typeName: ZodFirstPartyTypeKind.ZodObject, + int(message) { + return this._addCheck({ + kind: "int", + message: errorUtil_js_1.errorUtil.toString(message), }); - return merged; } - // merge< - // Incoming extends AnyZodObject, - // Augmentation extends Incoming["shape"], - // NewOutput extends { - // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation - // ? Augmentation[k]["_output"] - // : k extends keyof Output - // ? Output[k] - // : never; - // }, - // NewInput extends { - // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation - // ? Augmentation[k]["_input"] - // : k extends keyof Input - // ? Input[k] - // : never; - // } - // >( - // merging: Incoming - // ): ZodObject< - // extendShape>, - // Incoming["_def"]["unknownKeys"], - // Incoming["_def"]["catchall"], - // NewOutput, - // NewInput - // > { - // const merged: any = new ZodObject({ - // unknownKeys: merging._def.unknownKeys, - // catchall: merging._def.catchall, - // shape: () => - // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), - // typeName: ZodFirstPartyTypeKind.ZodObject, - // }) as any; - // return merged; - // } - setKey(key, schema) { - return this.augment({ [key]: schema }); + positive(message) { + return this._addCheck({ + kind: "min", + value: 0, + inclusive: false, + message: errorUtil_js_1.errorUtil.toString(message), + }); } - // merge( - // merging: Incoming - // ): //ZodObject = (merging) => { - // ZodObject< - // extendShape>, - // Incoming["_def"]["unknownKeys"], - // Incoming["_def"]["catchall"] - // > { - // // const mergedShape = objectUtil.mergeShapes( - // // this._def.shape(), - // // merging._def.shape() - // // ); - // const merged: any = new ZodObject({ - // unknownKeys: merging._def.unknownKeys, - // catchall: merging._def.catchall, - // shape: () => - // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), - // typeName: ZodFirstPartyTypeKind.ZodObject, - // }) as any; - // return merged; - // } - catchall(index) { - return new ZodObject({ - ...this._def, - catchall: index, + negative(message) { + return this._addCheck({ + kind: "max", + value: 0, + inclusive: false, + message: errorUtil_js_1.errorUtil.toString(message), }); } - pick(mask) { - const shape = {}; - util_1.util.objectKeys(mask).forEach((key) => { - if (mask[key] && this.shape[key]) { - shape[key] = this.shape[key]; - } + nonpositive(message) { + return this._addCheck({ + kind: "max", + value: 0, + inclusive: true, + message: errorUtil_js_1.errorUtil.toString(message), }); - return new ZodObject({ - ...this._def, - shape: () => shape, + } + nonnegative(message) { + return this._addCheck({ + kind: "min", + value: 0, + inclusive: true, + message: errorUtil_js_1.errorUtil.toString(message), }); } - omit(mask) { - const shape = {}; - util_1.util.objectKeys(this.shape).forEach((key) => { - if (!mask[key]) { - shape[key] = this.shape[key]; - } + multipleOf(value, message) { + return this._addCheck({ + kind: "multipleOf", + value: value, + message: errorUtil_js_1.errorUtil.toString(message), }); - return new ZodObject({ - ...this._def, - shape: () => shape, + } + finite(message) { + return this._addCheck({ + kind: "finite", + message: errorUtil_js_1.errorUtil.toString(message), }); } - /** - * @deprecated - */ - deepPartial() { - return deepPartialify(this); + safe(message) { + return this._addCheck({ + kind: "min", + inclusive: true, + value: Number.MIN_SAFE_INTEGER, + message: errorUtil_js_1.errorUtil.toString(message), + })._addCheck({ + kind: "max", + inclusive: true, + value: Number.MAX_SAFE_INTEGER, + message: errorUtil_js_1.errorUtil.toString(message), + }); } - partial(mask) { - const newShape = {}; - util_1.util.objectKeys(this.shape).forEach((key) => { - const fieldSchema = this.shape[key]; - if (mask && !mask[key]) { - newShape[key] = fieldSchema; + get minValue() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; } - else { - newShape[key] = fieldSchema.optional(); + } + return min; + } + get maxValue() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; } - }); - return new ZodObject({ - ...this._def, - shape: () => newShape, - }); + } + return max; } - required(mask) { - const newShape = {}; - util_1.util.objectKeys(this.shape).forEach((key) => { - if (mask && !mask[key]) { - newShape[key] = this.shape[key]; + get isInt() { + return !!this._def.checks.find((ch) => ch.kind === "int" || (ch.kind === "multipleOf" && util_js_1.util.isInteger(ch.value))); + } + get isFinite() { + let max = null; + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") { + return true; } - else { - const fieldSchema = this.shape[key]; - let newField = fieldSchema; - while (newField instanceof ZodOptional) { - newField = newField._def.innerType; - } - newShape[key] = newField; + else if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; } - }); - return new ZodObject({ - ...this._def, - shape: () => newShape, - }); - } - keyof() { - return createZodEnum(util_1.util.objectKeys(this.shape)); + else if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return Number.isFinite(min) && Number.isFinite(max); } } -exports.ZodObject = ZodObject; -ZodObject.create = (shape, params) => { - return new ZodObject({ - shape: () => shape, - unknownKeys: "strip", - catchall: ZodNever.create(), - typeName: ZodFirstPartyTypeKind.ZodObject, - ...processCreateParams(params), - }); -}; -ZodObject.strictCreate = (shape, params) => { - return new ZodObject({ - shape: () => shape, - unknownKeys: "strict", - catchall: ZodNever.create(), - typeName: ZodFirstPartyTypeKind.ZodObject, - ...processCreateParams(params), - }); -}; -ZodObject.lazycreate = (shape, params) => { - return new ZodObject({ - shape, - unknownKeys: "strip", - catchall: ZodNever.create(), - typeName: ZodFirstPartyTypeKind.ZodObject, +exports.ZodNumber = ZodNumber; +ZodNumber.create = (params) => { + return new ZodNumber({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodNumber, + coerce: params?.coerce || false, ...processCreateParams(params), }); }; -class ZodUnion extends ZodType { +class ZodBigInt extends ZodType { + constructor() { + super(...arguments); + this.min = this.gte; + this.max = this.lte; + } _parse(input) { - const { ctx } = this._processInputParams(input); - const options = this._def.options; - function handleResults(results) { - // return first issue-free validation if it exists - for (const result of results) { - if (result.result.status === "valid") { - return result.result; - } + if (this._def.coerce) { + try { + input.data = BigInt(input.data); } - for (const result of results) { - if (result.result.status === "dirty") { - // add issues from dirty option - ctx.common.issues.push(...result.ctx.common.issues); - return result.result; - } + catch { + return this._getInvalidInput(input); } - // return invalid - const unionErrors = results.map((result) => new ZodError_1.ZodError(result.ctx.common.issues)); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_union, - unionErrors, - }); - return parseUtil_1.INVALID; } - if (ctx.common.async) { - return Promise.all(options.map(async (option) => { - const childCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [], - }, - parent: null, - }; - return { - result: await option._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: childCtx, - }), - ctx: childCtx, - }; - })).then(handleResults); + const parsedType = this._getType(input); + if (parsedType !== util_js_1.ZodParsedType.bigint) { + return this._getInvalidInput(input); } - else { - let dirty = undefined; - const issues = []; - for (const option of options) { - const childCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [], - }, - parent: null, - }; - const result = option._parseSync({ - data: ctx.data, - path: ctx.path, - parent: childCtx, - }); - if (result.status === "valid") { - return result; + let ctx = undefined; + const status = new parseUtil_js_1.ParseStatus(); + for (const check of this._def.checks) { + if (check.kind === "min") { + const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; + if (tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.too_small, + type: "bigint", + minimum: check.value, + inclusive: check.inclusive, + message: check.message, + }); + status.dirty(); } - else if (result.status === "dirty" && !dirty) { - dirty = { result, ctx: childCtx }; + } + else if (check.kind === "max") { + const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; + if (tooBig) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.too_big, + type: "bigint", + maximum: check.value, + inclusive: check.inclusive, + message: check.message, + }); + status.dirty(); } - if (childCtx.common.issues.length) { - issues.push(childCtx.common.issues); + } + else if (check.kind === "multipleOf") { + if (input.data % check.value !== BigInt(0)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.not_multiple_of, + multipleOf: check.value, + message: check.message, + }); + status.dirty(); } } - if (dirty) { - ctx.common.issues.push(...dirty.ctx.common.issues); - return dirty.result; + else { + util_js_1.util.assertNever(check); } - const unionErrors = issues.map((issues) => new ZodError_1.ZodError(issues)); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_union, - unionErrors, - }); - return parseUtil_1.INVALID; } + return { status: status.value, value: input.data }; } - get options() { - return this._def.options; - } -} -exports.ZodUnion = ZodUnion; -ZodUnion.create = (types, params) => { - return new ZodUnion({ - options: types, - typeName: ZodFirstPartyTypeKind.ZodUnion, - ...processCreateParams(params), - }); -}; -///////////////////////////////////////////////////// -///////////////////////////////////////////////////// -////////// ////////// -////////// ZodDiscriminatedUnion ////////// -////////// ////////// -///////////////////////////////////////////////////// -///////////////////////////////////////////////////// -const getDiscriminator = (type) => { - if (type instanceof ZodLazy) { - return getDiscriminator(type.schema); + _getInvalidInput(input) { + const ctx = this._getOrReturnCtx(input); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.bigint, + received: ctx.parsedType, + }); + return parseUtil_js_1.INVALID; } - else if (type instanceof ZodEffects) { - return getDiscriminator(type.innerType()); + gte(value, message) { + return this.setLimit("min", value, true, errorUtil_js_1.errorUtil.toString(message)); } - else if (type instanceof ZodLiteral) { - return [type.value]; + gt(value, message) { + return this.setLimit("min", value, false, errorUtil_js_1.errorUtil.toString(message)); } - else if (type instanceof ZodEnum) { - return type.options; + lte(value, message) { + return this.setLimit("max", value, true, errorUtil_js_1.errorUtil.toString(message)); } - else if (type instanceof ZodNativeEnum) { - // eslint-disable-next-line ban/ban - return util_1.util.objectValues(type.enum); + lt(value, message) { + return this.setLimit("max", value, false, errorUtil_js_1.errorUtil.toString(message)); } - else if (type instanceof ZodDefault) { - return getDiscriminator(type._def.innerType); + setLimit(kind, value, inclusive, message) { + return new ZodBigInt({ + ...this._def, + checks: [ + ...this._def.checks, + { + kind, + value, + inclusive, + message: errorUtil_js_1.errorUtil.toString(message), + }, + ], + }); } - else if (type instanceof ZodUndefined) { - return [undefined]; + _addCheck(check) { + return new ZodBigInt({ + ...this._def, + checks: [...this._def.checks, check], + }); } - else if (type instanceof ZodNull) { - return [null]; + positive(message) { + return this._addCheck({ + kind: "min", + value: BigInt(0), + inclusive: false, + message: errorUtil_js_1.errorUtil.toString(message), + }); } - else if (type instanceof ZodOptional) { - return [undefined, ...getDiscriminator(type.unwrap())]; + negative(message) { + return this._addCheck({ + kind: "max", + value: BigInt(0), + inclusive: false, + message: errorUtil_js_1.errorUtil.toString(message), + }); } - else if (type instanceof ZodNullable) { - return [null, ...getDiscriminator(type.unwrap())]; + nonpositive(message) { + return this._addCheck({ + kind: "max", + value: BigInt(0), + inclusive: true, + message: errorUtil_js_1.errorUtil.toString(message), + }); } - else if (type instanceof ZodBranded) { - return getDiscriminator(type.unwrap()); + nonnegative(message) { + return this._addCheck({ + kind: "min", + value: BigInt(0), + inclusive: true, + message: errorUtil_js_1.errorUtil.toString(message), + }); } - else if (type instanceof ZodReadonly) { - return getDiscriminator(type.unwrap()); + multipleOf(value, message) { + return this._addCheck({ + kind: "multipleOf", + value, + message: errorUtil_js_1.errorUtil.toString(message), + }); } - else if (type instanceof ZodCatch) { - return getDiscriminator(type._def.innerType); + get minValue() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min; } - else { - return []; + get maxValue() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; } +} +exports.ZodBigInt = ZodBigInt; +ZodBigInt.create = (params) => { + return new ZodBigInt({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodBigInt, + coerce: params?.coerce ?? false, + ...processCreateParams(params), + }); }; -class ZodDiscriminatedUnion extends ZodType { +class ZodBoolean extends ZodType { _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== util_1.ZodParsedType.object) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.object, + if (this._def.coerce) { + input.data = Boolean(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== util_js_1.ZodParsedType.boolean) { + const ctx = this._getOrReturnCtx(input); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.boolean, received: ctx.parsedType, }); - return parseUtil_1.INVALID; + return parseUtil_js_1.INVALID; } - const discriminator = this.discriminator; - const discriminatorValue = ctx.data[discriminator]; - const option = this.optionsMap.get(discriminatorValue); - if (!option) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_union_discriminator, - options: Array.from(this.optionsMap.keys()), - path: [discriminator], - }); - return parseUtil_1.INVALID; + return (0, parseUtil_js_1.OK)(input.data); + } +} +exports.ZodBoolean = ZodBoolean; +ZodBoolean.create = (params) => { + return new ZodBoolean({ + typeName: ZodFirstPartyTypeKind.ZodBoolean, + coerce: params?.coerce || false, + ...processCreateParams(params), + }); +}; +class ZodDate extends ZodType { + _parse(input) { + if (this._def.coerce) { + input.data = new Date(input.data); } - if (ctx.common.async) { - return option._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx, + const parsedType = this._getType(input); + if (parsedType !== util_js_1.ZodParsedType.date) { + const ctx = this._getOrReturnCtx(input); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.date, + received: ctx.parsedType, }); + return parseUtil_js_1.INVALID; } - else { - return option._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx, + if (Number.isNaN(input.data.getTime())) { + const ctx = this._getOrReturnCtx(input); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_date, }); + return parseUtil_js_1.INVALID; } - } - get discriminator() { - return this._def.discriminator; - } - get options() { - return this._def.options; - } - get optionsMap() { - return this._def.optionsMap; - } - /** - * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor. - * However, it only allows a union of objects, all of which need to share a discriminator property. This property must - * have a different value for each object in the union. - * @param discriminator the name of the discriminator property - * @param types an array of object schemas - * @param params - */ - static create(discriminator, options, params) { - // Get all the valid discriminator values - const optionsMap = new Map(); - // try { - for (const type of options) { - const discriminatorValues = getDiscriminator(type.shape[discriminator]); - if (!discriminatorValues.length) { - throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); + const status = new parseUtil_js_1.ParseStatus(); + let ctx = undefined; + for (const check of this._def.checks) { + if (check.kind === "min") { + if (input.data.getTime() < check.value) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.too_small, + message: check.message, + inclusive: true, + exact: false, + minimum: check.value, + type: "date", + }); + status.dirty(); + } } - for (const value of discriminatorValues) { - if (optionsMap.has(value)) { - throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); + else if (check.kind === "max") { + if (input.data.getTime() > check.value) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.too_big, + message: check.message, + inclusive: true, + exact: false, + maximum: check.value, + type: "date", + }); + status.dirty(); } - optionsMap.set(value, type); + } + else { + util_js_1.util.assertNever(check); } } - return new ZodDiscriminatedUnion({ - typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion, - discriminator, - options, - optionsMap, - ...processCreateParams(params), + return { + status: status.value, + value: new Date(input.data.getTime()), + }; + } + _addCheck(check) { + return new ZodDate({ + ...this._def, + checks: [...this._def.checks, check], }); } -} -exports.ZodDiscriminatedUnion = ZodDiscriminatedUnion; -function mergeValues(a, b) { - const aType = (0, util_1.getParsedType)(a); - const bType = (0, util_1.getParsedType)(b); - if (a === b) { - return { valid: true, data: a }; + min(minDate, message) { + return this._addCheck({ + kind: "min", + value: minDate.getTime(), + message: errorUtil_js_1.errorUtil.toString(message), + }); } - else if (aType === util_1.ZodParsedType.object && bType === util_1.ZodParsedType.object) { - const bKeys = util_1.util.objectKeys(b); - const sharedKeys = util_1.util - .objectKeys(a) - .filter((key) => bKeys.indexOf(key) !== -1); - const newObj = { ...a, ...b }; - for (const key of sharedKeys) { - const sharedValue = mergeValues(a[key], b[key]); - if (!sharedValue.valid) { - return { valid: false }; + max(maxDate, message) { + return this._addCheck({ + kind: "max", + value: maxDate.getTime(), + message: errorUtil_js_1.errorUtil.toString(message), + }); + } + get minDate() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; } - newObj[key] = sharedValue.data; } - return { valid: true, data: newObj }; + return min != null ? new Date(min) : null; } - else if (aType === util_1.ZodParsedType.array && bType === util_1.ZodParsedType.array) { - if (a.length !== b.length) { - return { valid: false }; - } - const newArray = []; - for (let index = 0; index < a.length; index++) { - const itemA = a[index]; - const itemB = b[index]; - const sharedValue = mergeValues(itemA, itemB); - if (!sharedValue.valid) { - return { valid: false }; + get maxDate() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; } - newArray.push(sharedValue.data); } - return { valid: true, data: newArray }; - } - else if (aType === util_1.ZodParsedType.date && - bType === util_1.ZodParsedType.date && - +a === +b) { - return { valid: true, data: a }; - } - else { - return { valid: false }; + return max != null ? new Date(max) : null; } } -class ZodIntersection extends ZodType { +exports.ZodDate = ZodDate; +ZodDate.create = (params) => { + return new ZodDate({ + checks: [], + coerce: params?.coerce || false, + typeName: ZodFirstPartyTypeKind.ZodDate, + ...processCreateParams(params), + }); +}; +class ZodSymbol extends ZodType { _parse(input) { - const { status, ctx } = this._processInputParams(input); - const handleParsed = (parsedLeft, parsedRight) => { - if ((0, parseUtil_1.isAborted)(parsedLeft) || (0, parseUtil_1.isAborted)(parsedRight)) { - return parseUtil_1.INVALID; - } - const merged = mergeValues(parsedLeft.value, parsedRight.value); - if (!merged.valid) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_intersection_types, - }); - return parseUtil_1.INVALID; - } - if ((0, parseUtil_1.isDirty)(parsedLeft) || (0, parseUtil_1.isDirty)(parsedRight)) { - status.dirty(); - } - return { status: status.value, value: merged.data }; - }; - if (ctx.common.async) { - return Promise.all([ - this._def.left._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }), - this._def.right._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }), - ]).then(([left, right]) => handleParsed(left, right)); - } - else { - return handleParsed(this._def.left._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }), this._def.right._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - })); + const parsedType = this._getType(input); + if (parsedType !== util_js_1.ZodParsedType.symbol) { + const ctx = this._getOrReturnCtx(input); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.symbol, + received: ctx.parsedType, + }); + return parseUtil_js_1.INVALID; } + return (0, parseUtil_js_1.OK)(input.data); } } -exports.ZodIntersection = ZodIntersection; -ZodIntersection.create = (left, right, params) => { - return new ZodIntersection({ - left: left, - right: right, - typeName: ZodFirstPartyTypeKind.ZodIntersection, +exports.ZodSymbol = ZodSymbol; +ZodSymbol.create = (params) => { + return new ZodSymbol({ + typeName: ZodFirstPartyTypeKind.ZodSymbol, ...processCreateParams(params), }); }; -class ZodTuple extends ZodType { +class ZodUndefined extends ZodType { _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== util_1.ZodParsedType.array) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.array, + const parsedType = this._getType(input); + if (parsedType !== util_js_1.ZodParsedType.undefined) { + const ctx = this._getOrReturnCtx(input); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.undefined, received: ctx.parsedType, }); - return parseUtil_1.INVALID; - } - if (ctx.data.length < this._def.items.length) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_small, - minimum: this._def.items.length, - inclusive: true, - exact: false, - type: "array", - }); - return parseUtil_1.INVALID; + return parseUtil_js_1.INVALID; } - const rest = this._def.rest; - if (!rest && ctx.data.length > this._def.items.length) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_big, - maximum: this._def.items.length, - inclusive: true, - exact: false, - type: "array", - }); - status.dirty(); - } - const items = [...ctx.data] - .map((item, itemIndex) => { - const schema = this._def.items[itemIndex] || this._def.rest; - if (!schema) - return null; - return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)); - }) - .filter((x) => !!x); // filter nulls - if (ctx.common.async) { - return Promise.all(items).then((results) => { - return parseUtil_1.ParseStatus.mergeArray(status, results); - }); - } - else { - return parseUtil_1.ParseStatus.mergeArray(status, items); - } - } - get items() { - return this._def.items; - } - rest(rest) { - return new ZodTuple({ - ...this._def, - rest, - }); + return (0, parseUtil_js_1.OK)(input.data); } } -exports.ZodTuple = ZodTuple; -ZodTuple.create = (schemas, params) => { - if (!Array.isArray(schemas)) { - throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); - } - return new ZodTuple({ - items: schemas, - typeName: ZodFirstPartyTypeKind.ZodTuple, - rest: null, +exports.ZodUndefined = ZodUndefined; +ZodUndefined.create = (params) => { + return new ZodUndefined({ + typeName: ZodFirstPartyTypeKind.ZodUndefined, ...processCreateParams(params), }); }; -class ZodRecord extends ZodType { - get keySchema() { - return this._def.keyType; - } - get valueSchema() { - return this._def.valueType; - } +class ZodNull extends ZodType { _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== util_1.ZodParsedType.object) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.object, + const parsedType = this._getType(input); + if (parsedType !== util_js_1.ZodParsedType.null) { + const ctx = this._getOrReturnCtx(input); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.null, received: ctx.parsedType, }); - return parseUtil_1.INVALID; - } - const pairs = []; - const keyType = this._def.keyType; - const valueType = this._def.valueType; - for (const key in ctx.data) { - pairs.push({ - key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)), - value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)), - alwaysSet: key in ctx.data, - }); - } - if (ctx.common.async) { - return parseUtil_1.ParseStatus.mergeObjectAsync(status, pairs); - } - else { - return parseUtil_1.ParseStatus.mergeObjectSync(status, pairs); + return parseUtil_js_1.INVALID; } + return (0, parseUtil_js_1.OK)(input.data); } - get element() { - return this._def.valueType; +} +exports.ZodNull = ZodNull; +ZodNull.create = (params) => { + return new ZodNull({ + typeName: ZodFirstPartyTypeKind.ZodNull, + ...processCreateParams(params), + }); +}; +class ZodAny extends ZodType { + constructor() { + super(...arguments); + // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject. + this._any = true; } - static create(first, second, third) { - if (second instanceof ZodType) { - return new ZodRecord({ - keyType: first, - valueType: second, - typeName: ZodFirstPartyTypeKind.ZodRecord, - ...processCreateParams(third), - }); - } - return new ZodRecord({ - keyType: ZodString.create(), - valueType: first, - typeName: ZodFirstPartyTypeKind.ZodRecord, - ...processCreateParams(second), - }); + _parse(input) { + return (0, parseUtil_js_1.OK)(input.data); } } -exports.ZodRecord = ZodRecord; -class ZodMap extends ZodType { - get keySchema() { - return this._def.keyType; +exports.ZodAny = ZodAny; +ZodAny.create = (params) => { + return new ZodAny({ + typeName: ZodFirstPartyTypeKind.ZodAny, + ...processCreateParams(params), + }); +}; +class ZodUnknown extends ZodType { + constructor() { + super(...arguments); + // required + this._unknown = true; } - get valueSchema() { - return this._def.valueType; + _parse(input) { + return (0, parseUtil_js_1.OK)(input.data); + } +} +exports.ZodUnknown = ZodUnknown; +ZodUnknown.create = (params) => { + return new ZodUnknown({ + typeName: ZodFirstPartyTypeKind.ZodUnknown, + ...processCreateParams(params), + }); +}; +class ZodNever extends ZodType { + _parse(input) { + const ctx = this._getOrReturnCtx(input); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.never, + received: ctx.parsedType, + }); + return parseUtil_js_1.INVALID; } +} +exports.ZodNever = ZodNever; +ZodNever.create = (params) => { + return new ZodNever({ + typeName: ZodFirstPartyTypeKind.ZodNever, + ...processCreateParams(params), + }); +}; +class ZodVoid extends ZodType { _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== util_1.ZodParsedType.map) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.map, + const parsedType = this._getType(input); + if (parsedType !== util_js_1.ZodParsedType.undefined) { + const ctx = this._getOrReturnCtx(input); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.void, received: ctx.parsedType, }); - return parseUtil_1.INVALID; - } - const keyType = this._def.keyType; - const valueType = this._def.valueType; - const pairs = [...ctx.data.entries()].map(([key, value], index) => { - return { - key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])), - value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])), - }; - }); - if (ctx.common.async) { - const finalMap = new Map(); - return Promise.resolve().then(async () => { - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - if (key.status === "aborted" || value.status === "aborted") { - return parseUtil_1.INVALID; - } - if (key.status === "dirty" || value.status === "dirty") { - status.dirty(); - } - finalMap.set(key.value, value.value); - } - return { status: status.value, value: finalMap }; - }); - } - else { - const finalMap = new Map(); - for (const pair of pairs) { - const key = pair.key; - const value = pair.value; - if (key.status === "aborted" || value.status === "aborted") { - return parseUtil_1.INVALID; - } - if (key.status === "dirty" || value.status === "dirty") { - status.dirty(); - } - finalMap.set(key.value, value.value); - } - return { status: status.value, value: finalMap }; + return parseUtil_js_1.INVALID; } + return (0, parseUtil_js_1.OK)(input.data); } } -exports.ZodMap = ZodMap; -ZodMap.create = (keyType, valueType, params) => { - return new ZodMap({ - valueType, - keyType, - typeName: ZodFirstPartyTypeKind.ZodMap, +exports.ZodVoid = ZodVoid; +ZodVoid.create = (params) => { + return new ZodVoid({ + typeName: ZodFirstPartyTypeKind.ZodVoid, ...processCreateParams(params), }); }; -class ZodSet extends ZodType { +class ZodArray extends ZodType { _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== util_1.ZodParsedType.set) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.set, + const { ctx, status } = this._processInputParams(input); + const def = this._def; + if (ctx.parsedType !== util_js_1.ZodParsedType.array) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.array, received: ctx.parsedType, }); - return parseUtil_1.INVALID; + return parseUtil_js_1.INVALID; } - const def = this._def; - if (def.minSize !== null) { - if (ctx.data.size < def.minSize.value) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_small, - minimum: def.minSize.value, - type: "set", + if (def.exactLength !== null) { + const tooBig = ctx.data.length > def.exactLength.value; + const tooSmall = ctx.data.length < def.exactLength.value; + if (tooBig || tooSmall) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: tooBig ? ZodError_js_1.ZodIssueCode.too_big : ZodError_js_1.ZodIssueCode.too_small, + minimum: (tooSmall ? def.exactLength.value : undefined), + maximum: (tooBig ? def.exactLength.value : undefined), + type: "array", inclusive: true, - exact: false, - message: def.minSize.message, + exact: true, + message: def.exactLength.message, }); status.dirty(); } } - if (def.maxSize !== null) { - if (ctx.data.size > def.maxSize.value) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_big, - maximum: def.maxSize.value, - type: "set", + if (def.minLength !== null) { + if (ctx.data.length < def.minLength.value) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.too_small, + minimum: def.minLength.value, + type: "array", inclusive: true, exact: false, - message: def.maxSize.message, + message: def.minLength.message, }); status.dirty(); } } - const valueType = this._def.valueType; - function finalizeSet(elements) { - const parsedSet = new Set(); - for (const element of elements) { - if (element.status === "aborted") - return parseUtil_1.INVALID; - if (element.status === "dirty") - status.dirty(); - parsedSet.add(element.value); + if (def.maxLength !== null) { + if (ctx.data.length > def.maxLength.value) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.too_big, + maximum: def.maxLength.value, + type: "array", + inclusive: true, + exact: false, + message: def.maxLength.message, + }); + status.dirty(); } - return { status: status.value, value: parsedSet }; } - const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i))); if (ctx.common.async) { - return Promise.all(elements).then((elements) => finalizeSet(elements)); - } - else { - return finalizeSet(elements); + return Promise.all([...ctx.data].map((item, i) => { + return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i)); + })).then((result) => { + return parseUtil_js_1.ParseStatus.mergeArray(status, result); + }); } + const result = [...ctx.data].map((item, i) => { + return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i)); + }); + return parseUtil_js_1.ParseStatus.mergeArray(status, result); + } + get element() { + return this._def.type; } - min(minSize, message) { - return new ZodSet({ + min(minLength, message) { + return new ZodArray({ ...this._def, - minSize: { value: minSize, message: errorUtil_1.errorUtil.toString(message) }, + minLength: { value: minLength, message: errorUtil_js_1.errorUtil.toString(message) }, }); } - max(maxSize, message) { - return new ZodSet({ + max(maxLength, message) { + return new ZodArray({ ...this._def, - maxSize: { value: maxSize, message: errorUtil_1.errorUtil.toString(message) }, + maxLength: { value: maxLength, message: errorUtil_js_1.errorUtil.toString(message) }, }); } - size(size, message) { - return this.min(size, message).max(size, message); + length(len, message) { + return new ZodArray({ + ...this._def, + exactLength: { value: len, message: errorUtil_js_1.errorUtil.toString(message) }, + }); } nonempty(message) { return this.min(1, message); } } -exports.ZodSet = ZodSet; -ZodSet.create = (valueType, params) => { - return new ZodSet({ - valueType, - minSize: null, - maxSize: null, - typeName: ZodFirstPartyTypeKind.ZodSet, +exports.ZodArray = ZodArray; +ZodArray.create = (schema, params) => { + return new ZodArray({ + type: schema, + minLength: null, + maxLength: null, + exactLength: null, + typeName: ZodFirstPartyTypeKind.ZodArray, ...processCreateParams(params), }); }; -class ZodFunction extends ZodType { +function deepPartialify(schema) { + if (schema instanceof ZodObject) { + const newShape = {}; + for (const key in schema.shape) { + const fieldSchema = schema.shape[key]; + newShape[key] = ZodOptional.create(deepPartialify(fieldSchema)); + } + return new ZodObject({ + ...schema._def, + shape: () => newShape, + }); + } + else if (schema instanceof ZodArray) { + return new ZodArray({ + ...schema._def, + type: deepPartialify(schema.element), + }); + } + else if (schema instanceof ZodOptional) { + return ZodOptional.create(deepPartialify(schema.unwrap())); + } + else if (schema instanceof ZodNullable) { + return ZodNullable.create(deepPartialify(schema.unwrap())); + } + else if (schema instanceof ZodTuple) { + return ZodTuple.create(schema.items.map((item) => deepPartialify(item))); + } + else { + return schema; + } +} +class ZodObject extends ZodType { constructor() { super(...arguments); - this.validate = this.implement; + this._cached = null; + /** + * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped. + * If you want to pass through unknown properties, use `.passthrough()` instead. + */ + this.nonstrict = this.passthrough; + // extend< + // Augmentation extends ZodRawShape, + // NewOutput extends util.flatten<{ + // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation + // ? Augmentation[k]["_output"] + // : k extends keyof Output + // ? Output[k] + // : never; + // }>, + // NewInput extends util.flatten<{ + // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation + // ? Augmentation[k]["_input"] + // : k extends keyof Input + // ? Input[k] + // : never; + // }> + // >( + // augmentation: Augmentation + // ): ZodObject< + // extendShape, + // UnknownKeys, + // Catchall, + // NewOutput, + // NewInput + // > { + // return new ZodObject({ + // ...this._def, + // shape: () => ({ + // ...this._def.shape(), + // ...augmentation, + // }), + // }) as any; + // } + /** + * @deprecated Use `.extend` instead + * */ + this.augment = this.extend; + } + _getCached() { + if (this._cached !== null) + return this._cached; + const shape = this._def.shape(); + const keys = util_js_1.util.objectKeys(shape); + this._cached = { shape, keys }; + return this._cached; } _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== util_1.ZodParsedType.function) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.function, + const parsedType = this._getType(input); + if (parsedType !== util_js_1.ZodParsedType.object) { + const ctx = this._getOrReturnCtx(input); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.object, received: ctx.parsedType, }); - return parseUtil_1.INVALID; + return parseUtil_js_1.INVALID; } - function makeArgsIssue(args, error) { - return (0, parseUtil_1.makeIssue)({ - data: args, - path: ctx.path, - errorMaps: [ - ctx.common.contextualErrorMap, - ctx.schemaErrorMap, - (0, errors_1.getErrorMap)(), - errors_1.defaultErrorMap, - ].filter((x) => !!x), - issueData: { - code: ZodError_1.ZodIssueCode.invalid_arguments, - argumentsError: error, - }, - }); + const { status, ctx } = this._processInputParams(input); + const { shape, keys: shapeKeys } = this._getCached(); + const extraKeys = []; + if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) { + for (const key in ctx.data) { + if (!shapeKeys.includes(key)) { + extraKeys.push(key); + } + } } - function makeReturnsIssue(returns, error) { - return (0, parseUtil_1.makeIssue)({ - data: returns, - path: ctx.path, - errorMaps: [ - ctx.common.contextualErrorMap, - ctx.schemaErrorMap, - (0, errors_1.getErrorMap)(), - errors_1.defaultErrorMap, - ].filter((x) => !!x), - issueData: { - code: ZodError_1.ZodIssueCode.invalid_return_type, - returnTypeError: error, - }, + const pairs = []; + for (const key of shapeKeys) { + const keyValidator = shape[key]; + const value = ctx.data[key]; + pairs.push({ + key: { status: "valid", value: key }, + value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), + alwaysSet: key in ctx.data, }); } - const params = { errorMap: ctx.common.contextualErrorMap }; - const fn = ctx.data; - if (this._def.returns instanceof ZodPromise) { - // Would love a way to avoid disabling this rule, but we need - // an alias (using an arrow function was what caused 2651). - // eslint-disable-next-line @typescript-eslint/no-this-alias - const me = this; - return (0, parseUtil_1.OK)(async function (...args) { - const error = new ZodError_1.ZodError([]); - const parsedArgs = await me._def.args - .parseAsync(args, params) - .catch((e) => { - error.addIssue(makeArgsIssue(args, e)); - throw error; - }); - const result = await Reflect.apply(fn, this, parsedArgs); - const parsedReturns = await me._def.returns._def.type - .parseAsync(result, params) - .catch((e) => { - error.addIssue(makeReturnsIssue(result, e)); - throw error; - }); - return parsedReturns; - }); + if (this._def.catchall instanceof ZodNever) { + const unknownKeys = this._def.unknownKeys; + if (unknownKeys === "passthrough") { + for (const key of extraKeys) { + pairs.push({ + key: { status: "valid", value: key }, + value: { status: "valid", value: ctx.data[key] }, + }); + } + } + else if (unknownKeys === "strict") { + if (extraKeys.length > 0) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.unrecognized_keys, + keys: extraKeys, + }); + status.dirty(); + } + } + else if (unknownKeys === "strip") { + } + else { + throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); + } } else { - // Would love a way to avoid disabling this rule, but we need - // an alias (using an arrow function was what caused 2651). - // eslint-disable-next-line @typescript-eslint/no-this-alias - const me = this; - return (0, parseUtil_1.OK)(function (...args) { - const parsedArgs = me._def.args.safeParse(args, params); - if (!parsedArgs.success) { - throw new ZodError_1.ZodError([makeArgsIssue(args, parsedArgs.error)]); - } - const result = Reflect.apply(fn, this, parsedArgs.data); - const parsedReturns = me._def.returns.safeParse(result, params); - if (!parsedReturns.success) { - throw new ZodError_1.ZodError([makeReturnsIssue(result, parsedReturns.error)]); + // run catchall validation + const catchall = this._def.catchall; + for (const key of extraKeys) { + const value = ctx.data[key]; + pairs.push({ + key: { status: "valid", value: key }, + value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value) + ), + alwaysSet: key in ctx.data, + }); + } + } + if (ctx.common.async) { + return Promise.resolve() + .then(async () => { + const syncPairs = []; + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + syncPairs.push({ + key, + value, + alwaysSet: pair.alwaysSet, + }); } - return parsedReturns.data; + return syncPairs; + }) + .then((syncPairs) => { + return parseUtil_js_1.ParseStatus.mergeObjectSync(status, syncPairs); }); } + else { + return parseUtil_js_1.ParseStatus.mergeObjectSync(status, pairs); + } } - parameters() { - return this._def.args; - } - returnType() { - return this._def.returns; + get shape() { + return this._def.shape(); } - args(...items) { - return new ZodFunction({ + strict(message) { + errorUtil_js_1.errorUtil.errToObj; + return new ZodObject({ ...this._def, - args: ZodTuple.create(items).rest(ZodUnknown.create()), + unknownKeys: "strict", + ...(message !== undefined + ? { + errorMap: (issue, ctx) => { + const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError; + if (issue.code === "unrecognized_keys") + return { + message: errorUtil_js_1.errorUtil.errToObj(message).message ?? defaultError, + }; + return { + message: defaultError, + }; + }, + } + : {}), }); } - returns(returnType) { - return new ZodFunction({ + strip() { + return new ZodObject({ ...this._def, - returns: returnType, + unknownKeys: "strip", }); } - implement(func) { - const validatedFunc = this.parse(func); - return validatedFunc; - } - strictImplement(func) { - const validatedFunc = this.parse(func); - return validatedFunc; - } - static create(args, returns, params) { - return new ZodFunction({ - args: (args - ? args - : ZodTuple.create([]).rest(ZodUnknown.create())), - returns: returns || ZodUnknown.create(), - typeName: ZodFirstPartyTypeKind.ZodFunction, - ...processCreateParams(params), + passthrough() { + return new ZodObject({ + ...this._def, + unknownKeys: "passthrough", }); } -} -exports.ZodFunction = ZodFunction; -class ZodLazy extends ZodType { - get schema() { - return this._def.getter(); - } - _parse(input) { - const { ctx } = this._processInputParams(input); - const lazySchema = this._def.getter(); - return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); + // const AugmentFactory = + // (def: Def) => + // ( + // augmentation: Augmentation + // ): ZodObject< + // extendShape, Augmentation>, + // Def["unknownKeys"], + // Def["catchall"] + // > => { + // return new ZodObject({ + // ...def, + // shape: () => ({ + // ...def.shape(), + // ...augmentation, + // }), + // }) as any; + // }; + extend(augmentation) { + return new ZodObject({ + ...this._def, + shape: () => ({ + ...this._def.shape(), + ...augmentation, + }), + }); } -} -exports.ZodLazy = ZodLazy; -ZodLazy.create = (getter, params) => { - return new ZodLazy({ - getter: getter, - typeName: ZodFirstPartyTypeKind.ZodLazy, - ...processCreateParams(params), - }); -}; -class ZodLiteral extends ZodType { - _parse(input) { - if (input.data !== this._def.value) { - const ctx = this._getOrReturnCtx(input); - (0, parseUtil_1.addIssueToContext)(ctx, { - received: ctx.data, - code: ZodError_1.ZodIssueCode.invalid_literal, - expected: this._def.value, - }); - return parseUtil_1.INVALID; - } - return { status: "valid", value: input.data }; + /** + * Prior to zod@1.0.12 there was a bug in the + * inferred type of merged objects. Please + * upgrade if you are experiencing issues. + */ + merge(merging) { + const merged = new ZodObject({ + unknownKeys: merging._def.unknownKeys, + catchall: merging._def.catchall, + shape: () => ({ + ...this._def.shape(), + ...merging._def.shape(), + }), + typeName: ZodFirstPartyTypeKind.ZodObject, + }); + return merged; } - get value() { - return this._def.value; + // merge< + // Incoming extends AnyZodObject, + // Augmentation extends Incoming["shape"], + // NewOutput extends { + // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation + // ? Augmentation[k]["_output"] + // : k extends keyof Output + // ? Output[k] + // : never; + // }, + // NewInput extends { + // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation + // ? Augmentation[k]["_input"] + // : k extends keyof Input + // ? Input[k] + // : never; + // } + // >( + // merging: Incoming + // ): ZodObject< + // extendShape>, + // Incoming["_def"]["unknownKeys"], + // Incoming["_def"]["catchall"], + // NewOutput, + // NewInput + // > { + // const merged: any = new ZodObject({ + // unknownKeys: merging._def.unknownKeys, + // catchall: merging._def.catchall, + // shape: () => + // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), + // typeName: ZodFirstPartyTypeKind.ZodObject, + // }) as any; + // return merged; + // } + setKey(key, schema) { + return this.augment({ [key]: schema }); } -} -exports.ZodLiteral = ZodLiteral; -ZodLiteral.create = (value, params) => { - return new ZodLiteral({ - value: value, - typeName: ZodFirstPartyTypeKind.ZodLiteral, - ...processCreateParams(params), - }); -}; -function createZodEnum(values, params) { - return new ZodEnum({ - values, - typeName: ZodFirstPartyTypeKind.ZodEnum, - ...processCreateParams(params), - }); -} -class ZodEnum extends ZodType { - constructor() { - super(...arguments); - _ZodEnum_cache.set(this, void 0); + // merge( + // merging: Incoming + // ): //ZodObject = (merging) => { + // ZodObject< + // extendShape>, + // Incoming["_def"]["unknownKeys"], + // Incoming["_def"]["catchall"] + // > { + // // const mergedShape = objectUtil.mergeShapes( + // // this._def.shape(), + // // merging._def.shape() + // // ); + // const merged: any = new ZodObject({ + // unknownKeys: merging._def.unknownKeys, + // catchall: merging._def.catchall, + // shape: () => + // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), + // typeName: ZodFirstPartyTypeKind.ZodObject, + // }) as any; + // return merged; + // } + catchall(index) { + return new ZodObject({ + ...this._def, + catchall: index, + }); } - _parse(input) { - if (typeof input.data !== "string") { - const ctx = this._getOrReturnCtx(input); - const expectedValues = this._def.values; - (0, parseUtil_1.addIssueToContext)(ctx, { - expected: util_1.util.joinValues(expectedValues), - received: ctx.parsedType, - code: ZodError_1.ZodIssueCode.invalid_type, - }); - return parseUtil_1.INVALID; - } - if (!__classPrivateFieldGet(this, _ZodEnum_cache, "f")) { - __classPrivateFieldSet(this, _ZodEnum_cache, new Set(this._def.values), "f"); - } - if (!__classPrivateFieldGet(this, _ZodEnum_cache, "f").has(input.data)) { - const ctx = this._getOrReturnCtx(input); - const expectedValues = this._def.values; - (0, parseUtil_1.addIssueToContext)(ctx, { - received: ctx.data, - code: ZodError_1.ZodIssueCode.invalid_enum_value, - options: expectedValues, - }); - return parseUtil_1.INVALID; + pick(mask) { + const shape = {}; + for (const key of util_js_1.util.objectKeys(mask)) { + if (mask[key] && this.shape[key]) { + shape[key] = this.shape[key]; + } } - return (0, parseUtil_1.OK)(input.data); - } - get options() { - return this._def.values; + return new ZodObject({ + ...this._def, + shape: () => shape, + }); } - get enum() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; + omit(mask) { + const shape = {}; + for (const key of util_js_1.util.objectKeys(this.shape)) { + if (!mask[key]) { + shape[key] = this.shape[key]; + } } - return enumValues; + return new ZodObject({ + ...this._def, + shape: () => shape, + }); } - get Values() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; + /** + * @deprecated + */ + deepPartial() { + return deepPartialify(this); } - get Enum() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; + partial(mask) { + const newShape = {}; + for (const key of util_js_1.util.objectKeys(this.shape)) { + const fieldSchema = this.shape[key]; + if (mask && !mask[key]) { + newShape[key] = fieldSchema; + } + else { + newShape[key] = fieldSchema.optional(); + } } - return enumValues; - } - extract(values, newDef = this._def) { - return ZodEnum.create(values, { + return new ZodObject({ ...this._def, - ...newDef, + shape: () => newShape, }); } - exclude(values, newDef = this._def) { - return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), { + required(mask) { + const newShape = {}; + for (const key of util_js_1.util.objectKeys(this.shape)) { + if (mask && !mask[key]) { + newShape[key] = this.shape[key]; + } + else { + const fieldSchema = this.shape[key]; + let newField = fieldSchema; + while (newField instanceof ZodOptional) { + newField = newField._def.innerType; + } + newShape[key] = newField; + } + } + return new ZodObject({ ...this._def, - ...newDef, + shape: () => newShape, }); } -} -exports.ZodEnum = ZodEnum; -_ZodEnum_cache = new WeakMap(); -ZodEnum.create = createZodEnum; -class ZodNativeEnum extends ZodType { - constructor() { - super(...arguments); - _ZodNativeEnum_cache.set(this, void 0); - } - _parse(input) { - const nativeEnumValues = util_1.util.getValidEnumValues(this._def.values); - const ctx = this._getOrReturnCtx(input); - if (ctx.parsedType !== util_1.ZodParsedType.string && - ctx.parsedType !== util_1.ZodParsedType.number) { - const expectedValues = util_1.util.objectValues(nativeEnumValues); - (0, parseUtil_1.addIssueToContext)(ctx, { - expected: util_1.util.joinValues(expectedValues), - received: ctx.parsedType, - code: ZodError_1.ZodIssueCode.invalid_type, - }); - return parseUtil_1.INVALID; - } - if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, "f")) { - __classPrivateFieldSet(this, _ZodNativeEnum_cache, new Set(util_1.util.getValidEnumValues(this._def.values)), "f"); - } - if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, "f").has(input.data)) { - const expectedValues = util_1.util.objectValues(nativeEnumValues); - (0, parseUtil_1.addIssueToContext)(ctx, { - received: ctx.data, - code: ZodError_1.ZodIssueCode.invalid_enum_value, - options: expectedValues, - }); - return parseUtil_1.INVALID; - } - return (0, parseUtil_1.OK)(input.data); - } - get enum() { - return this._def.values; + keyof() { + return createZodEnum(util_js_1.util.objectKeys(this.shape)); } } -exports.ZodNativeEnum = ZodNativeEnum; -_ZodNativeEnum_cache = new WeakMap(); -ZodNativeEnum.create = (values, params) => { - return new ZodNativeEnum({ - values: values, - typeName: ZodFirstPartyTypeKind.ZodNativeEnum, +exports.ZodObject = ZodObject; +ZodObject.create = (shape, params) => { + return new ZodObject({ + shape: () => shape, + unknownKeys: "strip", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, ...processCreateParams(params), }); }; -class ZodPromise extends ZodType { - unwrap() { - return this._def.type; - } - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== util_1.ZodParsedType.promise && - ctx.common.async === false) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.promise, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - const promisified = ctx.parsedType === util_1.ZodParsedType.promise - ? ctx.data - : Promise.resolve(ctx.data); - return (0, parseUtil_1.OK)(promisified.then((data) => { - return this._def.type.parseAsync(data, { - path: ctx.path, - errorMap: ctx.common.contextualErrorMap, - }); - })); - } -} -exports.ZodPromise = ZodPromise; -ZodPromise.create = (schema, params) => { - return new ZodPromise({ - type: schema, - typeName: ZodFirstPartyTypeKind.ZodPromise, +ZodObject.strictCreate = (shape, params) => { + return new ZodObject({ + shape: () => shape, + unknownKeys: "strict", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, ...processCreateParams(params), }); }; -class ZodEffects extends ZodType { - innerType() { - return this._def.schema; - } - sourceType() { - return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects - ? this._def.schema.sourceType() - : this._def.schema; - } +ZodObject.lazycreate = (shape, params) => { + return new ZodObject({ + shape, + unknownKeys: "strip", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params), + }); +}; +class ZodUnion extends ZodType { _parse(input) { - const { status, ctx } = this._processInputParams(input); - const effect = this._def.effect || null; - const checkCtx = { - addIssue: (arg) => { - (0, parseUtil_1.addIssueToContext)(ctx, arg); - if (arg.fatal) { - status.abort(); - } - else { - status.dirty(); + const { ctx } = this._processInputParams(input); + const options = this._def.options; + function handleResults(results) { + // return first issue-free validation if it exists + for (const result of results) { + if (result.result.status === "valid") { + return result.result; } - }, - get path() { - return ctx.path; - }, - }; - checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); - if (effect.type === "preprocess") { - const processed = effect.transform(ctx.data, checkCtx); - if (ctx.common.async) { - return Promise.resolve(processed).then(async (processed) => { - if (status.value === "aborted") - return parseUtil_1.INVALID; - const result = await this._def.schema._parseAsync({ - data: processed, - path: ctx.path, - parent: ctx, - }); - if (result.status === "aborted") - return parseUtil_1.INVALID; - if (result.status === "dirty") - return (0, parseUtil_1.DIRTY)(result.value); - if (status.value === "dirty") - return (0, parseUtil_1.DIRTY)(result.value); - return result; - }); - } - else { - if (status.value === "aborted") - return parseUtil_1.INVALID; - const result = this._def.schema._parseSync({ - data: processed, - path: ctx.path, - parent: ctx, - }); - if (result.status === "aborted") - return parseUtil_1.INVALID; - if (result.status === "dirty") - return (0, parseUtil_1.DIRTY)(result.value); - if (status.value === "dirty") - return (0, parseUtil_1.DIRTY)(result.value); - return result; } - } - if (effect.type === "refinement") { - const executeRefinement = (acc) => { - const result = effect.refinement(acc, checkCtx); - if (ctx.common.async) { - return Promise.resolve(result); - } - if (result instanceof Promise) { - throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); + for (const result of results) { + if (result.result.status === "dirty") { + // add issues from dirty option + ctx.common.issues.push(...result.ctx.common.issues); + return result.result; } - return acc; - }; - if (ctx.common.async === false) { - const inner = this._def.schema._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }); - if (inner.status === "aborted") - return parseUtil_1.INVALID; - if (inner.status === "dirty") - status.dirty(); - // return value is ignored - executeRefinement(inner.value); - return { status: status.value, value: inner.value }; - } - else { - return this._def.schema - ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }) - .then((inner) => { - if (inner.status === "aborted") - return parseUtil_1.INVALID; - if (inner.status === "dirty") - status.dirty(); - return executeRefinement(inner.value).then(() => { - return { status: status.value, value: inner.value }; - }); - }); } + // return invalid + const unionErrors = results.map((result) => new ZodError_js_1.ZodError(result.ctx.common.issues)); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_union, + unionErrors, + }); + return parseUtil_js_1.INVALID; } - if (effect.type === "transform") { - if (ctx.common.async === false) { - const base = this._def.schema._parseSync({ + if (ctx.common.async) { + return Promise.all(options.map(async (option) => { + const childCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [], + }, + parent: null, + }; + return { + result: await option._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: childCtx, + }), + ctx: childCtx, + }; + })).then(handleResults); + } + else { + let dirty = undefined; + const issues = []; + for (const option of options) { + const childCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [], + }, + parent: null, + }; + const result = option._parseSync({ data: ctx.data, path: ctx.path, - parent: ctx, + parent: childCtx, }); - if (!(0, parseUtil_1.isValid)(base)) - return base; - const result = effect.transform(base.value, checkCtx); - if (result instanceof Promise) { - throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); + if (result.status === "valid") { + return result; + } + else if (result.status === "dirty" && !dirty) { + dirty = { result, ctx: childCtx }; + } + if (childCtx.common.issues.length) { + issues.push(childCtx.common.issues); } - return { status: status.value, value: result }; } - else { - return this._def.schema - ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }) - .then((base) => { - if (!(0, parseUtil_1.isValid)(base)) - return base; - return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ status: status.value, value: result })); - }); + if (dirty) { + ctx.common.issues.push(...dirty.ctx.common.issues); + return dirty.result; } + const unionErrors = issues.map((issues) => new ZodError_js_1.ZodError(issues)); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_union, + unionErrors, + }); + return parseUtil_js_1.INVALID; } - util_1.util.assertNever(effect); + } + get options() { + return this._def.options; } } -exports.ZodEffects = ZodEffects; -exports.ZodTransformer = ZodEffects; -ZodEffects.create = (schema, effect, params) => { - return new ZodEffects({ - schema, - typeName: ZodFirstPartyTypeKind.ZodEffects, - effect, - ...processCreateParams(params), - }); -}; -ZodEffects.createWithPreprocess = (preprocess, schema, params) => { - return new ZodEffects({ - schema, - effect: { type: "preprocess", transform: preprocess }, - typeName: ZodFirstPartyTypeKind.ZodEffects, +exports.ZodUnion = ZodUnion; +ZodUnion.create = (types, params) => { + return new ZodUnion({ + options: types, + typeName: ZodFirstPartyTypeKind.ZodUnion, ...processCreateParams(params), }); }; -class ZodOptional extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType === util_1.ZodParsedType.undefined) { - return (0, parseUtil_1.OK)(undefined); - } - return this._def.innerType._parse(input); +///////////////////////////////////////////////////// +///////////////////////////////////////////////////// +////////// ////////// +////////// ZodDiscriminatedUnion ////////// +////////// ////////// +///////////////////////////////////////////////////// +///////////////////////////////////////////////////// +const getDiscriminator = (type) => { + if (type instanceof ZodLazy) { + return getDiscriminator(type.schema); } - unwrap() { - return this._def.innerType; + else if (type instanceof ZodEffects) { + return getDiscriminator(type.innerType()); } -} -exports.ZodOptional = ZodOptional; -ZodOptional.create = (type, params) => { - return new ZodOptional({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodOptional, - ...processCreateParams(params), - }); -}; -class ZodNullable extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType === util_1.ZodParsedType.null) { - return (0, parseUtil_1.OK)(null); - } - return this._def.innerType._parse(input); + else if (type instanceof ZodLiteral) { + return [type.value]; } - unwrap() { - return this._def.innerType; + else if (type instanceof ZodEnum) { + return type.options; } -} -exports.ZodNullable = ZodNullable; -ZodNullable.create = (type, params) => { - return new ZodNullable({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodNullable, - ...processCreateParams(params), - }); -}; -class ZodDefault extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - let data = ctx.data; - if (ctx.parsedType === util_1.ZodParsedType.undefined) { - data = this._def.defaultValue(); - } - return this._def.innerType._parse({ - data, - path: ctx.path, - parent: ctx, - }); + else if (type instanceof ZodNativeEnum) { + // eslint-disable-next-line ban/ban + return util_js_1.util.objectValues(type.enum); } - removeDefault() { - return this._def.innerType; + else if (type instanceof ZodDefault) { + return getDiscriminator(type._def.innerType); } -} -exports.ZodDefault = ZodDefault; -ZodDefault.create = (type, params) => { - return new ZodDefault({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodDefault, - defaultValue: typeof params.default === "function" - ? params.default - : () => params.default, - ...processCreateParams(params), - }); -}; -class ZodCatch extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - // newCtx is used to not collect issues from inner types in ctx - const newCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [], - }, - }; - const result = this._def.innerType._parse({ - data: newCtx.data, - path: newCtx.path, - parent: { - ...newCtx, - }, - }); - if ((0, parseUtil_1.isAsync)(result)) { - return result.then((result) => { - return { - status: "valid", - value: result.status === "valid" - ? result.value - : this._def.catchValue({ - get error() { - return new ZodError_1.ZodError(newCtx.common.issues); - }, - input: newCtx.data, - }), - }; - }); - } - else { - return { - status: "valid", - value: result.status === "valid" - ? result.value - : this._def.catchValue({ - get error() { - return new ZodError_1.ZodError(newCtx.common.issues); - }, - input: newCtx.data, - }), - }; - } + else if (type instanceof ZodUndefined) { + return [undefined]; } - removeCatch() { - return this._def.innerType; + else if (type instanceof ZodNull) { + return [null]; + } + else if (type instanceof ZodOptional) { + return [undefined, ...getDiscriminator(type.unwrap())]; + } + else if (type instanceof ZodNullable) { + return [null, ...getDiscriminator(type.unwrap())]; + } + else if (type instanceof ZodBranded) { + return getDiscriminator(type.unwrap()); + } + else if (type instanceof ZodReadonly) { + return getDiscriminator(type.unwrap()); + } + else if (type instanceof ZodCatch) { + return getDiscriminator(type._def.innerType); + } + else { + return []; } -} -exports.ZodCatch = ZodCatch; -ZodCatch.create = (type, params) => { - return new ZodCatch({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodCatch, - catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, - ...processCreateParams(params), - }); }; -class ZodNaN extends ZodType { +class ZodDiscriminatedUnion extends ZodType { _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== util_1.ZodParsedType.nan) { - const ctx = this._getOrReturnCtx(input); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.nan, + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== util_js_1.ZodParsedType.object) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.object, received: ctx.parsedType, }); - return parseUtil_1.INVALID; + return parseUtil_js_1.INVALID; + } + const discriminator = this.discriminator; + const discriminatorValue = ctx.data[discriminator]; + const option = this.optionsMap.get(discriminatorValue); + if (!option) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_union_discriminator, + options: Array.from(this.optionsMap.keys()), + path: [discriminator], + }); + return parseUtil_js_1.INVALID; } - return { status: "valid", value: input.data }; - } -} -exports.ZodNaN = ZodNaN; -ZodNaN.create = (params) => { - return new ZodNaN({ - typeName: ZodFirstPartyTypeKind.ZodNaN, - ...processCreateParams(params), - }); -}; -exports.BRAND = Symbol("zod_brand"); -class ZodBranded extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - const data = ctx.data; - return this._def.type._parse({ - data, - path: ctx.path, - parent: ctx, - }); - } - unwrap() { - return this._def.type; - } -} -exports.ZodBranded = ZodBranded; -class ZodPipeline extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); if (ctx.common.async) { - const handleAsync = async () => { - const inResult = await this._def.in._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }); - if (inResult.status === "aborted") - return parseUtil_1.INVALID; - if (inResult.status === "dirty") { - status.dirty(); - return (0, parseUtil_1.DIRTY)(inResult.value); - } - else { - return this._def.out._parseAsync({ - data: inResult.value, - path: ctx.path, - parent: ctx, - }); - } - }; - return handleAsync(); + return option._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); } else { - const inResult = this._def.in._parseSync({ + return option._parseSync({ data: ctx.data, path: ctx.path, parent: ctx, }); - if (inResult.status === "aborted") - return parseUtil_1.INVALID; - if (inResult.status === "dirty") { - status.dirty(); - return { - status: "dirty", - value: inResult.value, - }; + } + } + get discriminator() { + return this._def.discriminator; + } + get options() { + return this._def.options; + } + get optionsMap() { + return this._def.optionsMap; + } + /** + * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor. + * However, it only allows a union of objects, all of which need to share a discriminator property. This property must + * have a different value for each object in the union. + * @param discriminator the name of the discriminator property + * @param types an array of object schemas + * @param params + */ + static create(discriminator, options, params) { + // Get all the valid discriminator values + const optionsMap = new Map(); + // try { + for (const type of options) { + const discriminatorValues = getDiscriminator(type.shape[discriminator]); + if (!discriminatorValues.length) { + throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); } - else { - return this._def.out._parseSync({ - data: inResult.value, - path: ctx.path, - parent: ctx, - }); + for (const value of discriminatorValues) { + if (optionsMap.has(value)) { + throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); + } + optionsMap.set(value, type); } } - } - static create(a, b) { - return new ZodPipeline({ - in: a, - out: b, - typeName: ZodFirstPartyTypeKind.ZodPipeline, + return new ZodDiscriminatedUnion({ + typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion, + discriminator, + options, + optionsMap, + ...processCreateParams(params), }); } } -exports.ZodPipeline = ZodPipeline; -class ZodReadonly extends ZodType { - _parse(input) { - const result = this._def.innerType._parse(input); - const freeze = (data) => { - if ((0, parseUtil_1.isValid)(data)) { - data.value = Object.freeze(data.value); - } - return data; - }; - return (0, parseUtil_1.isAsync)(result) - ? result.then((data) => freeze(data)) - : freeze(result); - } - unwrap() { - return this._def.innerType; +exports.ZodDiscriminatedUnion = ZodDiscriminatedUnion; +function mergeValues(a, b) { + const aType = (0, util_js_1.getParsedType)(a); + const bType = (0, util_js_1.getParsedType)(b); + if (a === b) { + return { valid: true, data: a }; } -} -exports.ZodReadonly = ZodReadonly; -ZodReadonly.create = (type, params) => { - return new ZodReadonly({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodReadonly, - ...processCreateParams(params), - }); -}; -//////////////////////////////////////// -//////////////////////////////////////// -////////// ////////// -////////// z.custom ////////// -////////// ////////// -//////////////////////////////////////// -//////////////////////////////////////// -function cleanParams(params, data) { - const p = typeof params === "function" - ? params(data) - : typeof params === "string" - ? { message: params } - : params; - const p2 = typeof p === "string" ? { message: p } : p; - return p2; -} -function custom(check, _params = {}, -/** - * @deprecated - * - * Pass `fatal` into the params object instead: - * - * ```ts - * z.string().custom((val) => val.length > 5, { fatal: false }) - * ``` - * - */ -fatal) { - if (check) - return ZodAny.create().superRefine((data, ctx) => { - var _a, _b; - const r = check(data); - if (r instanceof Promise) { - return r.then((r) => { - var _a, _b; - if (!r) { - const params = cleanParams(_params, data); - const _fatal = (_b = (_a = params.fatal) !== null && _a !== void 0 ? _a : fatal) !== null && _b !== void 0 ? _b : true; - ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); - } - }); - } - if (!r) { - const params = cleanParams(_params, data); - const _fatal = (_b = (_a = params.fatal) !== null && _a !== void 0 ? _a : fatal) !== null && _b !== void 0 ? _b : true; - ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); + else if (aType === util_js_1.ZodParsedType.object && bType === util_js_1.ZodParsedType.object) { + const bKeys = util_js_1.util.objectKeys(b); + const sharedKeys = util_js_1.util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1); + const newObj = { ...a, ...b }; + for (const key of sharedKeys) { + const sharedValue = mergeValues(a[key], b[key]); + if (!sharedValue.valid) { + return { valid: false }; } - return; - }); - return ZodAny.create(); -} -exports.custom = custom; -exports.late = { - object: ZodObject.lazycreate, -}; -var ZodFirstPartyTypeKind; -(function (ZodFirstPartyTypeKind) { - ZodFirstPartyTypeKind["ZodString"] = "ZodString"; - ZodFirstPartyTypeKind["ZodNumber"] = "ZodNumber"; - ZodFirstPartyTypeKind["ZodNaN"] = "ZodNaN"; - ZodFirstPartyTypeKind["ZodBigInt"] = "ZodBigInt"; - ZodFirstPartyTypeKind["ZodBoolean"] = "ZodBoolean"; - ZodFirstPartyTypeKind["ZodDate"] = "ZodDate"; - ZodFirstPartyTypeKind["ZodSymbol"] = "ZodSymbol"; - ZodFirstPartyTypeKind["ZodUndefined"] = "ZodUndefined"; - ZodFirstPartyTypeKind["ZodNull"] = "ZodNull"; - ZodFirstPartyTypeKind["ZodAny"] = "ZodAny"; - ZodFirstPartyTypeKind["ZodUnknown"] = "ZodUnknown"; - ZodFirstPartyTypeKind["ZodNever"] = "ZodNever"; - ZodFirstPartyTypeKind["ZodVoid"] = "ZodVoid"; - ZodFirstPartyTypeKind["ZodArray"] = "ZodArray"; - ZodFirstPartyTypeKind["ZodObject"] = "ZodObject"; - ZodFirstPartyTypeKind["ZodUnion"] = "ZodUnion"; - ZodFirstPartyTypeKind["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; - ZodFirstPartyTypeKind["ZodIntersection"] = "ZodIntersection"; - ZodFirstPartyTypeKind["ZodTuple"] = "ZodTuple"; - ZodFirstPartyTypeKind["ZodRecord"] = "ZodRecord"; - ZodFirstPartyTypeKind["ZodMap"] = "ZodMap"; - ZodFirstPartyTypeKind["ZodSet"] = "ZodSet"; - ZodFirstPartyTypeKind["ZodFunction"] = "ZodFunction"; - ZodFirstPartyTypeKind["ZodLazy"] = "ZodLazy"; - ZodFirstPartyTypeKind["ZodLiteral"] = "ZodLiteral"; - ZodFirstPartyTypeKind["ZodEnum"] = "ZodEnum"; - ZodFirstPartyTypeKind["ZodEffects"] = "ZodEffects"; - ZodFirstPartyTypeKind["ZodNativeEnum"] = "ZodNativeEnum"; - ZodFirstPartyTypeKind["ZodOptional"] = "ZodOptional"; - ZodFirstPartyTypeKind["ZodNullable"] = "ZodNullable"; - ZodFirstPartyTypeKind["ZodDefault"] = "ZodDefault"; - ZodFirstPartyTypeKind["ZodCatch"] = "ZodCatch"; - ZodFirstPartyTypeKind["ZodPromise"] = "ZodPromise"; - ZodFirstPartyTypeKind["ZodBranded"] = "ZodBranded"; - ZodFirstPartyTypeKind["ZodPipeline"] = "ZodPipeline"; - ZodFirstPartyTypeKind["ZodReadonly"] = "ZodReadonly"; -})(ZodFirstPartyTypeKind || (exports.ZodFirstPartyTypeKind = ZodFirstPartyTypeKind = {})); -// requires TS 4.4+ -class Class { - constructor(..._) { } -} -const instanceOfType = ( -// const instanceOfType = any>( -cls, params = { - message: `Input not instance of ${cls.name}`, -}) => custom((data) => data instanceof cls, params); -exports["instanceof"] = instanceOfType; -const stringType = ZodString.create; -exports.string = stringType; -const numberType = ZodNumber.create; -exports.number = numberType; -const nanType = ZodNaN.create; -exports.nan = nanType; -const bigIntType = ZodBigInt.create; -exports.bigint = bigIntType; -const booleanType = ZodBoolean.create; -exports.boolean = booleanType; -const dateType = ZodDate.create; -exports.date = dateType; -const symbolType = ZodSymbol.create; -exports.symbol = symbolType; -const undefinedType = ZodUndefined.create; -exports.undefined = undefinedType; -const nullType = ZodNull.create; -exports["null"] = nullType; -const anyType = ZodAny.create; -exports.any = anyType; -const unknownType = ZodUnknown.create; -exports.unknown = unknownType; -const neverType = ZodNever.create; -exports.never = neverType; -const voidType = ZodVoid.create; -exports["void"] = voidType; -const arrayType = ZodArray.create; -exports.array = arrayType; -const objectType = ZodObject.create; -exports.object = objectType; -const strictObjectType = ZodObject.strictCreate; -exports.strictObject = strictObjectType; -const unionType = ZodUnion.create; -exports.union = unionType; -const discriminatedUnionType = ZodDiscriminatedUnion.create; -exports.discriminatedUnion = discriminatedUnionType; -const intersectionType = ZodIntersection.create; -exports.intersection = intersectionType; -const tupleType = ZodTuple.create; -exports.tuple = tupleType; -const recordType = ZodRecord.create; -exports.record = recordType; -const mapType = ZodMap.create; -exports.map = mapType; -const setType = ZodSet.create; -exports.set = setType; -const functionType = ZodFunction.create; -exports["function"] = functionType; -const lazyType = ZodLazy.create; -exports.lazy = lazyType; -const literalType = ZodLiteral.create; -exports.literal = literalType; -const enumType = ZodEnum.create; -exports["enum"] = enumType; -const nativeEnumType = ZodNativeEnum.create; -exports.nativeEnum = nativeEnumType; -const promiseType = ZodPromise.create; -exports.promise = promiseType; -const effectsType = ZodEffects.create; -exports.effect = effectsType; -exports.transformer = effectsType; -const optionalType = ZodOptional.create; -exports.optional = optionalType; -const nullableType = ZodNullable.create; -exports.nullable = nullableType; -const preprocessType = ZodEffects.createWithPreprocess; -exports.preprocess = preprocessType; -const pipelineType = ZodPipeline.create; -exports.pipeline = pipelineType; -const ostring = () => stringType().optional(); -exports.ostring = ostring; -const onumber = () => numberType().optional(); -exports.onumber = onumber; -const oboolean = () => booleanType().optional(); -exports.oboolean = oboolean; -exports.coerce = { - string: ((arg) => ZodString.create({ ...arg, coerce: true })), - number: ((arg) => ZodNumber.create({ ...arg, coerce: true })), - boolean: ((arg) => ZodBoolean.create({ - ...arg, - coerce: true, - })), - bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })), - date: ((arg) => ZodDate.create({ ...arg, coerce: true })), -}; -exports.NEVER = parseUtil_1.INVALID; - - -/***/ }), - -/***/ 2078: -/***/ ((module) => { - -module.exports = eval("require")("encoding"); - - -/***/ }), - -/***/ 2613: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("assert"); - -/***/ }), - -/***/ 290: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("async_hooks"); - -/***/ }), - -/***/ 181: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("buffer"); - -/***/ }), - -/***/ 5317: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("child_process"); - -/***/ }), - -/***/ 4236: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("console"); - -/***/ }), - -/***/ 6982: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("crypto"); - -/***/ }), - -/***/ 1637: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("diagnostics_channel"); - -/***/ }), - -/***/ 4434: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("events"); - -/***/ }), - -/***/ 9896: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("fs"); - -/***/ }), - -/***/ 8611: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("http"); - -/***/ }), - -/***/ 5675: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("http2"); - -/***/ }), - -/***/ 5692: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("https"); - -/***/ }), - -/***/ 9278: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("net"); - -/***/ }), - -/***/ 7598: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:crypto"); - -/***/ }), - -/***/ 8474: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:events"); - -/***/ }), - -/***/ 7075: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:stream"); - -/***/ }), - -/***/ 7975: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:util"); - -/***/ }), - -/***/ 857: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("os"); - -/***/ }), - -/***/ 6928: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("path"); - -/***/ }), - -/***/ 2987: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("perf_hooks"); - -/***/ }), - -/***/ 4876: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("punycode"); - -/***/ }), - -/***/ 3480: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("querystring"); - -/***/ }), - -/***/ 2203: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("stream"); - -/***/ }), - -/***/ 3774: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("stream/web"); - -/***/ }), - -/***/ 3193: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("string_decoder"); - -/***/ }), - -/***/ 3557: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("timers"); - -/***/ }), - -/***/ 4756: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("tls"); - -/***/ }), - -/***/ 7016: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("url"); - -/***/ }), - -/***/ 9023: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("util"); - -/***/ }), - -/***/ 8253: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("util/types"); - -/***/ }), - -/***/ 8167: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("worker_threads"); - -/***/ }), - -/***/ 3106: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("zlib"); - -/***/ }), - -/***/ 7182: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const WritableStream = (__nccwpck_require__(7075).Writable) -const inherits = (__nccwpck_require__(7975).inherits) - -const StreamSearch = __nccwpck_require__(4136) - -const PartStream = __nccwpck_require__(612) -const HeaderParser = __nccwpck_require__(2271) - -const DASH = 45 -const B_ONEDASH = Buffer.from('-') -const B_CRLF = Buffer.from('\r\n') -const EMPTY_FN = function () {} - -function Dicer (cfg) { - if (!(this instanceof Dicer)) { return new Dicer(cfg) } - WritableStream.call(this, cfg) - - if (!cfg || (!cfg.headerFirst && typeof cfg.boundary !== 'string')) { throw new TypeError('Boundary required') } - - if (typeof cfg.boundary === 'string') { this.setBoundary(cfg.boundary) } else { this._bparser = undefined } - - this._headerFirst = cfg.headerFirst - - this._dashes = 0 - this._parts = 0 - this._finished = false - this._realFinish = false - this._isPreamble = true - this._justMatched = false - this._firstWrite = true - this._inHeader = true - this._part = undefined - this._cb = undefined - this._ignoreData = false - this._partOpts = { highWaterMark: cfg.partHwm } - this._pause = false - - const self = this - this._hparser = new HeaderParser(cfg) - this._hparser.on('header', function (header) { - self._inHeader = false - self._part.emit('header', header) - }) + newObj[key] = sharedValue.data; + } + return { valid: true, data: newObj }; + } + else if (aType === util_js_1.ZodParsedType.array && bType === util_js_1.ZodParsedType.array) { + if (a.length !== b.length) { + return { valid: false }; + } + const newArray = []; + for (let index = 0; index < a.length; index++) { + const itemA = a[index]; + const itemB = b[index]; + const sharedValue = mergeValues(itemA, itemB); + if (!sharedValue.valid) { + return { valid: false }; + } + newArray.push(sharedValue.data); + } + return { valid: true, data: newArray }; + } + else if (aType === util_js_1.ZodParsedType.date && bType === util_js_1.ZodParsedType.date && +a === +b) { + return { valid: true, data: a }; + } + else { + return { valid: false }; + } } -inherits(Dicer, WritableStream) - -Dicer.prototype.emit = function (ev) { - if (ev === 'finish' && !this._realFinish) { - if (!this._finished) { - const self = this - process.nextTick(function () { - self.emit('error', new Error('Unexpected end of multipart data')) - if (self._part && !self._ignoreData) { - const type = (self._isPreamble ? 'Preamble' : 'Part') - self._part.emit('error', new Error(type + ' terminated early due to unexpected end of multipart data')) - self._part.push(null) - process.nextTick(function () { - self._realFinish = true - self.emit('finish') - self._realFinish = false - }) - return +class ZodIntersection extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + const handleParsed = (parsedLeft, parsedRight) => { + if ((0, parseUtil_js_1.isAborted)(parsedLeft) || (0, parseUtil_js_1.isAborted)(parsedRight)) { + return parseUtil_js_1.INVALID; + } + const merged = mergeValues(parsedLeft.value, parsedRight.value); + if (!merged.valid) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_intersection_types, + }); + return parseUtil_js_1.INVALID; + } + if ((0, parseUtil_js_1.isDirty)(parsedLeft) || (0, parseUtil_js_1.isDirty)(parsedRight)) { + status.dirty(); + } + return { status: status.value, value: merged.data }; + }; + if (ctx.common.async) { + return Promise.all([ + this._def.left._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }), + this._def.right._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }), + ]).then(([left, right]) => handleParsed(left, right)); + } + else { + return handleParsed(this._def.left._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }), this._def.right._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + })); } - self._realFinish = true - self.emit('finish') - self._realFinish = false - }) } - } else { WritableStream.prototype.emit.apply(this, arguments) } } - -Dicer.prototype._write = function (data, encoding, cb) { - // ignore unexpected data (e.g. extra trailer data after finished) - if (!this._hparser && !this._bparser) { return cb() } - - if (this._headerFirst && this._isPreamble) { - if (!this._part) { - this._part = new PartStream(this._partOpts) - if (this.listenerCount('preamble') !== 0) { this.emit('preamble', this._part) } else { this._ignore() } +exports.ZodIntersection = ZodIntersection; +ZodIntersection.create = (left, right, params) => { + return new ZodIntersection({ + left: left, + right: right, + typeName: ZodFirstPartyTypeKind.ZodIntersection, + ...processCreateParams(params), + }); +}; +// type ZodTupleItems = [ZodTypeAny, ...ZodTypeAny[]]; +class ZodTuple extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== util_js_1.ZodParsedType.array) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.array, + received: ctx.parsedType, + }); + return parseUtil_js_1.INVALID; + } + if (ctx.data.length < this._def.items.length) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.too_small, + minimum: this._def.items.length, + inclusive: true, + exact: false, + type: "array", + }); + return parseUtil_js_1.INVALID; + } + const rest = this._def.rest; + if (!rest && ctx.data.length > this._def.items.length) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.too_big, + maximum: this._def.items.length, + inclusive: true, + exact: false, + type: "array", + }); + status.dirty(); + } + const items = [...ctx.data] + .map((item, itemIndex) => { + const schema = this._def.items[itemIndex] || this._def.rest; + if (!schema) + return null; + return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)); + }) + .filter((x) => !!x); // filter nulls + if (ctx.common.async) { + return Promise.all(items).then((results) => { + return parseUtil_js_1.ParseStatus.mergeArray(status, results); + }); + } + else { + return parseUtil_js_1.ParseStatus.mergeArray(status, items); + } + } + get items() { + return this._def.items; + } + rest(rest) { + return new ZodTuple({ + ...this._def, + rest, + }); } - const r = this._hparser.push(data) - if (!this._inHeader && r !== undefined && r < data.length) { data = data.slice(r) } else { return cb() } - } - - // allows for "easier" testing - if (this._firstWrite) { - this._bparser.push(B_CRLF) - this._firstWrite = false - } - - this._bparser.push(data) - - if (this._pause) { this._cb = cb } else { cb() } } - -Dicer.prototype.reset = function () { - this._part = undefined - this._bparser = undefined - this._hparser = undefined +exports.ZodTuple = ZodTuple; +ZodTuple.create = (schemas, params) => { + if (!Array.isArray(schemas)) { + throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); + } + return new ZodTuple({ + items: schemas, + typeName: ZodFirstPartyTypeKind.ZodTuple, + rest: null, + ...processCreateParams(params), + }); +}; +class ZodRecord extends ZodType { + get keySchema() { + return this._def.keyType; + } + get valueSchema() { + return this._def.valueType; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== util_js_1.ZodParsedType.object) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.object, + received: ctx.parsedType, + }); + return parseUtil_js_1.INVALID; + } + const pairs = []; + const keyType = this._def.keyType; + const valueType = this._def.valueType; + for (const key in ctx.data) { + pairs.push({ + key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)), + value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)), + alwaysSet: key in ctx.data, + }); + } + if (ctx.common.async) { + return parseUtil_js_1.ParseStatus.mergeObjectAsync(status, pairs); + } + else { + return parseUtil_js_1.ParseStatus.mergeObjectSync(status, pairs); + } + } + get element() { + return this._def.valueType; + } + static create(first, second, third) { + if (second instanceof ZodType) { + return new ZodRecord({ + keyType: first, + valueType: second, + typeName: ZodFirstPartyTypeKind.ZodRecord, + ...processCreateParams(third), + }); + } + return new ZodRecord({ + keyType: ZodString.create(), + valueType: first, + typeName: ZodFirstPartyTypeKind.ZodRecord, + ...processCreateParams(second), + }); + } } - -Dicer.prototype.setBoundary = function (boundary) { - const self = this - this._bparser = new StreamSearch('\r\n--' + boundary) - this._bparser.on('info', function (isMatch, data, start, end) { - self._oninfo(isMatch, data, start, end) - }) +exports.ZodRecord = ZodRecord; +class ZodMap extends ZodType { + get keySchema() { + return this._def.keyType; + } + get valueSchema() { + return this._def.valueType; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== util_js_1.ZodParsedType.map) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.map, + received: ctx.parsedType, + }); + return parseUtil_js_1.INVALID; + } + const keyType = this._def.keyType; + const valueType = this._def.valueType; + const pairs = [...ctx.data.entries()].map(([key, value], index) => { + return { + key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])), + value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])), + }; + }); + if (ctx.common.async) { + const finalMap = new Map(); + return Promise.resolve().then(async () => { + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + if (key.status === "aborted" || value.status === "aborted") { + return parseUtil_js_1.INVALID; + } + if (key.status === "dirty" || value.status === "dirty") { + status.dirty(); + } + finalMap.set(key.value, value.value); + } + return { status: status.value, value: finalMap }; + }); + } + else { + const finalMap = new Map(); + for (const pair of pairs) { + const key = pair.key; + const value = pair.value; + if (key.status === "aborted" || value.status === "aborted") { + return parseUtil_js_1.INVALID; + } + if (key.status === "dirty" || value.status === "dirty") { + status.dirty(); + } + finalMap.set(key.value, value.value); + } + return { status: status.value, value: finalMap }; + } + } } - -Dicer.prototype._ignore = function () { - if (this._part && !this._ignoreData) { - this._ignoreData = true - this._part.on('error', EMPTY_FN) - // we must perform some kind of read on the stream even though we are - // ignoring the data, otherwise node's Readable stream will not emit 'end' - // after pushing null to the stream - this._part.resume() - } +exports.ZodMap = ZodMap; +ZodMap.create = (keyType, valueType, params) => { + return new ZodMap({ + valueType, + keyType, + typeName: ZodFirstPartyTypeKind.ZodMap, + ...processCreateParams(params), + }); +}; +class ZodSet extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== util_js_1.ZodParsedType.set) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.set, + received: ctx.parsedType, + }); + return parseUtil_js_1.INVALID; + } + const def = this._def; + if (def.minSize !== null) { + if (ctx.data.size < def.minSize.value) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.too_small, + minimum: def.minSize.value, + type: "set", + inclusive: true, + exact: false, + message: def.minSize.message, + }); + status.dirty(); + } + } + if (def.maxSize !== null) { + if (ctx.data.size > def.maxSize.value) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.too_big, + maximum: def.maxSize.value, + type: "set", + inclusive: true, + exact: false, + message: def.maxSize.message, + }); + status.dirty(); + } + } + const valueType = this._def.valueType; + function finalizeSet(elements) { + const parsedSet = new Set(); + for (const element of elements) { + if (element.status === "aborted") + return parseUtil_js_1.INVALID; + if (element.status === "dirty") + status.dirty(); + parsedSet.add(element.value); + } + return { status: status.value, value: parsedSet }; + } + const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i))); + if (ctx.common.async) { + return Promise.all(elements).then((elements) => finalizeSet(elements)); + } + else { + return finalizeSet(elements); + } + } + min(minSize, message) { + return new ZodSet({ + ...this._def, + minSize: { value: minSize, message: errorUtil_js_1.errorUtil.toString(message) }, + }); + } + max(maxSize, message) { + return new ZodSet({ + ...this._def, + maxSize: { value: maxSize, message: errorUtil_js_1.errorUtil.toString(message) }, + }); + } + size(size, message) { + return this.min(size, message).max(size, message); + } + nonempty(message) { + return this.min(1, message); + } } - -Dicer.prototype._oninfo = function (isMatch, data, start, end) { - let buf; const self = this; let i = 0; let r; let shouldWriteMore = true - - if (!this._part && this._justMatched && data) { - while (this._dashes < 2 && (start + i) < end) { - if (data[start + i] === DASH) { - ++i - ++this._dashes - } else { - if (this._dashes) { buf = B_ONEDASH } - this._dashes = 0 - break - } +exports.ZodSet = ZodSet; +ZodSet.create = (valueType, params) => { + return new ZodSet({ + valueType, + minSize: null, + maxSize: null, + typeName: ZodFirstPartyTypeKind.ZodSet, + ...processCreateParams(params), + }); +}; +class ZodFunction extends ZodType { + constructor() { + super(...arguments); + this.validate = this.implement; } - if (this._dashes === 2) { - if ((start + i) < end && this.listenerCount('trailer') !== 0) { this.emit('trailer', data.slice(start + i, end)) } - this.reset() - this._finished = true - // no more parts will be added - if (self._parts === 0) { - self._realFinish = true - self.emit('finish') - self._realFinish = false - } + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== util_js_1.ZodParsedType.function) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.function, + received: ctx.parsedType, + }); + return parseUtil_js_1.INVALID; + } + function makeArgsIssue(args, error) { + return (0, parseUtil_js_1.makeIssue)({ + data: args, + path: ctx.path, + errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, (0, errors_js_1.getErrorMap)(), errors_js_1.defaultErrorMap].filter((x) => !!x), + issueData: { + code: ZodError_js_1.ZodIssueCode.invalid_arguments, + argumentsError: error, + }, + }); + } + function makeReturnsIssue(returns, error) { + return (0, parseUtil_js_1.makeIssue)({ + data: returns, + path: ctx.path, + errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, (0, errors_js_1.getErrorMap)(), errors_js_1.defaultErrorMap].filter((x) => !!x), + issueData: { + code: ZodError_js_1.ZodIssueCode.invalid_return_type, + returnTypeError: error, + }, + }); + } + const params = { errorMap: ctx.common.contextualErrorMap }; + const fn = ctx.data; + if (this._def.returns instanceof ZodPromise) { + // Would love a way to avoid disabling this rule, but we need + // an alias (using an arrow function was what caused 2651). + // eslint-disable-next-line @typescript-eslint/no-this-alias + const me = this; + return (0, parseUtil_js_1.OK)(async function (...args) { + const error = new ZodError_js_1.ZodError([]); + const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => { + error.addIssue(makeArgsIssue(args, e)); + throw error; + }); + const result = await Reflect.apply(fn, this, parsedArgs); + const parsedReturns = await me._def.returns._def.type + .parseAsync(result, params) + .catch((e) => { + error.addIssue(makeReturnsIssue(result, e)); + throw error; + }); + return parsedReturns; + }); + } + else { + // Would love a way to avoid disabling this rule, but we need + // an alias (using an arrow function was what caused 2651). + // eslint-disable-next-line @typescript-eslint/no-this-alias + const me = this; + return (0, parseUtil_js_1.OK)(function (...args) { + const parsedArgs = me._def.args.safeParse(args, params); + if (!parsedArgs.success) { + throw new ZodError_js_1.ZodError([makeArgsIssue(args, parsedArgs.error)]); + } + const result = Reflect.apply(fn, this, parsedArgs.data); + const parsedReturns = me._def.returns.safeParse(result, params); + if (!parsedReturns.success) { + throw new ZodError_js_1.ZodError([makeReturnsIssue(result, parsedReturns.error)]); + } + return parsedReturns.data; + }); + } } - if (this._dashes) { return } - } - if (this._justMatched) { this._justMatched = false } - if (!this._part) { - this._part = new PartStream(this._partOpts) - this._part._read = function (n) { - self._unpause() + parameters() { + return this._def.args; } - if (this._isPreamble && this.listenerCount('preamble') !== 0) { - this.emit('preamble', this._part) - } else if (this._isPreamble !== true && this.listenerCount('part') !== 0) { - this.emit('part', this._part) - } else { - this._ignore() + returnType() { + return this._def.returns; } - if (!this._isPreamble) { this._inHeader = true } - } - if (data && start < end && !this._ignoreData) { - if (this._isPreamble || !this._inHeader) { - if (buf) { shouldWriteMore = this._part.push(buf) } - shouldWriteMore = this._part.push(data.slice(start, end)) - if (!shouldWriteMore) { this._pause = true } - } else if (!this._isPreamble && this._inHeader) { - if (buf) { this._hparser.push(buf) } - r = this._hparser.push(data.slice(start, end)) - if (!this._inHeader && r !== undefined && r < end) { this._oninfo(false, data, start + r, end) } + args(...items) { + return new ZodFunction({ + ...this._def, + args: ZodTuple.create(items).rest(ZodUnknown.create()), + }); } - } - if (isMatch) { - this._hparser.reset() - if (this._isPreamble) { this._isPreamble = false } else { - if (start !== end) { - ++this._parts - this._part.on('end', function () { - if (--self._parts === 0) { - if (self._finished) { - self._realFinish = true - self.emit('finish') - self._realFinish = false - } else { - self._unpause() - } - } - }) - } + returns(returnType) { + return new ZodFunction({ + ...this._def, + returns: returnType, + }); + } + implement(func) { + const validatedFunc = this.parse(func); + return validatedFunc; } - this._part.push(null) - this._part = undefined - this._ignoreData = false - this._justMatched = true - this._dashes = 0 - } -} - -Dicer.prototype._unpause = function () { - if (!this._pause) { return } - - this._pause = false - if (this._cb) { - const cb = this._cb - this._cb = undefined - cb() - } -} - -module.exports = Dicer - - -/***/ }), - -/***/ 2271: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const EventEmitter = (__nccwpck_require__(8474).EventEmitter) -const inherits = (__nccwpck_require__(7975).inherits) -const getLimit = __nccwpck_require__(2393) - -const StreamSearch = __nccwpck_require__(4136) - -const B_DCRLF = Buffer.from('\r\n\r\n') -const RE_CRLF = /\r\n/g -const RE_HDR = /^([^:]+):[ \t]?([\x00-\xFF]+)?$/ // eslint-disable-line no-control-regex - -function HeaderParser (cfg) { - EventEmitter.call(this) - - cfg = cfg || {} - const self = this - this.nread = 0 - this.maxed = false - this.npairs = 0 - this.maxHeaderPairs = getLimit(cfg, 'maxHeaderPairs', 2000) - this.maxHeaderSize = getLimit(cfg, 'maxHeaderSize', 80 * 1024) - this.buffer = '' - this.header = {} - this.finished = false - this.ss = new StreamSearch(B_DCRLF) - this.ss.on('info', function (isMatch, data, start, end) { - if (data && !self.maxed) { - if (self.nread + end - start >= self.maxHeaderSize) { - end = self.maxHeaderSize - self.nread + start - self.nread = self.maxHeaderSize - self.maxed = true - } else { self.nread += (end - start) } - - self.buffer += data.toString('binary', start, end) + strictImplement(func) { + const validatedFunc = this.parse(func); + return validatedFunc; + } + static create(args, returns, params) { + return new ZodFunction({ + args: (args ? args : ZodTuple.create([]).rest(ZodUnknown.create())), + returns: returns || ZodUnknown.create(), + typeName: ZodFirstPartyTypeKind.ZodFunction, + ...processCreateParams(params), + }); } - if (isMatch) { self._finish() } - }) -} -inherits(HeaderParser, EventEmitter) - -HeaderParser.prototype.push = function (data) { - const r = this.ss.push(data) - if (this.finished) { return r } -} - -HeaderParser.prototype.reset = function () { - this.finished = false - this.buffer = '' - this.header = {} - this.ss.reset() -} - -HeaderParser.prototype._finish = function () { - if (this.buffer) { this._parseHeader() } - this.ss.matches = this.ss.maxMatches - const header = this.header - this.header = {} - this.buffer = '' - this.finished = true - this.nread = this.npairs = 0 - this.maxed = false - this.emit('header', header) } - -HeaderParser.prototype._parseHeader = function () { - if (this.npairs === this.maxHeaderPairs) { return } - - const lines = this.buffer.split(RE_CRLF) - const len = lines.length - let m, h - - for (var i = 0; i < len; ++i) { // eslint-disable-line no-var - if (lines[i].length === 0) { continue } - if (lines[i][0] === '\t' || lines[i][0] === ' ') { - // folded header content - // RFC2822 says to just remove the CRLF and not the whitespace following - // it, so we follow the RFC and include the leading whitespace ... - if (h) { - this.header[h][this.header[h].length - 1] += lines[i] - continue - } +exports.ZodFunction = ZodFunction; +class ZodLazy extends ZodType { + get schema() { + return this._def.getter(); } - - const posColon = lines[i].indexOf(':') - if ( - posColon === -1 || - posColon === 0 - ) { - return + _parse(input) { + const { ctx } = this._processInputParams(input); + const lazySchema = this._def.getter(); + return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); } - m = RE_HDR.exec(lines[i]) - h = m[1].toLowerCase() - this.header[h] = this.header[h] || [] - this.header[h].push((m[2] || '')) - if (++this.npairs === this.maxHeaderPairs) { break } - } -} - -module.exports = HeaderParser - - -/***/ }), - -/***/ 612: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const inherits = (__nccwpck_require__(7975).inherits) -const ReadableStream = (__nccwpck_require__(7075).Readable) - -function PartStream (opts) { - ReadableStream.call(this, opts) -} -inherits(PartStream, ReadableStream) - -PartStream.prototype._read = function (n) {} - -module.exports = PartStream - - -/***/ }), - -/***/ 4136: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -/** - * Copyright Brian White. All rights reserved. - * - * @see https://github.com/mscdex/streamsearch - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to - * deal in the Software without restriction, including without limitation the - * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or - * sell copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS - * IN THE SOFTWARE. - * - * Based heavily on the Streaming Boyer-Moore-Horspool C++ implementation - * by Hongli Lai at: https://github.com/FooBarWidget/boyer-moore-horspool - */ -const EventEmitter = (__nccwpck_require__(8474).EventEmitter) -const inherits = (__nccwpck_require__(7975).inherits) - -function SBMH (needle) { - if (typeof needle === 'string') { - needle = Buffer.from(needle) - } - - if (!Buffer.isBuffer(needle)) { - throw new TypeError('The needle has to be a String or a Buffer.') - } - - const needleLength = needle.length - - if (needleLength === 0) { - throw new Error('The needle cannot be an empty String/Buffer.') - } - - if (needleLength > 256) { - throw new Error('The needle cannot have a length bigger than 256.') - } - - this.maxMatches = Infinity - this.matches = 0 - - this._occ = new Array(256) - .fill(needleLength) // Initialize occurrence table. - this._lookbehind_size = 0 - this._needle = needle - this._bufpos = 0 - - this._lookbehind = Buffer.alloc(needleLength) - - // Populate occurrence table with analysis of the needle, - // ignoring last letter. - for (var i = 0; i < needleLength - 1; ++i) { // eslint-disable-line no-var - this._occ[needle[i]] = needleLength - 1 - i - } } -inherits(SBMH, EventEmitter) - -SBMH.prototype.reset = function () { - this._lookbehind_size = 0 - this.matches = 0 - this._bufpos = 0 +exports.ZodLazy = ZodLazy; +ZodLazy.create = (getter, params) => { + return new ZodLazy({ + getter: getter, + typeName: ZodFirstPartyTypeKind.ZodLazy, + ...processCreateParams(params), + }); +}; +class ZodLiteral extends ZodType { + _parse(input) { + if (input.data !== this._def.value) { + const ctx = this._getOrReturnCtx(input); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + received: ctx.data, + code: ZodError_js_1.ZodIssueCode.invalid_literal, + expected: this._def.value, + }); + return parseUtil_js_1.INVALID; + } + return { status: "valid", value: input.data }; + } + get value() { + return this._def.value; + } } - -SBMH.prototype.push = function (chunk, pos) { - if (!Buffer.isBuffer(chunk)) { - chunk = Buffer.from(chunk, 'binary') - } - const chlen = chunk.length - this._bufpos = pos || 0 - let r - while (r !== chlen && this.matches < this.maxMatches) { r = this._sbmh_feed(chunk) } - return r +exports.ZodLiteral = ZodLiteral; +ZodLiteral.create = (value, params) => { + return new ZodLiteral({ + value: value, + typeName: ZodFirstPartyTypeKind.ZodLiteral, + ...processCreateParams(params), + }); +}; +function createZodEnum(values, params) { + return new ZodEnum({ + values, + typeName: ZodFirstPartyTypeKind.ZodEnum, + ...processCreateParams(params), + }); } - -SBMH.prototype._sbmh_feed = function (data) { - const len = data.length - const needle = this._needle - const needleLength = needle.length - const lastNeedleChar = needle[needleLength - 1] - - // Positive: points to a position in `data` - // pos == 3 points to data[3] - // Negative: points to a position in the lookbehind buffer - // pos == -2 points to lookbehind[lookbehind_size - 2] - let pos = -this._lookbehind_size - let ch - - if (pos < 0) { - // Lookbehind buffer is not empty. Perform Boyer-Moore-Horspool - // search with character lookup code that considers both the - // lookbehind buffer and the current round's haystack data. - // - // Loop until - // there is a match. - // or until - // we've moved past the position that requires the - // lookbehind buffer. In this case we switch to the - // optimized loop. - // or until - // the character to look at lies outside the haystack. - while (pos < 0 && pos <= len - needleLength) { - ch = this._sbmh_lookup_char(data, pos + needleLength - 1) - - if ( - ch === lastNeedleChar && - this._sbmh_memcmp(data, pos, needleLength - 1) - ) { - this._lookbehind_size = 0 - ++this.matches - this.emit('info', true) - - return (this._bufpos = pos + needleLength) - } - pos += this._occ[ch] +class ZodEnum extends ZodType { + _parse(input) { + if (typeof input.data !== "string") { + const ctx = this._getOrReturnCtx(input); + const expectedValues = this._def.values; + (0, parseUtil_js_1.addIssueToContext)(ctx, { + expected: util_js_1.util.joinValues(expectedValues), + received: ctx.parsedType, + code: ZodError_js_1.ZodIssueCode.invalid_type, + }); + return parseUtil_js_1.INVALID; + } + if (!this._cache) { + this._cache = new Set(this._def.values); + } + if (!this._cache.has(input.data)) { + const ctx = this._getOrReturnCtx(input); + const expectedValues = this._def.values; + (0, parseUtil_js_1.addIssueToContext)(ctx, { + received: ctx.data, + code: ZodError_js_1.ZodIssueCode.invalid_enum_value, + options: expectedValues, + }); + return parseUtil_js_1.INVALID; + } + return (0, parseUtil_js_1.OK)(input.data); } - - // No match. - - if (pos < 0) { - // There's too few data for Boyer-Moore-Horspool to run, - // so let's use a different algorithm to skip as much as - // we can. - // Forward pos until - // the trailing part of lookbehind + data - // looks like the beginning of the needle - // or until - // pos == 0 - while (pos < 0 && !this._sbmh_memcmp(data, pos, len - pos)) { ++pos } + get options() { + return this._def.values; } - - if (pos >= 0) { - // Discard lookbehind buffer. - this.emit('info', false, this._lookbehind, 0, this._lookbehind_size) - this._lookbehind_size = 0 - } else { - // Cut off part of the lookbehind buffer that has - // been processed and append the entire haystack - // into it. - const bytesToCutOff = this._lookbehind_size + pos - if (bytesToCutOff > 0) { - // The cut off data is guaranteed not to contain the needle. - this.emit('info', false, this._lookbehind, 0, bytesToCutOff) - } - - this._lookbehind.copy(this._lookbehind, 0, bytesToCutOff, - this._lookbehind_size - bytesToCutOff) - this._lookbehind_size -= bytesToCutOff - - data.copy(this._lookbehind, this._lookbehind_size) - this._lookbehind_size += len - - this._bufpos = len - return len + get enum() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues; } - } - - pos += (pos >= 0) * this._bufpos - - // Lookbehind buffer is now empty. We only need to check if the - // needle is in the haystack. - if (data.indexOf(needle, pos) !== -1) { - pos = data.indexOf(needle, pos) - ++this.matches - if (pos > 0) { this.emit('info', true, data, this._bufpos, pos) } else { this.emit('info', true) } - - return (this._bufpos = pos + needleLength) - } else { - pos = len - needleLength - } - - // There was no match. If there's trailing haystack data that we cannot - // match yet using the Boyer-Moore-Horspool algorithm (because the trailing - // data is less than the needle size) then match using a modified - // algorithm that starts matching from the beginning instead of the end. - // Whatever trailing data is left after running this algorithm is added to - // the lookbehind buffer. - while ( - pos < len && - ( - data[pos] !== needle[0] || - ( - (Buffer.compare( - data.subarray(pos, pos + len - pos), - needle.subarray(0, len - pos) - ) !== 0) - ) - ) - ) { - ++pos - } - if (pos < len) { - data.copy(this._lookbehind, 0, pos, pos + (len - pos)) - this._lookbehind_size = len - pos - } - - // Everything until pos is guaranteed not to contain needle data. - if (pos > 0) { this.emit('info', false, data, this._bufpos, pos < len ? pos : len) } - - this._bufpos = len - return len -} - -SBMH.prototype._sbmh_lookup_char = function (data, pos) { - return (pos < 0) - ? this._lookbehind[this._lookbehind_size + pos] - : data[pos] -} - -SBMH.prototype._sbmh_memcmp = function (data, pos, len) { - for (var i = 0; i < len; ++i) { // eslint-disable-line no-var - if (this._sbmh_lookup_char(data, pos + i) !== this._needle[i]) { return false } - } - return true -} - -module.exports = SBMH - - -/***/ }), - -/***/ 9581: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const WritableStream = (__nccwpck_require__(7075).Writable) -const { inherits } = __nccwpck_require__(7975) -const Dicer = __nccwpck_require__(7182) - -const MultipartParser = __nccwpck_require__(1192) -const UrlencodedParser = __nccwpck_require__(855) -const parseParams = __nccwpck_require__(8929) - -function Busboy (opts) { - if (!(this instanceof Busboy)) { return new Busboy(opts) } - - if (typeof opts !== 'object') { - throw new TypeError('Busboy expected an options-Object.') - } - if (typeof opts.headers !== 'object') { - throw new TypeError('Busboy expected an options-Object with headers-attribute.') - } - if (typeof opts.headers['content-type'] !== 'string') { - throw new TypeError('Missing Content-Type-header.') - } - - const { - headers, - ...streamOptions - } = opts - - this.opts = { - autoDestroy: false, - ...streamOptions - } - WritableStream.call(this, this.opts) - - this._done = false - this._parser = this.getParserByHeaders(headers) - this._finished = false -} -inherits(Busboy, WritableStream) - -Busboy.prototype.emit = function (ev) { - if (ev === 'finish') { - if (!this._done) { - this._parser?.end() - return - } else if (this._finished) { - return + get Values() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues; + } + get Enum() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues; + } + extract(values, newDef = this._def) { + return ZodEnum.create(values, { + ...this._def, + ...newDef, + }); + } + exclude(values, newDef = this._def) { + return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), { + ...this._def, + ...newDef, + }); } - this._finished = true - } - WritableStream.prototype.emit.apply(this, arguments) -} - -Busboy.prototype.getParserByHeaders = function (headers) { - const parsed = parseParams(headers['content-type']) - - const cfg = { - defCharset: this.opts.defCharset, - fileHwm: this.opts.fileHwm, - headers, - highWaterMark: this.opts.highWaterMark, - isPartAFile: this.opts.isPartAFile, - limits: this.opts.limits, - parsedConType: parsed, - preservePath: this.opts.preservePath - } - - if (MultipartParser.detect.test(parsed[0])) { - return new MultipartParser(this, cfg) - } - if (UrlencodedParser.detect.test(parsed[0])) { - return new UrlencodedParser(this, cfg) - } - throw new Error('Unsupported Content-Type.') -} - -Busboy.prototype._write = function (chunk, encoding, cb) { - this._parser.write(chunk, cb) } - -module.exports = Busboy -module.exports["default"] = Busboy -module.exports.Busboy = Busboy - -module.exports.Dicer = Dicer - - -/***/ }), - -/***/ 1192: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -// TODO: -// * support 1 nested multipart level -// (see second multipart example here: -// http://www.w3.org/TR/html401/interact/forms.html#didx-multipartform-data) -// * support limits.fieldNameSize -// -- this will require modifications to utils.parseParams - -const { Readable } = __nccwpck_require__(7075) -const { inherits } = __nccwpck_require__(7975) - -const Dicer = __nccwpck_require__(7182) - -const parseParams = __nccwpck_require__(8929) -const decodeText = __nccwpck_require__(2747) -const basename = __nccwpck_require__(692) -const getLimit = __nccwpck_require__(2393) - -const RE_BOUNDARY = /^boundary$/i -const RE_FIELD = /^form-data$/i -const RE_CHARSET = /^charset$/i -const RE_FILENAME = /^filename$/i -const RE_NAME = /^name$/i - -Multipart.detect = /^multipart\/form-data/i -function Multipart (boy, cfg) { - let i - let len - const self = this - let boundary - const limits = cfg.limits - const isPartAFile = cfg.isPartAFile || ((fieldName, contentType, fileName) => (contentType === 'application/octet-stream' || fileName !== undefined)) - const parsedConType = cfg.parsedConType || [] - const defCharset = cfg.defCharset || 'utf8' - const preservePath = cfg.preservePath - const fileOpts = { highWaterMark: cfg.fileHwm } - - for (i = 0, len = parsedConType.length; i < len; ++i) { - if (Array.isArray(parsedConType[i]) && - RE_BOUNDARY.test(parsedConType[i][0])) { - boundary = parsedConType[i][1] - break +exports.ZodEnum = ZodEnum; +ZodEnum.create = createZodEnum; +class ZodNativeEnum extends ZodType { + _parse(input) { + const nativeEnumValues = util_js_1.util.getValidEnumValues(this._def.values); + const ctx = this._getOrReturnCtx(input); + if (ctx.parsedType !== util_js_1.ZodParsedType.string && ctx.parsedType !== util_js_1.ZodParsedType.number) { + const expectedValues = util_js_1.util.objectValues(nativeEnumValues); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + expected: util_js_1.util.joinValues(expectedValues), + received: ctx.parsedType, + code: ZodError_js_1.ZodIssueCode.invalid_type, + }); + return parseUtil_js_1.INVALID; + } + if (!this._cache) { + this._cache = new Set(util_js_1.util.getValidEnumValues(this._def.values)); + } + if (!this._cache.has(input.data)) { + const expectedValues = util_js_1.util.objectValues(nativeEnumValues); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + received: ctx.data, + code: ZodError_js_1.ZodIssueCode.invalid_enum_value, + options: expectedValues, + }); + return parseUtil_js_1.INVALID; + } + return (0, parseUtil_js_1.OK)(input.data); } - } - - function checkFinished () { - if (nends === 0 && finished && !boy._done) { - finished = false - self.end() + get enum() { + return this._def.values; } - } - - if (typeof boundary !== 'string') { throw new Error('Multipart: Boundary not found') } - - const fieldSizeLimit = getLimit(limits, 'fieldSize', 1 * 1024 * 1024) - const fileSizeLimit = getLimit(limits, 'fileSize', Infinity) - const filesLimit = getLimit(limits, 'files', Infinity) - const fieldsLimit = getLimit(limits, 'fields', Infinity) - const partsLimit = getLimit(limits, 'parts', Infinity) - const headerPairsLimit = getLimit(limits, 'headerPairs', 2000) - const headerSizeLimit = getLimit(limits, 'headerSize', 80 * 1024) - - let nfiles = 0 - let nfields = 0 - let nends = 0 - let curFile - let curField - let finished = false - - this._needDrain = false - this._pause = false - this._cb = undefined - this._nparts = 0 - this._boy = boy - - const parserCfg = { - boundary, - maxHeaderPairs: headerPairsLimit, - maxHeaderSize: headerSizeLimit, - partHwm: fileOpts.highWaterMark, - highWaterMark: cfg.highWaterMark - } - - this.parser = new Dicer(parserCfg) - this.parser.on('drain', function () { - self._needDrain = false - if (self._cb && !self._pause) { - const cb = self._cb - self._cb = undefined - cb() +} +exports.ZodNativeEnum = ZodNativeEnum; +ZodNativeEnum.create = (values, params) => { + return new ZodNativeEnum({ + values: values, + typeName: ZodFirstPartyTypeKind.ZodNativeEnum, + ...processCreateParams(params), + }); +}; +class ZodPromise extends ZodType { + unwrap() { + return this._def.type; } - }).on('part', function onPart (part) { - if (++self._nparts > partsLimit) { - self.parser.removeListener('part', onPart) - self.parser.on('part', skipPart) - boy.hitPartsLimit = true - boy.emit('partsLimit') - return skipPart(part) + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== util_js_1.ZodParsedType.promise && ctx.common.async === false) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.promise, + received: ctx.parsedType, + }); + return parseUtil_js_1.INVALID; + } + const promisified = ctx.parsedType === util_js_1.ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data); + return (0, parseUtil_js_1.OK)(promisified.then((data) => { + return this._def.type.parseAsync(data, { + path: ctx.path, + errorMap: ctx.common.contextualErrorMap, + }); + })); } - - // hack because streams2 _always_ doesn't emit 'end' until nextTick, so let - // us emit 'end' early since we know the part has ended if we are already - // seeing the next part - if (curField) { - const field = curField - field.emit('end') - field.removeAllListeners('end') +} +exports.ZodPromise = ZodPromise; +ZodPromise.create = (schema, params) => { + return new ZodPromise({ + type: schema, + typeName: ZodFirstPartyTypeKind.ZodPromise, + ...processCreateParams(params), + }); +}; +class ZodEffects extends ZodType { + innerType() { + return this._def.schema; } - - part.on('header', function (header) { - let contype - let fieldname - let parsed - let charset - let encoding - let filename - let nsize = 0 - - if (header['content-type']) { - parsed = parseParams(header['content-type'][0]) - if (parsed[0]) { - contype = parsed[0].toLowerCase() - for (i = 0, len = parsed.length; i < len; ++i) { - if (RE_CHARSET.test(parsed[i][0])) { - charset = parsed[i][1].toLowerCase() - break + sourceType() { + return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects + ? this._def.schema.sourceType() + : this._def.schema; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + const effect = this._def.effect || null; + const checkCtx = { + addIssue: (arg) => { + (0, parseUtil_js_1.addIssueToContext)(ctx, arg); + if (arg.fatal) { + status.abort(); + } + else { + status.dirty(); + } + }, + get path() { + return ctx.path; + }, + }; + checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); + if (effect.type === "preprocess") { + const processed = effect.transform(ctx.data, checkCtx); + if (ctx.common.async) { + return Promise.resolve(processed).then(async (processed) => { + if (status.value === "aborted") + return parseUtil_js_1.INVALID; + const result = await this._def.schema._parseAsync({ + data: processed, + path: ctx.path, + parent: ctx, + }); + if (result.status === "aborted") + return parseUtil_js_1.INVALID; + if (result.status === "dirty") + return (0, parseUtil_js_1.DIRTY)(result.value); + if (status.value === "dirty") + return (0, parseUtil_js_1.DIRTY)(result.value); + return result; + }); + } + else { + if (status.value === "aborted") + return parseUtil_js_1.INVALID; + const result = this._def.schema._parseSync({ + data: processed, + path: ctx.path, + parent: ctx, + }); + if (result.status === "aborted") + return parseUtil_js_1.INVALID; + if (result.status === "dirty") + return (0, parseUtil_js_1.DIRTY)(result.value); + if (status.value === "dirty") + return (0, parseUtil_js_1.DIRTY)(result.value); + return result; } - } } - } - - if (contype === undefined) { contype = 'text/plain' } - if (charset === undefined) { charset = defCharset } - - if (header['content-disposition']) { - parsed = parseParams(header['content-disposition'][0]) - if (!RE_FIELD.test(parsed[0])) { return skipPart(part) } - for (i = 0, len = parsed.length; i < len; ++i) { - if (RE_NAME.test(parsed[i][0])) { - fieldname = parsed[i][1] - } else if (RE_FILENAME.test(parsed[i][0])) { - filename = parsed[i][1] - if (!preservePath) { filename = basename(filename) } - } + if (effect.type === "refinement") { + const executeRefinement = (acc) => { + const result = effect.refinement(acc, checkCtx); + if (ctx.common.async) { + return Promise.resolve(result); + } + if (result instanceof Promise) { + throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); + } + return acc; + }; + if (ctx.common.async === false) { + const inner = this._def.schema._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + if (inner.status === "aborted") + return parseUtil_js_1.INVALID; + if (inner.status === "dirty") + status.dirty(); + // return value is ignored + executeRefinement(inner.value); + return { status: status.value, value: inner.value }; + } + else { + return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => { + if (inner.status === "aborted") + return parseUtil_js_1.INVALID; + if (inner.status === "dirty") + status.dirty(); + return executeRefinement(inner.value).then(() => { + return { status: status.value, value: inner.value }; + }); + }); + } } - } else { return skipPart(part) } - - if (header['content-transfer-encoding']) { encoding = header['content-transfer-encoding'][0].toLowerCase() } else { encoding = '7bit' } - - let onData, - onEnd - - if (isPartAFile(fieldname, contype, filename)) { - // file/binary field - if (nfiles === filesLimit) { - if (!boy.hitFilesLimit) { - boy.hitFilesLimit = true - boy.emit('filesLimit') - } - return skipPart(part) + if (effect.type === "transform") { + if (ctx.common.async === false) { + const base = this._def.schema._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + if (!(0, parseUtil_js_1.isValid)(base)) + return parseUtil_js_1.INVALID; + const result = effect.transform(base.value, checkCtx); + if (result instanceof Promise) { + throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); + } + return { status: status.value, value: result }; + } + else { + return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => { + if (!(0, parseUtil_js_1.isValid)(base)) + return parseUtil_js_1.INVALID; + return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ + status: status.value, + value: result, + })); + }); + } } - - ++nfiles - - if (boy.listenerCount('file') === 0) { - self.parser._ignore() - return + util_js_1.util.assertNever(effect); + } +} +exports.ZodEffects = ZodEffects; +exports.ZodTransformer = ZodEffects; +ZodEffects.create = (schema, effect, params) => { + return new ZodEffects({ + schema, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect, + ...processCreateParams(params), + }); +}; +ZodEffects.createWithPreprocess = (preprocess, schema, params) => { + return new ZodEffects({ + schema, + effect: { type: "preprocess", transform: preprocess }, + typeName: ZodFirstPartyTypeKind.ZodEffects, + ...processCreateParams(params), + }); +}; +class ZodOptional extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType === util_js_1.ZodParsedType.undefined) { + return (0, parseUtil_js_1.OK)(undefined); } - - ++nends - const file = new FileStream(fileOpts) - curFile = file - file.on('end', function () { - --nends - self._pause = false - checkFinished() - if (self._cb && !self._needDrain) { - const cb = self._cb - self._cb = undefined - cb() - } - }) - file._read = function (n) { - if (!self._pause) { return } - self._pause = false - if (self._cb && !self._needDrain) { - const cb = self._cb - self._cb = undefined - cb() - } + return this._def.innerType._parse(input); + } + unwrap() { + return this._def.innerType; + } +} +exports.ZodOptional = ZodOptional; +ZodOptional.create = (type, params) => { + return new ZodOptional({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodOptional, + ...processCreateParams(params), + }); +}; +class ZodNullable extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType === util_js_1.ZodParsedType.null) { + return (0, parseUtil_js_1.OK)(null); } - boy.emit('file', fieldname, file, filename, encoding, contype) - - onData = function (data) { - if ((nsize += data.length) > fileSizeLimit) { - const extralen = fileSizeLimit - nsize + data.length - if (extralen > 0) { file.push(data.slice(0, extralen)) } - file.truncated = true - file.bytesRead = fileSizeLimit - part.removeAllListeners('data') - file.emit('limit') - return - } else if (!file.push(data)) { self._pause = true } - - file.bytesRead = nsize + return this._def.innerType._parse(input); + } + unwrap() { + return this._def.innerType; + } +} +exports.ZodNullable = ZodNullable; +ZodNullable.create = (type, params) => { + return new ZodNullable({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodNullable, + ...processCreateParams(params), + }); +}; +class ZodDefault extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + let data = ctx.data; + if (ctx.parsedType === util_js_1.ZodParsedType.undefined) { + data = this._def.defaultValue(); } - - onEnd = function () { - curFile = undefined - file.push(null) + return this._def.innerType._parse({ + data, + path: ctx.path, + parent: ctx, + }); + } + removeDefault() { + return this._def.innerType; + } +} +exports.ZodDefault = ZodDefault; +ZodDefault.create = (type, params) => { + return new ZodDefault({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodDefault, + defaultValue: typeof params.default === "function" ? params.default : () => params.default, + ...processCreateParams(params), + }); +}; +class ZodCatch extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + // newCtx is used to not collect issues from inner types in ctx + const newCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [], + }, + }; + const result = this._def.innerType._parse({ + data: newCtx.data, + path: newCtx.path, + parent: { + ...newCtx, + }, + }); + if ((0, parseUtil_js_1.isAsync)(result)) { + return result.then((result) => { + return { + status: "valid", + value: result.status === "valid" + ? result.value + : this._def.catchValue({ + get error() { + return new ZodError_js_1.ZodError(newCtx.common.issues); + }, + input: newCtx.data, + }), + }; + }); } - } else { - // non-file field - if (nfields === fieldsLimit) { - if (!boy.hitFieldsLimit) { - boy.hitFieldsLimit = true - boy.emit('fieldsLimit') - } - return skipPart(part) + else { + return { + status: "valid", + value: result.status === "valid" + ? result.value + : this._def.catchValue({ + get error() { + return new ZodError_js_1.ZodError(newCtx.common.issues); + }, + input: newCtx.data, + }), + }; } - - ++nfields - ++nends - let buffer = '' - let truncated = false - curField = part - - onData = function (data) { - if ((nsize += data.length) > fieldSizeLimit) { - const extralen = (fieldSizeLimit - (nsize - data.length)) - buffer += data.toString('binary', 0, extralen) - truncated = true - part.removeAllListeners('data') - } else { buffer += data.toString('binary') } + } + removeCatch() { + return this._def.innerType; + } +} +exports.ZodCatch = ZodCatch; +ZodCatch.create = (type, params) => { + return new ZodCatch({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodCatch, + catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, + ...processCreateParams(params), + }); +}; +class ZodNaN extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== util_js_1.ZodParsedType.nan) { + const ctx = this._getOrReturnCtx(input); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.nan, + received: ctx.parsedType, + }); + return parseUtil_js_1.INVALID; } - - onEnd = function () { - curField = undefined - if (buffer.length) { buffer = decodeText(buffer, 'binary', charset) } - boy.emit('field', fieldname, buffer, false, truncated, encoding, contype) - --nends - checkFinished() + return { status: "valid", value: input.data }; + } +} +exports.ZodNaN = ZodNaN; +ZodNaN.create = (params) => { + return new ZodNaN({ + typeName: ZodFirstPartyTypeKind.ZodNaN, + ...processCreateParams(params), + }); +}; +exports.BRAND = Symbol("zod_brand"); +class ZodBranded extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + const data = ctx.data; + return this._def.type._parse({ + data, + path: ctx.path, + parent: ctx, + }); + } + unwrap() { + return this._def.type; + } +} +exports.ZodBranded = ZodBranded; +class ZodPipeline extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.common.async) { + const handleAsync = async () => { + const inResult = await this._def.in._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + if (inResult.status === "aborted") + return parseUtil_js_1.INVALID; + if (inResult.status === "dirty") { + status.dirty(); + return (0, parseUtil_js_1.DIRTY)(inResult.value); + } + else { + return this._def.out._parseAsync({ + data: inResult.value, + path: ctx.path, + parent: ctx, + }); + } + }; + return handleAsync(); } - } - - /* As of node@2efe4ab761666 (v0.10.29+/v0.11.14+), busboy had become - broken. Streams2/streams3 is a huge black box of confusion, but - somehow overriding the sync state seems to fix things again (and still - seems to work for previous node versions). - */ - part._readableState.sync = false - - part.on('data', onData) - part.on('end', onEnd) - }).on('error', function (err) { - if (curFile) { curFile.emit('error', err) } - }) - }).on('error', function (err) { - boy.emit('error', err) - }).on('finish', function () { - finished = true - checkFinished() - }) + else { + const inResult = this._def.in._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + if (inResult.status === "aborted") + return parseUtil_js_1.INVALID; + if (inResult.status === "dirty") { + status.dirty(); + return { + status: "dirty", + value: inResult.value, + }; + } + else { + return this._def.out._parseSync({ + data: inResult.value, + path: ctx.path, + parent: ctx, + }); + } + } + } + static create(a, b) { + return new ZodPipeline({ + in: a, + out: b, + typeName: ZodFirstPartyTypeKind.ZodPipeline, + }); + } } - -Multipart.prototype.write = function (chunk, cb) { - const r = this.parser.write(chunk) - if (r && !this._pause) { - cb() - } else { - this._needDrain = !r - this._cb = cb - } +exports.ZodPipeline = ZodPipeline; +class ZodReadonly extends ZodType { + _parse(input) { + const result = this._def.innerType._parse(input); + const freeze = (data) => { + if ((0, parseUtil_js_1.isValid)(data)) { + data.value = Object.freeze(data.value); + } + return data; + }; + return (0, parseUtil_js_1.isAsync)(result) ? result.then((data) => freeze(data)) : freeze(result); + } + unwrap() { + return this._def.innerType; + } } - -Multipart.prototype.end = function () { - const self = this - - if (self.parser.writable) { - self.parser.end() - } else if (!self._boy._done) { - process.nextTick(function () { - self._boy._done = true - self._boy.emit('finish') - }) - } +exports.ZodReadonly = ZodReadonly; +ZodReadonly.create = (type, params) => { + return new ZodReadonly({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodReadonly, + ...processCreateParams(params), + }); +}; +//////////////////////////////////////// +//////////////////////////////////////// +////////// ////////// +////////// z.custom ////////// +////////// ////////// +//////////////////////////////////////// +//////////////////////////////////////// +function cleanParams(params, data) { + const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params; + const p2 = typeof p === "string" ? { message: p } : p; + return p2; } - -function skipPart (part) { - part.resume() +function custom(check, _params = {}, +/** + * @deprecated + * + * Pass `fatal` into the params object instead: + * + * ```ts + * z.string().custom((val) => val.length > 5, { fatal: false }) + * ``` + * + */ +fatal) { + if (check) + return ZodAny.create().superRefine((data, ctx) => { + const r = check(data); + if (r instanceof Promise) { + return r.then((r) => { + if (!r) { + const params = cleanParams(_params, data); + const _fatal = params.fatal ?? fatal ?? true; + ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); + } + }); + } + if (!r) { + const params = cleanParams(_params, data); + const _fatal = params.fatal ?? fatal ?? true; + ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); + } + return; + }); + return ZodAny.create(); } - -function FileStream (opts) { - Readable.call(this, opts) - - this.bytesRead = 0 - - this.truncated = false +exports.late = { + object: ZodObject.lazycreate, +}; +var ZodFirstPartyTypeKind; +(function (ZodFirstPartyTypeKind) { + ZodFirstPartyTypeKind["ZodString"] = "ZodString"; + ZodFirstPartyTypeKind["ZodNumber"] = "ZodNumber"; + ZodFirstPartyTypeKind["ZodNaN"] = "ZodNaN"; + ZodFirstPartyTypeKind["ZodBigInt"] = "ZodBigInt"; + ZodFirstPartyTypeKind["ZodBoolean"] = "ZodBoolean"; + ZodFirstPartyTypeKind["ZodDate"] = "ZodDate"; + ZodFirstPartyTypeKind["ZodSymbol"] = "ZodSymbol"; + ZodFirstPartyTypeKind["ZodUndefined"] = "ZodUndefined"; + ZodFirstPartyTypeKind["ZodNull"] = "ZodNull"; + ZodFirstPartyTypeKind["ZodAny"] = "ZodAny"; + ZodFirstPartyTypeKind["ZodUnknown"] = "ZodUnknown"; + ZodFirstPartyTypeKind["ZodNever"] = "ZodNever"; + ZodFirstPartyTypeKind["ZodVoid"] = "ZodVoid"; + ZodFirstPartyTypeKind["ZodArray"] = "ZodArray"; + ZodFirstPartyTypeKind["ZodObject"] = "ZodObject"; + ZodFirstPartyTypeKind["ZodUnion"] = "ZodUnion"; + ZodFirstPartyTypeKind["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; + ZodFirstPartyTypeKind["ZodIntersection"] = "ZodIntersection"; + ZodFirstPartyTypeKind["ZodTuple"] = "ZodTuple"; + ZodFirstPartyTypeKind["ZodRecord"] = "ZodRecord"; + ZodFirstPartyTypeKind["ZodMap"] = "ZodMap"; + ZodFirstPartyTypeKind["ZodSet"] = "ZodSet"; + ZodFirstPartyTypeKind["ZodFunction"] = "ZodFunction"; + ZodFirstPartyTypeKind["ZodLazy"] = "ZodLazy"; + ZodFirstPartyTypeKind["ZodLiteral"] = "ZodLiteral"; + ZodFirstPartyTypeKind["ZodEnum"] = "ZodEnum"; + ZodFirstPartyTypeKind["ZodEffects"] = "ZodEffects"; + ZodFirstPartyTypeKind["ZodNativeEnum"] = "ZodNativeEnum"; + ZodFirstPartyTypeKind["ZodOptional"] = "ZodOptional"; + ZodFirstPartyTypeKind["ZodNullable"] = "ZodNullable"; + ZodFirstPartyTypeKind["ZodDefault"] = "ZodDefault"; + ZodFirstPartyTypeKind["ZodCatch"] = "ZodCatch"; + ZodFirstPartyTypeKind["ZodPromise"] = "ZodPromise"; + ZodFirstPartyTypeKind["ZodBranded"] = "ZodBranded"; + ZodFirstPartyTypeKind["ZodPipeline"] = "ZodPipeline"; + ZodFirstPartyTypeKind["ZodReadonly"] = "ZodReadonly"; +})(ZodFirstPartyTypeKind || (exports.ZodFirstPartyTypeKind = ZodFirstPartyTypeKind = {})); +// requires TS 4.4+ +class Class { + constructor(..._) { } } - -inherits(FileStream, Readable) - -FileStream.prototype._read = function (n) {} - -module.exports = Multipart - - -/***/ }), - -/***/ 855: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +const instanceOfType = ( +// const instanceOfType = any>( +cls, params = { + message: `Input not instance of ${cls.name}`, +}) => custom((data) => data instanceof cls, params); +exports["instanceof"] = instanceOfType; +const stringType = ZodString.create; +exports.string = stringType; +const numberType = ZodNumber.create; +exports.number = numberType; +const nanType = ZodNaN.create; +exports.nan = nanType; +const bigIntType = ZodBigInt.create; +exports.bigint = bigIntType; +const booleanType = ZodBoolean.create; +exports.boolean = booleanType; +const dateType = ZodDate.create; +exports.date = dateType; +const symbolType = ZodSymbol.create; +exports.symbol = symbolType; +const undefinedType = ZodUndefined.create; +exports.undefined = undefinedType; +const nullType = ZodNull.create; +exports["null"] = nullType; +const anyType = ZodAny.create; +exports.any = anyType; +const unknownType = ZodUnknown.create; +exports.unknown = unknownType; +const neverType = ZodNever.create; +exports.never = neverType; +const voidType = ZodVoid.create; +exports["void"] = voidType; +const arrayType = ZodArray.create; +exports.array = arrayType; +const objectType = ZodObject.create; +exports.object = objectType; +const strictObjectType = ZodObject.strictCreate; +exports.strictObject = strictObjectType; +const unionType = ZodUnion.create; +exports.union = unionType; +const discriminatedUnionType = ZodDiscriminatedUnion.create; +exports.discriminatedUnion = discriminatedUnionType; +const intersectionType = ZodIntersection.create; +exports.intersection = intersectionType; +const tupleType = ZodTuple.create; +exports.tuple = tupleType; +const recordType = ZodRecord.create; +exports.record = recordType; +const mapType = ZodMap.create; +exports.map = mapType; +const setType = ZodSet.create; +exports.set = setType; +const functionType = ZodFunction.create; +exports["function"] = functionType; +const lazyType = ZodLazy.create; +exports.lazy = lazyType; +const literalType = ZodLiteral.create; +exports.literal = literalType; +const enumType = ZodEnum.create; +exports["enum"] = enumType; +const nativeEnumType = ZodNativeEnum.create; +exports.nativeEnum = nativeEnumType; +const promiseType = ZodPromise.create; +exports.promise = promiseType; +const effectsType = ZodEffects.create; +exports.effect = effectsType; +exports.transformer = effectsType; +const optionalType = ZodOptional.create; +exports.optional = optionalType; +const nullableType = ZodNullable.create; +exports.nullable = nullableType; +const preprocessType = ZodEffects.createWithPreprocess; +exports.preprocess = preprocessType; +const pipelineType = ZodPipeline.create; +exports.pipeline = pipelineType; +const ostring = () => stringType().optional(); +exports.ostring = ostring; +const onumber = () => numberType().optional(); +exports.onumber = onumber; +const oboolean = () => booleanType().optional(); +exports.oboolean = oboolean; +exports.coerce = { + string: ((arg) => ZodString.create({ ...arg, coerce: true })), + number: ((arg) => ZodNumber.create({ ...arg, coerce: true })), + boolean: ((arg) => ZodBoolean.create({ + ...arg, + coerce: true, + })), + bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })), + date: ((arg) => ZodDate.create({ ...arg, coerce: true })), +}; +exports.NEVER = parseUtil_js_1.INVALID; +/***/ }) -const Decoder = __nccwpck_require__(1496) -const decodeText = __nccwpck_require__(2747) -const getLimit = __nccwpck_require__(2393) +/******/ }); +/************************************************************************/ +/******/ // The module cache +/******/ var __webpack_module_cache__ = {}; +/******/ +/******/ // The require function +/******/ function __nccwpck_require__(moduleId) { +/******/ // Check if module is in cache +/******/ var cachedModule = __webpack_module_cache__[moduleId]; +/******/ if (cachedModule !== undefined) { +/******/ return cachedModule.exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = __webpack_module_cache__[moduleId] = { +/******/ id: moduleId, +/******/ loaded: false, +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ var threw = true; +/******/ try { +/******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __nccwpck_require__); +/******/ threw = false; +/******/ } finally { +/******/ if(threw) delete __webpack_module_cache__[moduleId]; +/******/ } +/******/ +/******/ // Flag the module as loaded +/******/ module.loaded = true; +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/************************************************************************/ +/******/ /* webpack/runtime/create fake namespace object */ +/******/ (() => { +/******/ var getProto = Object.getPrototypeOf ? (obj) => (Object.getPrototypeOf(obj)) : (obj) => (obj.__proto__); +/******/ var leafPrototypes; +/******/ // create a fake namespace object +/******/ // mode & 1: value is a module id, require it +/******/ // mode & 2: merge all properties of value into the ns +/******/ // mode & 4: return value when already ns object +/******/ // mode & 16: return value when it's Promise-like +/******/ // mode & 8|1: behave like require +/******/ __nccwpck_require__.t = function(value, mode) { +/******/ if(mode & 1) value = this(value); +/******/ if(mode & 8) return value; +/******/ if(typeof value === 'object' && value) { +/******/ if((mode & 4) && value.__esModule) return value; +/******/ if((mode & 16) && typeof value.then === 'function') return value; +/******/ } +/******/ var ns = Object.create(null); +/******/ __nccwpck_require__.r(ns); +/******/ var def = {}; +/******/ leafPrototypes = leafPrototypes || [null, getProto({}), getProto([]), getProto(getProto)]; +/******/ for(var current = mode & 2 && value; typeof current == 'object' && !~leafPrototypes.indexOf(current); current = getProto(current)) { +/******/ Object.getOwnPropertyNames(current).forEach((key) => (def[key] = () => (value[key]))); +/******/ } +/******/ def['default'] = () => (value); +/******/ __nccwpck_require__.d(ns, def); +/******/ return ns; +/******/ }; +/******/ })(); +/******/ +/******/ /* webpack/runtime/define property getters */ +/******/ (() => { +/******/ // define getter functions for harmony exports +/******/ __nccwpck_require__.d = (exports, definition) => { +/******/ for(var key in definition) { +/******/ if(__nccwpck_require__.o(definition, key) && !__nccwpck_require__.o(exports, key)) { +/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] }); +/******/ } +/******/ } +/******/ }; +/******/ })(); +/******/ +/******/ /* webpack/runtime/hasOwnProperty shorthand */ +/******/ (() => { +/******/ __nccwpck_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) +/******/ })(); +/******/ +/******/ /* webpack/runtime/make namespace object */ +/******/ (() => { +/******/ // define __esModule on exports +/******/ __nccwpck_require__.r = (exports) => { +/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { +/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); +/******/ } +/******/ Object.defineProperty(exports, '__esModule', { value: true }); +/******/ }; +/******/ })(); +/******/ +/******/ /* webpack/runtime/node module decorator */ +/******/ (() => { +/******/ __nccwpck_require__.nmd = (module) => { +/******/ module.paths = []; +/******/ if (!module.children) module.children = []; +/******/ return module; +/******/ }; +/******/ })(); +/******/ +/******/ /* webpack/runtime/compat */ +/******/ +/******/ if (typeof __nccwpck_require__ !== 'undefined') __nccwpck_require__.ab = new URL('.', import.meta.url).pathname.slice(import.meta.url.match(/^file:\/\/\/\w:/) ? 1 : 0, -1) + "/"; +/******/ +/************************************************************************/ +var __webpack_exports__ = {}; -const RE_CHARSET = /^charset$/i +// NAMESPACE OBJECT: ./node_modules/@langchain/core/dist/utils/fast-json-patch/src/core.js +var src_core_namespaceObject = {}; +__nccwpck_require__.r(src_core_namespaceObject); +__nccwpck_require__.d(src_core_namespaceObject, { + JsonPatchError: () => (JsonPatchError), + _areEquals: () => (_areEquals), + applyOperation: () => (applyOperation), + applyPatch: () => (core_applyPatch), + applyReducer: () => (applyReducer), + deepClone: () => (deepClone), + getValueByPointer: () => (getValueByPointer), + validate: () => (core_validate), + validator: () => (validator) +}); -UrlEncoded.detect = /^application\/x-www-form-urlencoded/i -function UrlEncoded (boy, cfg) { - const limits = cfg.limits - const parsedConType = cfg.parsedConType - this.boy = boy +// EXTERNAL MODULE: ./node_modules/@actions/core/lib/core.js +var lib_core = __nccwpck_require__(7484); +// EXTERNAL MODULE: ./node_modules/@actions/github/lib/github.js +var github = __nccwpck_require__(3228); +;// CONCATENATED MODULE: ./node_modules/openai/internal/tslib.mjs +function __classPrivateFieldSet(receiver, state, value, kind, f) { + if (kind === "m") + throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) + throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) + throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return kind === "a" ? f.call(receiver, value) : f ? (f.value = value) : state.set(receiver, value), value; +} +function __classPrivateFieldGet(receiver, state, kind, f) { + if (kind === "a" && !f) + throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) + throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +} - this.fieldSizeLimit = getLimit(limits, 'fieldSize', 1 * 1024 * 1024) - this.fieldNameSizeLimit = getLimit(limits, 'fieldNameSize', 100) - this.fieldsLimit = getLimit(limits, 'fields', Infinity) - let charset - for (var i = 0, len = parsedConType.length; i < len; ++i) { // eslint-disable-line no-var - if (Array.isArray(parsedConType[i]) && - RE_CHARSET.test(parsedConType[i][0])) { - charset = parsedConType[i][1].toLowerCase() - break +;// CONCATENATED MODULE: ./node_modules/openai/internal/utils/uuid.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +/** + * https://stackoverflow.com/a/2117523 + */ +let uuid4 = function () { + const { crypto } = globalThis; + if (crypto?.randomUUID) { + uuid4 = crypto.randomUUID.bind(crypto); + return crypto.randomUUID(); } - } - - if (charset === undefined) { charset = cfg.defCharset || 'utf8' } - - this.decoder = new Decoder() - this.charset = charset - this._fields = 0 - this._state = 'key' - this._checkingBytes = true - this._bytesKey = 0 - this._bytesVal = 0 - this._key = '' - this._val = '' - this._keyTrunc = false - this._valTrunc = false - this._hitLimit = false + const u8 = new Uint8Array(1); + const randomByte = crypto ? () => crypto.getRandomValues(u8)[0] : () => (Math.random() * 0xff) & 0xff; + return '10000000-1000-4000-8000-100000000000'.replace(/[018]/g, (c) => (+c ^ (randomByte() & (15 >> (+c / 4)))).toString(16)); +}; +//# sourceMappingURL=uuid.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/internal/errors.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +function isAbortError(err) { + return (typeof err === 'object' && + err !== null && + // Spec-compliant fetch implementations + (('name' in err && err.name === 'AbortError') || + // Expo fetch + ('message' in err && String(err.message).includes('FetchRequestCanceledException')))); } - -UrlEncoded.prototype.write = function (data, cb) { - if (this._fields === this.fieldsLimit) { - if (!this.boy.hitFieldsLimit) { - this.boy.hitFieldsLimit = true - this.boy.emit('fieldsLimit') +const castToError = (err) => { + if (err instanceof Error) + return err; + if (typeof err === 'object' && err !== null) { + try { + if (Object.prototype.toString.call(err) === '[object Error]') { + // @ts-ignore - not all envs have native support for cause yet + const error = new Error(err.message, err.cause ? { cause: err.cause } : {}); + if (err.stack) + error.stack = err.stack; + // @ts-ignore - not all envs have native support for cause yet + if (err.cause && !error.cause) + error.cause = err.cause; + if (err.name) + error.name = err.name; + return error; + } + } + catch { } + try { + return new Error(JSON.stringify(err)); + } + catch { } } - return cb() - } - - let idxeq; let idxamp; let i; let p = 0; const len = data.length + return new Error(err); +}; +//# sourceMappingURL=errors.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/core/error.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - while (p < len) { - if (this._state === 'key') { - idxeq = idxamp = undefined - for (i = p; i < len; ++i) { - if (!this._checkingBytes) { ++p } - if (data[i] === 0x3D/* = */) { - idxeq = i - break - } else if (data[i] === 0x26/* & */) { - idxamp = i - break +class error_OpenAIError extends Error { +} +class APIError extends error_OpenAIError { + constructor(status, error, message, headers) { + super(`${APIError.makeMessage(status, error, message)}`); + this.status = status; + this.headers = headers; + this.requestID = headers?.get('x-request-id'); + this.error = error; + const data = error; + this.code = data?.['code']; + this.param = data?.['param']; + this.type = data?.['type']; + } + static makeMessage(status, error, message) { + const msg = error?.message ? + typeof error.message === 'string' ? + error.message + : JSON.stringify(error.message) + : error ? JSON.stringify(error) + : message; + if (status && msg) { + return `${status} ${msg}`; } - if (this._checkingBytes && this._bytesKey === this.fieldNameSizeLimit) { - this._hitLimit = true - break - } else if (this._checkingBytes) { ++this._bytesKey } - } - - if (idxeq !== undefined) { - // key with assignment - if (idxeq > p) { this._key += this.decoder.write(data.toString('binary', p, idxeq)) } - this._state = 'val' - - this._hitLimit = false - this._checkingBytes = true - this._val = '' - this._bytesVal = 0 - this._valTrunc = false - this.decoder.reset() - - p = idxeq + 1 - } else if (idxamp !== undefined) { - // key with no assignment - ++this._fields - let key; const keyTrunc = this._keyTrunc - if (idxamp > p) { key = (this._key += this.decoder.write(data.toString('binary', p, idxamp))) } else { key = this._key } - - this._hitLimit = false - this._checkingBytes = true - this._key = '' - this._bytesKey = 0 - this._keyTrunc = false - this.decoder.reset() - - if (key.length) { - this.boy.emit('field', decodeText(key, 'binary', this.charset), - '', - keyTrunc, - false) + if (status) { + return `${status} status code (no body)`; } - - p = idxamp + 1 - if (this._fields === this.fieldsLimit) { return cb() } - } else if (this._hitLimit) { - // we may not have hit the actual limit if there are encoded bytes... - if (i > p) { this._key += this.decoder.write(data.toString('binary', p, i)) } - p = i - if ((this._bytesKey = this._key.length) === this.fieldNameSizeLimit) { - // yep, we actually did hit the limit - this._checkingBytes = false - this._keyTrunc = true + if (msg) { + return msg; } - } else { - if (p < len) { this._key += this.decoder.write(data.toString('binary', p)) } - p = len - } - } else { - idxamp = undefined - for (i = p; i < len; ++i) { - if (!this._checkingBytes) { ++p } - if (data[i] === 0x26/* & */) { - idxamp = i - break + return '(no status code or body)'; + } + static generate(status, errorResponse, message, headers) { + if (!status || !headers) { + return new APIConnectionError({ message, cause: castToError(errorResponse) }); } - if (this._checkingBytes && this._bytesVal === this.fieldSizeLimit) { - this._hitLimit = true - break - } else if (this._checkingBytes) { ++this._bytesVal } - } - - if (idxamp !== undefined) { - ++this._fields - if (idxamp > p) { this._val += this.decoder.write(data.toString('binary', p, idxamp)) } - this.boy.emit('field', decodeText(this._key, 'binary', this.charset), - decodeText(this._val, 'binary', this.charset), - this._keyTrunc, - this._valTrunc) - this._state = 'key' - - this._hitLimit = false - this._checkingBytes = true - this._key = '' - this._bytesKey = 0 - this._keyTrunc = false - this.decoder.reset() - - p = idxamp + 1 - if (this._fields === this.fieldsLimit) { return cb() } - } else if (this._hitLimit) { - // we may not have hit the actual limit if there are encoded bytes... - if (i > p) { this._val += this.decoder.write(data.toString('binary', p, i)) } - p = i - if ((this._val === '' && this.fieldSizeLimit === 0) || - (this._bytesVal = this._val.length) === this.fieldSizeLimit) { - // yep, we actually did hit the limit - this._checkingBytes = false - this._valTrunc = true + const error = errorResponse?.['error']; + if (status === 400) { + return new BadRequestError(status, error, message, headers); } - } else { - if (p < len) { this._val += this.decoder.write(data.toString('binary', p)) } - p = len - } + if (status === 401) { + return new AuthenticationError(status, error, message, headers); + } + if (status === 403) { + return new PermissionDeniedError(status, error, message, headers); + } + if (status === 404) { + return new NotFoundError(status, error, message, headers); + } + if (status === 409) { + return new ConflictError(status, error, message, headers); + } + if (status === 422) { + return new UnprocessableEntityError(status, error, message, headers); + } + if (status === 429) { + return new RateLimitError(status, error, message, headers); + } + if (status >= 500) { + return new InternalServerError(status, error, message, headers); + } + return new APIError(status, error, message, headers); } - } - cb() } - -UrlEncoded.prototype.end = function () { - if (this.boy._done) { return } - - if (this._state === 'key' && this._key.length > 0) { - this.boy.emit('field', decodeText(this._key, 'binary', this.charset), - '', - this._keyTrunc, - false) - } else if (this._state === 'val') { - this.boy.emit('field', decodeText(this._key, 'binary', this.charset), - decodeText(this._val, 'binary', this.charset), - this._keyTrunc, - this._valTrunc) - } - this.boy._done = true - this.boy.emit('finish') +class APIUserAbortError extends APIError { + constructor({ message } = {}) { + super(undefined, undefined, message || 'Request was aborted.', undefined); + } } - -module.exports = UrlEncoded - - -/***/ }), - -/***/ 1496: -/***/ ((module) => { - - - -const RE_PLUS = /\+/g - -const HEX = [ - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, - 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 -] - -function Decoder () { - this.buffer = undefined +class APIConnectionError extends APIError { + constructor({ message, cause }) { + super(undefined, undefined, message || 'Connection error.', undefined); + // in some environments the 'cause' property is already declared + // @ts-ignore + if (cause) + this.cause = cause; + } } -Decoder.prototype.write = function (str) { - // Replace '+' with ' ' before decoding - str = str.replace(RE_PLUS, ' ') - let res = '' - let i = 0; let p = 0; const len = str.length - for (; i < len; ++i) { - if (this.buffer !== undefined) { - if (!HEX[str.charCodeAt(i)]) { - res += '%' + this.buffer - this.buffer = undefined - --i // retry character - } else { - this.buffer += str[i] - ++p - if (this.buffer.length === 2) { - res += String.fromCharCode(parseInt(this.buffer, 16)) - this.buffer = undefined - } - } - } else if (str[i] === '%') { - if (i > p) { - res += str.substring(p, i) - p = i - } - this.buffer = '' - ++p +class APIConnectionTimeoutError extends APIConnectionError { + constructor({ message } = {}) { + super({ message: message ?? 'Request timed out.' }); } - } - if (p < len && this.buffer === undefined) { res += str.substring(p) } - return res } -Decoder.prototype.reset = function () { - this.buffer = undefined +class BadRequestError extends APIError { } - -module.exports = Decoder - - -/***/ }), - -/***/ 692: -/***/ ((module) => { - - - -module.exports = function basename (path) { - if (typeof path !== 'string') { return '' } - for (var i = path.length - 1; i >= 0; --i) { // eslint-disable-line no-var - switch (path.charCodeAt(i)) { - case 0x2F: // '/' - case 0x5C: // '\' - path = path.slice(i + 1) - return (path === '..' || path === '.' ? '' : path) +class AuthenticationError extends APIError { +} +class PermissionDeniedError extends APIError { +} +class NotFoundError extends APIError { +} +class ConflictError extends APIError { +} +class UnprocessableEntityError extends APIError { +} +class RateLimitError extends APIError { +} +class InternalServerError extends APIError { +} +class LengthFinishReasonError extends error_OpenAIError { + constructor() { + super(`Could not parse response content as the length limit was reached`); } - } - return (path === '..' || path === '.' ? '' : path) } +class ContentFilterFinishReasonError extends error_OpenAIError { + constructor() { + super(`Could not parse response content as the request was rejected by the content filter`); + } +} +class InvalidWebhookSignatureError extends Error { + constructor(message) { + super(message); + } +} +//# sourceMappingURL=error.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/internal/utils/values.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -/***/ }), - -/***/ 2747: -/***/ (function(module) { - - - -// Node has always utf-8 -const utf8Decoder = new TextDecoder('utf-8') -const textDecoders = new Map([ - ['utf-8', utf8Decoder], - ['utf8', utf8Decoder] -]) - -function getDecoder (charset) { - let lc - while (true) { - switch (charset) { - case 'utf-8': - case 'utf8': - return decoders.utf8 - case 'latin1': - case 'ascii': // TODO: Make these a separate, strict decoder? - case 'us-ascii': - case 'iso-8859-1': - case 'iso8859-1': - case 'iso88591': - case 'iso_8859-1': - case 'windows-1252': - case 'iso_8859-1:1987': - case 'cp1252': - case 'x-cp1252': - return decoders.latin1 - case 'utf16le': - case 'utf-16le': - case 'ucs2': - case 'ucs-2': - return decoders.utf16le - case 'base64': - return decoders.base64 - default: - if (lc === undefined) { - lc = true - charset = charset.toLowerCase() - continue - } - return decoders.other.bind(charset) +// https://url.spec.whatwg.org/#url-scheme-string +const startsWithSchemeRegexp = /^[a-z][a-z0-9+.-]*:/i; +const isAbsoluteURL = (url) => { + return startsWithSchemeRegexp.test(url); +}; +let values_isArray = (val) => ((values_isArray = Array.isArray), values_isArray(val)); +let isReadonlyArray = values_isArray; +/** Returns an object if the given value isn't an object, otherwise returns as-is */ +function maybeObj(x) { + if (typeof x !== 'object') { + return {}; + } + return x ?? {}; +} +// https://stackoverflow.com/a/34491287 +function isEmptyObj(obj) { + if (!obj) + return true; + for (const _k in obj) + return false; + return true; +} +// https://eslint.org/docs/latest/rules/no-prototype-builtins +function hasOwn(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} +function isObj(obj) { + return obj != null && typeof obj === 'object' && !Array.isArray(obj); +} +const ensurePresent = (value) => { + if (value == null) { + throw new OpenAIError(`Expected a value to be given but received ${value} instead.`); + } + return value; +}; +const validatePositiveInteger = (name, n) => { + if (typeof n !== 'number' || !Number.isInteger(n)) { + throw new error_OpenAIError(`${name} must be an integer`); + } + if (n < 0) { + throw new error_OpenAIError(`${name} must be a positive integer`); + } + return n; +}; +const coerceInteger = (value) => { + if (typeof value === 'number') + return Math.round(value); + if (typeof value === 'string') + return parseInt(value, 10); + throw new OpenAIError(`Could not coerce ${value} (type: ${typeof value}) into a number`); +}; +const coerceFloat = (value) => { + if (typeof value === 'number') + return value; + if (typeof value === 'string') + return parseFloat(value); + throw new OpenAIError(`Could not coerce ${value} (type: ${typeof value}) into a number`); +}; +const coerceBoolean = (value) => { + if (typeof value === 'boolean') + return value; + if (typeof value === 'string') + return value === 'true'; + return Boolean(value); +}; +const maybeCoerceInteger = (value) => { + if (value == null) { + return undefined; } - } -} - -const decoders = { - utf8: (data, sourceEncoding) => { - if (data.length === 0) { - return '' + return coerceInteger(value); +}; +const maybeCoerceFloat = (value) => { + if (value == null) { + return undefined; } - if (typeof data === 'string') { - data = Buffer.from(data, sourceEncoding) + return coerceFloat(value); +}; +const maybeCoerceBoolean = (value) => { + if (value == null) { + return undefined; } - return data.utf8Slice(0, data.length) - }, - - latin1: (data, sourceEncoding) => { - if (data.length === 0) { - return '' + return coerceBoolean(value); +}; +const safeJSON = (text) => { + try { + return JSON.parse(text); } - if (typeof data === 'string') { - return data + catch (err) { + return undefined; } - return data.latin1Slice(0, data.length) - }, +}; +//# sourceMappingURL=values.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/internal/utils/sleep.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); +//# sourceMappingURL=sleep.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/version.mjs +const VERSION = '5.22.0'; // x-release-please-version +//# sourceMappingURL=version.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/internal/detect-platform.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - utf16le: (data, sourceEncoding) => { - if (data.length === 0) { - return '' +const isRunningInBrowser = () => { + return ( + // @ts-ignore + typeof window !== 'undefined' && + // @ts-ignore + typeof window.document !== 'undefined' && + // @ts-ignore + typeof navigator !== 'undefined'); +}; +/** + * Note this does not detect 'browser'; for that, use getBrowserInfo(). + */ +function getDetectedPlatform() { + if (typeof Deno !== 'undefined' && Deno.build != null) { + return 'deno'; } - if (typeof data === 'string') { - data = Buffer.from(data, sourceEncoding) + if (typeof EdgeRuntime !== 'undefined') { + return 'edge'; } - return data.ucs2Slice(0, data.length) - }, - - base64: (data, sourceEncoding) => { - if (data.length === 0) { - return '' + if (Object.prototype.toString.call(typeof globalThis.process !== 'undefined' ? globalThis.process : 0) === '[object process]') { + return 'node'; } - if (typeof data === 'string') { - data = Buffer.from(data, sourceEncoding) + return 'unknown'; +} +const getPlatformProperties = () => { + const detectedPlatform = getDetectedPlatform(); + if (detectedPlatform === 'deno') { + return { + 'X-Stainless-Lang': 'js', + 'X-Stainless-Package-Version': VERSION, + 'X-Stainless-OS': normalizePlatform(Deno.build.os), + 'X-Stainless-Arch': normalizeArch(Deno.build.arch), + 'X-Stainless-Runtime': 'deno', + 'X-Stainless-Runtime-Version': typeof Deno.version === 'string' ? Deno.version : Deno.version?.deno ?? 'unknown', + }; } - return data.base64Slice(0, data.length) - }, - - other: (data, sourceEncoding) => { - if (data.length === 0) { - return '' + if (typeof EdgeRuntime !== 'undefined') { + return { + 'X-Stainless-Lang': 'js', + 'X-Stainless-Package-Version': VERSION, + 'X-Stainless-OS': 'Unknown', + 'X-Stainless-Arch': `other:${EdgeRuntime}`, + 'X-Stainless-Runtime': 'edge', + 'X-Stainless-Runtime-Version': globalThis.process.version, + }; } - if (typeof data === 'string') { - data = Buffer.from(data, sourceEncoding) + // Check if Node.js + if (detectedPlatform === 'node') { + return { + 'X-Stainless-Lang': 'js', + 'X-Stainless-Package-Version': VERSION, + 'X-Stainless-OS': normalizePlatform(globalThis.process.platform ?? 'unknown'), + 'X-Stainless-Arch': normalizeArch(globalThis.process.arch ?? 'unknown'), + 'X-Stainless-Runtime': 'node', + 'X-Stainless-Runtime-Version': globalThis.process.version ?? 'unknown', + }; } - - if (textDecoders.has(this.toString())) { - try { - return textDecoders.get(this).decode(data) - } catch {} + const browserInfo = getBrowserInfo(); + if (browserInfo) { + return { + 'X-Stainless-Lang': 'js', + 'X-Stainless-Package-Version': VERSION, + 'X-Stainless-OS': 'Unknown', + 'X-Stainless-Arch': 'unknown', + 'X-Stainless-Runtime': `browser:${browserInfo.browser}`, + 'X-Stainless-Runtime-Version': browserInfo.version, + }; } - return typeof data === 'string' - ? data - : data.toString() - } -} - -function decodeText (text, sourceEncoding, destEncoding) { - if (text) { - return getDecoder(destEncoding)(text, sourceEncoding) - } - return text -} - -module.exports = decodeText - - -/***/ }), - -/***/ 2393: -/***/ ((module) => { - - - -module.exports = function getLimit (limits, name, defaultLimit) { - if ( - !limits || - limits[name] === undefined || - limits[name] === null - ) { return defaultLimit } - - if ( - typeof limits[name] !== 'number' || - isNaN(limits[name]) - ) { throw new TypeError('Limit ' + name + ' is not a valid number') } - - return limits[name] -} - - -/***/ }), - -/***/ 8929: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -/* eslint-disable object-property-newline */ - - -const decodeText = __nccwpck_require__(2747) - -const RE_ENCODED = /%[a-fA-F0-9][a-fA-F0-9]/g - -const EncodedLookup = { - '%00': '\x00', '%01': '\x01', '%02': '\x02', '%03': '\x03', '%04': '\x04', - '%05': '\x05', '%06': '\x06', '%07': '\x07', '%08': '\x08', '%09': '\x09', - '%0a': '\x0a', '%0A': '\x0a', '%0b': '\x0b', '%0B': '\x0b', '%0c': '\x0c', - '%0C': '\x0c', '%0d': '\x0d', '%0D': '\x0d', '%0e': '\x0e', '%0E': '\x0e', - '%0f': '\x0f', '%0F': '\x0f', '%10': '\x10', '%11': '\x11', '%12': '\x12', - '%13': '\x13', '%14': '\x14', '%15': '\x15', '%16': '\x16', '%17': '\x17', - '%18': '\x18', '%19': '\x19', '%1a': '\x1a', '%1A': '\x1a', '%1b': '\x1b', - '%1B': '\x1b', '%1c': '\x1c', '%1C': '\x1c', '%1d': '\x1d', '%1D': '\x1d', - '%1e': '\x1e', '%1E': '\x1e', '%1f': '\x1f', '%1F': '\x1f', '%20': '\x20', - '%21': '\x21', '%22': '\x22', '%23': '\x23', '%24': '\x24', '%25': '\x25', - '%26': '\x26', '%27': '\x27', '%28': '\x28', '%29': '\x29', '%2a': '\x2a', - '%2A': '\x2a', '%2b': '\x2b', '%2B': '\x2b', '%2c': '\x2c', '%2C': '\x2c', - '%2d': '\x2d', '%2D': '\x2d', '%2e': '\x2e', '%2E': '\x2e', '%2f': '\x2f', - '%2F': '\x2f', '%30': '\x30', '%31': '\x31', '%32': '\x32', '%33': '\x33', - '%34': '\x34', '%35': '\x35', '%36': '\x36', '%37': '\x37', '%38': '\x38', - '%39': '\x39', '%3a': '\x3a', '%3A': '\x3a', '%3b': '\x3b', '%3B': '\x3b', - '%3c': '\x3c', '%3C': '\x3c', '%3d': '\x3d', '%3D': '\x3d', '%3e': '\x3e', - '%3E': '\x3e', '%3f': '\x3f', '%3F': '\x3f', '%40': '\x40', '%41': '\x41', - '%42': '\x42', '%43': '\x43', '%44': '\x44', '%45': '\x45', '%46': '\x46', - '%47': '\x47', '%48': '\x48', '%49': '\x49', '%4a': '\x4a', '%4A': '\x4a', - '%4b': '\x4b', '%4B': '\x4b', '%4c': '\x4c', '%4C': '\x4c', '%4d': '\x4d', - '%4D': '\x4d', '%4e': '\x4e', '%4E': '\x4e', '%4f': '\x4f', '%4F': '\x4f', - '%50': '\x50', '%51': '\x51', '%52': '\x52', '%53': '\x53', '%54': '\x54', - '%55': '\x55', '%56': '\x56', '%57': '\x57', '%58': '\x58', '%59': '\x59', - '%5a': '\x5a', '%5A': '\x5a', '%5b': '\x5b', '%5B': '\x5b', '%5c': '\x5c', - '%5C': '\x5c', '%5d': '\x5d', '%5D': '\x5d', '%5e': '\x5e', '%5E': '\x5e', - '%5f': '\x5f', '%5F': '\x5f', '%60': '\x60', '%61': '\x61', '%62': '\x62', - '%63': '\x63', '%64': '\x64', '%65': '\x65', '%66': '\x66', '%67': '\x67', - '%68': '\x68', '%69': '\x69', '%6a': '\x6a', '%6A': '\x6a', '%6b': '\x6b', - '%6B': '\x6b', '%6c': '\x6c', '%6C': '\x6c', '%6d': '\x6d', '%6D': '\x6d', - '%6e': '\x6e', '%6E': '\x6e', '%6f': '\x6f', '%6F': '\x6f', '%70': '\x70', - '%71': '\x71', '%72': '\x72', '%73': '\x73', '%74': '\x74', '%75': '\x75', - '%76': '\x76', '%77': '\x77', '%78': '\x78', '%79': '\x79', '%7a': '\x7a', - '%7A': '\x7a', '%7b': '\x7b', '%7B': '\x7b', '%7c': '\x7c', '%7C': '\x7c', - '%7d': '\x7d', '%7D': '\x7d', '%7e': '\x7e', '%7E': '\x7e', '%7f': '\x7f', - '%7F': '\x7f', '%80': '\x80', '%81': '\x81', '%82': '\x82', '%83': '\x83', - '%84': '\x84', '%85': '\x85', '%86': '\x86', '%87': '\x87', '%88': '\x88', - '%89': '\x89', '%8a': '\x8a', '%8A': '\x8a', '%8b': '\x8b', '%8B': '\x8b', - '%8c': '\x8c', '%8C': '\x8c', '%8d': '\x8d', '%8D': '\x8d', '%8e': '\x8e', - '%8E': '\x8e', '%8f': '\x8f', '%8F': '\x8f', '%90': '\x90', '%91': '\x91', - '%92': '\x92', '%93': '\x93', '%94': '\x94', '%95': '\x95', '%96': '\x96', - '%97': '\x97', '%98': '\x98', '%99': '\x99', '%9a': '\x9a', '%9A': '\x9a', - '%9b': '\x9b', '%9B': '\x9b', '%9c': '\x9c', '%9C': '\x9c', '%9d': '\x9d', - '%9D': '\x9d', '%9e': '\x9e', '%9E': '\x9e', '%9f': '\x9f', '%9F': '\x9f', - '%a0': '\xa0', '%A0': '\xa0', '%a1': '\xa1', '%A1': '\xa1', '%a2': '\xa2', - '%A2': '\xa2', '%a3': '\xa3', '%A3': '\xa3', '%a4': '\xa4', '%A4': '\xa4', - '%a5': '\xa5', '%A5': '\xa5', '%a6': '\xa6', '%A6': '\xa6', '%a7': '\xa7', - '%A7': '\xa7', '%a8': '\xa8', '%A8': '\xa8', '%a9': '\xa9', '%A9': '\xa9', - '%aa': '\xaa', '%Aa': '\xaa', '%aA': '\xaa', '%AA': '\xaa', '%ab': '\xab', - '%Ab': '\xab', '%aB': '\xab', '%AB': '\xab', '%ac': '\xac', '%Ac': '\xac', - '%aC': '\xac', '%AC': '\xac', '%ad': '\xad', '%Ad': '\xad', '%aD': '\xad', - '%AD': '\xad', '%ae': '\xae', '%Ae': '\xae', '%aE': '\xae', '%AE': '\xae', - '%af': '\xaf', '%Af': '\xaf', '%aF': '\xaf', '%AF': '\xaf', '%b0': '\xb0', - '%B0': '\xb0', '%b1': '\xb1', '%B1': '\xb1', '%b2': '\xb2', '%B2': '\xb2', - '%b3': '\xb3', '%B3': '\xb3', '%b4': '\xb4', '%B4': '\xb4', '%b5': '\xb5', - '%B5': '\xb5', '%b6': '\xb6', '%B6': '\xb6', '%b7': '\xb7', '%B7': '\xb7', - '%b8': '\xb8', '%B8': '\xb8', '%b9': '\xb9', '%B9': '\xb9', '%ba': '\xba', - '%Ba': '\xba', '%bA': '\xba', '%BA': '\xba', '%bb': '\xbb', '%Bb': '\xbb', - '%bB': '\xbb', '%BB': '\xbb', '%bc': '\xbc', '%Bc': '\xbc', '%bC': '\xbc', - '%BC': '\xbc', '%bd': '\xbd', '%Bd': '\xbd', '%bD': '\xbd', '%BD': '\xbd', - '%be': '\xbe', '%Be': '\xbe', '%bE': '\xbe', '%BE': '\xbe', '%bf': '\xbf', - '%Bf': '\xbf', '%bF': '\xbf', '%BF': '\xbf', '%c0': '\xc0', '%C0': '\xc0', - '%c1': '\xc1', '%C1': '\xc1', '%c2': '\xc2', '%C2': '\xc2', '%c3': '\xc3', - '%C3': '\xc3', '%c4': '\xc4', '%C4': '\xc4', '%c5': '\xc5', '%C5': '\xc5', - '%c6': '\xc6', '%C6': '\xc6', '%c7': '\xc7', '%C7': '\xc7', '%c8': '\xc8', - '%C8': '\xc8', '%c9': '\xc9', '%C9': '\xc9', '%ca': '\xca', '%Ca': '\xca', - '%cA': '\xca', '%CA': '\xca', '%cb': '\xcb', '%Cb': '\xcb', '%cB': '\xcb', - '%CB': '\xcb', '%cc': '\xcc', '%Cc': '\xcc', '%cC': '\xcc', '%CC': '\xcc', - '%cd': '\xcd', '%Cd': '\xcd', '%cD': '\xcd', '%CD': '\xcd', '%ce': '\xce', - '%Ce': '\xce', '%cE': '\xce', '%CE': '\xce', '%cf': '\xcf', '%Cf': '\xcf', - '%cF': '\xcf', '%CF': '\xcf', '%d0': '\xd0', '%D0': '\xd0', '%d1': '\xd1', - '%D1': '\xd1', '%d2': '\xd2', '%D2': '\xd2', '%d3': '\xd3', '%D3': '\xd3', - '%d4': '\xd4', '%D4': '\xd4', '%d5': '\xd5', '%D5': '\xd5', '%d6': '\xd6', - '%D6': '\xd6', '%d7': '\xd7', '%D7': '\xd7', '%d8': '\xd8', '%D8': '\xd8', - '%d9': '\xd9', '%D9': '\xd9', '%da': '\xda', '%Da': '\xda', '%dA': '\xda', - '%DA': '\xda', '%db': '\xdb', '%Db': '\xdb', '%dB': '\xdb', '%DB': '\xdb', - '%dc': '\xdc', '%Dc': '\xdc', '%dC': '\xdc', '%DC': '\xdc', '%dd': '\xdd', - '%Dd': '\xdd', '%dD': '\xdd', '%DD': '\xdd', '%de': '\xde', '%De': '\xde', - '%dE': '\xde', '%DE': '\xde', '%df': '\xdf', '%Df': '\xdf', '%dF': '\xdf', - '%DF': '\xdf', '%e0': '\xe0', '%E0': '\xe0', '%e1': '\xe1', '%E1': '\xe1', - '%e2': '\xe2', '%E2': '\xe2', '%e3': '\xe3', '%E3': '\xe3', '%e4': '\xe4', - '%E4': '\xe4', '%e5': '\xe5', '%E5': '\xe5', '%e6': '\xe6', '%E6': '\xe6', - '%e7': '\xe7', '%E7': '\xe7', '%e8': '\xe8', '%E8': '\xe8', '%e9': '\xe9', - '%E9': '\xe9', '%ea': '\xea', '%Ea': '\xea', '%eA': '\xea', '%EA': '\xea', - '%eb': '\xeb', '%Eb': '\xeb', '%eB': '\xeb', '%EB': '\xeb', '%ec': '\xec', - '%Ec': '\xec', '%eC': '\xec', '%EC': '\xec', '%ed': '\xed', '%Ed': '\xed', - '%eD': '\xed', '%ED': '\xed', '%ee': '\xee', '%Ee': '\xee', '%eE': '\xee', - '%EE': '\xee', '%ef': '\xef', '%Ef': '\xef', '%eF': '\xef', '%EF': '\xef', - '%f0': '\xf0', '%F0': '\xf0', '%f1': '\xf1', '%F1': '\xf1', '%f2': '\xf2', - '%F2': '\xf2', '%f3': '\xf3', '%F3': '\xf3', '%f4': '\xf4', '%F4': '\xf4', - '%f5': '\xf5', '%F5': '\xf5', '%f6': '\xf6', '%F6': '\xf6', '%f7': '\xf7', - '%F7': '\xf7', '%f8': '\xf8', '%F8': '\xf8', '%f9': '\xf9', '%F9': '\xf9', - '%fa': '\xfa', '%Fa': '\xfa', '%fA': '\xfa', '%FA': '\xfa', '%fb': '\xfb', - '%Fb': '\xfb', '%fB': '\xfb', '%FB': '\xfb', '%fc': '\xfc', '%Fc': '\xfc', - '%fC': '\xfc', '%FC': '\xfc', '%fd': '\xfd', '%Fd': '\xfd', '%fD': '\xfd', - '%FD': '\xfd', '%fe': '\xfe', '%Fe': '\xfe', '%fE': '\xfe', '%FE': '\xfe', - '%ff': '\xff', '%Ff': '\xff', '%fF': '\xff', '%FF': '\xff' -} - -function encodedReplacer (match) { - return EncodedLookup[match] -} - -const STATE_KEY = 0 -const STATE_VALUE = 1 -const STATE_CHARSET = 2 -const STATE_LANG = 3 - -function parseParams (str) { - const res = [] - let state = STATE_KEY - let charset = '' - let inquote = false - let escaping = false - let p = 0 - let tmp = '' - const len = str.length - - for (var i = 0; i < len; ++i) { // eslint-disable-line no-var - const char = str[i] - if (char === '\\' && inquote) { - if (escaping) { escaping = false } else { - escaping = true - continue - } - } else if (char === '"') { - if (!escaping) { - if (inquote) { - inquote = false - state = STATE_KEY - } else { inquote = true } - continue - } else { escaping = false } - } else { - if (escaping && inquote) { tmp += '\\' } - escaping = false - if ((state === STATE_CHARSET || state === STATE_LANG) && char === "'") { - if (state === STATE_CHARSET) { - state = STATE_LANG - charset = tmp.substring(1) - } else { state = STATE_VALUE } - tmp = '' - continue - } else if (state === STATE_KEY && - (char === '*' || char === '=') && - res.length) { - state = char === '*' - ? STATE_CHARSET - : STATE_VALUE - res[p] = [tmp, undefined] - tmp = '' - continue - } else if (!inquote && char === ';') { - state = STATE_KEY - if (charset) { - if (tmp.length) { - tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer), - 'binary', - charset) - } - charset = '' - } else if (tmp.length) { - tmp = decodeText(tmp, 'binary', 'utf8') - } - if (res[p] === undefined) { res[p] = tmp } else { res[p][1] = tmp } - tmp = '' - ++p - continue - } else if (!inquote && (char === ' ' || char === '\t')) { continue } + // TODO add support for Cloudflare workers, etc. + return { + 'X-Stainless-Lang': 'js', + 'X-Stainless-Package-Version': VERSION, + 'X-Stainless-OS': 'Unknown', + 'X-Stainless-Arch': 'unknown', + 'X-Stainless-Runtime': 'unknown', + 'X-Stainless-Runtime-Version': 'unknown', + }; +}; +// Note: modified from https://github.com/JS-DevTools/host-environment/blob/b1ab79ecde37db5d6e163c050e54fe7d287d7c92/src/isomorphic.browser.ts +function getBrowserInfo() { + if (typeof navigator === 'undefined' || !navigator) { + return null; } - tmp += char - } - if (charset && tmp.length) { - tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer), - 'binary', - charset) - } else if (tmp) { - tmp = decodeText(tmp, 'binary', 'utf8') - } - - if (res[p] === undefined) { - if (tmp) { res[p] = tmp } - } else { res[p][1] = tmp } - - return res -} - -module.exports = parseParams - - -/***/ }), - -/***/ 6220: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => { - - -// EXPORTS -__nccwpck_require__.d(__webpack_exports__, { - Y: () => (/* binding */ Blob) -}); - -;// CONCATENATED MODULE: ./node_modules/web-streams-polyfill/dist/ponyfill.mjs -/** - * @license - * web-streams-polyfill v4.0.0-beta.3 - * Copyright 2021 Mattias Buelens, Diwank Singh Tomer and other contributors. - * This code is released under the MIT license. - * SPDX-License-Identifier: MIT - */ -const e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol:e=>`Symbol(${e})`;function t(){}function r(e){return"object"==typeof e&&null!==e||"function"==typeof e}const o=t;function n(e,t){try{Object.defineProperty(e,"name",{value:t,configurable:!0})}catch(e){}}const a=Promise,i=Promise.prototype.then,l=Promise.resolve.bind(a),s=Promise.reject.bind(a);function u(e){return new a(e)}function c(e){return l(e)}function d(e){return s(e)}function f(e,t,r){return i.call(e,t,r)}function b(e,t,r){f(f(e,t,r),void 0,o)}function h(e,t){b(e,t)}function _(e,t){b(e,void 0,t)}function p(e,t,r){return f(e,t,r)}function m(e){f(e,void 0,o)}let y=e=>{if("function"==typeof queueMicrotask)y=queueMicrotask;else{const e=c(void 0);y=t=>f(e,t)}return y(e)};function g(e,t,r){if("function"!=typeof e)throw new TypeError("Argument is not a function");return Function.prototype.apply.call(e,t,r)}function w(e,t,r){try{return c(g(e,t,r))}catch(e){return d(e)}}class S{constructor(){this._cursor=0,this._size=0,this._front={_elements:[],_next:void 0},this._back=this._front,this._cursor=0,this._size=0}get length(){return this._size}push(e){const t=this._back;let r=t;16383===t._elements.length&&(r={_elements:[],_next:void 0}),t._elements.push(e),r!==t&&(this._back=r,t._next=r),++this._size}shift(){const e=this._front;let t=e;const r=this._cursor;let o=r+1;const n=e._elements,a=n[r];return 16384===o&&(t=e._next,o=0),--this._size,this._cursor=o,e!==t&&(this._front=t),n[r]=void 0,a}forEach(e){let t=this._cursor,r=this._front,o=r._elements;for(;!(t===o.length&&void 0===r._next||t===o.length&&(r=r._next,o=r._elements,t=0,0===o.length));)e(o[t]),++t}peek(){const e=this._front,t=this._cursor;return e._elements[t]}}const v=e("[[AbortSteps]]"),R=e("[[ErrorSteps]]"),T=e("[[CancelSteps]]"),q=e("[[PullSteps]]"),C=e("[[ReleaseSteps]]");function E(e,t){e._ownerReadableStream=t,t._reader=e,"readable"===t._state?O(e):"closed"===t._state?function(e){O(e),j(e)}(e):B(e,t._storedError)}function P(e,t){return Gt(e._ownerReadableStream,t)}function W(e){const t=e._ownerReadableStream;"readable"===t._state?A(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):function(e,t){B(e,t)}(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")),t._readableStreamController[C](),t._reader=void 0,e._ownerReadableStream=void 0}function k(e){return new TypeError("Cannot "+e+" a stream using a released reader")}function O(e){e._closedPromise=u(((t,r)=>{e._closedPromise_resolve=t,e._closedPromise_reject=r}))}function B(e,t){O(e),A(e,t)}function A(e,t){void 0!==e._closedPromise_reject&&(m(e._closedPromise),e._closedPromise_reject(t),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0)}function j(e){void 0!==e._closedPromise_resolve&&(e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0)}const z=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},L=Math.trunc||function(e){return e<0?Math.ceil(e):Math.floor(e)};function F(e,t){if(void 0!==e&&("object"!=typeof(r=e)&&"function"!=typeof r))throw new TypeError(`${t} is not an object.`);var r}function I(e,t){if("function"!=typeof e)throw new TypeError(`${t} is not a function.`)}function D(e,t){if(!function(e){return"object"==typeof e&&null!==e||"function"==typeof e}(e))throw new TypeError(`${t} is not an object.`)}function $(e,t,r){if(void 0===e)throw new TypeError(`Parameter ${t} is required in '${r}'.`)}function M(e,t,r){if(void 0===e)throw new TypeError(`${t} is required in '${r}'.`)}function Y(e){return Number(e)}function Q(e){return 0===e?0:e}function N(e,t){const r=Number.MAX_SAFE_INTEGER;let o=Number(e);if(o=Q(o),!z(o))throw new TypeError(`${t} is not a finite number`);if(o=function(e){return Q(L(e))}(o),o<0||o>r)throw new TypeError(`${t} is outside the accepted range of 0 to ${r}, inclusive`);return z(o)&&0!==o?o:0}function H(e){if(!r(e))return!1;if("function"!=typeof e.getReader)return!1;try{return"boolean"==typeof e.locked}catch(e){return!1}}function x(e){if(!r(e))return!1;if("function"!=typeof e.getWriter)return!1;try{return"boolean"==typeof e.locked}catch(e){return!1}}function V(e,t){if(!Vt(e))throw new TypeError(`${t} is not a ReadableStream.`)}function U(e,t){e._reader._readRequests.push(t)}function G(e,t,r){const o=e._reader._readRequests.shift();r?o._closeSteps():o._chunkSteps(t)}function X(e){return e._reader._readRequests.length}function J(e){const t=e._reader;return void 0!==t&&!!K(t)}class ReadableStreamDefaultReader{constructor(e){if($(e,1,"ReadableStreamDefaultReader"),V(e,"First parameter"),Ut(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");E(this,e),this._readRequests=new S}get closed(){return K(this)?this._closedPromise:d(ee("closed"))}cancel(e){return K(this)?void 0===this._ownerReadableStream?d(k("cancel")):P(this,e):d(ee("cancel"))}read(){if(!K(this))return d(ee("read"));if(void 0===this._ownerReadableStream)return d(k("read from"));let e,t;const r=u(((r,o)=>{e=r,t=o}));return function(e,t){const r=e._ownerReadableStream;r._disturbed=!0,"closed"===r._state?t._closeSteps():"errored"===r._state?t._errorSteps(r._storedError):r._readableStreamController[q](t)}(this,{_chunkSteps:t=>e({value:t,done:!1}),_closeSteps:()=>e({value:void 0,done:!0}),_errorSteps:e=>t(e)}),r}releaseLock(){if(!K(this))throw ee("releaseLock");void 0!==this._ownerReadableStream&&function(e){W(e);const t=new TypeError("Reader was released");Z(e,t)}(this)}}function K(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readRequests")&&e instanceof ReadableStreamDefaultReader)}function Z(e,t){const r=e._readRequests;e._readRequests=new S,r.forEach((e=>{e._errorSteps(t)}))}function ee(e){return new TypeError(`ReadableStreamDefaultReader.prototype.${e} can only be used on a ReadableStreamDefaultReader`)}Object.defineProperties(ReadableStreamDefaultReader.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),n(ReadableStreamDefaultReader.prototype.cancel,"cancel"),n(ReadableStreamDefaultReader.prototype.read,"read"),n(ReadableStreamDefaultReader.prototype.releaseLock,"releaseLock"),"symbol"==typeof e.toStringTag&&Object.defineProperty(ReadableStreamDefaultReader.prototype,e.toStringTag,{value:"ReadableStreamDefaultReader",configurable:!0});class te{constructor(e,t){this._ongoingPromise=void 0,this._isFinished=!1,this._reader=e,this._preventCancel=t}next(){const e=()=>this._nextSteps();return this._ongoingPromise=this._ongoingPromise?p(this._ongoingPromise,e,e):e(),this._ongoingPromise}return(e){const t=()=>this._returnSteps(e);return this._ongoingPromise?p(this._ongoingPromise,t,t):t()}_nextSteps(){if(this._isFinished)return Promise.resolve({value:void 0,done:!0});const e=this._reader;return void 0===e?d(k("iterate")):f(e.read(),(e=>{var t;return this._ongoingPromise=void 0,e.done&&(this._isFinished=!0,null===(t=this._reader)||void 0===t||t.releaseLock(),this._reader=void 0),e}),(e=>{var t;throw this._ongoingPromise=void 0,this._isFinished=!0,null===(t=this._reader)||void 0===t||t.releaseLock(),this._reader=void 0,e}))}_returnSteps(e){if(this._isFinished)return Promise.resolve({value:e,done:!0});this._isFinished=!0;const t=this._reader;if(void 0===t)return d(k("finish iterating"));if(this._reader=void 0,!this._preventCancel){const r=t.cancel(e);return t.releaseLock(),p(r,(()=>({value:e,done:!0})))}return t.releaseLock(),c({value:e,done:!0})}}const re={next(){return oe(this)?this._asyncIteratorImpl.next():d(ne("next"))},return(e){return oe(this)?this._asyncIteratorImpl.return(e):d(ne("return"))}};function oe(e){if(!r(e))return!1;if(!Object.prototype.hasOwnProperty.call(e,"_asyncIteratorImpl"))return!1;try{return e._asyncIteratorImpl instanceof te}catch(e){return!1}}function ne(e){return new TypeError(`ReadableStreamAsyncIterator.${e} can only be used on a ReadableSteamAsyncIterator`)}"symbol"==typeof e.asyncIterator&&Object.defineProperty(re,e.asyncIterator,{value(){return this},writable:!0,configurable:!0});const ae=Number.isNaN||function(e){return e!=e};function ie(e,t,r,o,n){new Uint8Array(e).set(new Uint8Array(r,o,n),t)}function le(e){const t=function(e,t,r){if(e.slice)return e.slice(t,r);const o=r-t,n=new ArrayBuffer(o);return ie(n,0,e,t,o),n}(e.buffer,e.byteOffset,e.byteOffset+e.byteLength);return new Uint8Array(t)}function se(e){const t=e._queue.shift();return e._queueTotalSize-=t.size,e._queueTotalSize<0&&(e._queueTotalSize=0),t.value}function ue(e,t,r){if("number"!=typeof(o=r)||ae(o)||o<0||r===1/0)throw new RangeError("Size must be a finite, non-NaN, non-negative number.");var o;e._queue.push({value:t,size:r}),e._queueTotalSize+=r}function ce(e){e._queue=new S,e._queueTotalSize=0}class ReadableStreamBYOBRequest{constructor(){throw new TypeError("Illegal constructor")}get view(){if(!fe(this))throw Be("view");return this._view}respond(e){if(!fe(this))throw Be("respond");if($(e,1,"respond"),e=N(e,"First parameter"),void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");this._view.buffer,function(e,t){const r=e._pendingPullIntos.peek();if("closed"===e._controlledReadableByteStream._state){if(0!==t)throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream")}else{if(0===t)throw new TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream");if(r.bytesFilled+t>r.byteLength)throw new RangeError("bytesWritten out of range")}r.buffer=r.buffer,qe(e,t)}(this._associatedReadableByteStreamController,e)}respondWithNewView(e){if(!fe(this))throw Be("respondWithNewView");if($(e,1,"respondWithNewView"),!ArrayBuffer.isView(e))throw new TypeError("You can only respond with array buffer views");if(void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");e.buffer,function(e,t){const r=e._pendingPullIntos.peek();if("closed"===e._controlledReadableByteStream._state){if(0!==t.byteLength)throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream")}else if(0===t.byteLength)throw new TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream");if(r.byteOffset+r.bytesFilled!==t.byteOffset)throw new RangeError("The region specified by view does not match byobRequest");if(r.bufferByteLength!==t.buffer.byteLength)throw new RangeError("The buffer of view has different capacity than byobRequest");if(r.bytesFilled+t.byteLength>r.byteLength)throw new RangeError("The region specified by view is larger than byobRequest");const o=t.byteLength;r.buffer=t.buffer,qe(e,o)}(this._associatedReadableByteStreamController,e)}}Object.defineProperties(ReadableStreamBYOBRequest.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),n(ReadableStreamBYOBRequest.prototype.respond,"respond"),n(ReadableStreamBYOBRequest.prototype.respondWithNewView,"respondWithNewView"),"symbol"==typeof e.toStringTag&&Object.defineProperty(ReadableStreamBYOBRequest.prototype,e.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});class ReadableByteStreamController{constructor(){throw new TypeError("Illegal constructor")}get byobRequest(){if(!de(this))throw Ae("byobRequest");return function(e){if(null===e._byobRequest&&e._pendingPullIntos.length>0){const t=e._pendingPullIntos.peek(),r=new Uint8Array(t.buffer,t.byteOffset+t.bytesFilled,t.byteLength-t.bytesFilled),o=Object.create(ReadableStreamBYOBRequest.prototype);!function(e,t,r){e._associatedReadableByteStreamController=t,e._view=r}(o,e,r),e._byobRequest=o}return e._byobRequest}(this)}get desiredSize(){if(!de(this))throw Ae("desiredSize");return ke(this)}close(){if(!de(this))throw Ae("close");if(this._closeRequested)throw new TypeError("The stream has already been closed; do not close it again!");const e=this._controlledReadableByteStream._state;if("readable"!==e)throw new TypeError(`The stream (in ${e} state) is not in the readable state and cannot be closed`);!function(e){const t=e._controlledReadableByteStream;if(e._closeRequested||"readable"!==t._state)return;if(e._queueTotalSize>0)return void(e._closeRequested=!0);if(e._pendingPullIntos.length>0){if(e._pendingPullIntos.peek().bytesFilled>0){const t=new TypeError("Insufficient bytes to fill elements in the given buffer");throw Pe(e,t),t}}Ee(e),Xt(t)}(this)}enqueue(e){if(!de(this))throw Ae("enqueue");if($(e,1,"enqueue"),!ArrayBuffer.isView(e))throw new TypeError("chunk must be an array buffer view");if(0===e.byteLength)throw new TypeError("chunk must have non-zero byteLength");if(0===e.buffer.byteLength)throw new TypeError("chunk's buffer must have non-zero byteLength");if(this._closeRequested)throw new TypeError("stream is closed or draining");const t=this._controlledReadableByteStream._state;if("readable"!==t)throw new TypeError(`The stream (in ${t} state) is not in the readable state and cannot be enqueued to`);!function(e,t){const r=e._controlledReadableByteStream;if(e._closeRequested||"readable"!==r._state)return;const o=t.buffer,n=t.byteOffset,a=t.byteLength,i=o;if(e._pendingPullIntos.length>0){const t=e._pendingPullIntos.peek();t.buffer,0,Re(e),t.buffer=t.buffer,"none"===t.readerType&&ge(e,t)}if(J(r))if(function(e){const t=e._controlledReadableByteStream._reader;for(;t._readRequests.length>0;){if(0===e._queueTotalSize)return;We(e,t._readRequests.shift())}}(e),0===X(r))me(e,i,n,a);else{e._pendingPullIntos.length>0&&Ce(e);G(r,new Uint8Array(i,n,a),!1)}else Le(r)?(me(e,i,n,a),Te(e)):me(e,i,n,a);be(e)}(this,e)}error(e){if(!de(this))throw Ae("error");Pe(this,e)}[T](e){he(this),ce(this);const t=this._cancelAlgorithm(e);return Ee(this),t}[q](e){const t=this._controlledReadableByteStream;if(this._queueTotalSize>0)return void We(this,e);const r=this._autoAllocateChunkSize;if(void 0!==r){let t;try{t=new ArrayBuffer(r)}catch(t){return void e._errorSteps(t)}const o={buffer:t,bufferByteLength:r,byteOffset:0,byteLength:r,bytesFilled:0,elementSize:1,viewConstructor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(o)}U(t,e),be(this)}[C](){if(this._pendingPullIntos.length>0){const e=this._pendingPullIntos.peek();e.readerType="none",this._pendingPullIntos=new S,this._pendingPullIntos.push(e)}}}function de(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableByteStream")&&e instanceof ReadableByteStreamController)}function fe(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_associatedReadableByteStreamController")&&e instanceof ReadableStreamBYOBRequest)}function be(e){const t=function(e){const t=e._controlledReadableByteStream;if("readable"!==t._state)return!1;if(e._closeRequested)return!1;if(!e._started)return!1;if(J(t)&&X(t)>0)return!0;if(Le(t)&&ze(t)>0)return!0;if(ke(e)>0)return!0;return!1}(e);if(!t)return;if(e._pulling)return void(e._pullAgain=!0);e._pulling=!0;b(e._pullAlgorithm(),(()=>(e._pulling=!1,e._pullAgain&&(e._pullAgain=!1,be(e)),null)),(t=>(Pe(e,t),null)))}function he(e){Re(e),e._pendingPullIntos=new S}function _e(e,t){let r=!1;"closed"===e._state&&(r=!0);const o=pe(t);"default"===t.readerType?G(e,o,r):function(e,t,r){const o=e._reader._readIntoRequests.shift();r?o._closeSteps(t):o._chunkSteps(t)}(e,o,r)}function pe(e){const t=e.bytesFilled,r=e.elementSize;return new e.viewConstructor(e.buffer,e.byteOffset,t/r)}function me(e,t,r,o){e._queue.push({buffer:t,byteOffset:r,byteLength:o}),e._queueTotalSize+=o}function ye(e,t,r,o){let n;try{n=t.slice(r,r+o)}catch(t){throw Pe(e,t),t}me(e,n,0,o)}function ge(e,t){t.bytesFilled>0&&ye(e,t.buffer,t.byteOffset,t.bytesFilled),Ce(e)}function we(e,t){const r=t.elementSize,o=t.bytesFilled-t.bytesFilled%r,n=Math.min(e._queueTotalSize,t.byteLength-t.bytesFilled),a=t.bytesFilled+n,i=a-a%r;let l=n,s=!1;i>o&&(l=i-t.bytesFilled,s=!0);const u=e._queue;for(;l>0;){const r=u.peek(),o=Math.min(l,r.byteLength),n=t.byteOffset+t.bytesFilled;ie(t.buffer,n,r.buffer,r.byteOffset,o),r.byteLength===o?u.shift():(r.byteOffset+=o,r.byteLength-=o),e._queueTotalSize-=o,Se(e,o,t),l-=o}return s}function Se(e,t,r){r.bytesFilled+=t}function ve(e){0===e._queueTotalSize&&e._closeRequested?(Ee(e),Xt(e._controlledReadableByteStream)):be(e)}function Re(e){null!==e._byobRequest&&(e._byobRequest._associatedReadableByteStreamController=void 0,e._byobRequest._view=null,e._byobRequest=null)}function Te(e){for(;e._pendingPullIntos.length>0;){if(0===e._queueTotalSize)return;const t=e._pendingPullIntos.peek();we(e,t)&&(Ce(e),_e(e._controlledReadableByteStream,t))}}function qe(e,t){const r=e._pendingPullIntos.peek();Re(e);"closed"===e._controlledReadableByteStream._state?function(e,t){"none"===t.readerType&&Ce(e);const r=e._controlledReadableByteStream;if(Le(r))for(;ze(r)>0;)_e(r,Ce(e))}(e,r):function(e,t,r){if(Se(0,t,r),"none"===r.readerType)return ge(e,r),void Te(e);if(r.bytesFilled0){const t=r.byteOffset+r.bytesFilled;ye(e,r.buffer,t-o,o)}r.bytesFilled-=o,_e(e._controlledReadableByteStream,r),Te(e)}(e,t,r),be(e)}function Ce(e){return e._pendingPullIntos.shift()}function Ee(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0}function Pe(e,t){const r=e._controlledReadableByteStream;"readable"===r._state&&(he(e),ce(e),Ee(e),Jt(r,t))}function We(e,t){const r=e._queue.shift();e._queueTotalSize-=r.byteLength,ve(e);const o=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);t._chunkSteps(o)}function ke(e){const t=e._controlledReadableByteStream._state;return"errored"===t?null:"closed"===t?0:e._strategyHWM-e._queueTotalSize}function Oe(e,t,r){const o=Object.create(ReadableByteStreamController.prototype);let n,a,i;n=void 0!==t.start?()=>t.start(o):()=>{},a=void 0!==t.pull?()=>t.pull(o):()=>c(void 0),i=void 0!==t.cancel?e=>t.cancel(e):()=>c(void 0);const l=t.autoAllocateChunkSize;if(0===l)throw new TypeError("autoAllocateChunkSize must be greater than 0");!function(e,t,r,o,n,a,i){t._controlledReadableByteStream=e,t._pullAgain=!1,t._pulling=!1,t._byobRequest=null,t._queue=t._queueTotalSize=void 0,ce(t),t._closeRequested=!1,t._started=!1,t._strategyHWM=a,t._pullAlgorithm=o,t._cancelAlgorithm=n,t._autoAllocateChunkSize=i,t._pendingPullIntos=new S,e._readableStreamController=t,b(c(r()),(()=>(t._started=!0,be(t),null)),(e=>(Pe(t,e),null)))}(e,o,n,a,i,r,l)}function Be(e){return new TypeError(`ReadableStreamBYOBRequest.prototype.${e} can only be used on a ReadableStreamBYOBRequest`)}function Ae(e){return new TypeError(`ReadableByteStreamController.prototype.${e} can only be used on a ReadableByteStreamController`)}function je(e,t){e._reader._readIntoRequests.push(t)}function ze(e){return e._reader._readIntoRequests.length}function Le(e){const t=e._reader;return void 0!==t&&!!Fe(t)}Object.defineProperties(ReadableByteStreamController.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},byobRequest:{enumerable:!0},desiredSize:{enumerable:!0}}),n(ReadableByteStreamController.prototype.close,"close"),n(ReadableByteStreamController.prototype.enqueue,"enqueue"),n(ReadableByteStreamController.prototype.error,"error"),"symbol"==typeof e.toStringTag&&Object.defineProperty(ReadableByteStreamController.prototype,e.toStringTag,{value:"ReadableByteStreamController",configurable:!0});class ReadableStreamBYOBReader{constructor(e){if($(e,1,"ReadableStreamBYOBReader"),V(e,"First parameter"),Ut(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");if(!de(e._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");E(this,e),this._readIntoRequests=new S}get closed(){return Fe(this)?this._closedPromise:d(De("closed"))}cancel(e){return Fe(this)?void 0===this._ownerReadableStream?d(k("cancel")):P(this,e):d(De("cancel"))}read(e){if(!Fe(this))return d(De("read"));if(!ArrayBuffer.isView(e))return d(new TypeError("view must be an array buffer view"));if(0===e.byteLength)return d(new TypeError("view must have non-zero byteLength"));if(0===e.buffer.byteLength)return d(new TypeError("view's buffer must have non-zero byteLength"));if(e.buffer,void 0===this._ownerReadableStream)return d(k("read from"));let t,r;const o=u(((e,o)=>{t=e,r=o}));return function(e,t,r){const o=e._ownerReadableStream;o._disturbed=!0,"errored"===o._state?r._errorSteps(o._storedError):function(e,t,r){const o=e._controlledReadableByteStream;let n=1;t.constructor!==DataView&&(n=t.constructor.BYTES_PER_ELEMENT);const a=t.constructor,i=t.buffer,l={buffer:i,bufferByteLength:i.byteLength,byteOffset:t.byteOffset,byteLength:t.byteLength,bytesFilled:0,elementSize:n,viewConstructor:a,readerType:"byob"};if(e._pendingPullIntos.length>0)return e._pendingPullIntos.push(l),void je(o,r);if("closed"!==o._state){if(e._queueTotalSize>0){if(we(e,l)){const t=pe(l);return ve(e),void r._chunkSteps(t)}if(e._closeRequested){const t=new TypeError("Insufficient bytes to fill elements in the given buffer");return Pe(e,t),void r._errorSteps(t)}}e._pendingPullIntos.push(l),je(o,r),be(e)}else{const e=new a(l.buffer,l.byteOffset,0);r._closeSteps(e)}}(o._readableStreamController,t,r)}(this,e,{_chunkSteps:e=>t({value:e,done:!1}),_closeSteps:e=>t({value:e,done:!0}),_errorSteps:e=>r(e)}),o}releaseLock(){if(!Fe(this))throw De("releaseLock");void 0!==this._ownerReadableStream&&function(e){W(e);const t=new TypeError("Reader was released");Ie(e,t)}(this)}}function Fe(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readIntoRequests")&&e instanceof ReadableStreamBYOBReader)}function Ie(e,t){const r=e._readIntoRequests;e._readIntoRequests=new S,r.forEach((e=>{e._errorSteps(t)}))}function De(e){return new TypeError(`ReadableStreamBYOBReader.prototype.${e} can only be used on a ReadableStreamBYOBReader`)}function $e(e,t){const{highWaterMark:r}=e;if(void 0===r)return t;if(ae(r)||r<0)throw new RangeError("Invalid highWaterMark");return r}function Me(e){const{size:t}=e;return t||(()=>1)}function Ye(e,t){F(e,t);const r=null==e?void 0:e.highWaterMark,o=null==e?void 0:e.size;return{highWaterMark:void 0===r?void 0:Y(r),size:void 0===o?void 0:Qe(o,`${t} has member 'size' that`)}}function Qe(e,t){return I(e,t),t=>Y(e(t))}function Ne(e,t,r){return I(e,r),r=>w(e,t,[r])}function He(e,t,r){return I(e,r),()=>w(e,t,[])}function xe(e,t,r){return I(e,r),r=>g(e,t,[r])}function Ve(e,t,r){return I(e,r),(r,o)=>w(e,t,[r,o])}Object.defineProperties(ReadableStreamBYOBReader.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),n(ReadableStreamBYOBReader.prototype.cancel,"cancel"),n(ReadableStreamBYOBReader.prototype.read,"read"),n(ReadableStreamBYOBReader.prototype.releaseLock,"releaseLock"),"symbol"==typeof e.toStringTag&&Object.defineProperty(ReadableStreamBYOBReader.prototype,e.toStringTag,{value:"ReadableStreamBYOBReader",configurable:!0});const Ue="function"==typeof AbortController;class WritableStream{constructor(e={},t={}){void 0===e?e=null:D(e,"First parameter");const r=Ye(t,"Second parameter"),o=function(e,t){F(e,t);const r=null==e?void 0:e.abort,o=null==e?void 0:e.close,n=null==e?void 0:e.start,a=null==e?void 0:e.type,i=null==e?void 0:e.write;return{abort:void 0===r?void 0:Ne(r,e,`${t} has member 'abort' that`),close:void 0===o?void 0:He(o,e,`${t} has member 'close' that`),start:void 0===n?void 0:xe(n,e,`${t} has member 'start' that`),write:void 0===i?void 0:Ve(i,e,`${t} has member 'write' that`),type:a}}(e,"First parameter");var n;(n=this)._state="writable",n._storedError=void 0,n._writer=void 0,n._writableStreamController=void 0,n._writeRequests=new S,n._inFlightWriteRequest=void 0,n._closeRequest=void 0,n._inFlightCloseRequest=void 0,n._pendingAbortRequest=void 0,n._backpressure=!1;if(void 0!==o.type)throw new RangeError("Invalid type is specified");const a=Me(r);!function(e,t,r,o){const n=Object.create(WritableStreamDefaultController.prototype);let a,i,l,s;a=void 0!==t.start?()=>t.start(n):()=>{};i=void 0!==t.write?e=>t.write(e,n):()=>c(void 0);l=void 0!==t.close?()=>t.close():()=>c(void 0);s=void 0!==t.abort?e=>t.abort(e):()=>c(void 0);!function(e,t,r,o,n,a,i,l){t._controlledWritableStream=e,e._writableStreamController=t,t._queue=void 0,t._queueTotalSize=void 0,ce(t),t._abortReason=void 0,t._abortController=function(){if(Ue)return new AbortController}(),t._started=!1,t._strategySizeAlgorithm=l,t._strategyHWM=i,t._writeAlgorithm=o,t._closeAlgorithm=n,t._abortAlgorithm=a;const s=bt(t);nt(e,s);const u=r();b(c(u),(()=>(t._started=!0,dt(t),null)),(r=>(t._started=!0,Ze(e,r),null)))}(e,n,a,i,l,s,r,o)}(this,o,$e(r,1),a)}get locked(){if(!Ge(this))throw _t("locked");return Xe(this)}abort(e){return Ge(this)?Xe(this)?d(new TypeError("Cannot abort a stream that already has a writer")):Je(this,e):d(_t("abort"))}close(){return Ge(this)?Xe(this)?d(new TypeError("Cannot close a stream that already has a writer")):rt(this)?d(new TypeError("Cannot close an already-closing stream")):Ke(this):d(_t("close"))}getWriter(){if(!Ge(this))throw _t("getWriter");return new WritableStreamDefaultWriter(this)}}function Ge(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_writableStreamController")&&e instanceof WritableStream)}function Xe(e){return void 0!==e._writer}function Je(e,t){var r;if("closed"===e._state||"errored"===e._state)return c(void 0);e._writableStreamController._abortReason=t,null===(r=e._writableStreamController._abortController)||void 0===r||r.abort(t);const o=e._state;if("closed"===o||"errored"===o)return c(void 0);if(void 0!==e._pendingAbortRequest)return e._pendingAbortRequest._promise;let n=!1;"erroring"===o&&(n=!0,t=void 0);const a=u(((r,o)=>{e._pendingAbortRequest={_promise:void 0,_resolve:r,_reject:o,_reason:t,_wasAlreadyErroring:n}}));return e._pendingAbortRequest._promise=a,n||et(e,t),a}function Ke(e){const t=e._state;if("closed"===t||"errored"===t)return d(new TypeError(`The stream (in ${t} state) is not in the writable state and cannot be closed`));const r=u(((t,r)=>{const o={_resolve:t,_reject:r};e._closeRequest=o})),o=e._writer;var n;return void 0!==o&&e._backpressure&&"writable"===t&&Et(o),ue(n=e._writableStreamController,lt,0),dt(n),r}function Ze(e,t){"writable"!==e._state?tt(e):et(e,t)}function et(e,t){const r=e._writableStreamController;e._state="erroring",e._storedError=t;const o=e._writer;void 0!==o&&it(o,t),!function(e){if(void 0===e._inFlightWriteRequest&&void 0===e._inFlightCloseRequest)return!1;return!0}(e)&&r._started&&tt(e)}function tt(e){e._state="errored",e._writableStreamController[R]();const t=e._storedError;if(e._writeRequests.forEach((e=>{e._reject(t)})),e._writeRequests=new S,void 0===e._pendingAbortRequest)return void ot(e);const r=e._pendingAbortRequest;if(e._pendingAbortRequest=void 0,r._wasAlreadyErroring)return r._reject(t),void ot(e);b(e._writableStreamController[v](r._reason),(()=>(r._resolve(),ot(e),null)),(t=>(r._reject(t),ot(e),null)))}function rt(e){return void 0!==e._closeRequest||void 0!==e._inFlightCloseRequest}function ot(e){void 0!==e._closeRequest&&(e._closeRequest._reject(e._storedError),e._closeRequest=void 0);const t=e._writer;void 0!==t&&St(t,e._storedError)}function nt(e,t){const r=e._writer;void 0!==r&&t!==e._backpressure&&(t?function(e){Rt(e)}(r):Et(r)),e._backpressure=t}Object.defineProperties(WritableStream.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),n(WritableStream.prototype.abort,"abort"),n(WritableStream.prototype.close,"close"),n(WritableStream.prototype.getWriter,"getWriter"),"symbol"==typeof e.toStringTag&&Object.defineProperty(WritableStream.prototype,e.toStringTag,{value:"WritableStream",configurable:!0});class WritableStreamDefaultWriter{constructor(e){if($(e,1,"WritableStreamDefaultWriter"),function(e,t){if(!Ge(e))throw new TypeError(`${t} is not a WritableStream.`)}(e,"First parameter"),Xe(e))throw new TypeError("This stream has already been locked for exclusive writing by another writer");this._ownerWritableStream=e,e._writer=this;const t=e._state;if("writable"===t)!rt(e)&&e._backpressure?Rt(this):qt(this),gt(this);else if("erroring"===t)Tt(this,e._storedError),gt(this);else if("closed"===t)qt(this),gt(r=this),vt(r);else{const t=e._storedError;Tt(this,t),wt(this,t)}var r}get closed(){return at(this)?this._closedPromise:d(mt("closed"))}get desiredSize(){if(!at(this))throw mt("desiredSize");if(void 0===this._ownerWritableStream)throw yt("desiredSize");return function(e){const t=e._ownerWritableStream,r=t._state;if("errored"===r||"erroring"===r)return null;if("closed"===r)return 0;return ct(t._writableStreamController)}(this)}get ready(){return at(this)?this._readyPromise:d(mt("ready"))}abort(e){return at(this)?void 0===this._ownerWritableStream?d(yt("abort")):function(e,t){return Je(e._ownerWritableStream,t)}(this,e):d(mt("abort"))}close(){if(!at(this))return d(mt("close"));const e=this._ownerWritableStream;return void 0===e?d(yt("close")):rt(e)?d(new TypeError("Cannot close an already-closing stream")):Ke(this._ownerWritableStream)}releaseLock(){if(!at(this))throw mt("releaseLock");void 0!==this._ownerWritableStream&&function(e){const t=e._ownerWritableStream,r=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");it(e,r),function(e,t){"pending"===e._closedPromiseState?St(e,t):function(e,t){wt(e,t)}(e,t)}(e,r),t._writer=void 0,e._ownerWritableStream=void 0}(this)}write(e){return at(this)?void 0===this._ownerWritableStream?d(yt("write to")):function(e,t){const r=e._ownerWritableStream,o=r._writableStreamController,n=function(e,t){try{return e._strategySizeAlgorithm(t)}catch(t){return ft(e,t),1}}(o,t);if(r!==e._ownerWritableStream)return d(yt("write to"));const a=r._state;if("errored"===a)return d(r._storedError);if(rt(r)||"closed"===a)return d(new TypeError("The stream is closing or closed and cannot be written to"));if("erroring"===a)return d(r._storedError);const i=function(e){return u(((t,r)=>{const o={_resolve:t,_reject:r};e._writeRequests.push(o)}))}(r);return function(e,t,r){try{ue(e,t,r)}catch(t){return void ft(e,t)}const o=e._controlledWritableStream;if(!rt(o)&&"writable"===o._state){nt(o,bt(e))}dt(e)}(o,t,n),i}(this,e):d(mt("write"))}}function at(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_ownerWritableStream")&&e instanceof WritableStreamDefaultWriter)}function it(e,t){"pending"===e._readyPromiseState?Ct(e,t):function(e,t){Tt(e,t)}(e,t)}Object.defineProperties(WritableStreamDefaultWriter.prototype,{abort:{enumerable:!0},close:{enumerable:!0},releaseLock:{enumerable:!0},write:{enumerable:!0},closed:{enumerable:!0},desiredSize:{enumerable:!0},ready:{enumerable:!0}}),n(WritableStreamDefaultWriter.prototype.abort,"abort"),n(WritableStreamDefaultWriter.prototype.close,"close"),n(WritableStreamDefaultWriter.prototype.releaseLock,"releaseLock"),n(WritableStreamDefaultWriter.prototype.write,"write"),"symbol"==typeof e.toStringTag&&Object.defineProperty(WritableStreamDefaultWriter.prototype,e.toStringTag,{value:"WritableStreamDefaultWriter",configurable:!0});const lt={};class WritableStreamDefaultController{constructor(){throw new TypeError("Illegal constructor")}get abortReason(){if(!st(this))throw pt("abortReason");return this._abortReason}get signal(){if(!st(this))throw pt("signal");if(void 0===this._abortController)throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported");return this._abortController.signal}error(e){if(!st(this))throw pt("error");"writable"===this._controlledWritableStream._state&&ht(this,e)}[v](e){const t=this._abortAlgorithm(e);return ut(this),t}[R](){ce(this)}}function st(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledWritableStream")&&e instanceof WritableStreamDefaultController)}function ut(e){e._writeAlgorithm=void 0,e._closeAlgorithm=void 0,e._abortAlgorithm=void 0,e._strategySizeAlgorithm=void 0}function ct(e){return e._strategyHWM-e._queueTotalSize}function dt(e){const t=e._controlledWritableStream;if(!e._started)return;if(void 0!==t._inFlightWriteRequest)return;if("erroring"===t._state)return void tt(t);if(0===e._queue.length)return;const r=e._queue.peek().value;r===lt?function(e){const t=e._controlledWritableStream;(function(e){e._inFlightCloseRequest=e._closeRequest,e._closeRequest=void 0})(t),se(e);const r=e._closeAlgorithm();ut(e),b(r,(()=>(function(e){e._inFlightCloseRequest._resolve(void 0),e._inFlightCloseRequest=void 0,"erroring"===e._state&&(e._storedError=void 0,void 0!==e._pendingAbortRequest&&(e._pendingAbortRequest._resolve(),e._pendingAbortRequest=void 0)),e._state="closed";const t=e._writer;void 0!==t&&vt(t)}(t),null)),(e=>(function(e,t){e._inFlightCloseRequest._reject(t),e._inFlightCloseRequest=void 0,void 0!==e._pendingAbortRequest&&(e._pendingAbortRequest._reject(t),e._pendingAbortRequest=void 0),Ze(e,t)}(t,e),null)))}(e):function(e,t){const r=e._controlledWritableStream;!function(e){e._inFlightWriteRequest=e._writeRequests.shift()}(r);b(e._writeAlgorithm(t),(()=>{!function(e){e._inFlightWriteRequest._resolve(void 0),e._inFlightWriteRequest=void 0}(r);const t=r._state;if(se(e),!rt(r)&&"writable"===t){const t=bt(e);nt(r,t)}return dt(e),null}),(t=>("writable"===r._state&&ut(e),function(e,t){e._inFlightWriteRequest._reject(t),e._inFlightWriteRequest=void 0,Ze(e,t)}(r,t),null)))}(e,r)}function ft(e,t){"writable"===e._controlledWritableStream._state&&ht(e,t)}function bt(e){return ct(e)<=0}function ht(e,t){const r=e._controlledWritableStream;ut(e),et(r,t)}function _t(e){return new TypeError(`WritableStream.prototype.${e} can only be used on a WritableStream`)}function pt(e){return new TypeError(`WritableStreamDefaultController.prototype.${e} can only be used on a WritableStreamDefaultController`)}function mt(e){return new TypeError(`WritableStreamDefaultWriter.prototype.${e} can only be used on a WritableStreamDefaultWriter`)}function yt(e){return new TypeError("Cannot "+e+" a stream using a released writer")}function gt(e){e._closedPromise=u(((t,r)=>{e._closedPromise_resolve=t,e._closedPromise_reject=r,e._closedPromiseState="pending"}))}function wt(e,t){gt(e),St(e,t)}function St(e,t){void 0!==e._closedPromise_reject&&(m(e._closedPromise),e._closedPromise_reject(t),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0,e._closedPromiseState="rejected")}function vt(e){void 0!==e._closedPromise_resolve&&(e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0,e._closedPromiseState="resolved")}function Rt(e){e._readyPromise=u(((t,r)=>{e._readyPromise_resolve=t,e._readyPromise_reject=r})),e._readyPromiseState="pending"}function Tt(e,t){Rt(e),Ct(e,t)}function qt(e){Rt(e),Et(e)}function Ct(e,t){void 0!==e._readyPromise_reject&&(m(e._readyPromise),e._readyPromise_reject(t),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="rejected")}function Et(e){void 0!==e._readyPromise_resolve&&(e._readyPromise_resolve(void 0),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="fulfilled")}Object.defineProperties(WritableStreamDefaultController.prototype,{abortReason:{enumerable:!0},signal:{enumerable:!0},error:{enumerable:!0}}),"symbol"==typeof e.toStringTag&&Object.defineProperty(WritableStreamDefaultController.prototype,e.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});const Pt="undefined"!=typeof DOMException?DOMException:void 0;const Wt=function(e){if("function"!=typeof e&&"object"!=typeof e)return!1;try{return new e,!0}catch(e){return!1}}(Pt)?Pt:function(){const e=function(e,t){this.message=e||"",this.name=t||"Error",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)};return e.prototype=Object.create(Error.prototype),Object.defineProperty(e.prototype,"constructor",{value:e,writable:!0,configurable:!0}),e}();function kt(e,t,r,o,n,a){const i=e.getReader(),l=t.getWriter();Vt(e)&&(e._disturbed=!0);let s,_,g,w=!1,S=!1,v="readable",R="writable",T=!1,q=!1;const C=u((e=>{g=e}));let E=Promise.resolve(void 0);return u(((P,W)=>{let k;function O(){if(w)return;const e=u(((e,t)=>{!function r(o){o?e():f(function(){if(w)return c(!0);return f(l.ready,(()=>f(i.read(),(e=>!!e.done||(E=l.write(e.value),m(E),!1)))))}(),r,t)}(!1)}));m(e)}function B(){return v="closed",r?L():z((()=>(Ge(t)&&(T=rt(t),R=t._state),T||"closed"===R?c(void 0):"erroring"===R||"errored"===R?d(_):(T=!0,l.close()))),!1,void 0),null}function A(e){return w||(v="errored",s=e,o?L(!0,e):z((()=>l.abort(e)),!0,e)),null}function j(e){return S||(R="errored",_=e,n?L(!0,e):z((()=>i.cancel(e)),!0,e)),null}if(void 0!==a&&(k=()=>{const e=void 0!==a.reason?a.reason:new Wt("Aborted","AbortError"),t=[];o||t.push((()=>"writable"===R?l.abort(e):c(void 0))),n||t.push((()=>"readable"===v?i.cancel(e):c(void 0))),z((()=>Promise.all(t.map((e=>e())))),!0,e)},a.aborted?k():a.addEventListener("abort",k)),Vt(e)&&(v=e._state,s=e._storedError),Ge(t)&&(R=t._state,_=t._storedError,T=rt(t)),Vt(e)&&Ge(t)&&(q=!0,g()),"errored"===v)A(s);else if("erroring"===R||"errored"===R)j(_);else if("closed"===v)B();else if(T||"closed"===R){const e=new TypeError("the destination writable stream closed before all data could be piped to it");n?L(!0,e):z((()=>i.cancel(e)),!0,e)}function z(e,t,r){function o(){return"writable"!==R||T?n():h(function(){let e;return c(function t(){if(e!==E)return e=E,p(E,t,t)}())}(),n),null}function n(){return e?b(e(),(()=>F(t,r)),(e=>F(!0,e))):F(t,r),null}w||(w=!0,q?o():h(C,o))}function L(e,t){z(void 0,e,t)}function F(e,t){return S=!0,l.releaseLock(),i.releaseLock(),void 0!==a&&a.removeEventListener("abort",k),e?W(t):P(void 0),null}w||(b(i.closed,B,A),b(l.closed,(function(){return S||(R="closed"),null}),j)),q?O():y((()=>{q=!0,g(),O()}))}))}function Ot(e,t){return function(e){try{return e.getReader({mode:"byob"}).releaseLock(),!0}catch(e){return!1}}(e)?function(e){let t,r,o,n,a,i=e.getReader(),l=!1,s=!1,d=!1,f=!1,h=!1,p=!1;const m=u((e=>{a=e}));function y(e){_(e.closed,(t=>(e!==i||(o.error(t),n.error(t),h&&p||a(void 0)),null)))}function g(){l&&(i.releaseLock(),i=e.getReader(),y(i),l=!1),b(i.read(),(e=>{var t,r;if(d=!1,f=!1,e.done)return h||o.close(),p||n.close(),null===(t=o.byobRequest)||void 0===t||t.respond(0),null===(r=n.byobRequest)||void 0===r||r.respond(0),h&&p||a(void 0),null;const l=e.value,u=l;let c=l;if(!h&&!p)try{c=le(l)}catch(e){return o.error(e),n.error(e),a(i.cancel(e)),null}return h||o.enqueue(u),p||n.enqueue(c),s=!1,d?S():f&&v(),null}),(()=>(s=!1,null)))}function w(t,r){l||(i.releaseLock(),i=e.getReader({mode:"byob"}),y(i),l=!0);const u=r?n:o,c=r?o:n;b(i.read(t),(e=>{var t;d=!1,f=!1;const o=r?p:h,n=r?h:p;if(e.done){o||u.close(),n||c.close();const r=e.value;return void 0!==r&&(o||u.byobRequest.respondWithNewView(r),n||null===(t=c.byobRequest)||void 0===t||t.respond(0)),o&&n||a(void 0),null}const l=e.value;if(n)o||u.byobRequest.respondWithNewView(l);else{let e;try{e=le(l)}catch(e){return u.error(e),c.error(e),a(i.cancel(e)),null}o||u.byobRequest.respondWithNewView(l),c.enqueue(e)}return s=!1,d?S():f&&v(),null}),(()=>(s=!1,null)))}function S(){if(s)return d=!0,c(void 0);s=!0;const e=o.byobRequest;return null===e?g():w(e.view,!1),c(void 0)}function v(){if(s)return f=!0,c(void 0);s=!0;const e=n.byobRequest;return null===e?g():w(e.view,!0),c(void 0)}function R(e){if(h=!0,t=e,p){const e=[t,r],o=i.cancel(e);a(o)}return m}function T(e){if(p=!0,r=e,h){const e=[t,r],o=i.cancel(e);a(o)}return m}const q=new ReadableStream({type:"bytes",start(e){o=e},pull:S,cancel:R}),C=new ReadableStream({type:"bytes",start(e){n=e},pull:v,cancel:T});return y(i),[q,C]}(e):function(e,t){const r=e.getReader();let o,n,a,i,l,s=!1,d=!1,f=!1,h=!1;const p=u((e=>{l=e}));function m(){return s?(d=!0,c(void 0)):(s=!0,b(r.read(),(e=>{if(d=!1,e.done)return f||a.close(),h||i.close(),f&&h||l(void 0),null;const t=e.value,r=t,o=t;return f||a.enqueue(r),h||i.enqueue(o),s=!1,d&&m(),null}),(()=>(s=!1,null))),c(void 0))}function y(e){if(f=!0,o=e,h){const e=[o,n],t=r.cancel(e);l(t)}return p}function g(e){if(h=!0,n=e,f){const e=[o,n],t=r.cancel(e);l(t)}return p}const w=new ReadableStream({start(e){a=e},pull:m,cancel:y}),S=new ReadableStream({start(e){i=e},pull:m,cancel:g});return _(r.closed,(e=>(a.error(e),i.error(e),f&&h||l(void 0),null))),[w,S]}(e)}class ReadableStreamDefaultController{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!Bt(this))throw Dt("desiredSize");return Lt(this)}close(){if(!Bt(this))throw Dt("close");if(!Ft(this))throw new TypeError("The stream is not in a state that permits close");!function(e){if(!Ft(e))return;const t=e._controlledReadableStream;e._closeRequested=!0,0===e._queue.length&&(jt(e),Xt(t))}(this)}enqueue(e){if(!Bt(this))throw Dt("enqueue");if(!Ft(this))throw new TypeError("The stream is not in a state that permits enqueue");return function(e,t){if(!Ft(e))return;const r=e._controlledReadableStream;if(Ut(r)&&X(r)>0)G(r,t,!1);else{let r;try{r=e._strategySizeAlgorithm(t)}catch(t){throw zt(e,t),t}try{ue(e,t,r)}catch(t){throw zt(e,t),t}}At(e)}(this,e)}error(e){if(!Bt(this))throw Dt("error");zt(this,e)}[T](e){ce(this);const t=this._cancelAlgorithm(e);return jt(this),t}[q](e){const t=this._controlledReadableStream;if(this._queue.length>0){const r=se(this);this._closeRequested&&0===this._queue.length?(jt(this),Xt(t)):At(this),e._chunkSteps(r)}else U(t,e),At(this)}[C](){}}function Bt(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableStream")&&e instanceof ReadableStreamDefaultController)}function At(e){const t=function(e){const t=e._controlledReadableStream;if(!Ft(e))return!1;if(!e._started)return!1;if(Ut(t)&&X(t)>0)return!0;if(Lt(e)>0)return!0;return!1}(e);if(!t)return;if(e._pulling)return void(e._pullAgain=!0);e._pulling=!0;b(e._pullAlgorithm(),(()=>(e._pulling=!1,e._pullAgain&&(e._pullAgain=!1,At(e)),null)),(t=>(zt(e,t),null)))}function jt(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0,e._strategySizeAlgorithm=void 0}function zt(e,t){const r=e._controlledReadableStream;"readable"===r._state&&(ce(e),jt(e),Jt(r,t))}function Lt(e){const t=e._controlledReadableStream._state;return"errored"===t?null:"closed"===t?0:e._strategyHWM-e._queueTotalSize}function Ft(e){return!e._closeRequested&&"readable"===e._controlledReadableStream._state}function It(e,t,r,o){const n=Object.create(ReadableStreamDefaultController.prototype);let a,i,l;a=void 0!==t.start?()=>t.start(n):()=>{},i=void 0!==t.pull?()=>t.pull(n):()=>c(void 0),l=void 0!==t.cancel?e=>t.cancel(e):()=>c(void 0),function(e,t,r,o,n,a,i){t._controlledReadableStream=e,t._queue=void 0,t._queueTotalSize=void 0,ce(t),t._started=!1,t._closeRequested=!1,t._pullAgain=!1,t._pulling=!1,t._strategySizeAlgorithm=i,t._strategyHWM=a,t._pullAlgorithm=o,t._cancelAlgorithm=n,e._readableStreamController=t,b(c(r()),(()=>(t._started=!0,At(t),null)),(e=>(zt(t,e),null)))}(e,n,a,i,l,r,o)}function Dt(e){return new TypeError(`ReadableStreamDefaultController.prototype.${e} can only be used on a ReadableStreamDefaultController`)}function $t(e,t,r){return I(e,r),r=>w(e,t,[r])}function Mt(e,t,r){return I(e,r),r=>w(e,t,[r])}function Yt(e,t,r){return I(e,r),r=>g(e,t,[r])}function Qt(e,t){if("bytes"!==(e=`${e}`))throw new TypeError(`${t} '${e}' is not a valid enumeration value for ReadableStreamType`);return e}function Nt(e,t){if("byob"!==(e=`${e}`))throw new TypeError(`${t} '${e}' is not a valid enumeration value for ReadableStreamReaderMode`);return e}function Ht(e,t){F(e,t);const r=null==e?void 0:e.preventAbort,o=null==e?void 0:e.preventCancel,n=null==e?void 0:e.preventClose,a=null==e?void 0:e.signal;return void 0!==a&&function(e,t){if(!function(e){if("object"!=typeof e||null===e)return!1;try{return"boolean"==typeof e.aborted}catch(e){return!1}}(e))throw new TypeError(`${t} is not an AbortSignal.`)}(a,`${t} has member 'signal' that`),{preventAbort:Boolean(r),preventCancel:Boolean(o),preventClose:Boolean(n),signal:a}}function xt(e,t){F(e,t);const r=null==e?void 0:e.readable;M(r,"readable","ReadableWritablePair"),function(e,t){if(!H(e))throw new TypeError(`${t} is not a ReadableStream.`)}(r,`${t} has member 'readable' that`);const o=null==e?void 0:e.writable;return M(o,"writable","ReadableWritablePair"),function(e,t){if(!x(e))throw new TypeError(`${t} is not a WritableStream.`)}(o,`${t} has member 'writable' that`),{readable:r,writable:o}}Object.defineProperties(ReadableStreamDefaultController.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},desiredSize:{enumerable:!0}}),n(ReadableStreamDefaultController.prototype.close,"close"),n(ReadableStreamDefaultController.prototype.enqueue,"enqueue"),n(ReadableStreamDefaultController.prototype.error,"error"),"symbol"==typeof e.toStringTag&&Object.defineProperty(ReadableStreamDefaultController.prototype,e.toStringTag,{value:"ReadableStreamDefaultController",configurable:!0});class ReadableStream{constructor(e={},t={}){void 0===e?e=null:D(e,"First parameter");const r=Ye(t,"Second parameter"),o=function(e,t){F(e,t);const r=e,o=null==r?void 0:r.autoAllocateChunkSize,n=null==r?void 0:r.cancel,a=null==r?void 0:r.pull,i=null==r?void 0:r.start,l=null==r?void 0:r.type;return{autoAllocateChunkSize:void 0===o?void 0:N(o,`${t} has member 'autoAllocateChunkSize' that`),cancel:void 0===n?void 0:$t(n,r,`${t} has member 'cancel' that`),pull:void 0===a?void 0:Mt(a,r,`${t} has member 'pull' that`),start:void 0===i?void 0:Yt(i,r,`${t} has member 'start' that`),type:void 0===l?void 0:Qt(l,`${t} has member 'type' that`)}}(e,"First parameter");var n;if((n=this)._state="readable",n._reader=void 0,n._storedError=void 0,n._disturbed=!1,"bytes"===o.type){if(void 0!==r.size)throw new RangeError("The strategy for a byte stream cannot have a size function");Oe(this,o,$e(r,0))}else{const e=Me(r);It(this,o,$e(r,1),e)}}get locked(){if(!Vt(this))throw Kt("locked");return Ut(this)}cancel(e){return Vt(this)?Ut(this)?d(new TypeError("Cannot cancel a stream that already has a reader")):Gt(this,e):d(Kt("cancel"))}getReader(e){if(!Vt(this))throw Kt("getReader");return void 0===function(e,t){F(e,t);const r=null==e?void 0:e.mode;return{mode:void 0===r?void 0:Nt(r,`${t} has member 'mode' that`)}}(e,"First parameter").mode?new ReadableStreamDefaultReader(this):function(e){return new ReadableStreamBYOBReader(e)}(this)}pipeThrough(e,t={}){if(!H(this))throw Kt("pipeThrough");$(e,1,"pipeThrough");const r=xt(e,"First parameter"),o=Ht(t,"Second parameter");if(this.locked)throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(r.writable.locked)throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");return m(kt(this,r.writable,o.preventClose,o.preventAbort,o.preventCancel,o.signal)),r.readable}pipeTo(e,t={}){if(!H(this))return d(Kt("pipeTo"));if(void 0===e)return d("Parameter 1 is required in 'pipeTo'.");if(!x(e))return d(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));let r;try{r=Ht(t,"Second parameter")}catch(e){return d(e)}return this.locked?d(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")):e.locked?d(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")):kt(this,e,r.preventClose,r.preventAbort,r.preventCancel,r.signal)}tee(){if(!H(this))throw Kt("tee");if(this.locked)throw new TypeError("Cannot tee a stream that already has a reader");return Ot(this)}values(e){if(!H(this))throw Kt("values");return function(e,t){const r=e.getReader(),o=new te(r,t),n=Object.create(re);return n._asyncIteratorImpl=o,n}(this,function(e,t){F(e,t);const r=null==e?void 0:e.preventCancel;return{preventCancel:Boolean(r)}}(e,"First parameter").preventCancel)}}function Vt(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readableStreamController")&&e instanceof ReadableStream)}function Ut(e){return void 0!==e._reader}function Gt(e,r){if(e._disturbed=!0,"closed"===e._state)return c(void 0);if("errored"===e._state)return d(e._storedError);Xt(e);const o=e._reader;if(void 0!==o&&Fe(o)){const e=o._readIntoRequests;o._readIntoRequests=new S,e.forEach((e=>{e._closeSteps(void 0)}))}return p(e._readableStreamController[T](r),t)}function Xt(e){e._state="closed";const t=e._reader;if(void 0!==t&&(j(t),K(t))){const e=t._readRequests;t._readRequests=new S,e.forEach((e=>{e._closeSteps()}))}}function Jt(e,t){e._state="errored",e._storedError=t;const r=e._reader;void 0!==r&&(A(r,t),K(r)?Z(r,t):Ie(r,t))}function Kt(e){return new TypeError(`ReadableStream.prototype.${e} can only be used on a ReadableStream`)}function Zt(e,t){F(e,t);const r=null==e?void 0:e.highWaterMark;return M(r,"highWaterMark","QueuingStrategyInit"),{highWaterMark:Y(r)}}Object.defineProperties(ReadableStream.prototype,{cancel:{enumerable:!0},getReader:{enumerable:!0},pipeThrough:{enumerable:!0},pipeTo:{enumerable:!0},tee:{enumerable:!0},values:{enumerable:!0},locked:{enumerable:!0}}),n(ReadableStream.prototype.cancel,"cancel"),n(ReadableStream.prototype.getReader,"getReader"),n(ReadableStream.prototype.pipeThrough,"pipeThrough"),n(ReadableStream.prototype.pipeTo,"pipeTo"),n(ReadableStream.prototype.tee,"tee"),n(ReadableStream.prototype.values,"values"),"symbol"==typeof e.toStringTag&&Object.defineProperty(ReadableStream.prototype,e.toStringTag,{value:"ReadableStream",configurable:!0}),"symbol"==typeof e.asyncIterator&&Object.defineProperty(ReadableStream.prototype,e.asyncIterator,{value:ReadableStream.prototype.values,writable:!0,configurable:!0});const er=e=>e.byteLength;n(er,"size");class ByteLengthQueuingStrategy{constructor(e){$(e,1,"ByteLengthQueuingStrategy"),e=Zt(e,"First parameter"),this._byteLengthQueuingStrategyHighWaterMark=e.highWaterMark}get highWaterMark(){if(!rr(this))throw tr("highWaterMark");return this._byteLengthQueuingStrategyHighWaterMark}get size(){if(!rr(this))throw tr("size");return er}}function tr(e){return new TypeError(`ByteLengthQueuingStrategy.prototype.${e} can only be used on a ByteLengthQueuingStrategy`)}function rr(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_byteLengthQueuingStrategyHighWaterMark")&&e instanceof ByteLengthQueuingStrategy)}Object.defineProperties(ByteLengthQueuingStrategy.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),"symbol"==typeof e.toStringTag&&Object.defineProperty(ByteLengthQueuingStrategy.prototype,e.toStringTag,{value:"ByteLengthQueuingStrategy",configurable:!0});const or=()=>1;n(or,"size");class CountQueuingStrategy{constructor(e){$(e,1,"CountQueuingStrategy"),e=Zt(e,"First parameter"),this._countQueuingStrategyHighWaterMark=e.highWaterMark}get highWaterMark(){if(!ar(this))throw nr("highWaterMark");return this._countQueuingStrategyHighWaterMark}get size(){if(!ar(this))throw nr("size");return or}}function nr(e){return new TypeError(`CountQueuingStrategy.prototype.${e} can only be used on a CountQueuingStrategy`)}function ar(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_countQueuingStrategyHighWaterMark")&&e instanceof CountQueuingStrategy)}function ir(e,t,r){return I(e,r),r=>w(e,t,[r])}function lr(e,t,r){return I(e,r),r=>g(e,t,[r])}function sr(e,t,r){return I(e,r),(r,o)=>w(e,t,[r,o])}Object.defineProperties(CountQueuingStrategy.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),"symbol"==typeof e.toStringTag&&Object.defineProperty(CountQueuingStrategy.prototype,e.toStringTag,{value:"CountQueuingStrategy",configurable:!0});class TransformStream{constructor(e={},t={},r={}){void 0===e&&(e=null);const o=Ye(t,"Second parameter"),n=Ye(r,"Third parameter"),a=function(e,t){F(e,t);const r=null==e?void 0:e.flush,o=null==e?void 0:e.readableType,n=null==e?void 0:e.start,a=null==e?void 0:e.transform,i=null==e?void 0:e.writableType;return{flush:void 0===r?void 0:ir(r,e,`${t} has member 'flush' that`),readableType:o,start:void 0===n?void 0:lr(n,e,`${t} has member 'start' that`),transform:void 0===a?void 0:sr(a,e,`${t} has member 'transform' that`),writableType:i}}(e,"First parameter");if(void 0!==a.readableType)throw new RangeError("Invalid readableType specified");if(void 0!==a.writableType)throw new RangeError("Invalid writableType specified");const i=$e(n,0),l=Me(n),s=$e(o,1),f=Me(o);let b;!function(e,t,r,o,n,a){function i(){return t}function l(t){return function(e,t){const r=e._transformStreamController;if(e._backpressure){return p(e._backpressureChangePromise,(()=>{if("erroring"===(Ge(e._writable)?e._writable._state:e._writableState))throw Ge(e._writable)?e._writable._storedError:e._writableStoredError;return pr(r,t)}))}return pr(r,t)}(e,t)}function s(t){return function(e,t){return cr(e,t),c(void 0)}(e,t)}function u(){return function(e){const t=e._transformStreamController,r=t._flushAlgorithm();return hr(t),p(r,(()=>{if("errored"===e._readableState)throw e._readableStoredError;gr(e)&&wr(e)}),(t=>{throw cr(e,t),e._readableStoredError}))}(e)}function d(){return function(e){return fr(e,!1),e._backpressureChangePromise}(e)}function f(t){return dr(e,t),c(void 0)}e._writableState="writable",e._writableStoredError=void 0,e._writableHasInFlightOperation=!1,e._writableStarted=!1,e._writable=function(e,t,r,o,n,a,i){return new WritableStream({start(r){e._writableController=r;try{const t=r.signal;void 0!==t&&t.addEventListener("abort",(()=>{"writable"===e._writableState&&(e._writableState="erroring",t.reason&&(e._writableStoredError=t.reason))}))}catch(e){}return p(t(),(()=>(e._writableStarted=!0,Cr(e),null)),(t=>{throw e._writableStarted=!0,Rr(e,t),t}))},write:t=>(function(e){e._writableHasInFlightOperation=!0}(e),p(r(t),(()=>(function(e){e._writableHasInFlightOperation=!1}(e),Cr(e),null)),(t=>{throw function(e,t){e._writableHasInFlightOperation=!1,Rr(e,t)}(e,t),t}))),close:()=>(function(e){e._writableHasInFlightOperation=!0}(e),p(o(),(()=>(function(e){e._writableHasInFlightOperation=!1;"erroring"===e._writableState&&(e._writableStoredError=void 0);e._writableState="closed"}(e),null)),(t=>{throw function(e,t){e._writableHasInFlightOperation=!1,e._writableState,Rr(e,t)}(e,t),t}))),abort:t=>(e._writableState="errored",e._writableStoredError=t,n(t))},{highWaterMark:a,size:i})}(e,i,l,u,s,r,o),e._readableState="readable",e._readableStoredError=void 0,e._readableCloseRequested=!1,e._readablePulling=!1,e._readable=function(e,t,r,o,n,a){return new ReadableStream({start:r=>(e._readableController=r,t().catch((t=>{Sr(e,t)}))),pull:()=>(e._readablePulling=!0,r().catch((t=>{Sr(e,t)}))),cancel:t=>(e._readableState="closed",o(t))},{highWaterMark:n,size:a})}(e,i,d,f,n,a),e._backpressure=void 0,e._backpressureChangePromise=void 0,e._backpressureChangePromise_resolve=void 0,fr(e,!0),e._transformStreamController=void 0}(this,u((e=>{b=e})),s,f,i,l),function(e,t){const r=Object.create(TransformStreamDefaultController.prototype);let o,n;o=void 0!==t.transform?e=>t.transform(e,r):e=>{try{return _r(r,e),c(void 0)}catch(e){return d(e)}};n=void 0!==t.flush?()=>t.flush(r):()=>c(void 0);!function(e,t,r,o){t._controlledTransformStream=e,e._transformStreamController=t,t._transformAlgorithm=r,t._flushAlgorithm=o}(e,r,o,n)}(this,a),void 0!==a.start?b(a.start(this._transformStreamController)):b(void 0)}get readable(){if(!ur(this))throw yr("readable");return this._readable}get writable(){if(!ur(this))throw yr("writable");return this._writable}}function ur(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_transformStreamController")&&e instanceof TransformStream)}function cr(e,t){Sr(e,t),dr(e,t)}function dr(e,t){hr(e._transformStreamController),function(e,t){e._writableController.error(t);"writable"===e._writableState&&Tr(e,t)}(e,t),e._backpressure&&fr(e,!1)}function fr(e,t){void 0!==e._backpressureChangePromise&&e._backpressureChangePromise_resolve(),e._backpressureChangePromise=u((t=>{e._backpressureChangePromise_resolve=t})),e._backpressure=t}Object.defineProperties(TransformStream.prototype,{readable:{enumerable:!0},writable:{enumerable:!0}}),"symbol"==typeof e.toStringTag&&Object.defineProperty(TransformStream.prototype,e.toStringTag,{value:"TransformStream",configurable:!0});class TransformStreamDefaultController{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!br(this))throw mr("desiredSize");return vr(this._controlledTransformStream)}enqueue(e){if(!br(this))throw mr("enqueue");_r(this,e)}error(e){if(!br(this))throw mr("error");var t;t=e,cr(this._controlledTransformStream,t)}terminate(){if(!br(this))throw mr("terminate");!function(e){const t=e._controlledTransformStream;gr(t)&&wr(t);const r=new TypeError("TransformStream terminated");dr(t,r)}(this)}}function br(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledTransformStream")&&e instanceof TransformStreamDefaultController)}function hr(e){e._transformAlgorithm=void 0,e._flushAlgorithm=void 0}function _r(e,t){const r=e._controlledTransformStream;if(!gr(r))throw new TypeError("Readable side is not in a state that permits enqueue");try{!function(e,t){e._readablePulling=!1;try{e._readableController.enqueue(t)}catch(t){throw Sr(e,t),t}}(r,t)}catch(e){throw dr(r,e),r._readableStoredError}const o=function(e){return!function(e){if(!gr(e))return!1;if(e._readablePulling)return!0;if(vr(e)>0)return!0;return!1}(e)}(r);o!==r._backpressure&&fr(r,!0)}function pr(e,t){return p(e._transformAlgorithm(t),void 0,(t=>{throw cr(e._controlledTransformStream,t),t}))}function mr(e){return new TypeError(`TransformStreamDefaultController.prototype.${e} can only be used on a TransformStreamDefaultController`)}function yr(e){return new TypeError(`TransformStream.prototype.${e} can only be used on a TransformStream`)}function gr(e){return!e._readableCloseRequested&&"readable"===e._readableState}function wr(e){e._readableState="closed",e._readableCloseRequested=!0,e._readableController.close()}function Sr(e,t){"readable"===e._readableState&&(e._readableState="errored",e._readableStoredError=t),e._readableController.error(t)}function vr(e){return e._readableController.desiredSize}function Rr(e,t){"writable"!==e._writableState?qr(e):Tr(e,t)}function Tr(e,t){e._writableState="erroring",e._writableStoredError=t,!function(e){return e._writableHasInFlightOperation}(e)&&e._writableStarted&&qr(e)}function qr(e){e._writableState="errored"}function Cr(e){"erroring"===e._writableState&&qr(e)}Object.defineProperties(TransformStreamDefaultController.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),n(TransformStreamDefaultController.prototype.enqueue,"enqueue"),n(TransformStreamDefaultController.prototype.error,"error"),n(TransformStreamDefaultController.prototype.terminate,"terminate"),"symbol"==typeof e.toStringTag&&Object.defineProperty(TransformStreamDefaultController.prototype,e.toStringTag,{value:"TransformStreamDefaultController",configurable:!0}); - -// EXTERNAL MODULE: ./node_modules/formdata-node/lib/esm/isFunction.js -var isFunction = __nccwpck_require__(5122); -;// CONCATENATED MODULE: ./node_modules/formdata-node/lib/esm/blobHelpers.js -/*! Based on fetch-blob. MIT License. Jimmy Wärting & David Frank */ - -const CHUNK_SIZE = 65536; -async function* clonePart(part) { - const end = part.byteOffset + part.byteLength; - let position = part.byteOffset; - while (position !== end) { - const size = Math.min(end - position, CHUNK_SIZE); - const chunk = part.buffer.slice(position, position + size); - position += chunk.byteLength; - yield new Uint8Array(chunk); + // NOTE: The order matters here! + const browserPatterns = [ + { key: 'edge', pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: 'ie', pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: 'ie', pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: 'chrome', pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: 'firefox', pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: 'safari', pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ }, + ]; + // Find the FIRST matching browser + for (const { key, pattern } of browserPatterns) { + const match = pattern.exec(navigator.userAgent); + if (match) { + const major = match[1] || 0; + const minor = match[2] || 0; + const patch = match[3] || 0; + return { browser: key, version: `${major}.${minor}.${patch}` }; + } } + return null; } -async function* consumeNodeBlob(blob) { - let position = 0; - while (position !== blob.size) { - const chunk = blob.slice(position, Math.min(blob.size, position + CHUNK_SIZE)); - const buffer = await chunk.arrayBuffer(); - position += buffer.byteLength; - yield new Uint8Array(buffer); +const normalizeArch = (arch) => { + // Node docs: + // - https://nodejs.org/api/process.html#processarch + // Deno docs: + // - https://doc.deno.land/deno/stable/~/Deno.build + if (arch === 'x32') + return 'x32'; + if (arch === 'x86_64' || arch === 'x64') + return 'x64'; + if (arch === 'arm') + return 'arm'; + if (arch === 'aarch64' || arch === 'arm64') + return 'arm64'; + if (arch) + return `other:${arch}`; + return 'unknown'; +}; +const normalizePlatform = (platform) => { + // Node platforms: + // - https://nodejs.org/api/process.html#processplatform + // Deno platforms: + // - https://doc.deno.land/deno/stable/~/Deno.build + // - https://github.com/denoland/deno/issues/14799 + platform = platform.toLowerCase(); + // NOTE: this iOS check is untested and may not work + // Node does not work natively on IOS, there is a fork at + // https://github.com/nodejs-mobile/nodejs-mobile + // however it is unknown at the time of writing how to detect if it is running + if (platform.includes('ios')) + return 'iOS'; + if (platform === 'android') + return 'Android'; + if (platform === 'darwin') + return 'MacOS'; + if (platform === 'win32') + return 'Windows'; + if (platform === 'freebsd') + return 'FreeBSD'; + if (platform === 'openbsd') + return 'OpenBSD'; + if (platform === 'linux') + return 'Linux'; + if (platform) + return `Other:${platform}`; + return 'Unknown'; +}; +let _platformHeaders; +const getPlatformHeaders = () => { + return (_platformHeaders ?? (_platformHeaders = getPlatformProperties())); +}; +//# sourceMappingURL=detect-platform.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/internal/shims.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +function getDefaultFetch() { + if (typeof fetch !== 'undefined') { + return fetch; } + throw new Error('`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`'); } -async function* consumeBlobParts(parts, clone = false) { - for (const part of parts) { - if (ArrayBuffer.isView(part)) { - if (clone) { - yield* clonePart(part); - } - else { - yield part; - } - } - else if ((0,isFunction/* isFunction */.T)(part.stream)) { - yield* part.stream(); - } - else { - yield* consumeNodeBlob(part); - } - } -} -function* sliceBlob(blobParts, blobSize, start = 0, end) { - end !== null && end !== void 0 ? end : (end = blobSize); - let relativeStart = start < 0 - ? Math.max(blobSize + start, 0) - : Math.min(start, blobSize); - let relativeEnd = end < 0 - ? Math.max(blobSize + end, 0) - : Math.min(end, blobSize); - const span = Math.max(relativeEnd - relativeStart, 0); - let added = 0; - for (const part of blobParts) { - if (added >= span) { - break; - } - const partSize = ArrayBuffer.isView(part) ? part.byteLength : part.size; - if (relativeStart && partSize <= relativeStart) { - relativeStart -= partSize; - relativeEnd -= partSize; - } - else { - let chunk; - if (ArrayBuffer.isView(part)) { - chunk = part.subarray(relativeStart, Math.min(partSize, relativeEnd)); - added += chunk.byteLength; - } - else { - chunk = part.slice(relativeStart, Math.min(partSize, relativeEnd)); - added += chunk.size; - } - relativeEnd -= partSize; - relativeStart = 0; - yield chunk; - } +function makeReadableStream(...args) { + const ReadableStream = globalThis.ReadableStream; + if (typeof ReadableStream === 'undefined') { + // Note: All of the platforms / runtimes we officially support already define + // `ReadableStream` as a global, so this should only ever be hit on unsupported runtimes. + throw new Error('`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`'); } + return new ReadableStream(...args); } - -;// CONCATENATED MODULE: ./node_modules/formdata-node/lib/esm/Blob.js -/*! Based on fetch-blob. MIT License. Jimmy Wärting & David Frank */ -var __classPrivateFieldGet = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) { - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); -}; -var __classPrivateFieldSet = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { - if (kind === "m") throw new TypeError("Private method is not writable"); - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); - return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; -}; -var _Blob_parts, _Blob_type, _Blob_size; - - - -class Blob { - constructor(blobParts = [], options = {}) { - _Blob_parts.set(this, []); - _Blob_type.set(this, ""); - _Blob_size.set(this, 0); - options !== null && options !== void 0 ? options : (options = {}); - if (typeof blobParts !== "object" || blobParts === null) { - throw new TypeError("Failed to construct 'Blob': " - + "The provided value cannot be converted to a sequence."); - } - if (!(0,isFunction/* isFunction */.T)(blobParts[Symbol.iterator])) { - throw new TypeError("Failed to construct 'Blob': " - + "The object must have a callable @@iterator property."); - } - if (typeof options !== "object" && !(0,isFunction/* isFunction */.T)(options)) { - throw new TypeError("Failed to construct 'Blob': parameter 2 cannot convert to dictionary."); - } - const encoder = new TextEncoder(); - for (const raw of blobParts) { - let part; - if (ArrayBuffer.isView(raw)) { - part = new Uint8Array(raw.buffer.slice(raw.byteOffset, raw.byteOffset + raw.byteLength)); - } - else if (raw instanceof ArrayBuffer) { - part = new Uint8Array(raw.slice(0)); - } - else if (raw instanceof Blob) { - part = raw; +function ReadableStreamFrom(iterable) { + let iter = Symbol.asyncIterator in iterable ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator](); + return makeReadableStream({ + start() { }, + async pull(controller) { + const { done, value } = await iter.next(); + if (done) { + controller.close(); } else { - part = encoder.encode(String(raw)); - } - __classPrivateFieldSet(this, _Blob_size, __classPrivateFieldGet(this, _Blob_size, "f") + (ArrayBuffer.isView(part) ? part.byteLength : part.size), "f"); - __classPrivateFieldGet(this, _Blob_parts, "f").push(part); - } - const type = options.type === undefined ? "" : String(options.type); - __classPrivateFieldSet(this, _Blob_type, /^[\x20-\x7E]*$/.test(type) ? type : "", "f"); - } - static [(_Blob_parts = new WeakMap(), _Blob_type = new WeakMap(), _Blob_size = new WeakMap(), Symbol.hasInstance)](value) { - return Boolean(value - && typeof value === "object" - && (0,isFunction/* isFunction */.T)(value.constructor) - && ((0,isFunction/* isFunction */.T)(value.stream) - || (0,isFunction/* isFunction */.T)(value.arrayBuffer)) - && /^(Blob|File)$/.test(value[Symbol.toStringTag])); - } - get type() { - return __classPrivateFieldGet(this, _Blob_type, "f"); - } - get size() { - return __classPrivateFieldGet(this, _Blob_size, "f"); - } - slice(start, end, contentType) { - return new Blob(sliceBlob(__classPrivateFieldGet(this, _Blob_parts, "f"), this.size, start, end), { - type: contentType - }); - } - async text() { - const decoder = new TextDecoder(); - let result = ""; - for await (const chunk of consumeBlobParts(__classPrivateFieldGet(this, _Blob_parts, "f"))) { - result += decoder.decode(chunk, { stream: true }); - } - result += decoder.decode(); - return result; - } - async arrayBuffer() { - const view = new Uint8Array(this.size); - let offset = 0; - for await (const chunk of consumeBlobParts(__classPrivateFieldGet(this, _Blob_parts, "f"))) { - view.set(chunk, offset); - offset += chunk.length; - } - return view.buffer; - } - stream() { - const iterator = consumeBlobParts(__classPrivateFieldGet(this, _Blob_parts, "f"), true); - return new ReadableStream({ - async pull(controller) { - const { value, done } = await iterator.next(); - if (done) { - return queueMicrotask(() => controller.close()); - } controller.enqueue(value); - }, - async cancel() { - await iterator.return(); } - }); - } - get [Symbol.toStringTag]() { - return "Blob"; - } + }, + async cancel() { + await iter.return?.(); + }, + }); } -Object.defineProperties(Blob.prototype, { - type: { enumerable: true }, - size: { enumerable: true }, - slice: { enumerable: true }, - stream: { enumerable: true }, - text: { enumerable: true }, - arrayBuffer: { enumerable: true } -}); - - -/***/ }), - -/***/ 2928: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => { - -/* harmony export */ __nccwpck_require__.d(__webpack_exports__, { -/* harmony export */ Z: () => (/* binding */ File) -/* harmony export */ }); -/* harmony import */ var _Blob_js__WEBPACK_IMPORTED_MODULE_0__ = __nccwpck_require__(6220); -var __classPrivateFieldSet = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { - if (kind === "m") throw new TypeError("Private method is not writable"); - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); - return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; -}; -var __classPrivateFieldGet = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) { - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); -}; -var _File_name, _File_lastModified; - -class File extends _Blob_js__WEBPACK_IMPORTED_MODULE_0__/* .Blob */ .Y { - constructor(fileBits, name, options = {}) { - super(fileBits, options); - _File_name.set(this, void 0); - _File_lastModified.set(this, 0); - if (arguments.length < 2) { - throw new TypeError("Failed to construct 'File': 2 arguments required, " - + `but only ${arguments.length} present.`); - } - __classPrivateFieldSet(this, _File_name, String(name), "f"); - const lastModified = options.lastModified === undefined - ? Date.now() - : Number(options.lastModified); - if (!Number.isNaN(lastModified)) { - __classPrivateFieldSet(this, _File_lastModified, lastModified, "f"); - } - } - static [(_File_name = new WeakMap(), _File_lastModified = new WeakMap(), Symbol.hasInstance)](value) { - return value instanceof _Blob_js__WEBPACK_IMPORTED_MODULE_0__/* .Blob */ .Y - && value[Symbol.toStringTag] === "File" - && typeof value.name === "string"; - } - get name() { - return __classPrivateFieldGet(this, _File_name, "f"); - } - get lastModified() { - return __classPrivateFieldGet(this, _File_lastModified, "f"); - } - get webkitRelativePath() { - return ""; - } - get [Symbol.toStringTag]() { - return "File"; +/** + * Most browsers don't yet have async iterable support for ReadableStream, + * and Node has a very different way of reading bytes from its "ReadableStream". + * + * This polyfill was pulled from https://github.com/MattiasBuelens/web-streams-polyfill/pull/122#issuecomment-1627354490 + */ +function ReadableStreamToAsyncIterable(stream) { + if (stream[Symbol.asyncIterator]) + return stream; + const reader = stream.getReader(); + return { + async next() { + try { + const result = await reader.read(); + if (result?.done) + reader.releaseLock(); // release lock when stream becomes closed + return result; + } + catch (e) { + reader.releaseLock(); // release lock when stream becomes errored + throw e; + } + }, + async return() { + const cancelPromise = reader.cancel(); + reader.releaseLock(); + await cancelPromise; + return { done: true, value: undefined }; + }, + [Symbol.asyncIterator]() { + return this; + }, + }; +} +/** + * Cancels a ReadableStream we don't need to consume. + * See https://undici.nodejs.org/#/?id=garbage-collection + */ +async function CancelReadableStream(stream) { + if (stream === null || typeof stream !== 'object') + return; + if (stream[Symbol.asyncIterator]) { + await stream[Symbol.asyncIterator]().return?.(); + return; } + const reader = stream.getReader(); + const cancelPromise = reader.cancel(); + reader.releaseLock(); + await cancelPromise; } - - -/***/ }), - -/***/ 928: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => { - -/* harmony export */ __nccwpck_require__.d(__webpack_exports__, { -/* harmony export */ f: () => (/* binding */ isFile) -/* harmony export */ }); -/* harmony import */ var _File_js__WEBPACK_IMPORTED_MODULE_0__ = __nccwpck_require__(2928); - -const isFile = (value) => value instanceof _File_js__WEBPACK_IMPORTED_MODULE_0__/* .File */ .Z; - - -/***/ }), - -/***/ 5122: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => { - -/* harmony export */ __nccwpck_require__.d(__webpack_exports__, { -/* harmony export */ T: () => (/* binding */ isFunction) -/* harmony export */ }); -const isFunction = (value) => (typeof value === "function"); - - -/***/ }), - -/***/ 2472: -/***/ ((module) => { - -module.exports = /*#__PURE__*/JSON.parse('[[[0,44],"disallowed_STD3_valid"],[[45,46],"valid"],[[47,47],"disallowed_STD3_valid"],[[48,57],"valid"],[[58,64],"disallowed_STD3_valid"],[[65,65],"mapped",[97]],[[66,66],"mapped",[98]],[[67,67],"mapped",[99]],[[68,68],"mapped",[100]],[[69,69],"mapped",[101]],[[70,70],"mapped",[102]],[[71,71],"mapped",[103]],[[72,72],"mapped",[104]],[[73,73],"mapped",[105]],[[74,74],"mapped",[106]],[[75,75],"mapped",[107]],[[76,76],"mapped",[108]],[[77,77],"mapped",[109]],[[78,78],"mapped",[110]],[[79,79],"mapped",[111]],[[80,80],"mapped",[112]],[[81,81],"mapped",[113]],[[82,82],"mapped",[114]],[[83,83],"mapped",[115]],[[84,84],"mapped",[116]],[[85,85],"mapped",[117]],[[86,86],"mapped",[118]],[[87,87],"mapped",[119]],[[88,88],"mapped",[120]],[[89,89],"mapped",[121]],[[90,90],"mapped",[122]],[[91,96],"disallowed_STD3_valid"],[[97,122],"valid"],[[123,127],"disallowed_STD3_valid"],[[128,159],"disallowed"],[[160,160],"disallowed_STD3_mapped",[32]],[[161,167],"valid",[],"NV8"],[[168,168],"disallowed_STD3_mapped",[32,776]],[[169,169],"valid",[],"NV8"],[[170,170],"mapped",[97]],[[171,172],"valid",[],"NV8"],[[173,173],"ignored"],[[174,174],"valid",[],"NV8"],[[175,175],"disallowed_STD3_mapped",[32,772]],[[176,177],"valid",[],"NV8"],[[178,178],"mapped",[50]],[[179,179],"mapped",[51]],[[180,180],"disallowed_STD3_mapped",[32,769]],[[181,181],"mapped",[956]],[[182,182],"valid",[],"NV8"],[[183,183],"valid"],[[184,184],"disallowed_STD3_mapped",[32,807]],[[185,185],"mapped",[49]],[[186,186],"mapped",[111]],[[187,187],"valid",[],"NV8"],[[188,188],"mapped",[49,8260,52]],[[189,189],"mapped",[49,8260,50]],[[190,190],"mapped",[51,8260,52]],[[191,191],"valid",[],"NV8"],[[192,192],"mapped",[224]],[[193,193],"mapped",[225]],[[194,194],"mapped",[226]],[[195,195],"mapped",[227]],[[196,196],"mapped",[228]],[[197,197],"mapped",[229]],[[198,198],"mapped",[230]],[[199,199],"mapped",[231]],[[200,200],"mapped",[232]],[[201,201],"mapped",[233]],[[202,202],"mapped",[234]],[[203,203],"mapped",[235]],[[204,204],"mapped",[236]],[[205,205],"mapped",[237]],[[206,206],"mapped",[238]],[[207,207],"mapped",[239]],[[208,208],"mapped",[240]],[[209,209],"mapped",[241]],[[210,210],"mapped",[242]],[[211,211],"mapped",[243]],[[212,212],"mapped",[244]],[[213,213],"mapped",[245]],[[214,214],"mapped",[246]],[[215,215],"valid",[],"NV8"],[[216,216],"mapped",[248]],[[217,217],"mapped",[249]],[[218,218],"mapped",[250]],[[219,219],"mapped",[251]],[[220,220],"mapped",[252]],[[221,221],"mapped",[253]],[[222,222],"mapped",[254]],[[223,223],"deviation",[115,115]],[[224,246],"valid"],[[247,247],"valid",[],"NV8"],[[248,255],"valid"],[[256,256],"mapped",[257]],[[257,257],"valid"],[[258,258],"mapped",[259]],[[259,259],"valid"],[[260,260],"mapped",[261]],[[261,261],"valid"],[[262,262],"mapped",[263]],[[263,263],"valid"],[[264,264],"mapped",[265]],[[265,265],"valid"],[[266,266],"mapped",[267]],[[267,267],"valid"],[[268,268],"mapped",[269]],[[269,269],"valid"],[[270,270],"mapped",[271]],[[271,271],"valid"],[[272,272],"mapped",[273]],[[273,273],"valid"],[[274,274],"mapped",[275]],[[275,275],"valid"],[[276,276],"mapped",[277]],[[277,277],"valid"],[[278,278],"mapped",[279]],[[279,279],"valid"],[[280,280],"mapped",[281]],[[281,281],"valid"],[[282,282],"mapped",[283]],[[283,283],"valid"],[[284,284],"mapped",[285]],[[285,285],"valid"],[[286,286],"mapped",[287]],[[287,287],"valid"],[[288,288],"mapped",[289]],[[289,289],"valid"],[[290,290],"mapped",[291]],[[291,291],"valid"],[[292,292],"mapped",[293]],[[293,293],"valid"],[[294,294],"mapped",[295]],[[295,295],"valid"],[[296,296],"mapped",[297]],[[297,297],"valid"],[[298,298],"mapped",[299]],[[299,299],"valid"],[[300,300],"mapped",[301]],[[301,301],"valid"],[[302,302],"mapped",[303]],[[303,303],"valid"],[[304,304],"mapped",[105,775]],[[305,305],"valid"],[[306,307],"mapped",[105,106]],[[308,308],"mapped",[309]],[[309,309],"valid"],[[310,310],"mapped",[311]],[[311,312],"valid"],[[313,313],"mapped",[314]],[[314,314],"valid"],[[315,315],"mapped",[316]],[[316,316],"valid"],[[317,317],"mapped",[318]],[[318,318],"valid"],[[319,320],"mapped",[108,183]],[[321,321],"mapped",[322]],[[322,322],"valid"],[[323,323],"mapped",[324]],[[324,324],"valid"],[[325,325],"mapped",[326]],[[326,326],"valid"],[[327,327],"mapped",[328]],[[328,328],"valid"],[[329,329],"mapped",[700,110]],[[330,330],"mapped",[331]],[[331,331],"valid"],[[332,332],"mapped",[333]],[[333,333],"valid"],[[334,334],"mapped",[335]],[[335,335],"valid"],[[336,336],"mapped",[337]],[[337,337],"valid"],[[338,338],"mapped",[339]],[[339,339],"valid"],[[340,340],"mapped",[341]],[[341,341],"valid"],[[342,342],"mapped",[343]],[[343,343],"valid"],[[344,344],"mapped",[345]],[[345,345],"valid"],[[346,346],"mapped",[347]],[[347,347],"valid"],[[348,348],"mapped",[349]],[[349,349],"valid"],[[350,350],"mapped",[351]],[[351,351],"valid"],[[352,352],"mapped",[353]],[[353,353],"valid"],[[354,354],"mapped",[355]],[[355,355],"valid"],[[356,356],"mapped",[357]],[[357,357],"valid"],[[358,358],"mapped",[359]],[[359,359],"valid"],[[360,360],"mapped",[361]],[[361,361],"valid"],[[362,362],"mapped",[363]],[[363,363],"valid"],[[364,364],"mapped",[365]],[[365,365],"valid"],[[366,366],"mapped",[367]],[[367,367],"valid"],[[368,368],"mapped",[369]],[[369,369],"valid"],[[370,370],"mapped",[371]],[[371,371],"valid"],[[372,372],"mapped",[373]],[[373,373],"valid"],[[374,374],"mapped",[375]],[[375,375],"valid"],[[376,376],"mapped",[255]],[[377,377],"mapped",[378]],[[378,378],"valid"],[[379,379],"mapped",[380]],[[380,380],"valid"],[[381,381],"mapped",[382]],[[382,382],"valid"],[[383,383],"mapped",[115]],[[384,384],"valid"],[[385,385],"mapped",[595]],[[386,386],"mapped",[387]],[[387,387],"valid"],[[388,388],"mapped",[389]],[[389,389],"valid"],[[390,390],"mapped",[596]],[[391,391],"mapped",[392]],[[392,392],"valid"],[[393,393],"mapped",[598]],[[394,394],"mapped",[599]],[[395,395],"mapped",[396]],[[396,397],"valid"],[[398,398],"mapped",[477]],[[399,399],"mapped",[601]],[[400,400],"mapped",[603]],[[401,401],"mapped",[402]],[[402,402],"valid"],[[403,403],"mapped",[608]],[[404,404],"mapped",[611]],[[405,405],"valid"],[[406,406],"mapped",[617]],[[407,407],"mapped",[616]],[[408,408],"mapped",[409]],[[409,411],"valid"],[[412,412],"mapped",[623]],[[413,413],"mapped",[626]],[[414,414],"valid"],[[415,415],"mapped",[629]],[[416,416],"mapped",[417]],[[417,417],"valid"],[[418,418],"mapped",[419]],[[419,419],"valid"],[[420,420],"mapped",[421]],[[421,421],"valid"],[[422,422],"mapped",[640]],[[423,423],"mapped",[424]],[[424,424],"valid"],[[425,425],"mapped",[643]],[[426,427],"valid"],[[428,428],"mapped",[429]],[[429,429],"valid"],[[430,430],"mapped",[648]],[[431,431],"mapped",[432]],[[432,432],"valid"],[[433,433],"mapped",[650]],[[434,434],"mapped",[651]],[[435,435],"mapped",[436]],[[436,436],"valid"],[[437,437],"mapped",[438]],[[438,438],"valid"],[[439,439],"mapped",[658]],[[440,440],"mapped",[441]],[[441,443],"valid"],[[444,444],"mapped",[445]],[[445,451],"valid"],[[452,454],"mapped",[100,382]],[[455,457],"mapped",[108,106]],[[458,460],"mapped",[110,106]],[[461,461],"mapped",[462]],[[462,462],"valid"],[[463,463],"mapped",[464]],[[464,464],"valid"],[[465,465],"mapped",[466]],[[466,466],"valid"],[[467,467],"mapped",[468]],[[468,468],"valid"],[[469,469],"mapped",[470]],[[470,470],"valid"],[[471,471],"mapped",[472]],[[472,472],"valid"],[[473,473],"mapped",[474]],[[474,474],"valid"],[[475,475],"mapped",[476]],[[476,477],"valid"],[[478,478],"mapped",[479]],[[479,479],"valid"],[[480,480],"mapped",[481]],[[481,481],"valid"],[[482,482],"mapped",[483]],[[483,483],"valid"],[[484,484],"mapped",[485]],[[485,485],"valid"],[[486,486],"mapped",[487]],[[487,487],"valid"],[[488,488],"mapped",[489]],[[489,489],"valid"],[[490,490],"mapped",[491]],[[491,491],"valid"],[[492,492],"mapped",[493]],[[493,493],"valid"],[[494,494],"mapped",[495]],[[495,496],"valid"],[[497,499],"mapped",[100,122]],[[500,500],"mapped",[501]],[[501,501],"valid"],[[502,502],"mapped",[405]],[[503,503],"mapped",[447]],[[504,504],"mapped",[505]],[[505,505],"valid"],[[506,506],"mapped",[507]],[[507,507],"valid"],[[508,508],"mapped",[509]],[[509,509],"valid"],[[510,510],"mapped",[511]],[[511,511],"valid"],[[512,512],"mapped",[513]],[[513,513],"valid"],[[514,514],"mapped",[515]],[[515,515],"valid"],[[516,516],"mapped",[517]],[[517,517],"valid"],[[518,518],"mapped",[519]],[[519,519],"valid"],[[520,520],"mapped",[521]],[[521,521],"valid"],[[522,522],"mapped",[523]],[[523,523],"valid"],[[524,524],"mapped",[525]],[[525,525],"valid"],[[526,526],"mapped",[527]],[[527,527],"valid"],[[528,528],"mapped",[529]],[[529,529],"valid"],[[530,530],"mapped",[531]],[[531,531],"valid"],[[532,532],"mapped",[533]],[[533,533],"valid"],[[534,534],"mapped",[535]],[[535,535],"valid"],[[536,536],"mapped",[537]],[[537,537],"valid"],[[538,538],"mapped",[539]],[[539,539],"valid"],[[540,540],"mapped",[541]],[[541,541],"valid"],[[542,542],"mapped",[543]],[[543,543],"valid"],[[544,544],"mapped",[414]],[[545,545],"valid"],[[546,546],"mapped",[547]],[[547,547],"valid"],[[548,548],"mapped",[549]],[[549,549],"valid"],[[550,550],"mapped",[551]],[[551,551],"valid"],[[552,552],"mapped",[553]],[[553,553],"valid"],[[554,554],"mapped",[555]],[[555,555],"valid"],[[556,556],"mapped",[557]],[[557,557],"valid"],[[558,558],"mapped",[559]],[[559,559],"valid"],[[560,560],"mapped",[561]],[[561,561],"valid"],[[562,562],"mapped",[563]],[[563,563],"valid"],[[564,566],"valid"],[[567,569],"valid"],[[570,570],"mapped",[11365]],[[571,571],"mapped",[572]],[[572,572],"valid"],[[573,573],"mapped",[410]],[[574,574],"mapped",[11366]],[[575,576],"valid"],[[577,577],"mapped",[578]],[[578,578],"valid"],[[579,579],"mapped",[384]],[[580,580],"mapped",[649]],[[581,581],"mapped",[652]],[[582,582],"mapped",[583]],[[583,583],"valid"],[[584,584],"mapped",[585]],[[585,585],"valid"],[[586,586],"mapped",[587]],[[587,587],"valid"],[[588,588],"mapped",[589]],[[589,589],"valid"],[[590,590],"mapped",[591]],[[591,591],"valid"],[[592,680],"valid"],[[681,685],"valid"],[[686,687],"valid"],[[688,688],"mapped",[104]],[[689,689],"mapped",[614]],[[690,690],"mapped",[106]],[[691,691],"mapped",[114]],[[692,692],"mapped",[633]],[[693,693],"mapped",[635]],[[694,694],"mapped",[641]],[[695,695],"mapped",[119]],[[696,696],"mapped",[121]],[[697,705],"valid"],[[706,709],"valid",[],"NV8"],[[710,721],"valid"],[[722,727],"valid",[],"NV8"],[[728,728],"disallowed_STD3_mapped",[32,774]],[[729,729],"disallowed_STD3_mapped",[32,775]],[[730,730],"disallowed_STD3_mapped",[32,778]],[[731,731],"disallowed_STD3_mapped",[32,808]],[[732,732],"disallowed_STD3_mapped",[32,771]],[[733,733],"disallowed_STD3_mapped",[32,779]],[[734,734],"valid",[],"NV8"],[[735,735],"valid",[],"NV8"],[[736,736],"mapped",[611]],[[737,737],"mapped",[108]],[[738,738],"mapped",[115]],[[739,739],"mapped",[120]],[[740,740],"mapped",[661]],[[741,745],"valid",[],"NV8"],[[746,747],"valid",[],"NV8"],[[748,748],"valid"],[[749,749],"valid",[],"NV8"],[[750,750],"valid"],[[751,767],"valid",[],"NV8"],[[768,831],"valid"],[[832,832],"mapped",[768]],[[833,833],"mapped",[769]],[[834,834],"valid"],[[835,835],"mapped",[787]],[[836,836],"mapped",[776,769]],[[837,837],"mapped",[953]],[[838,846],"valid"],[[847,847],"ignored"],[[848,855],"valid"],[[856,860],"valid"],[[861,863],"valid"],[[864,865],"valid"],[[866,866],"valid"],[[867,879],"valid"],[[880,880],"mapped",[881]],[[881,881],"valid"],[[882,882],"mapped",[883]],[[883,883],"valid"],[[884,884],"mapped",[697]],[[885,885],"valid"],[[886,886],"mapped",[887]],[[887,887],"valid"],[[888,889],"disallowed"],[[890,890],"disallowed_STD3_mapped",[32,953]],[[891,893],"valid"],[[894,894],"disallowed_STD3_mapped",[59]],[[895,895],"mapped",[1011]],[[896,899],"disallowed"],[[900,900],"disallowed_STD3_mapped",[32,769]],[[901,901],"disallowed_STD3_mapped",[32,776,769]],[[902,902],"mapped",[940]],[[903,903],"mapped",[183]],[[904,904],"mapped",[941]],[[905,905],"mapped",[942]],[[906,906],"mapped",[943]],[[907,907],"disallowed"],[[908,908],"mapped",[972]],[[909,909],"disallowed"],[[910,910],"mapped",[973]],[[911,911],"mapped",[974]],[[912,912],"valid"],[[913,913],"mapped",[945]],[[914,914],"mapped",[946]],[[915,915],"mapped",[947]],[[916,916],"mapped",[948]],[[917,917],"mapped",[949]],[[918,918],"mapped",[950]],[[919,919],"mapped",[951]],[[920,920],"mapped",[952]],[[921,921],"mapped",[953]],[[922,922],"mapped",[954]],[[923,923],"mapped",[955]],[[924,924],"mapped",[956]],[[925,925],"mapped",[957]],[[926,926],"mapped",[958]],[[927,927],"mapped",[959]],[[928,928],"mapped",[960]],[[929,929],"mapped",[961]],[[930,930],"disallowed"],[[931,931],"mapped",[963]],[[932,932],"mapped",[964]],[[933,933],"mapped",[965]],[[934,934],"mapped",[966]],[[935,935],"mapped",[967]],[[936,936],"mapped",[968]],[[937,937],"mapped",[969]],[[938,938],"mapped",[970]],[[939,939],"mapped",[971]],[[940,961],"valid"],[[962,962],"deviation",[963]],[[963,974],"valid"],[[975,975],"mapped",[983]],[[976,976],"mapped",[946]],[[977,977],"mapped",[952]],[[978,978],"mapped",[965]],[[979,979],"mapped",[973]],[[980,980],"mapped",[971]],[[981,981],"mapped",[966]],[[982,982],"mapped",[960]],[[983,983],"valid"],[[984,984],"mapped",[985]],[[985,985],"valid"],[[986,986],"mapped",[987]],[[987,987],"valid"],[[988,988],"mapped",[989]],[[989,989],"valid"],[[990,990],"mapped",[991]],[[991,991],"valid"],[[992,992],"mapped",[993]],[[993,993],"valid"],[[994,994],"mapped",[995]],[[995,995],"valid"],[[996,996],"mapped",[997]],[[997,997],"valid"],[[998,998],"mapped",[999]],[[999,999],"valid"],[[1000,1000],"mapped",[1001]],[[1001,1001],"valid"],[[1002,1002],"mapped",[1003]],[[1003,1003],"valid"],[[1004,1004],"mapped",[1005]],[[1005,1005],"valid"],[[1006,1006],"mapped",[1007]],[[1007,1007],"valid"],[[1008,1008],"mapped",[954]],[[1009,1009],"mapped",[961]],[[1010,1010],"mapped",[963]],[[1011,1011],"valid"],[[1012,1012],"mapped",[952]],[[1013,1013],"mapped",[949]],[[1014,1014],"valid",[],"NV8"],[[1015,1015],"mapped",[1016]],[[1016,1016],"valid"],[[1017,1017],"mapped",[963]],[[1018,1018],"mapped",[1019]],[[1019,1019],"valid"],[[1020,1020],"valid"],[[1021,1021],"mapped",[891]],[[1022,1022],"mapped",[892]],[[1023,1023],"mapped",[893]],[[1024,1024],"mapped",[1104]],[[1025,1025],"mapped",[1105]],[[1026,1026],"mapped",[1106]],[[1027,1027],"mapped",[1107]],[[1028,1028],"mapped",[1108]],[[1029,1029],"mapped",[1109]],[[1030,1030],"mapped",[1110]],[[1031,1031],"mapped",[1111]],[[1032,1032],"mapped",[1112]],[[1033,1033],"mapped",[1113]],[[1034,1034],"mapped",[1114]],[[1035,1035],"mapped",[1115]],[[1036,1036],"mapped",[1116]],[[1037,1037],"mapped",[1117]],[[1038,1038],"mapped",[1118]],[[1039,1039],"mapped",[1119]],[[1040,1040],"mapped",[1072]],[[1041,1041],"mapped",[1073]],[[1042,1042],"mapped",[1074]],[[1043,1043],"mapped",[1075]],[[1044,1044],"mapped",[1076]],[[1045,1045],"mapped",[1077]],[[1046,1046],"mapped",[1078]],[[1047,1047],"mapped",[1079]],[[1048,1048],"mapped",[1080]],[[1049,1049],"mapped",[1081]],[[1050,1050],"mapped",[1082]],[[1051,1051],"mapped",[1083]],[[1052,1052],"mapped",[1084]],[[1053,1053],"mapped",[1085]],[[1054,1054],"mapped",[1086]],[[1055,1055],"mapped",[1087]],[[1056,1056],"mapped",[1088]],[[1057,1057],"mapped",[1089]],[[1058,1058],"mapped",[1090]],[[1059,1059],"mapped",[1091]],[[1060,1060],"mapped",[1092]],[[1061,1061],"mapped",[1093]],[[1062,1062],"mapped",[1094]],[[1063,1063],"mapped",[1095]],[[1064,1064],"mapped",[1096]],[[1065,1065],"mapped",[1097]],[[1066,1066],"mapped",[1098]],[[1067,1067],"mapped",[1099]],[[1068,1068],"mapped",[1100]],[[1069,1069],"mapped",[1101]],[[1070,1070],"mapped",[1102]],[[1071,1071],"mapped",[1103]],[[1072,1103],"valid"],[[1104,1104],"valid"],[[1105,1116],"valid"],[[1117,1117],"valid"],[[1118,1119],"valid"],[[1120,1120],"mapped",[1121]],[[1121,1121],"valid"],[[1122,1122],"mapped",[1123]],[[1123,1123],"valid"],[[1124,1124],"mapped",[1125]],[[1125,1125],"valid"],[[1126,1126],"mapped",[1127]],[[1127,1127],"valid"],[[1128,1128],"mapped",[1129]],[[1129,1129],"valid"],[[1130,1130],"mapped",[1131]],[[1131,1131],"valid"],[[1132,1132],"mapped",[1133]],[[1133,1133],"valid"],[[1134,1134],"mapped",[1135]],[[1135,1135],"valid"],[[1136,1136],"mapped",[1137]],[[1137,1137],"valid"],[[1138,1138],"mapped",[1139]],[[1139,1139],"valid"],[[1140,1140],"mapped",[1141]],[[1141,1141],"valid"],[[1142,1142],"mapped",[1143]],[[1143,1143],"valid"],[[1144,1144],"mapped",[1145]],[[1145,1145],"valid"],[[1146,1146],"mapped",[1147]],[[1147,1147],"valid"],[[1148,1148],"mapped",[1149]],[[1149,1149],"valid"],[[1150,1150],"mapped",[1151]],[[1151,1151],"valid"],[[1152,1152],"mapped",[1153]],[[1153,1153],"valid"],[[1154,1154],"valid",[],"NV8"],[[1155,1158],"valid"],[[1159,1159],"valid"],[[1160,1161],"valid",[],"NV8"],[[1162,1162],"mapped",[1163]],[[1163,1163],"valid"],[[1164,1164],"mapped",[1165]],[[1165,1165],"valid"],[[1166,1166],"mapped",[1167]],[[1167,1167],"valid"],[[1168,1168],"mapped",[1169]],[[1169,1169],"valid"],[[1170,1170],"mapped",[1171]],[[1171,1171],"valid"],[[1172,1172],"mapped",[1173]],[[1173,1173],"valid"],[[1174,1174],"mapped",[1175]],[[1175,1175],"valid"],[[1176,1176],"mapped",[1177]],[[1177,1177],"valid"],[[1178,1178],"mapped",[1179]],[[1179,1179],"valid"],[[1180,1180],"mapped",[1181]],[[1181,1181],"valid"],[[1182,1182],"mapped",[1183]],[[1183,1183],"valid"],[[1184,1184],"mapped",[1185]],[[1185,1185],"valid"],[[1186,1186],"mapped",[1187]],[[1187,1187],"valid"],[[1188,1188],"mapped",[1189]],[[1189,1189],"valid"],[[1190,1190],"mapped",[1191]],[[1191,1191],"valid"],[[1192,1192],"mapped",[1193]],[[1193,1193],"valid"],[[1194,1194],"mapped",[1195]],[[1195,1195],"valid"],[[1196,1196],"mapped",[1197]],[[1197,1197],"valid"],[[1198,1198],"mapped",[1199]],[[1199,1199],"valid"],[[1200,1200],"mapped",[1201]],[[1201,1201],"valid"],[[1202,1202],"mapped",[1203]],[[1203,1203],"valid"],[[1204,1204],"mapped",[1205]],[[1205,1205],"valid"],[[1206,1206],"mapped",[1207]],[[1207,1207],"valid"],[[1208,1208],"mapped",[1209]],[[1209,1209],"valid"],[[1210,1210],"mapped",[1211]],[[1211,1211],"valid"],[[1212,1212],"mapped",[1213]],[[1213,1213],"valid"],[[1214,1214],"mapped",[1215]],[[1215,1215],"valid"],[[1216,1216],"disallowed"],[[1217,1217],"mapped",[1218]],[[1218,1218],"valid"],[[1219,1219],"mapped",[1220]],[[1220,1220],"valid"],[[1221,1221],"mapped",[1222]],[[1222,1222],"valid"],[[1223,1223],"mapped",[1224]],[[1224,1224],"valid"],[[1225,1225],"mapped",[1226]],[[1226,1226],"valid"],[[1227,1227],"mapped",[1228]],[[1228,1228],"valid"],[[1229,1229],"mapped",[1230]],[[1230,1230],"valid"],[[1231,1231],"valid"],[[1232,1232],"mapped",[1233]],[[1233,1233],"valid"],[[1234,1234],"mapped",[1235]],[[1235,1235],"valid"],[[1236,1236],"mapped",[1237]],[[1237,1237],"valid"],[[1238,1238],"mapped",[1239]],[[1239,1239],"valid"],[[1240,1240],"mapped",[1241]],[[1241,1241],"valid"],[[1242,1242],"mapped",[1243]],[[1243,1243],"valid"],[[1244,1244],"mapped",[1245]],[[1245,1245],"valid"],[[1246,1246],"mapped",[1247]],[[1247,1247],"valid"],[[1248,1248],"mapped",[1249]],[[1249,1249],"valid"],[[1250,1250],"mapped",[1251]],[[1251,1251],"valid"],[[1252,1252],"mapped",[1253]],[[1253,1253],"valid"],[[1254,1254],"mapped",[1255]],[[1255,1255],"valid"],[[1256,1256],"mapped",[1257]],[[1257,1257],"valid"],[[1258,1258],"mapped",[1259]],[[1259,1259],"valid"],[[1260,1260],"mapped",[1261]],[[1261,1261],"valid"],[[1262,1262],"mapped",[1263]],[[1263,1263],"valid"],[[1264,1264],"mapped",[1265]],[[1265,1265],"valid"],[[1266,1266],"mapped",[1267]],[[1267,1267],"valid"],[[1268,1268],"mapped",[1269]],[[1269,1269],"valid"],[[1270,1270],"mapped",[1271]],[[1271,1271],"valid"],[[1272,1272],"mapped",[1273]],[[1273,1273],"valid"],[[1274,1274],"mapped",[1275]],[[1275,1275],"valid"],[[1276,1276],"mapped",[1277]],[[1277,1277],"valid"],[[1278,1278],"mapped",[1279]],[[1279,1279],"valid"],[[1280,1280],"mapped",[1281]],[[1281,1281],"valid"],[[1282,1282],"mapped",[1283]],[[1283,1283],"valid"],[[1284,1284],"mapped",[1285]],[[1285,1285],"valid"],[[1286,1286],"mapped",[1287]],[[1287,1287],"valid"],[[1288,1288],"mapped",[1289]],[[1289,1289],"valid"],[[1290,1290],"mapped",[1291]],[[1291,1291],"valid"],[[1292,1292],"mapped",[1293]],[[1293,1293],"valid"],[[1294,1294],"mapped",[1295]],[[1295,1295],"valid"],[[1296,1296],"mapped",[1297]],[[1297,1297],"valid"],[[1298,1298],"mapped",[1299]],[[1299,1299],"valid"],[[1300,1300],"mapped",[1301]],[[1301,1301],"valid"],[[1302,1302],"mapped",[1303]],[[1303,1303],"valid"],[[1304,1304],"mapped",[1305]],[[1305,1305],"valid"],[[1306,1306],"mapped",[1307]],[[1307,1307],"valid"],[[1308,1308],"mapped",[1309]],[[1309,1309],"valid"],[[1310,1310],"mapped",[1311]],[[1311,1311],"valid"],[[1312,1312],"mapped",[1313]],[[1313,1313],"valid"],[[1314,1314],"mapped",[1315]],[[1315,1315],"valid"],[[1316,1316],"mapped",[1317]],[[1317,1317],"valid"],[[1318,1318],"mapped",[1319]],[[1319,1319],"valid"],[[1320,1320],"mapped",[1321]],[[1321,1321],"valid"],[[1322,1322],"mapped",[1323]],[[1323,1323],"valid"],[[1324,1324],"mapped",[1325]],[[1325,1325],"valid"],[[1326,1326],"mapped",[1327]],[[1327,1327],"valid"],[[1328,1328],"disallowed"],[[1329,1329],"mapped",[1377]],[[1330,1330],"mapped",[1378]],[[1331,1331],"mapped",[1379]],[[1332,1332],"mapped",[1380]],[[1333,1333],"mapped",[1381]],[[1334,1334],"mapped",[1382]],[[1335,1335],"mapped",[1383]],[[1336,1336],"mapped",[1384]],[[1337,1337],"mapped",[1385]],[[1338,1338],"mapped",[1386]],[[1339,1339],"mapped",[1387]],[[1340,1340],"mapped",[1388]],[[1341,1341],"mapped",[1389]],[[1342,1342],"mapped",[1390]],[[1343,1343],"mapped",[1391]],[[1344,1344],"mapped",[1392]],[[1345,1345],"mapped",[1393]],[[1346,1346],"mapped",[1394]],[[1347,1347],"mapped",[1395]],[[1348,1348],"mapped",[1396]],[[1349,1349],"mapped",[1397]],[[1350,1350],"mapped",[1398]],[[1351,1351],"mapped",[1399]],[[1352,1352],"mapped",[1400]],[[1353,1353],"mapped",[1401]],[[1354,1354],"mapped",[1402]],[[1355,1355],"mapped",[1403]],[[1356,1356],"mapped",[1404]],[[1357,1357],"mapped",[1405]],[[1358,1358],"mapped",[1406]],[[1359,1359],"mapped",[1407]],[[1360,1360],"mapped",[1408]],[[1361,1361],"mapped",[1409]],[[1362,1362],"mapped",[1410]],[[1363,1363],"mapped",[1411]],[[1364,1364],"mapped",[1412]],[[1365,1365],"mapped",[1413]],[[1366,1366],"mapped",[1414]],[[1367,1368],"disallowed"],[[1369,1369],"valid"],[[1370,1375],"valid",[],"NV8"],[[1376,1376],"disallowed"],[[1377,1414],"valid"],[[1415,1415],"mapped",[1381,1410]],[[1416,1416],"disallowed"],[[1417,1417],"valid",[],"NV8"],[[1418,1418],"valid",[],"NV8"],[[1419,1420],"disallowed"],[[1421,1422],"valid",[],"NV8"],[[1423,1423],"valid",[],"NV8"],[[1424,1424],"disallowed"],[[1425,1441],"valid"],[[1442,1442],"valid"],[[1443,1455],"valid"],[[1456,1465],"valid"],[[1466,1466],"valid"],[[1467,1469],"valid"],[[1470,1470],"valid",[],"NV8"],[[1471,1471],"valid"],[[1472,1472],"valid",[],"NV8"],[[1473,1474],"valid"],[[1475,1475],"valid",[],"NV8"],[[1476,1476],"valid"],[[1477,1477],"valid"],[[1478,1478],"valid",[],"NV8"],[[1479,1479],"valid"],[[1480,1487],"disallowed"],[[1488,1514],"valid"],[[1515,1519],"disallowed"],[[1520,1524],"valid"],[[1525,1535],"disallowed"],[[1536,1539],"disallowed"],[[1540,1540],"disallowed"],[[1541,1541],"disallowed"],[[1542,1546],"valid",[],"NV8"],[[1547,1547],"valid",[],"NV8"],[[1548,1548],"valid",[],"NV8"],[[1549,1551],"valid",[],"NV8"],[[1552,1557],"valid"],[[1558,1562],"valid"],[[1563,1563],"valid",[],"NV8"],[[1564,1564],"disallowed"],[[1565,1565],"disallowed"],[[1566,1566],"valid",[],"NV8"],[[1567,1567],"valid",[],"NV8"],[[1568,1568],"valid"],[[1569,1594],"valid"],[[1595,1599],"valid"],[[1600,1600],"valid",[],"NV8"],[[1601,1618],"valid"],[[1619,1621],"valid"],[[1622,1624],"valid"],[[1625,1630],"valid"],[[1631,1631],"valid"],[[1632,1641],"valid"],[[1642,1645],"valid",[],"NV8"],[[1646,1647],"valid"],[[1648,1652],"valid"],[[1653,1653],"mapped",[1575,1652]],[[1654,1654],"mapped",[1608,1652]],[[1655,1655],"mapped",[1735,1652]],[[1656,1656],"mapped",[1610,1652]],[[1657,1719],"valid"],[[1720,1721],"valid"],[[1722,1726],"valid"],[[1727,1727],"valid"],[[1728,1742],"valid"],[[1743,1743],"valid"],[[1744,1747],"valid"],[[1748,1748],"valid",[],"NV8"],[[1749,1756],"valid"],[[1757,1757],"disallowed"],[[1758,1758],"valid",[],"NV8"],[[1759,1768],"valid"],[[1769,1769],"valid",[],"NV8"],[[1770,1773],"valid"],[[1774,1775],"valid"],[[1776,1785],"valid"],[[1786,1790],"valid"],[[1791,1791],"valid"],[[1792,1805],"valid",[],"NV8"],[[1806,1806],"disallowed"],[[1807,1807],"disallowed"],[[1808,1836],"valid"],[[1837,1839],"valid"],[[1840,1866],"valid"],[[1867,1868],"disallowed"],[[1869,1871],"valid"],[[1872,1901],"valid"],[[1902,1919],"valid"],[[1920,1968],"valid"],[[1969,1969],"valid"],[[1970,1983],"disallowed"],[[1984,2037],"valid"],[[2038,2042],"valid",[],"NV8"],[[2043,2047],"disallowed"],[[2048,2093],"valid"],[[2094,2095],"disallowed"],[[2096,2110],"valid",[],"NV8"],[[2111,2111],"disallowed"],[[2112,2139],"valid"],[[2140,2141],"disallowed"],[[2142,2142],"valid",[],"NV8"],[[2143,2207],"disallowed"],[[2208,2208],"valid"],[[2209,2209],"valid"],[[2210,2220],"valid"],[[2221,2226],"valid"],[[2227,2228],"valid"],[[2229,2274],"disallowed"],[[2275,2275],"valid"],[[2276,2302],"valid"],[[2303,2303],"valid"],[[2304,2304],"valid"],[[2305,2307],"valid"],[[2308,2308],"valid"],[[2309,2361],"valid"],[[2362,2363],"valid"],[[2364,2381],"valid"],[[2382,2382],"valid"],[[2383,2383],"valid"],[[2384,2388],"valid"],[[2389,2389],"valid"],[[2390,2391],"valid"],[[2392,2392],"mapped",[2325,2364]],[[2393,2393],"mapped",[2326,2364]],[[2394,2394],"mapped",[2327,2364]],[[2395,2395],"mapped",[2332,2364]],[[2396,2396],"mapped",[2337,2364]],[[2397,2397],"mapped",[2338,2364]],[[2398,2398],"mapped",[2347,2364]],[[2399,2399],"mapped",[2351,2364]],[[2400,2403],"valid"],[[2404,2405],"valid",[],"NV8"],[[2406,2415],"valid"],[[2416,2416],"valid",[],"NV8"],[[2417,2418],"valid"],[[2419,2423],"valid"],[[2424,2424],"valid"],[[2425,2426],"valid"],[[2427,2428],"valid"],[[2429,2429],"valid"],[[2430,2431],"valid"],[[2432,2432],"valid"],[[2433,2435],"valid"],[[2436,2436],"disallowed"],[[2437,2444],"valid"],[[2445,2446],"disallowed"],[[2447,2448],"valid"],[[2449,2450],"disallowed"],[[2451,2472],"valid"],[[2473,2473],"disallowed"],[[2474,2480],"valid"],[[2481,2481],"disallowed"],[[2482,2482],"valid"],[[2483,2485],"disallowed"],[[2486,2489],"valid"],[[2490,2491],"disallowed"],[[2492,2492],"valid"],[[2493,2493],"valid"],[[2494,2500],"valid"],[[2501,2502],"disallowed"],[[2503,2504],"valid"],[[2505,2506],"disallowed"],[[2507,2509],"valid"],[[2510,2510],"valid"],[[2511,2518],"disallowed"],[[2519,2519],"valid"],[[2520,2523],"disallowed"],[[2524,2524],"mapped",[2465,2492]],[[2525,2525],"mapped",[2466,2492]],[[2526,2526],"disallowed"],[[2527,2527],"mapped",[2479,2492]],[[2528,2531],"valid"],[[2532,2533],"disallowed"],[[2534,2545],"valid"],[[2546,2554],"valid",[],"NV8"],[[2555,2555],"valid",[],"NV8"],[[2556,2560],"disallowed"],[[2561,2561],"valid"],[[2562,2562],"valid"],[[2563,2563],"valid"],[[2564,2564],"disallowed"],[[2565,2570],"valid"],[[2571,2574],"disallowed"],[[2575,2576],"valid"],[[2577,2578],"disallowed"],[[2579,2600],"valid"],[[2601,2601],"disallowed"],[[2602,2608],"valid"],[[2609,2609],"disallowed"],[[2610,2610],"valid"],[[2611,2611],"mapped",[2610,2620]],[[2612,2612],"disallowed"],[[2613,2613],"valid"],[[2614,2614],"mapped",[2616,2620]],[[2615,2615],"disallowed"],[[2616,2617],"valid"],[[2618,2619],"disallowed"],[[2620,2620],"valid"],[[2621,2621],"disallowed"],[[2622,2626],"valid"],[[2627,2630],"disallowed"],[[2631,2632],"valid"],[[2633,2634],"disallowed"],[[2635,2637],"valid"],[[2638,2640],"disallowed"],[[2641,2641],"valid"],[[2642,2648],"disallowed"],[[2649,2649],"mapped",[2582,2620]],[[2650,2650],"mapped",[2583,2620]],[[2651,2651],"mapped",[2588,2620]],[[2652,2652],"valid"],[[2653,2653],"disallowed"],[[2654,2654],"mapped",[2603,2620]],[[2655,2661],"disallowed"],[[2662,2676],"valid"],[[2677,2677],"valid"],[[2678,2688],"disallowed"],[[2689,2691],"valid"],[[2692,2692],"disallowed"],[[2693,2699],"valid"],[[2700,2700],"valid"],[[2701,2701],"valid"],[[2702,2702],"disallowed"],[[2703,2705],"valid"],[[2706,2706],"disallowed"],[[2707,2728],"valid"],[[2729,2729],"disallowed"],[[2730,2736],"valid"],[[2737,2737],"disallowed"],[[2738,2739],"valid"],[[2740,2740],"disallowed"],[[2741,2745],"valid"],[[2746,2747],"disallowed"],[[2748,2757],"valid"],[[2758,2758],"disallowed"],[[2759,2761],"valid"],[[2762,2762],"disallowed"],[[2763,2765],"valid"],[[2766,2767],"disallowed"],[[2768,2768],"valid"],[[2769,2783],"disallowed"],[[2784,2784],"valid"],[[2785,2787],"valid"],[[2788,2789],"disallowed"],[[2790,2799],"valid"],[[2800,2800],"valid",[],"NV8"],[[2801,2801],"valid",[],"NV8"],[[2802,2808],"disallowed"],[[2809,2809],"valid"],[[2810,2816],"disallowed"],[[2817,2819],"valid"],[[2820,2820],"disallowed"],[[2821,2828],"valid"],[[2829,2830],"disallowed"],[[2831,2832],"valid"],[[2833,2834],"disallowed"],[[2835,2856],"valid"],[[2857,2857],"disallowed"],[[2858,2864],"valid"],[[2865,2865],"disallowed"],[[2866,2867],"valid"],[[2868,2868],"disallowed"],[[2869,2869],"valid"],[[2870,2873],"valid"],[[2874,2875],"disallowed"],[[2876,2883],"valid"],[[2884,2884],"valid"],[[2885,2886],"disallowed"],[[2887,2888],"valid"],[[2889,2890],"disallowed"],[[2891,2893],"valid"],[[2894,2901],"disallowed"],[[2902,2903],"valid"],[[2904,2907],"disallowed"],[[2908,2908],"mapped",[2849,2876]],[[2909,2909],"mapped",[2850,2876]],[[2910,2910],"disallowed"],[[2911,2913],"valid"],[[2914,2915],"valid"],[[2916,2917],"disallowed"],[[2918,2927],"valid"],[[2928,2928],"valid",[],"NV8"],[[2929,2929],"valid"],[[2930,2935],"valid",[],"NV8"],[[2936,2945],"disallowed"],[[2946,2947],"valid"],[[2948,2948],"disallowed"],[[2949,2954],"valid"],[[2955,2957],"disallowed"],[[2958,2960],"valid"],[[2961,2961],"disallowed"],[[2962,2965],"valid"],[[2966,2968],"disallowed"],[[2969,2970],"valid"],[[2971,2971],"disallowed"],[[2972,2972],"valid"],[[2973,2973],"disallowed"],[[2974,2975],"valid"],[[2976,2978],"disallowed"],[[2979,2980],"valid"],[[2981,2983],"disallowed"],[[2984,2986],"valid"],[[2987,2989],"disallowed"],[[2990,2997],"valid"],[[2998,2998],"valid"],[[2999,3001],"valid"],[[3002,3005],"disallowed"],[[3006,3010],"valid"],[[3011,3013],"disallowed"],[[3014,3016],"valid"],[[3017,3017],"disallowed"],[[3018,3021],"valid"],[[3022,3023],"disallowed"],[[3024,3024],"valid"],[[3025,3030],"disallowed"],[[3031,3031],"valid"],[[3032,3045],"disallowed"],[[3046,3046],"valid"],[[3047,3055],"valid"],[[3056,3058],"valid",[],"NV8"],[[3059,3066],"valid",[],"NV8"],[[3067,3071],"disallowed"],[[3072,3072],"valid"],[[3073,3075],"valid"],[[3076,3076],"disallowed"],[[3077,3084],"valid"],[[3085,3085],"disallowed"],[[3086,3088],"valid"],[[3089,3089],"disallowed"],[[3090,3112],"valid"],[[3113,3113],"disallowed"],[[3114,3123],"valid"],[[3124,3124],"valid"],[[3125,3129],"valid"],[[3130,3132],"disallowed"],[[3133,3133],"valid"],[[3134,3140],"valid"],[[3141,3141],"disallowed"],[[3142,3144],"valid"],[[3145,3145],"disallowed"],[[3146,3149],"valid"],[[3150,3156],"disallowed"],[[3157,3158],"valid"],[[3159,3159],"disallowed"],[[3160,3161],"valid"],[[3162,3162],"valid"],[[3163,3167],"disallowed"],[[3168,3169],"valid"],[[3170,3171],"valid"],[[3172,3173],"disallowed"],[[3174,3183],"valid"],[[3184,3191],"disallowed"],[[3192,3199],"valid",[],"NV8"],[[3200,3200],"disallowed"],[[3201,3201],"valid"],[[3202,3203],"valid"],[[3204,3204],"disallowed"],[[3205,3212],"valid"],[[3213,3213],"disallowed"],[[3214,3216],"valid"],[[3217,3217],"disallowed"],[[3218,3240],"valid"],[[3241,3241],"disallowed"],[[3242,3251],"valid"],[[3252,3252],"disallowed"],[[3253,3257],"valid"],[[3258,3259],"disallowed"],[[3260,3261],"valid"],[[3262,3268],"valid"],[[3269,3269],"disallowed"],[[3270,3272],"valid"],[[3273,3273],"disallowed"],[[3274,3277],"valid"],[[3278,3284],"disallowed"],[[3285,3286],"valid"],[[3287,3293],"disallowed"],[[3294,3294],"valid"],[[3295,3295],"disallowed"],[[3296,3297],"valid"],[[3298,3299],"valid"],[[3300,3301],"disallowed"],[[3302,3311],"valid"],[[3312,3312],"disallowed"],[[3313,3314],"valid"],[[3315,3328],"disallowed"],[[3329,3329],"valid"],[[3330,3331],"valid"],[[3332,3332],"disallowed"],[[3333,3340],"valid"],[[3341,3341],"disallowed"],[[3342,3344],"valid"],[[3345,3345],"disallowed"],[[3346,3368],"valid"],[[3369,3369],"valid"],[[3370,3385],"valid"],[[3386,3386],"valid"],[[3387,3388],"disallowed"],[[3389,3389],"valid"],[[3390,3395],"valid"],[[3396,3396],"valid"],[[3397,3397],"disallowed"],[[3398,3400],"valid"],[[3401,3401],"disallowed"],[[3402,3405],"valid"],[[3406,3406],"valid"],[[3407,3414],"disallowed"],[[3415,3415],"valid"],[[3416,3422],"disallowed"],[[3423,3423],"valid"],[[3424,3425],"valid"],[[3426,3427],"valid"],[[3428,3429],"disallowed"],[[3430,3439],"valid"],[[3440,3445],"valid",[],"NV8"],[[3446,3448],"disallowed"],[[3449,3449],"valid",[],"NV8"],[[3450,3455],"valid"],[[3456,3457],"disallowed"],[[3458,3459],"valid"],[[3460,3460],"disallowed"],[[3461,3478],"valid"],[[3479,3481],"disallowed"],[[3482,3505],"valid"],[[3506,3506],"disallowed"],[[3507,3515],"valid"],[[3516,3516],"disallowed"],[[3517,3517],"valid"],[[3518,3519],"disallowed"],[[3520,3526],"valid"],[[3527,3529],"disallowed"],[[3530,3530],"valid"],[[3531,3534],"disallowed"],[[3535,3540],"valid"],[[3541,3541],"disallowed"],[[3542,3542],"valid"],[[3543,3543],"disallowed"],[[3544,3551],"valid"],[[3552,3557],"disallowed"],[[3558,3567],"valid"],[[3568,3569],"disallowed"],[[3570,3571],"valid"],[[3572,3572],"valid",[],"NV8"],[[3573,3584],"disallowed"],[[3585,3634],"valid"],[[3635,3635],"mapped",[3661,3634]],[[3636,3642],"valid"],[[3643,3646],"disallowed"],[[3647,3647],"valid",[],"NV8"],[[3648,3662],"valid"],[[3663,3663],"valid",[],"NV8"],[[3664,3673],"valid"],[[3674,3675],"valid",[],"NV8"],[[3676,3712],"disallowed"],[[3713,3714],"valid"],[[3715,3715],"disallowed"],[[3716,3716],"valid"],[[3717,3718],"disallowed"],[[3719,3720],"valid"],[[3721,3721],"disallowed"],[[3722,3722],"valid"],[[3723,3724],"disallowed"],[[3725,3725],"valid"],[[3726,3731],"disallowed"],[[3732,3735],"valid"],[[3736,3736],"disallowed"],[[3737,3743],"valid"],[[3744,3744],"disallowed"],[[3745,3747],"valid"],[[3748,3748],"disallowed"],[[3749,3749],"valid"],[[3750,3750],"disallowed"],[[3751,3751],"valid"],[[3752,3753],"disallowed"],[[3754,3755],"valid"],[[3756,3756],"disallowed"],[[3757,3762],"valid"],[[3763,3763],"mapped",[3789,3762]],[[3764,3769],"valid"],[[3770,3770],"disallowed"],[[3771,3773],"valid"],[[3774,3775],"disallowed"],[[3776,3780],"valid"],[[3781,3781],"disallowed"],[[3782,3782],"valid"],[[3783,3783],"disallowed"],[[3784,3789],"valid"],[[3790,3791],"disallowed"],[[3792,3801],"valid"],[[3802,3803],"disallowed"],[[3804,3804],"mapped",[3755,3737]],[[3805,3805],"mapped",[3755,3745]],[[3806,3807],"valid"],[[3808,3839],"disallowed"],[[3840,3840],"valid"],[[3841,3850],"valid",[],"NV8"],[[3851,3851],"valid"],[[3852,3852],"mapped",[3851]],[[3853,3863],"valid",[],"NV8"],[[3864,3865],"valid"],[[3866,3871],"valid",[],"NV8"],[[3872,3881],"valid"],[[3882,3892],"valid",[],"NV8"],[[3893,3893],"valid"],[[3894,3894],"valid",[],"NV8"],[[3895,3895],"valid"],[[3896,3896],"valid",[],"NV8"],[[3897,3897],"valid"],[[3898,3901],"valid",[],"NV8"],[[3902,3906],"valid"],[[3907,3907],"mapped",[3906,4023]],[[3908,3911],"valid"],[[3912,3912],"disallowed"],[[3913,3916],"valid"],[[3917,3917],"mapped",[3916,4023]],[[3918,3921],"valid"],[[3922,3922],"mapped",[3921,4023]],[[3923,3926],"valid"],[[3927,3927],"mapped",[3926,4023]],[[3928,3931],"valid"],[[3932,3932],"mapped",[3931,4023]],[[3933,3944],"valid"],[[3945,3945],"mapped",[3904,4021]],[[3946,3946],"valid"],[[3947,3948],"valid"],[[3949,3952],"disallowed"],[[3953,3954],"valid"],[[3955,3955],"mapped",[3953,3954]],[[3956,3956],"valid"],[[3957,3957],"mapped",[3953,3956]],[[3958,3958],"mapped",[4018,3968]],[[3959,3959],"mapped",[4018,3953,3968]],[[3960,3960],"mapped",[4019,3968]],[[3961,3961],"mapped",[4019,3953,3968]],[[3962,3968],"valid"],[[3969,3969],"mapped",[3953,3968]],[[3970,3972],"valid"],[[3973,3973],"valid",[],"NV8"],[[3974,3979],"valid"],[[3980,3983],"valid"],[[3984,3986],"valid"],[[3987,3987],"mapped",[3986,4023]],[[3988,3989],"valid"],[[3990,3990],"valid"],[[3991,3991],"valid"],[[3992,3992],"disallowed"],[[3993,3996],"valid"],[[3997,3997],"mapped",[3996,4023]],[[3998,4001],"valid"],[[4002,4002],"mapped",[4001,4023]],[[4003,4006],"valid"],[[4007,4007],"mapped",[4006,4023]],[[4008,4011],"valid"],[[4012,4012],"mapped",[4011,4023]],[[4013,4013],"valid"],[[4014,4016],"valid"],[[4017,4023],"valid"],[[4024,4024],"valid"],[[4025,4025],"mapped",[3984,4021]],[[4026,4028],"valid"],[[4029,4029],"disallowed"],[[4030,4037],"valid",[],"NV8"],[[4038,4038],"valid"],[[4039,4044],"valid",[],"NV8"],[[4045,4045],"disallowed"],[[4046,4046],"valid",[],"NV8"],[[4047,4047],"valid",[],"NV8"],[[4048,4049],"valid",[],"NV8"],[[4050,4052],"valid",[],"NV8"],[[4053,4056],"valid",[],"NV8"],[[4057,4058],"valid",[],"NV8"],[[4059,4095],"disallowed"],[[4096,4129],"valid"],[[4130,4130],"valid"],[[4131,4135],"valid"],[[4136,4136],"valid"],[[4137,4138],"valid"],[[4139,4139],"valid"],[[4140,4146],"valid"],[[4147,4149],"valid"],[[4150,4153],"valid"],[[4154,4159],"valid"],[[4160,4169],"valid"],[[4170,4175],"valid",[],"NV8"],[[4176,4185],"valid"],[[4186,4249],"valid"],[[4250,4253],"valid"],[[4254,4255],"valid",[],"NV8"],[[4256,4293],"disallowed"],[[4294,4294],"disallowed"],[[4295,4295],"mapped",[11559]],[[4296,4300],"disallowed"],[[4301,4301],"mapped",[11565]],[[4302,4303],"disallowed"],[[4304,4342],"valid"],[[4343,4344],"valid"],[[4345,4346],"valid"],[[4347,4347],"valid",[],"NV8"],[[4348,4348],"mapped",[4316]],[[4349,4351],"valid"],[[4352,4441],"valid",[],"NV8"],[[4442,4446],"valid",[],"NV8"],[[4447,4448],"disallowed"],[[4449,4514],"valid",[],"NV8"],[[4515,4519],"valid",[],"NV8"],[[4520,4601],"valid",[],"NV8"],[[4602,4607],"valid",[],"NV8"],[[4608,4614],"valid"],[[4615,4615],"valid"],[[4616,4678],"valid"],[[4679,4679],"valid"],[[4680,4680],"valid"],[[4681,4681],"disallowed"],[[4682,4685],"valid"],[[4686,4687],"disallowed"],[[4688,4694],"valid"],[[4695,4695],"disallowed"],[[4696,4696],"valid"],[[4697,4697],"disallowed"],[[4698,4701],"valid"],[[4702,4703],"disallowed"],[[4704,4742],"valid"],[[4743,4743],"valid"],[[4744,4744],"valid"],[[4745,4745],"disallowed"],[[4746,4749],"valid"],[[4750,4751],"disallowed"],[[4752,4782],"valid"],[[4783,4783],"valid"],[[4784,4784],"valid"],[[4785,4785],"disallowed"],[[4786,4789],"valid"],[[4790,4791],"disallowed"],[[4792,4798],"valid"],[[4799,4799],"disallowed"],[[4800,4800],"valid"],[[4801,4801],"disallowed"],[[4802,4805],"valid"],[[4806,4807],"disallowed"],[[4808,4814],"valid"],[[4815,4815],"valid"],[[4816,4822],"valid"],[[4823,4823],"disallowed"],[[4824,4846],"valid"],[[4847,4847],"valid"],[[4848,4878],"valid"],[[4879,4879],"valid"],[[4880,4880],"valid"],[[4881,4881],"disallowed"],[[4882,4885],"valid"],[[4886,4887],"disallowed"],[[4888,4894],"valid"],[[4895,4895],"valid"],[[4896,4934],"valid"],[[4935,4935],"valid"],[[4936,4954],"valid"],[[4955,4956],"disallowed"],[[4957,4958],"valid"],[[4959,4959],"valid"],[[4960,4960],"valid",[],"NV8"],[[4961,4988],"valid",[],"NV8"],[[4989,4991],"disallowed"],[[4992,5007],"valid"],[[5008,5017],"valid",[],"NV8"],[[5018,5023],"disallowed"],[[5024,5108],"valid"],[[5109,5109],"valid"],[[5110,5111],"disallowed"],[[5112,5112],"mapped",[5104]],[[5113,5113],"mapped",[5105]],[[5114,5114],"mapped",[5106]],[[5115,5115],"mapped",[5107]],[[5116,5116],"mapped",[5108]],[[5117,5117],"mapped",[5109]],[[5118,5119],"disallowed"],[[5120,5120],"valid",[],"NV8"],[[5121,5740],"valid"],[[5741,5742],"valid",[],"NV8"],[[5743,5750],"valid"],[[5751,5759],"valid"],[[5760,5760],"disallowed"],[[5761,5786],"valid"],[[5787,5788],"valid",[],"NV8"],[[5789,5791],"disallowed"],[[5792,5866],"valid"],[[5867,5872],"valid",[],"NV8"],[[5873,5880],"valid"],[[5881,5887],"disallowed"],[[5888,5900],"valid"],[[5901,5901],"disallowed"],[[5902,5908],"valid"],[[5909,5919],"disallowed"],[[5920,5940],"valid"],[[5941,5942],"valid",[],"NV8"],[[5943,5951],"disallowed"],[[5952,5971],"valid"],[[5972,5983],"disallowed"],[[5984,5996],"valid"],[[5997,5997],"disallowed"],[[5998,6000],"valid"],[[6001,6001],"disallowed"],[[6002,6003],"valid"],[[6004,6015],"disallowed"],[[6016,6067],"valid"],[[6068,6069],"disallowed"],[[6070,6099],"valid"],[[6100,6102],"valid",[],"NV8"],[[6103,6103],"valid"],[[6104,6107],"valid",[],"NV8"],[[6108,6108],"valid"],[[6109,6109],"valid"],[[6110,6111],"disallowed"],[[6112,6121],"valid"],[[6122,6127],"disallowed"],[[6128,6137],"valid",[],"NV8"],[[6138,6143],"disallowed"],[[6144,6149],"valid",[],"NV8"],[[6150,6150],"disallowed"],[[6151,6154],"valid",[],"NV8"],[[6155,6157],"ignored"],[[6158,6158],"disallowed"],[[6159,6159],"disallowed"],[[6160,6169],"valid"],[[6170,6175],"disallowed"],[[6176,6263],"valid"],[[6264,6271],"disallowed"],[[6272,6313],"valid"],[[6314,6314],"valid"],[[6315,6319],"disallowed"],[[6320,6389],"valid"],[[6390,6399],"disallowed"],[[6400,6428],"valid"],[[6429,6430],"valid"],[[6431,6431],"disallowed"],[[6432,6443],"valid"],[[6444,6447],"disallowed"],[[6448,6459],"valid"],[[6460,6463],"disallowed"],[[6464,6464],"valid",[],"NV8"],[[6465,6467],"disallowed"],[[6468,6469],"valid",[],"NV8"],[[6470,6509],"valid"],[[6510,6511],"disallowed"],[[6512,6516],"valid"],[[6517,6527],"disallowed"],[[6528,6569],"valid"],[[6570,6571],"valid"],[[6572,6575],"disallowed"],[[6576,6601],"valid"],[[6602,6607],"disallowed"],[[6608,6617],"valid"],[[6618,6618],"valid",[],"XV8"],[[6619,6621],"disallowed"],[[6622,6623],"valid",[],"NV8"],[[6624,6655],"valid",[],"NV8"],[[6656,6683],"valid"],[[6684,6685],"disallowed"],[[6686,6687],"valid",[],"NV8"],[[6688,6750],"valid"],[[6751,6751],"disallowed"],[[6752,6780],"valid"],[[6781,6782],"disallowed"],[[6783,6793],"valid"],[[6794,6799],"disallowed"],[[6800,6809],"valid"],[[6810,6815],"disallowed"],[[6816,6822],"valid",[],"NV8"],[[6823,6823],"valid"],[[6824,6829],"valid",[],"NV8"],[[6830,6831],"disallowed"],[[6832,6845],"valid"],[[6846,6846],"valid",[],"NV8"],[[6847,6911],"disallowed"],[[6912,6987],"valid"],[[6988,6991],"disallowed"],[[6992,7001],"valid"],[[7002,7018],"valid",[],"NV8"],[[7019,7027],"valid"],[[7028,7036],"valid",[],"NV8"],[[7037,7039],"disallowed"],[[7040,7082],"valid"],[[7083,7085],"valid"],[[7086,7097],"valid"],[[7098,7103],"valid"],[[7104,7155],"valid"],[[7156,7163],"disallowed"],[[7164,7167],"valid",[],"NV8"],[[7168,7223],"valid"],[[7224,7226],"disallowed"],[[7227,7231],"valid",[],"NV8"],[[7232,7241],"valid"],[[7242,7244],"disallowed"],[[7245,7293],"valid"],[[7294,7295],"valid",[],"NV8"],[[7296,7359],"disallowed"],[[7360,7367],"valid",[],"NV8"],[[7368,7375],"disallowed"],[[7376,7378],"valid"],[[7379,7379],"valid",[],"NV8"],[[7380,7410],"valid"],[[7411,7414],"valid"],[[7415,7415],"disallowed"],[[7416,7417],"valid"],[[7418,7423],"disallowed"],[[7424,7467],"valid"],[[7468,7468],"mapped",[97]],[[7469,7469],"mapped",[230]],[[7470,7470],"mapped",[98]],[[7471,7471],"valid"],[[7472,7472],"mapped",[100]],[[7473,7473],"mapped",[101]],[[7474,7474],"mapped",[477]],[[7475,7475],"mapped",[103]],[[7476,7476],"mapped",[104]],[[7477,7477],"mapped",[105]],[[7478,7478],"mapped",[106]],[[7479,7479],"mapped",[107]],[[7480,7480],"mapped",[108]],[[7481,7481],"mapped",[109]],[[7482,7482],"mapped",[110]],[[7483,7483],"valid"],[[7484,7484],"mapped",[111]],[[7485,7485],"mapped",[547]],[[7486,7486],"mapped",[112]],[[7487,7487],"mapped",[114]],[[7488,7488],"mapped",[116]],[[7489,7489],"mapped",[117]],[[7490,7490],"mapped",[119]],[[7491,7491],"mapped",[97]],[[7492,7492],"mapped",[592]],[[7493,7493],"mapped",[593]],[[7494,7494],"mapped",[7426]],[[7495,7495],"mapped",[98]],[[7496,7496],"mapped",[100]],[[7497,7497],"mapped",[101]],[[7498,7498],"mapped",[601]],[[7499,7499],"mapped",[603]],[[7500,7500],"mapped",[604]],[[7501,7501],"mapped",[103]],[[7502,7502],"valid"],[[7503,7503],"mapped",[107]],[[7504,7504],"mapped",[109]],[[7505,7505],"mapped",[331]],[[7506,7506],"mapped",[111]],[[7507,7507],"mapped",[596]],[[7508,7508],"mapped",[7446]],[[7509,7509],"mapped",[7447]],[[7510,7510],"mapped",[112]],[[7511,7511],"mapped",[116]],[[7512,7512],"mapped",[117]],[[7513,7513],"mapped",[7453]],[[7514,7514],"mapped",[623]],[[7515,7515],"mapped",[118]],[[7516,7516],"mapped",[7461]],[[7517,7517],"mapped",[946]],[[7518,7518],"mapped",[947]],[[7519,7519],"mapped",[948]],[[7520,7520],"mapped",[966]],[[7521,7521],"mapped",[967]],[[7522,7522],"mapped",[105]],[[7523,7523],"mapped",[114]],[[7524,7524],"mapped",[117]],[[7525,7525],"mapped",[118]],[[7526,7526],"mapped",[946]],[[7527,7527],"mapped",[947]],[[7528,7528],"mapped",[961]],[[7529,7529],"mapped",[966]],[[7530,7530],"mapped",[967]],[[7531,7531],"valid"],[[7532,7543],"valid"],[[7544,7544],"mapped",[1085]],[[7545,7578],"valid"],[[7579,7579],"mapped",[594]],[[7580,7580],"mapped",[99]],[[7581,7581],"mapped",[597]],[[7582,7582],"mapped",[240]],[[7583,7583],"mapped",[604]],[[7584,7584],"mapped",[102]],[[7585,7585],"mapped",[607]],[[7586,7586],"mapped",[609]],[[7587,7587],"mapped",[613]],[[7588,7588],"mapped",[616]],[[7589,7589],"mapped",[617]],[[7590,7590],"mapped",[618]],[[7591,7591],"mapped",[7547]],[[7592,7592],"mapped",[669]],[[7593,7593],"mapped",[621]],[[7594,7594],"mapped",[7557]],[[7595,7595],"mapped",[671]],[[7596,7596],"mapped",[625]],[[7597,7597],"mapped",[624]],[[7598,7598],"mapped",[626]],[[7599,7599],"mapped",[627]],[[7600,7600],"mapped",[628]],[[7601,7601],"mapped",[629]],[[7602,7602],"mapped",[632]],[[7603,7603],"mapped",[642]],[[7604,7604],"mapped",[643]],[[7605,7605],"mapped",[427]],[[7606,7606],"mapped",[649]],[[7607,7607],"mapped",[650]],[[7608,7608],"mapped",[7452]],[[7609,7609],"mapped",[651]],[[7610,7610],"mapped",[652]],[[7611,7611],"mapped",[122]],[[7612,7612],"mapped",[656]],[[7613,7613],"mapped",[657]],[[7614,7614],"mapped",[658]],[[7615,7615],"mapped",[952]],[[7616,7619],"valid"],[[7620,7626],"valid"],[[7627,7654],"valid"],[[7655,7669],"valid"],[[7670,7675],"disallowed"],[[7676,7676],"valid"],[[7677,7677],"valid"],[[7678,7679],"valid"],[[7680,7680],"mapped",[7681]],[[7681,7681],"valid"],[[7682,7682],"mapped",[7683]],[[7683,7683],"valid"],[[7684,7684],"mapped",[7685]],[[7685,7685],"valid"],[[7686,7686],"mapped",[7687]],[[7687,7687],"valid"],[[7688,7688],"mapped",[7689]],[[7689,7689],"valid"],[[7690,7690],"mapped",[7691]],[[7691,7691],"valid"],[[7692,7692],"mapped",[7693]],[[7693,7693],"valid"],[[7694,7694],"mapped",[7695]],[[7695,7695],"valid"],[[7696,7696],"mapped",[7697]],[[7697,7697],"valid"],[[7698,7698],"mapped",[7699]],[[7699,7699],"valid"],[[7700,7700],"mapped",[7701]],[[7701,7701],"valid"],[[7702,7702],"mapped",[7703]],[[7703,7703],"valid"],[[7704,7704],"mapped",[7705]],[[7705,7705],"valid"],[[7706,7706],"mapped",[7707]],[[7707,7707],"valid"],[[7708,7708],"mapped",[7709]],[[7709,7709],"valid"],[[7710,7710],"mapped",[7711]],[[7711,7711],"valid"],[[7712,7712],"mapped",[7713]],[[7713,7713],"valid"],[[7714,7714],"mapped",[7715]],[[7715,7715],"valid"],[[7716,7716],"mapped",[7717]],[[7717,7717],"valid"],[[7718,7718],"mapped",[7719]],[[7719,7719],"valid"],[[7720,7720],"mapped",[7721]],[[7721,7721],"valid"],[[7722,7722],"mapped",[7723]],[[7723,7723],"valid"],[[7724,7724],"mapped",[7725]],[[7725,7725],"valid"],[[7726,7726],"mapped",[7727]],[[7727,7727],"valid"],[[7728,7728],"mapped",[7729]],[[7729,7729],"valid"],[[7730,7730],"mapped",[7731]],[[7731,7731],"valid"],[[7732,7732],"mapped",[7733]],[[7733,7733],"valid"],[[7734,7734],"mapped",[7735]],[[7735,7735],"valid"],[[7736,7736],"mapped",[7737]],[[7737,7737],"valid"],[[7738,7738],"mapped",[7739]],[[7739,7739],"valid"],[[7740,7740],"mapped",[7741]],[[7741,7741],"valid"],[[7742,7742],"mapped",[7743]],[[7743,7743],"valid"],[[7744,7744],"mapped",[7745]],[[7745,7745],"valid"],[[7746,7746],"mapped",[7747]],[[7747,7747],"valid"],[[7748,7748],"mapped",[7749]],[[7749,7749],"valid"],[[7750,7750],"mapped",[7751]],[[7751,7751],"valid"],[[7752,7752],"mapped",[7753]],[[7753,7753],"valid"],[[7754,7754],"mapped",[7755]],[[7755,7755],"valid"],[[7756,7756],"mapped",[7757]],[[7757,7757],"valid"],[[7758,7758],"mapped",[7759]],[[7759,7759],"valid"],[[7760,7760],"mapped",[7761]],[[7761,7761],"valid"],[[7762,7762],"mapped",[7763]],[[7763,7763],"valid"],[[7764,7764],"mapped",[7765]],[[7765,7765],"valid"],[[7766,7766],"mapped",[7767]],[[7767,7767],"valid"],[[7768,7768],"mapped",[7769]],[[7769,7769],"valid"],[[7770,7770],"mapped",[7771]],[[7771,7771],"valid"],[[7772,7772],"mapped",[7773]],[[7773,7773],"valid"],[[7774,7774],"mapped",[7775]],[[7775,7775],"valid"],[[7776,7776],"mapped",[7777]],[[7777,7777],"valid"],[[7778,7778],"mapped",[7779]],[[7779,7779],"valid"],[[7780,7780],"mapped",[7781]],[[7781,7781],"valid"],[[7782,7782],"mapped",[7783]],[[7783,7783],"valid"],[[7784,7784],"mapped",[7785]],[[7785,7785],"valid"],[[7786,7786],"mapped",[7787]],[[7787,7787],"valid"],[[7788,7788],"mapped",[7789]],[[7789,7789],"valid"],[[7790,7790],"mapped",[7791]],[[7791,7791],"valid"],[[7792,7792],"mapped",[7793]],[[7793,7793],"valid"],[[7794,7794],"mapped",[7795]],[[7795,7795],"valid"],[[7796,7796],"mapped",[7797]],[[7797,7797],"valid"],[[7798,7798],"mapped",[7799]],[[7799,7799],"valid"],[[7800,7800],"mapped",[7801]],[[7801,7801],"valid"],[[7802,7802],"mapped",[7803]],[[7803,7803],"valid"],[[7804,7804],"mapped",[7805]],[[7805,7805],"valid"],[[7806,7806],"mapped",[7807]],[[7807,7807],"valid"],[[7808,7808],"mapped",[7809]],[[7809,7809],"valid"],[[7810,7810],"mapped",[7811]],[[7811,7811],"valid"],[[7812,7812],"mapped",[7813]],[[7813,7813],"valid"],[[7814,7814],"mapped",[7815]],[[7815,7815],"valid"],[[7816,7816],"mapped",[7817]],[[7817,7817],"valid"],[[7818,7818],"mapped",[7819]],[[7819,7819],"valid"],[[7820,7820],"mapped",[7821]],[[7821,7821],"valid"],[[7822,7822],"mapped",[7823]],[[7823,7823],"valid"],[[7824,7824],"mapped",[7825]],[[7825,7825],"valid"],[[7826,7826],"mapped",[7827]],[[7827,7827],"valid"],[[7828,7828],"mapped",[7829]],[[7829,7833],"valid"],[[7834,7834],"mapped",[97,702]],[[7835,7835],"mapped",[7777]],[[7836,7837],"valid"],[[7838,7838],"mapped",[115,115]],[[7839,7839],"valid"],[[7840,7840],"mapped",[7841]],[[7841,7841],"valid"],[[7842,7842],"mapped",[7843]],[[7843,7843],"valid"],[[7844,7844],"mapped",[7845]],[[7845,7845],"valid"],[[7846,7846],"mapped",[7847]],[[7847,7847],"valid"],[[7848,7848],"mapped",[7849]],[[7849,7849],"valid"],[[7850,7850],"mapped",[7851]],[[7851,7851],"valid"],[[7852,7852],"mapped",[7853]],[[7853,7853],"valid"],[[7854,7854],"mapped",[7855]],[[7855,7855],"valid"],[[7856,7856],"mapped",[7857]],[[7857,7857],"valid"],[[7858,7858],"mapped",[7859]],[[7859,7859],"valid"],[[7860,7860],"mapped",[7861]],[[7861,7861],"valid"],[[7862,7862],"mapped",[7863]],[[7863,7863],"valid"],[[7864,7864],"mapped",[7865]],[[7865,7865],"valid"],[[7866,7866],"mapped",[7867]],[[7867,7867],"valid"],[[7868,7868],"mapped",[7869]],[[7869,7869],"valid"],[[7870,7870],"mapped",[7871]],[[7871,7871],"valid"],[[7872,7872],"mapped",[7873]],[[7873,7873],"valid"],[[7874,7874],"mapped",[7875]],[[7875,7875],"valid"],[[7876,7876],"mapped",[7877]],[[7877,7877],"valid"],[[7878,7878],"mapped",[7879]],[[7879,7879],"valid"],[[7880,7880],"mapped",[7881]],[[7881,7881],"valid"],[[7882,7882],"mapped",[7883]],[[7883,7883],"valid"],[[7884,7884],"mapped",[7885]],[[7885,7885],"valid"],[[7886,7886],"mapped",[7887]],[[7887,7887],"valid"],[[7888,7888],"mapped",[7889]],[[7889,7889],"valid"],[[7890,7890],"mapped",[7891]],[[7891,7891],"valid"],[[7892,7892],"mapped",[7893]],[[7893,7893],"valid"],[[7894,7894],"mapped",[7895]],[[7895,7895],"valid"],[[7896,7896],"mapped",[7897]],[[7897,7897],"valid"],[[7898,7898],"mapped",[7899]],[[7899,7899],"valid"],[[7900,7900],"mapped",[7901]],[[7901,7901],"valid"],[[7902,7902],"mapped",[7903]],[[7903,7903],"valid"],[[7904,7904],"mapped",[7905]],[[7905,7905],"valid"],[[7906,7906],"mapped",[7907]],[[7907,7907],"valid"],[[7908,7908],"mapped",[7909]],[[7909,7909],"valid"],[[7910,7910],"mapped",[7911]],[[7911,7911],"valid"],[[7912,7912],"mapped",[7913]],[[7913,7913],"valid"],[[7914,7914],"mapped",[7915]],[[7915,7915],"valid"],[[7916,7916],"mapped",[7917]],[[7917,7917],"valid"],[[7918,7918],"mapped",[7919]],[[7919,7919],"valid"],[[7920,7920],"mapped",[7921]],[[7921,7921],"valid"],[[7922,7922],"mapped",[7923]],[[7923,7923],"valid"],[[7924,7924],"mapped",[7925]],[[7925,7925],"valid"],[[7926,7926],"mapped",[7927]],[[7927,7927],"valid"],[[7928,7928],"mapped",[7929]],[[7929,7929],"valid"],[[7930,7930],"mapped",[7931]],[[7931,7931],"valid"],[[7932,7932],"mapped",[7933]],[[7933,7933],"valid"],[[7934,7934],"mapped",[7935]],[[7935,7935],"valid"],[[7936,7943],"valid"],[[7944,7944],"mapped",[7936]],[[7945,7945],"mapped",[7937]],[[7946,7946],"mapped",[7938]],[[7947,7947],"mapped",[7939]],[[7948,7948],"mapped",[7940]],[[7949,7949],"mapped",[7941]],[[7950,7950],"mapped",[7942]],[[7951,7951],"mapped",[7943]],[[7952,7957],"valid"],[[7958,7959],"disallowed"],[[7960,7960],"mapped",[7952]],[[7961,7961],"mapped",[7953]],[[7962,7962],"mapped",[7954]],[[7963,7963],"mapped",[7955]],[[7964,7964],"mapped",[7956]],[[7965,7965],"mapped",[7957]],[[7966,7967],"disallowed"],[[7968,7975],"valid"],[[7976,7976],"mapped",[7968]],[[7977,7977],"mapped",[7969]],[[7978,7978],"mapped",[7970]],[[7979,7979],"mapped",[7971]],[[7980,7980],"mapped",[7972]],[[7981,7981],"mapped",[7973]],[[7982,7982],"mapped",[7974]],[[7983,7983],"mapped",[7975]],[[7984,7991],"valid"],[[7992,7992],"mapped",[7984]],[[7993,7993],"mapped",[7985]],[[7994,7994],"mapped",[7986]],[[7995,7995],"mapped",[7987]],[[7996,7996],"mapped",[7988]],[[7997,7997],"mapped",[7989]],[[7998,7998],"mapped",[7990]],[[7999,7999],"mapped",[7991]],[[8000,8005],"valid"],[[8006,8007],"disallowed"],[[8008,8008],"mapped",[8000]],[[8009,8009],"mapped",[8001]],[[8010,8010],"mapped",[8002]],[[8011,8011],"mapped",[8003]],[[8012,8012],"mapped",[8004]],[[8013,8013],"mapped",[8005]],[[8014,8015],"disallowed"],[[8016,8023],"valid"],[[8024,8024],"disallowed"],[[8025,8025],"mapped",[8017]],[[8026,8026],"disallowed"],[[8027,8027],"mapped",[8019]],[[8028,8028],"disallowed"],[[8029,8029],"mapped",[8021]],[[8030,8030],"disallowed"],[[8031,8031],"mapped",[8023]],[[8032,8039],"valid"],[[8040,8040],"mapped",[8032]],[[8041,8041],"mapped",[8033]],[[8042,8042],"mapped",[8034]],[[8043,8043],"mapped",[8035]],[[8044,8044],"mapped",[8036]],[[8045,8045],"mapped",[8037]],[[8046,8046],"mapped",[8038]],[[8047,8047],"mapped",[8039]],[[8048,8048],"valid"],[[8049,8049],"mapped",[940]],[[8050,8050],"valid"],[[8051,8051],"mapped",[941]],[[8052,8052],"valid"],[[8053,8053],"mapped",[942]],[[8054,8054],"valid"],[[8055,8055],"mapped",[943]],[[8056,8056],"valid"],[[8057,8057],"mapped",[972]],[[8058,8058],"valid"],[[8059,8059],"mapped",[973]],[[8060,8060],"valid"],[[8061,8061],"mapped",[974]],[[8062,8063],"disallowed"],[[8064,8064],"mapped",[7936,953]],[[8065,8065],"mapped",[7937,953]],[[8066,8066],"mapped",[7938,953]],[[8067,8067],"mapped",[7939,953]],[[8068,8068],"mapped",[7940,953]],[[8069,8069],"mapped",[7941,953]],[[8070,8070],"mapped",[7942,953]],[[8071,8071],"mapped",[7943,953]],[[8072,8072],"mapped",[7936,953]],[[8073,8073],"mapped",[7937,953]],[[8074,8074],"mapped",[7938,953]],[[8075,8075],"mapped",[7939,953]],[[8076,8076],"mapped",[7940,953]],[[8077,8077],"mapped",[7941,953]],[[8078,8078],"mapped",[7942,953]],[[8079,8079],"mapped",[7943,953]],[[8080,8080],"mapped",[7968,953]],[[8081,8081],"mapped",[7969,953]],[[8082,8082],"mapped",[7970,953]],[[8083,8083],"mapped",[7971,953]],[[8084,8084],"mapped",[7972,953]],[[8085,8085],"mapped",[7973,953]],[[8086,8086],"mapped",[7974,953]],[[8087,8087],"mapped",[7975,953]],[[8088,8088],"mapped",[7968,953]],[[8089,8089],"mapped",[7969,953]],[[8090,8090],"mapped",[7970,953]],[[8091,8091],"mapped",[7971,953]],[[8092,8092],"mapped",[7972,953]],[[8093,8093],"mapped",[7973,953]],[[8094,8094],"mapped",[7974,953]],[[8095,8095],"mapped",[7975,953]],[[8096,8096],"mapped",[8032,953]],[[8097,8097],"mapped",[8033,953]],[[8098,8098],"mapped",[8034,953]],[[8099,8099],"mapped",[8035,953]],[[8100,8100],"mapped",[8036,953]],[[8101,8101],"mapped",[8037,953]],[[8102,8102],"mapped",[8038,953]],[[8103,8103],"mapped",[8039,953]],[[8104,8104],"mapped",[8032,953]],[[8105,8105],"mapped",[8033,953]],[[8106,8106],"mapped",[8034,953]],[[8107,8107],"mapped",[8035,953]],[[8108,8108],"mapped",[8036,953]],[[8109,8109],"mapped",[8037,953]],[[8110,8110],"mapped",[8038,953]],[[8111,8111],"mapped",[8039,953]],[[8112,8113],"valid"],[[8114,8114],"mapped",[8048,953]],[[8115,8115],"mapped",[945,953]],[[8116,8116],"mapped",[940,953]],[[8117,8117],"disallowed"],[[8118,8118],"valid"],[[8119,8119],"mapped",[8118,953]],[[8120,8120],"mapped",[8112]],[[8121,8121],"mapped",[8113]],[[8122,8122],"mapped",[8048]],[[8123,8123],"mapped",[940]],[[8124,8124],"mapped",[945,953]],[[8125,8125],"disallowed_STD3_mapped",[32,787]],[[8126,8126],"mapped",[953]],[[8127,8127],"disallowed_STD3_mapped",[32,787]],[[8128,8128],"disallowed_STD3_mapped",[32,834]],[[8129,8129],"disallowed_STD3_mapped",[32,776,834]],[[8130,8130],"mapped",[8052,953]],[[8131,8131],"mapped",[951,953]],[[8132,8132],"mapped",[942,953]],[[8133,8133],"disallowed"],[[8134,8134],"valid"],[[8135,8135],"mapped",[8134,953]],[[8136,8136],"mapped",[8050]],[[8137,8137],"mapped",[941]],[[8138,8138],"mapped",[8052]],[[8139,8139],"mapped",[942]],[[8140,8140],"mapped",[951,953]],[[8141,8141],"disallowed_STD3_mapped",[32,787,768]],[[8142,8142],"disallowed_STD3_mapped",[32,787,769]],[[8143,8143],"disallowed_STD3_mapped",[32,787,834]],[[8144,8146],"valid"],[[8147,8147],"mapped",[912]],[[8148,8149],"disallowed"],[[8150,8151],"valid"],[[8152,8152],"mapped",[8144]],[[8153,8153],"mapped",[8145]],[[8154,8154],"mapped",[8054]],[[8155,8155],"mapped",[943]],[[8156,8156],"disallowed"],[[8157,8157],"disallowed_STD3_mapped",[32,788,768]],[[8158,8158],"disallowed_STD3_mapped",[32,788,769]],[[8159,8159],"disallowed_STD3_mapped",[32,788,834]],[[8160,8162],"valid"],[[8163,8163],"mapped",[944]],[[8164,8167],"valid"],[[8168,8168],"mapped",[8160]],[[8169,8169],"mapped",[8161]],[[8170,8170],"mapped",[8058]],[[8171,8171],"mapped",[973]],[[8172,8172],"mapped",[8165]],[[8173,8173],"disallowed_STD3_mapped",[32,776,768]],[[8174,8174],"disallowed_STD3_mapped",[32,776,769]],[[8175,8175],"disallowed_STD3_mapped",[96]],[[8176,8177],"disallowed"],[[8178,8178],"mapped",[8060,953]],[[8179,8179],"mapped",[969,953]],[[8180,8180],"mapped",[974,953]],[[8181,8181],"disallowed"],[[8182,8182],"valid"],[[8183,8183],"mapped",[8182,953]],[[8184,8184],"mapped",[8056]],[[8185,8185],"mapped",[972]],[[8186,8186],"mapped",[8060]],[[8187,8187],"mapped",[974]],[[8188,8188],"mapped",[969,953]],[[8189,8189],"disallowed_STD3_mapped",[32,769]],[[8190,8190],"disallowed_STD3_mapped",[32,788]],[[8191,8191],"disallowed"],[[8192,8202],"disallowed_STD3_mapped",[32]],[[8203,8203],"ignored"],[[8204,8205],"deviation",[]],[[8206,8207],"disallowed"],[[8208,8208],"valid",[],"NV8"],[[8209,8209],"mapped",[8208]],[[8210,8214],"valid",[],"NV8"],[[8215,8215],"disallowed_STD3_mapped",[32,819]],[[8216,8227],"valid",[],"NV8"],[[8228,8230],"disallowed"],[[8231,8231],"valid",[],"NV8"],[[8232,8238],"disallowed"],[[8239,8239],"disallowed_STD3_mapped",[32]],[[8240,8242],"valid",[],"NV8"],[[8243,8243],"mapped",[8242,8242]],[[8244,8244],"mapped",[8242,8242,8242]],[[8245,8245],"valid",[],"NV8"],[[8246,8246],"mapped",[8245,8245]],[[8247,8247],"mapped",[8245,8245,8245]],[[8248,8251],"valid",[],"NV8"],[[8252,8252],"disallowed_STD3_mapped",[33,33]],[[8253,8253],"valid",[],"NV8"],[[8254,8254],"disallowed_STD3_mapped",[32,773]],[[8255,8262],"valid",[],"NV8"],[[8263,8263],"disallowed_STD3_mapped",[63,63]],[[8264,8264],"disallowed_STD3_mapped",[63,33]],[[8265,8265],"disallowed_STD3_mapped",[33,63]],[[8266,8269],"valid",[],"NV8"],[[8270,8274],"valid",[],"NV8"],[[8275,8276],"valid",[],"NV8"],[[8277,8278],"valid",[],"NV8"],[[8279,8279],"mapped",[8242,8242,8242,8242]],[[8280,8286],"valid",[],"NV8"],[[8287,8287],"disallowed_STD3_mapped",[32]],[[8288,8288],"ignored"],[[8289,8291],"disallowed"],[[8292,8292],"ignored"],[[8293,8293],"disallowed"],[[8294,8297],"disallowed"],[[8298,8303],"disallowed"],[[8304,8304],"mapped",[48]],[[8305,8305],"mapped",[105]],[[8306,8307],"disallowed"],[[8308,8308],"mapped",[52]],[[8309,8309],"mapped",[53]],[[8310,8310],"mapped",[54]],[[8311,8311],"mapped",[55]],[[8312,8312],"mapped",[56]],[[8313,8313],"mapped",[57]],[[8314,8314],"disallowed_STD3_mapped",[43]],[[8315,8315],"mapped",[8722]],[[8316,8316],"disallowed_STD3_mapped",[61]],[[8317,8317],"disallowed_STD3_mapped",[40]],[[8318,8318],"disallowed_STD3_mapped",[41]],[[8319,8319],"mapped",[110]],[[8320,8320],"mapped",[48]],[[8321,8321],"mapped",[49]],[[8322,8322],"mapped",[50]],[[8323,8323],"mapped",[51]],[[8324,8324],"mapped",[52]],[[8325,8325],"mapped",[53]],[[8326,8326],"mapped",[54]],[[8327,8327],"mapped",[55]],[[8328,8328],"mapped",[56]],[[8329,8329],"mapped",[57]],[[8330,8330],"disallowed_STD3_mapped",[43]],[[8331,8331],"mapped",[8722]],[[8332,8332],"disallowed_STD3_mapped",[61]],[[8333,8333],"disallowed_STD3_mapped",[40]],[[8334,8334],"disallowed_STD3_mapped",[41]],[[8335,8335],"disallowed"],[[8336,8336],"mapped",[97]],[[8337,8337],"mapped",[101]],[[8338,8338],"mapped",[111]],[[8339,8339],"mapped",[120]],[[8340,8340],"mapped",[601]],[[8341,8341],"mapped",[104]],[[8342,8342],"mapped",[107]],[[8343,8343],"mapped",[108]],[[8344,8344],"mapped",[109]],[[8345,8345],"mapped",[110]],[[8346,8346],"mapped",[112]],[[8347,8347],"mapped",[115]],[[8348,8348],"mapped",[116]],[[8349,8351],"disallowed"],[[8352,8359],"valid",[],"NV8"],[[8360,8360],"mapped",[114,115]],[[8361,8362],"valid",[],"NV8"],[[8363,8363],"valid",[],"NV8"],[[8364,8364],"valid",[],"NV8"],[[8365,8367],"valid",[],"NV8"],[[8368,8369],"valid",[],"NV8"],[[8370,8373],"valid",[],"NV8"],[[8374,8376],"valid",[],"NV8"],[[8377,8377],"valid",[],"NV8"],[[8378,8378],"valid",[],"NV8"],[[8379,8381],"valid",[],"NV8"],[[8382,8382],"valid",[],"NV8"],[[8383,8399],"disallowed"],[[8400,8417],"valid",[],"NV8"],[[8418,8419],"valid",[],"NV8"],[[8420,8426],"valid",[],"NV8"],[[8427,8427],"valid",[],"NV8"],[[8428,8431],"valid",[],"NV8"],[[8432,8432],"valid",[],"NV8"],[[8433,8447],"disallowed"],[[8448,8448],"disallowed_STD3_mapped",[97,47,99]],[[8449,8449],"disallowed_STD3_mapped",[97,47,115]],[[8450,8450],"mapped",[99]],[[8451,8451],"mapped",[176,99]],[[8452,8452],"valid",[],"NV8"],[[8453,8453],"disallowed_STD3_mapped",[99,47,111]],[[8454,8454],"disallowed_STD3_mapped",[99,47,117]],[[8455,8455],"mapped",[603]],[[8456,8456],"valid",[],"NV8"],[[8457,8457],"mapped",[176,102]],[[8458,8458],"mapped",[103]],[[8459,8462],"mapped",[104]],[[8463,8463],"mapped",[295]],[[8464,8465],"mapped",[105]],[[8466,8467],"mapped",[108]],[[8468,8468],"valid",[],"NV8"],[[8469,8469],"mapped",[110]],[[8470,8470],"mapped",[110,111]],[[8471,8472],"valid",[],"NV8"],[[8473,8473],"mapped",[112]],[[8474,8474],"mapped",[113]],[[8475,8477],"mapped",[114]],[[8478,8479],"valid",[],"NV8"],[[8480,8480],"mapped",[115,109]],[[8481,8481],"mapped",[116,101,108]],[[8482,8482],"mapped",[116,109]],[[8483,8483],"valid",[],"NV8"],[[8484,8484],"mapped",[122]],[[8485,8485],"valid",[],"NV8"],[[8486,8486],"mapped",[969]],[[8487,8487],"valid",[],"NV8"],[[8488,8488],"mapped",[122]],[[8489,8489],"valid",[],"NV8"],[[8490,8490],"mapped",[107]],[[8491,8491],"mapped",[229]],[[8492,8492],"mapped",[98]],[[8493,8493],"mapped",[99]],[[8494,8494],"valid",[],"NV8"],[[8495,8496],"mapped",[101]],[[8497,8497],"mapped",[102]],[[8498,8498],"disallowed"],[[8499,8499],"mapped",[109]],[[8500,8500],"mapped",[111]],[[8501,8501],"mapped",[1488]],[[8502,8502],"mapped",[1489]],[[8503,8503],"mapped",[1490]],[[8504,8504],"mapped",[1491]],[[8505,8505],"mapped",[105]],[[8506,8506],"valid",[],"NV8"],[[8507,8507],"mapped",[102,97,120]],[[8508,8508],"mapped",[960]],[[8509,8510],"mapped",[947]],[[8511,8511],"mapped",[960]],[[8512,8512],"mapped",[8721]],[[8513,8516],"valid",[],"NV8"],[[8517,8518],"mapped",[100]],[[8519,8519],"mapped",[101]],[[8520,8520],"mapped",[105]],[[8521,8521],"mapped",[106]],[[8522,8523],"valid",[],"NV8"],[[8524,8524],"valid",[],"NV8"],[[8525,8525],"valid",[],"NV8"],[[8526,8526],"valid"],[[8527,8527],"valid",[],"NV8"],[[8528,8528],"mapped",[49,8260,55]],[[8529,8529],"mapped",[49,8260,57]],[[8530,8530],"mapped",[49,8260,49,48]],[[8531,8531],"mapped",[49,8260,51]],[[8532,8532],"mapped",[50,8260,51]],[[8533,8533],"mapped",[49,8260,53]],[[8534,8534],"mapped",[50,8260,53]],[[8535,8535],"mapped",[51,8260,53]],[[8536,8536],"mapped",[52,8260,53]],[[8537,8537],"mapped",[49,8260,54]],[[8538,8538],"mapped",[53,8260,54]],[[8539,8539],"mapped",[49,8260,56]],[[8540,8540],"mapped",[51,8260,56]],[[8541,8541],"mapped",[53,8260,56]],[[8542,8542],"mapped",[55,8260,56]],[[8543,8543],"mapped",[49,8260]],[[8544,8544],"mapped",[105]],[[8545,8545],"mapped",[105,105]],[[8546,8546],"mapped",[105,105,105]],[[8547,8547],"mapped",[105,118]],[[8548,8548],"mapped",[118]],[[8549,8549],"mapped",[118,105]],[[8550,8550],"mapped",[118,105,105]],[[8551,8551],"mapped",[118,105,105,105]],[[8552,8552],"mapped",[105,120]],[[8553,8553],"mapped",[120]],[[8554,8554],"mapped",[120,105]],[[8555,8555],"mapped",[120,105,105]],[[8556,8556],"mapped",[108]],[[8557,8557],"mapped",[99]],[[8558,8558],"mapped",[100]],[[8559,8559],"mapped",[109]],[[8560,8560],"mapped",[105]],[[8561,8561],"mapped",[105,105]],[[8562,8562],"mapped",[105,105,105]],[[8563,8563],"mapped",[105,118]],[[8564,8564],"mapped",[118]],[[8565,8565],"mapped",[118,105]],[[8566,8566],"mapped",[118,105,105]],[[8567,8567],"mapped",[118,105,105,105]],[[8568,8568],"mapped",[105,120]],[[8569,8569],"mapped",[120]],[[8570,8570],"mapped",[120,105]],[[8571,8571],"mapped",[120,105,105]],[[8572,8572],"mapped",[108]],[[8573,8573],"mapped",[99]],[[8574,8574],"mapped",[100]],[[8575,8575],"mapped",[109]],[[8576,8578],"valid",[],"NV8"],[[8579,8579],"disallowed"],[[8580,8580],"valid"],[[8581,8584],"valid",[],"NV8"],[[8585,8585],"mapped",[48,8260,51]],[[8586,8587],"valid",[],"NV8"],[[8588,8591],"disallowed"],[[8592,8682],"valid",[],"NV8"],[[8683,8691],"valid",[],"NV8"],[[8692,8703],"valid",[],"NV8"],[[8704,8747],"valid",[],"NV8"],[[8748,8748],"mapped",[8747,8747]],[[8749,8749],"mapped",[8747,8747,8747]],[[8750,8750],"valid",[],"NV8"],[[8751,8751],"mapped",[8750,8750]],[[8752,8752],"mapped",[8750,8750,8750]],[[8753,8799],"valid",[],"NV8"],[[8800,8800],"disallowed_STD3_valid"],[[8801,8813],"valid",[],"NV8"],[[8814,8815],"disallowed_STD3_valid"],[[8816,8945],"valid",[],"NV8"],[[8946,8959],"valid",[],"NV8"],[[8960,8960],"valid",[],"NV8"],[[8961,8961],"valid",[],"NV8"],[[8962,9000],"valid",[],"NV8"],[[9001,9001],"mapped",[12296]],[[9002,9002],"mapped",[12297]],[[9003,9082],"valid",[],"NV8"],[[9083,9083],"valid",[],"NV8"],[[9084,9084],"valid",[],"NV8"],[[9085,9114],"valid",[],"NV8"],[[9115,9166],"valid",[],"NV8"],[[9167,9168],"valid",[],"NV8"],[[9169,9179],"valid",[],"NV8"],[[9180,9191],"valid",[],"NV8"],[[9192,9192],"valid",[],"NV8"],[[9193,9203],"valid",[],"NV8"],[[9204,9210],"valid",[],"NV8"],[[9211,9215],"disallowed"],[[9216,9252],"valid",[],"NV8"],[[9253,9254],"valid",[],"NV8"],[[9255,9279],"disallowed"],[[9280,9290],"valid",[],"NV8"],[[9291,9311],"disallowed"],[[9312,9312],"mapped",[49]],[[9313,9313],"mapped",[50]],[[9314,9314],"mapped",[51]],[[9315,9315],"mapped",[52]],[[9316,9316],"mapped",[53]],[[9317,9317],"mapped",[54]],[[9318,9318],"mapped",[55]],[[9319,9319],"mapped",[56]],[[9320,9320],"mapped",[57]],[[9321,9321],"mapped",[49,48]],[[9322,9322],"mapped",[49,49]],[[9323,9323],"mapped",[49,50]],[[9324,9324],"mapped",[49,51]],[[9325,9325],"mapped",[49,52]],[[9326,9326],"mapped",[49,53]],[[9327,9327],"mapped",[49,54]],[[9328,9328],"mapped",[49,55]],[[9329,9329],"mapped",[49,56]],[[9330,9330],"mapped",[49,57]],[[9331,9331],"mapped",[50,48]],[[9332,9332],"disallowed_STD3_mapped",[40,49,41]],[[9333,9333],"disallowed_STD3_mapped",[40,50,41]],[[9334,9334],"disallowed_STD3_mapped",[40,51,41]],[[9335,9335],"disallowed_STD3_mapped",[40,52,41]],[[9336,9336],"disallowed_STD3_mapped",[40,53,41]],[[9337,9337],"disallowed_STD3_mapped",[40,54,41]],[[9338,9338],"disallowed_STD3_mapped",[40,55,41]],[[9339,9339],"disallowed_STD3_mapped",[40,56,41]],[[9340,9340],"disallowed_STD3_mapped",[40,57,41]],[[9341,9341],"disallowed_STD3_mapped",[40,49,48,41]],[[9342,9342],"disallowed_STD3_mapped",[40,49,49,41]],[[9343,9343],"disallowed_STD3_mapped",[40,49,50,41]],[[9344,9344],"disallowed_STD3_mapped",[40,49,51,41]],[[9345,9345],"disallowed_STD3_mapped",[40,49,52,41]],[[9346,9346],"disallowed_STD3_mapped",[40,49,53,41]],[[9347,9347],"disallowed_STD3_mapped",[40,49,54,41]],[[9348,9348],"disallowed_STD3_mapped",[40,49,55,41]],[[9349,9349],"disallowed_STD3_mapped",[40,49,56,41]],[[9350,9350],"disallowed_STD3_mapped",[40,49,57,41]],[[9351,9351],"disallowed_STD3_mapped",[40,50,48,41]],[[9352,9371],"disallowed"],[[9372,9372],"disallowed_STD3_mapped",[40,97,41]],[[9373,9373],"disallowed_STD3_mapped",[40,98,41]],[[9374,9374],"disallowed_STD3_mapped",[40,99,41]],[[9375,9375],"disallowed_STD3_mapped",[40,100,41]],[[9376,9376],"disallowed_STD3_mapped",[40,101,41]],[[9377,9377],"disallowed_STD3_mapped",[40,102,41]],[[9378,9378],"disallowed_STD3_mapped",[40,103,41]],[[9379,9379],"disallowed_STD3_mapped",[40,104,41]],[[9380,9380],"disallowed_STD3_mapped",[40,105,41]],[[9381,9381],"disallowed_STD3_mapped",[40,106,41]],[[9382,9382],"disallowed_STD3_mapped",[40,107,41]],[[9383,9383],"disallowed_STD3_mapped",[40,108,41]],[[9384,9384],"disallowed_STD3_mapped",[40,109,41]],[[9385,9385],"disallowed_STD3_mapped",[40,110,41]],[[9386,9386],"disallowed_STD3_mapped",[40,111,41]],[[9387,9387],"disallowed_STD3_mapped",[40,112,41]],[[9388,9388],"disallowed_STD3_mapped",[40,113,41]],[[9389,9389],"disallowed_STD3_mapped",[40,114,41]],[[9390,9390],"disallowed_STD3_mapped",[40,115,41]],[[9391,9391],"disallowed_STD3_mapped",[40,116,41]],[[9392,9392],"disallowed_STD3_mapped",[40,117,41]],[[9393,9393],"disallowed_STD3_mapped",[40,118,41]],[[9394,9394],"disallowed_STD3_mapped",[40,119,41]],[[9395,9395],"disallowed_STD3_mapped",[40,120,41]],[[9396,9396],"disallowed_STD3_mapped",[40,121,41]],[[9397,9397],"disallowed_STD3_mapped",[40,122,41]],[[9398,9398],"mapped",[97]],[[9399,9399],"mapped",[98]],[[9400,9400],"mapped",[99]],[[9401,9401],"mapped",[100]],[[9402,9402],"mapped",[101]],[[9403,9403],"mapped",[102]],[[9404,9404],"mapped",[103]],[[9405,9405],"mapped",[104]],[[9406,9406],"mapped",[105]],[[9407,9407],"mapped",[106]],[[9408,9408],"mapped",[107]],[[9409,9409],"mapped",[108]],[[9410,9410],"mapped",[109]],[[9411,9411],"mapped",[110]],[[9412,9412],"mapped",[111]],[[9413,9413],"mapped",[112]],[[9414,9414],"mapped",[113]],[[9415,9415],"mapped",[114]],[[9416,9416],"mapped",[115]],[[9417,9417],"mapped",[116]],[[9418,9418],"mapped",[117]],[[9419,9419],"mapped",[118]],[[9420,9420],"mapped",[119]],[[9421,9421],"mapped",[120]],[[9422,9422],"mapped",[121]],[[9423,9423],"mapped",[122]],[[9424,9424],"mapped",[97]],[[9425,9425],"mapped",[98]],[[9426,9426],"mapped",[99]],[[9427,9427],"mapped",[100]],[[9428,9428],"mapped",[101]],[[9429,9429],"mapped",[102]],[[9430,9430],"mapped",[103]],[[9431,9431],"mapped",[104]],[[9432,9432],"mapped",[105]],[[9433,9433],"mapped",[106]],[[9434,9434],"mapped",[107]],[[9435,9435],"mapped",[108]],[[9436,9436],"mapped",[109]],[[9437,9437],"mapped",[110]],[[9438,9438],"mapped",[111]],[[9439,9439],"mapped",[112]],[[9440,9440],"mapped",[113]],[[9441,9441],"mapped",[114]],[[9442,9442],"mapped",[115]],[[9443,9443],"mapped",[116]],[[9444,9444],"mapped",[117]],[[9445,9445],"mapped",[118]],[[9446,9446],"mapped",[119]],[[9447,9447],"mapped",[120]],[[9448,9448],"mapped",[121]],[[9449,9449],"mapped",[122]],[[9450,9450],"mapped",[48]],[[9451,9470],"valid",[],"NV8"],[[9471,9471],"valid",[],"NV8"],[[9472,9621],"valid",[],"NV8"],[[9622,9631],"valid",[],"NV8"],[[9632,9711],"valid",[],"NV8"],[[9712,9719],"valid",[],"NV8"],[[9720,9727],"valid",[],"NV8"],[[9728,9747],"valid",[],"NV8"],[[9748,9749],"valid",[],"NV8"],[[9750,9751],"valid",[],"NV8"],[[9752,9752],"valid",[],"NV8"],[[9753,9753],"valid",[],"NV8"],[[9754,9839],"valid",[],"NV8"],[[9840,9841],"valid",[],"NV8"],[[9842,9853],"valid",[],"NV8"],[[9854,9855],"valid",[],"NV8"],[[9856,9865],"valid",[],"NV8"],[[9866,9873],"valid",[],"NV8"],[[9874,9884],"valid",[],"NV8"],[[9885,9885],"valid",[],"NV8"],[[9886,9887],"valid",[],"NV8"],[[9888,9889],"valid",[],"NV8"],[[9890,9905],"valid",[],"NV8"],[[9906,9906],"valid",[],"NV8"],[[9907,9916],"valid",[],"NV8"],[[9917,9919],"valid",[],"NV8"],[[9920,9923],"valid",[],"NV8"],[[9924,9933],"valid",[],"NV8"],[[9934,9934],"valid",[],"NV8"],[[9935,9953],"valid",[],"NV8"],[[9954,9954],"valid",[],"NV8"],[[9955,9955],"valid",[],"NV8"],[[9956,9959],"valid",[],"NV8"],[[9960,9983],"valid",[],"NV8"],[[9984,9984],"valid",[],"NV8"],[[9985,9988],"valid",[],"NV8"],[[9989,9989],"valid",[],"NV8"],[[9990,9993],"valid",[],"NV8"],[[9994,9995],"valid",[],"NV8"],[[9996,10023],"valid",[],"NV8"],[[10024,10024],"valid",[],"NV8"],[[10025,10059],"valid",[],"NV8"],[[10060,10060],"valid",[],"NV8"],[[10061,10061],"valid",[],"NV8"],[[10062,10062],"valid",[],"NV8"],[[10063,10066],"valid",[],"NV8"],[[10067,10069],"valid",[],"NV8"],[[10070,10070],"valid",[],"NV8"],[[10071,10071],"valid",[],"NV8"],[[10072,10078],"valid",[],"NV8"],[[10079,10080],"valid",[],"NV8"],[[10081,10087],"valid",[],"NV8"],[[10088,10101],"valid",[],"NV8"],[[10102,10132],"valid",[],"NV8"],[[10133,10135],"valid",[],"NV8"],[[10136,10159],"valid",[],"NV8"],[[10160,10160],"valid",[],"NV8"],[[10161,10174],"valid",[],"NV8"],[[10175,10175],"valid",[],"NV8"],[[10176,10182],"valid",[],"NV8"],[[10183,10186],"valid",[],"NV8"],[[10187,10187],"valid",[],"NV8"],[[10188,10188],"valid",[],"NV8"],[[10189,10189],"valid",[],"NV8"],[[10190,10191],"valid",[],"NV8"],[[10192,10219],"valid",[],"NV8"],[[10220,10223],"valid",[],"NV8"],[[10224,10239],"valid",[],"NV8"],[[10240,10495],"valid",[],"NV8"],[[10496,10763],"valid",[],"NV8"],[[10764,10764],"mapped",[8747,8747,8747,8747]],[[10765,10867],"valid",[],"NV8"],[[10868,10868],"disallowed_STD3_mapped",[58,58,61]],[[10869,10869],"disallowed_STD3_mapped",[61,61]],[[10870,10870],"disallowed_STD3_mapped",[61,61,61]],[[10871,10971],"valid",[],"NV8"],[[10972,10972],"mapped",[10973,824]],[[10973,11007],"valid",[],"NV8"],[[11008,11021],"valid",[],"NV8"],[[11022,11027],"valid",[],"NV8"],[[11028,11034],"valid",[],"NV8"],[[11035,11039],"valid",[],"NV8"],[[11040,11043],"valid",[],"NV8"],[[11044,11084],"valid",[],"NV8"],[[11085,11087],"valid",[],"NV8"],[[11088,11092],"valid",[],"NV8"],[[11093,11097],"valid",[],"NV8"],[[11098,11123],"valid",[],"NV8"],[[11124,11125],"disallowed"],[[11126,11157],"valid",[],"NV8"],[[11158,11159],"disallowed"],[[11160,11193],"valid",[],"NV8"],[[11194,11196],"disallowed"],[[11197,11208],"valid",[],"NV8"],[[11209,11209],"disallowed"],[[11210,11217],"valid",[],"NV8"],[[11218,11243],"disallowed"],[[11244,11247],"valid",[],"NV8"],[[11248,11263],"disallowed"],[[11264,11264],"mapped",[11312]],[[11265,11265],"mapped",[11313]],[[11266,11266],"mapped",[11314]],[[11267,11267],"mapped",[11315]],[[11268,11268],"mapped",[11316]],[[11269,11269],"mapped",[11317]],[[11270,11270],"mapped",[11318]],[[11271,11271],"mapped",[11319]],[[11272,11272],"mapped",[11320]],[[11273,11273],"mapped",[11321]],[[11274,11274],"mapped",[11322]],[[11275,11275],"mapped",[11323]],[[11276,11276],"mapped",[11324]],[[11277,11277],"mapped",[11325]],[[11278,11278],"mapped",[11326]],[[11279,11279],"mapped",[11327]],[[11280,11280],"mapped",[11328]],[[11281,11281],"mapped",[11329]],[[11282,11282],"mapped",[11330]],[[11283,11283],"mapped",[11331]],[[11284,11284],"mapped",[11332]],[[11285,11285],"mapped",[11333]],[[11286,11286],"mapped",[11334]],[[11287,11287],"mapped",[11335]],[[11288,11288],"mapped",[11336]],[[11289,11289],"mapped",[11337]],[[11290,11290],"mapped",[11338]],[[11291,11291],"mapped",[11339]],[[11292,11292],"mapped",[11340]],[[11293,11293],"mapped",[11341]],[[11294,11294],"mapped",[11342]],[[11295,11295],"mapped",[11343]],[[11296,11296],"mapped",[11344]],[[11297,11297],"mapped",[11345]],[[11298,11298],"mapped",[11346]],[[11299,11299],"mapped",[11347]],[[11300,11300],"mapped",[11348]],[[11301,11301],"mapped",[11349]],[[11302,11302],"mapped",[11350]],[[11303,11303],"mapped",[11351]],[[11304,11304],"mapped",[11352]],[[11305,11305],"mapped",[11353]],[[11306,11306],"mapped",[11354]],[[11307,11307],"mapped",[11355]],[[11308,11308],"mapped",[11356]],[[11309,11309],"mapped",[11357]],[[11310,11310],"mapped",[11358]],[[11311,11311],"disallowed"],[[11312,11358],"valid"],[[11359,11359],"disallowed"],[[11360,11360],"mapped",[11361]],[[11361,11361],"valid"],[[11362,11362],"mapped",[619]],[[11363,11363],"mapped",[7549]],[[11364,11364],"mapped",[637]],[[11365,11366],"valid"],[[11367,11367],"mapped",[11368]],[[11368,11368],"valid"],[[11369,11369],"mapped",[11370]],[[11370,11370],"valid"],[[11371,11371],"mapped",[11372]],[[11372,11372],"valid"],[[11373,11373],"mapped",[593]],[[11374,11374],"mapped",[625]],[[11375,11375],"mapped",[592]],[[11376,11376],"mapped",[594]],[[11377,11377],"valid"],[[11378,11378],"mapped",[11379]],[[11379,11379],"valid"],[[11380,11380],"valid"],[[11381,11381],"mapped",[11382]],[[11382,11383],"valid"],[[11384,11387],"valid"],[[11388,11388],"mapped",[106]],[[11389,11389],"mapped",[118]],[[11390,11390],"mapped",[575]],[[11391,11391],"mapped",[576]],[[11392,11392],"mapped",[11393]],[[11393,11393],"valid"],[[11394,11394],"mapped",[11395]],[[11395,11395],"valid"],[[11396,11396],"mapped",[11397]],[[11397,11397],"valid"],[[11398,11398],"mapped",[11399]],[[11399,11399],"valid"],[[11400,11400],"mapped",[11401]],[[11401,11401],"valid"],[[11402,11402],"mapped",[11403]],[[11403,11403],"valid"],[[11404,11404],"mapped",[11405]],[[11405,11405],"valid"],[[11406,11406],"mapped",[11407]],[[11407,11407],"valid"],[[11408,11408],"mapped",[11409]],[[11409,11409],"valid"],[[11410,11410],"mapped",[11411]],[[11411,11411],"valid"],[[11412,11412],"mapped",[11413]],[[11413,11413],"valid"],[[11414,11414],"mapped",[11415]],[[11415,11415],"valid"],[[11416,11416],"mapped",[11417]],[[11417,11417],"valid"],[[11418,11418],"mapped",[11419]],[[11419,11419],"valid"],[[11420,11420],"mapped",[11421]],[[11421,11421],"valid"],[[11422,11422],"mapped",[11423]],[[11423,11423],"valid"],[[11424,11424],"mapped",[11425]],[[11425,11425],"valid"],[[11426,11426],"mapped",[11427]],[[11427,11427],"valid"],[[11428,11428],"mapped",[11429]],[[11429,11429],"valid"],[[11430,11430],"mapped",[11431]],[[11431,11431],"valid"],[[11432,11432],"mapped",[11433]],[[11433,11433],"valid"],[[11434,11434],"mapped",[11435]],[[11435,11435],"valid"],[[11436,11436],"mapped",[11437]],[[11437,11437],"valid"],[[11438,11438],"mapped",[11439]],[[11439,11439],"valid"],[[11440,11440],"mapped",[11441]],[[11441,11441],"valid"],[[11442,11442],"mapped",[11443]],[[11443,11443],"valid"],[[11444,11444],"mapped",[11445]],[[11445,11445],"valid"],[[11446,11446],"mapped",[11447]],[[11447,11447],"valid"],[[11448,11448],"mapped",[11449]],[[11449,11449],"valid"],[[11450,11450],"mapped",[11451]],[[11451,11451],"valid"],[[11452,11452],"mapped",[11453]],[[11453,11453],"valid"],[[11454,11454],"mapped",[11455]],[[11455,11455],"valid"],[[11456,11456],"mapped",[11457]],[[11457,11457],"valid"],[[11458,11458],"mapped",[11459]],[[11459,11459],"valid"],[[11460,11460],"mapped",[11461]],[[11461,11461],"valid"],[[11462,11462],"mapped",[11463]],[[11463,11463],"valid"],[[11464,11464],"mapped",[11465]],[[11465,11465],"valid"],[[11466,11466],"mapped",[11467]],[[11467,11467],"valid"],[[11468,11468],"mapped",[11469]],[[11469,11469],"valid"],[[11470,11470],"mapped",[11471]],[[11471,11471],"valid"],[[11472,11472],"mapped",[11473]],[[11473,11473],"valid"],[[11474,11474],"mapped",[11475]],[[11475,11475],"valid"],[[11476,11476],"mapped",[11477]],[[11477,11477],"valid"],[[11478,11478],"mapped",[11479]],[[11479,11479],"valid"],[[11480,11480],"mapped",[11481]],[[11481,11481],"valid"],[[11482,11482],"mapped",[11483]],[[11483,11483],"valid"],[[11484,11484],"mapped",[11485]],[[11485,11485],"valid"],[[11486,11486],"mapped",[11487]],[[11487,11487],"valid"],[[11488,11488],"mapped",[11489]],[[11489,11489],"valid"],[[11490,11490],"mapped",[11491]],[[11491,11492],"valid"],[[11493,11498],"valid",[],"NV8"],[[11499,11499],"mapped",[11500]],[[11500,11500],"valid"],[[11501,11501],"mapped",[11502]],[[11502,11505],"valid"],[[11506,11506],"mapped",[11507]],[[11507,11507],"valid"],[[11508,11512],"disallowed"],[[11513,11519],"valid",[],"NV8"],[[11520,11557],"valid"],[[11558,11558],"disallowed"],[[11559,11559],"valid"],[[11560,11564],"disallowed"],[[11565,11565],"valid"],[[11566,11567],"disallowed"],[[11568,11621],"valid"],[[11622,11623],"valid"],[[11624,11630],"disallowed"],[[11631,11631],"mapped",[11617]],[[11632,11632],"valid",[],"NV8"],[[11633,11646],"disallowed"],[[11647,11647],"valid"],[[11648,11670],"valid"],[[11671,11679],"disallowed"],[[11680,11686],"valid"],[[11687,11687],"disallowed"],[[11688,11694],"valid"],[[11695,11695],"disallowed"],[[11696,11702],"valid"],[[11703,11703],"disallowed"],[[11704,11710],"valid"],[[11711,11711],"disallowed"],[[11712,11718],"valid"],[[11719,11719],"disallowed"],[[11720,11726],"valid"],[[11727,11727],"disallowed"],[[11728,11734],"valid"],[[11735,11735],"disallowed"],[[11736,11742],"valid"],[[11743,11743],"disallowed"],[[11744,11775],"valid"],[[11776,11799],"valid",[],"NV8"],[[11800,11803],"valid",[],"NV8"],[[11804,11805],"valid",[],"NV8"],[[11806,11822],"valid",[],"NV8"],[[11823,11823],"valid"],[[11824,11824],"valid",[],"NV8"],[[11825,11825],"valid",[],"NV8"],[[11826,11835],"valid",[],"NV8"],[[11836,11842],"valid",[],"NV8"],[[11843,11903],"disallowed"],[[11904,11929],"valid",[],"NV8"],[[11930,11930],"disallowed"],[[11931,11934],"valid",[],"NV8"],[[11935,11935],"mapped",[27597]],[[11936,12018],"valid",[],"NV8"],[[12019,12019],"mapped",[40863]],[[12020,12031],"disallowed"],[[12032,12032],"mapped",[19968]],[[12033,12033],"mapped",[20008]],[[12034,12034],"mapped",[20022]],[[12035,12035],"mapped",[20031]],[[12036,12036],"mapped",[20057]],[[12037,12037],"mapped",[20101]],[[12038,12038],"mapped",[20108]],[[12039,12039],"mapped",[20128]],[[12040,12040],"mapped",[20154]],[[12041,12041],"mapped",[20799]],[[12042,12042],"mapped",[20837]],[[12043,12043],"mapped",[20843]],[[12044,12044],"mapped",[20866]],[[12045,12045],"mapped",[20886]],[[12046,12046],"mapped",[20907]],[[12047,12047],"mapped",[20960]],[[12048,12048],"mapped",[20981]],[[12049,12049],"mapped",[20992]],[[12050,12050],"mapped",[21147]],[[12051,12051],"mapped",[21241]],[[12052,12052],"mapped",[21269]],[[12053,12053],"mapped",[21274]],[[12054,12054],"mapped",[21304]],[[12055,12055],"mapped",[21313]],[[12056,12056],"mapped",[21340]],[[12057,12057],"mapped",[21353]],[[12058,12058],"mapped",[21378]],[[12059,12059],"mapped",[21430]],[[12060,12060],"mapped",[21448]],[[12061,12061],"mapped",[21475]],[[12062,12062],"mapped",[22231]],[[12063,12063],"mapped",[22303]],[[12064,12064],"mapped",[22763]],[[12065,12065],"mapped",[22786]],[[12066,12066],"mapped",[22794]],[[12067,12067],"mapped",[22805]],[[12068,12068],"mapped",[22823]],[[12069,12069],"mapped",[22899]],[[12070,12070],"mapped",[23376]],[[12071,12071],"mapped",[23424]],[[12072,12072],"mapped",[23544]],[[12073,12073],"mapped",[23567]],[[12074,12074],"mapped",[23586]],[[12075,12075],"mapped",[23608]],[[12076,12076],"mapped",[23662]],[[12077,12077],"mapped",[23665]],[[12078,12078],"mapped",[24027]],[[12079,12079],"mapped",[24037]],[[12080,12080],"mapped",[24049]],[[12081,12081],"mapped",[24062]],[[12082,12082],"mapped",[24178]],[[12083,12083],"mapped",[24186]],[[12084,12084],"mapped",[24191]],[[12085,12085],"mapped",[24308]],[[12086,12086],"mapped",[24318]],[[12087,12087],"mapped",[24331]],[[12088,12088],"mapped",[24339]],[[12089,12089],"mapped",[24400]],[[12090,12090],"mapped",[24417]],[[12091,12091],"mapped",[24435]],[[12092,12092],"mapped",[24515]],[[12093,12093],"mapped",[25096]],[[12094,12094],"mapped",[25142]],[[12095,12095],"mapped",[25163]],[[12096,12096],"mapped",[25903]],[[12097,12097],"mapped",[25908]],[[12098,12098],"mapped",[25991]],[[12099,12099],"mapped",[26007]],[[12100,12100],"mapped",[26020]],[[12101,12101],"mapped",[26041]],[[12102,12102],"mapped",[26080]],[[12103,12103],"mapped",[26085]],[[12104,12104],"mapped",[26352]],[[12105,12105],"mapped",[26376]],[[12106,12106],"mapped",[26408]],[[12107,12107],"mapped",[27424]],[[12108,12108],"mapped",[27490]],[[12109,12109],"mapped",[27513]],[[12110,12110],"mapped",[27571]],[[12111,12111],"mapped",[27595]],[[12112,12112],"mapped",[27604]],[[12113,12113],"mapped",[27611]],[[12114,12114],"mapped",[27663]],[[12115,12115],"mapped",[27668]],[[12116,12116],"mapped",[27700]],[[12117,12117],"mapped",[28779]],[[12118,12118],"mapped",[29226]],[[12119,12119],"mapped",[29238]],[[12120,12120],"mapped",[29243]],[[12121,12121],"mapped",[29247]],[[12122,12122],"mapped",[29255]],[[12123,12123],"mapped",[29273]],[[12124,12124],"mapped",[29275]],[[12125,12125],"mapped",[29356]],[[12126,12126],"mapped",[29572]],[[12127,12127],"mapped",[29577]],[[12128,12128],"mapped",[29916]],[[12129,12129],"mapped",[29926]],[[12130,12130],"mapped",[29976]],[[12131,12131],"mapped",[29983]],[[12132,12132],"mapped",[29992]],[[12133,12133],"mapped",[30000]],[[12134,12134],"mapped",[30091]],[[12135,12135],"mapped",[30098]],[[12136,12136],"mapped",[30326]],[[12137,12137],"mapped",[30333]],[[12138,12138],"mapped",[30382]],[[12139,12139],"mapped",[30399]],[[12140,12140],"mapped",[30446]],[[12141,12141],"mapped",[30683]],[[12142,12142],"mapped",[30690]],[[12143,12143],"mapped",[30707]],[[12144,12144],"mapped",[31034]],[[12145,12145],"mapped",[31160]],[[12146,12146],"mapped",[31166]],[[12147,12147],"mapped",[31348]],[[12148,12148],"mapped",[31435]],[[12149,12149],"mapped",[31481]],[[12150,12150],"mapped",[31859]],[[12151,12151],"mapped",[31992]],[[12152,12152],"mapped",[32566]],[[12153,12153],"mapped",[32593]],[[12154,12154],"mapped",[32650]],[[12155,12155],"mapped",[32701]],[[12156,12156],"mapped",[32769]],[[12157,12157],"mapped",[32780]],[[12158,12158],"mapped",[32786]],[[12159,12159],"mapped",[32819]],[[12160,12160],"mapped",[32895]],[[12161,12161],"mapped",[32905]],[[12162,12162],"mapped",[33251]],[[12163,12163],"mapped",[33258]],[[12164,12164],"mapped",[33267]],[[12165,12165],"mapped",[33276]],[[12166,12166],"mapped",[33292]],[[12167,12167],"mapped",[33307]],[[12168,12168],"mapped",[33311]],[[12169,12169],"mapped",[33390]],[[12170,12170],"mapped",[33394]],[[12171,12171],"mapped",[33400]],[[12172,12172],"mapped",[34381]],[[12173,12173],"mapped",[34411]],[[12174,12174],"mapped",[34880]],[[12175,12175],"mapped",[34892]],[[12176,12176],"mapped",[34915]],[[12177,12177],"mapped",[35198]],[[12178,12178],"mapped",[35211]],[[12179,12179],"mapped",[35282]],[[12180,12180],"mapped",[35328]],[[12181,12181],"mapped",[35895]],[[12182,12182],"mapped",[35910]],[[12183,12183],"mapped",[35925]],[[12184,12184],"mapped",[35960]],[[12185,12185],"mapped",[35997]],[[12186,12186],"mapped",[36196]],[[12187,12187],"mapped",[36208]],[[12188,12188],"mapped",[36275]],[[12189,12189],"mapped",[36523]],[[12190,12190],"mapped",[36554]],[[12191,12191],"mapped",[36763]],[[12192,12192],"mapped",[36784]],[[12193,12193],"mapped",[36789]],[[12194,12194],"mapped",[37009]],[[12195,12195],"mapped",[37193]],[[12196,12196],"mapped",[37318]],[[12197,12197],"mapped",[37324]],[[12198,12198],"mapped",[37329]],[[12199,12199],"mapped",[38263]],[[12200,12200],"mapped",[38272]],[[12201,12201],"mapped",[38428]],[[12202,12202],"mapped",[38582]],[[12203,12203],"mapped",[38585]],[[12204,12204],"mapped",[38632]],[[12205,12205],"mapped",[38737]],[[12206,12206],"mapped",[38750]],[[12207,12207],"mapped",[38754]],[[12208,12208],"mapped",[38761]],[[12209,12209],"mapped",[38859]],[[12210,12210],"mapped",[38893]],[[12211,12211],"mapped",[38899]],[[12212,12212],"mapped",[38913]],[[12213,12213],"mapped",[39080]],[[12214,12214],"mapped",[39131]],[[12215,12215],"mapped",[39135]],[[12216,12216],"mapped",[39318]],[[12217,12217],"mapped",[39321]],[[12218,12218],"mapped",[39340]],[[12219,12219],"mapped",[39592]],[[12220,12220],"mapped",[39640]],[[12221,12221],"mapped",[39647]],[[12222,12222],"mapped",[39717]],[[12223,12223],"mapped",[39727]],[[12224,12224],"mapped",[39730]],[[12225,12225],"mapped",[39740]],[[12226,12226],"mapped",[39770]],[[12227,12227],"mapped",[40165]],[[12228,12228],"mapped",[40565]],[[12229,12229],"mapped",[40575]],[[12230,12230],"mapped",[40613]],[[12231,12231],"mapped",[40635]],[[12232,12232],"mapped",[40643]],[[12233,12233],"mapped",[40653]],[[12234,12234],"mapped",[40657]],[[12235,12235],"mapped",[40697]],[[12236,12236],"mapped",[40701]],[[12237,12237],"mapped",[40718]],[[12238,12238],"mapped",[40723]],[[12239,12239],"mapped",[40736]],[[12240,12240],"mapped",[40763]],[[12241,12241],"mapped",[40778]],[[12242,12242],"mapped",[40786]],[[12243,12243],"mapped",[40845]],[[12244,12244],"mapped",[40860]],[[12245,12245],"mapped",[40864]],[[12246,12271],"disallowed"],[[12272,12283],"disallowed"],[[12284,12287],"disallowed"],[[12288,12288],"disallowed_STD3_mapped",[32]],[[12289,12289],"valid",[],"NV8"],[[12290,12290],"mapped",[46]],[[12291,12292],"valid",[],"NV8"],[[12293,12295],"valid"],[[12296,12329],"valid",[],"NV8"],[[12330,12333],"valid"],[[12334,12341],"valid",[],"NV8"],[[12342,12342],"mapped",[12306]],[[12343,12343],"valid",[],"NV8"],[[12344,12344],"mapped",[21313]],[[12345,12345],"mapped",[21316]],[[12346,12346],"mapped",[21317]],[[12347,12347],"valid",[],"NV8"],[[12348,12348],"valid"],[[12349,12349],"valid",[],"NV8"],[[12350,12350],"valid",[],"NV8"],[[12351,12351],"valid",[],"NV8"],[[12352,12352],"disallowed"],[[12353,12436],"valid"],[[12437,12438],"valid"],[[12439,12440],"disallowed"],[[12441,12442],"valid"],[[12443,12443],"disallowed_STD3_mapped",[32,12441]],[[12444,12444],"disallowed_STD3_mapped",[32,12442]],[[12445,12446],"valid"],[[12447,12447],"mapped",[12424,12426]],[[12448,12448],"valid",[],"NV8"],[[12449,12542],"valid"],[[12543,12543],"mapped",[12467,12488]],[[12544,12548],"disallowed"],[[12549,12588],"valid"],[[12589,12589],"valid"],[[12590,12592],"disallowed"],[[12593,12593],"mapped",[4352]],[[12594,12594],"mapped",[4353]],[[12595,12595],"mapped",[4522]],[[12596,12596],"mapped",[4354]],[[12597,12597],"mapped",[4524]],[[12598,12598],"mapped",[4525]],[[12599,12599],"mapped",[4355]],[[12600,12600],"mapped",[4356]],[[12601,12601],"mapped",[4357]],[[12602,12602],"mapped",[4528]],[[12603,12603],"mapped",[4529]],[[12604,12604],"mapped",[4530]],[[12605,12605],"mapped",[4531]],[[12606,12606],"mapped",[4532]],[[12607,12607],"mapped",[4533]],[[12608,12608],"mapped",[4378]],[[12609,12609],"mapped",[4358]],[[12610,12610],"mapped",[4359]],[[12611,12611],"mapped",[4360]],[[12612,12612],"mapped",[4385]],[[12613,12613],"mapped",[4361]],[[12614,12614],"mapped",[4362]],[[12615,12615],"mapped",[4363]],[[12616,12616],"mapped",[4364]],[[12617,12617],"mapped",[4365]],[[12618,12618],"mapped",[4366]],[[12619,12619],"mapped",[4367]],[[12620,12620],"mapped",[4368]],[[12621,12621],"mapped",[4369]],[[12622,12622],"mapped",[4370]],[[12623,12623],"mapped",[4449]],[[12624,12624],"mapped",[4450]],[[12625,12625],"mapped",[4451]],[[12626,12626],"mapped",[4452]],[[12627,12627],"mapped",[4453]],[[12628,12628],"mapped",[4454]],[[12629,12629],"mapped",[4455]],[[12630,12630],"mapped",[4456]],[[12631,12631],"mapped",[4457]],[[12632,12632],"mapped",[4458]],[[12633,12633],"mapped",[4459]],[[12634,12634],"mapped",[4460]],[[12635,12635],"mapped",[4461]],[[12636,12636],"mapped",[4462]],[[12637,12637],"mapped",[4463]],[[12638,12638],"mapped",[4464]],[[12639,12639],"mapped",[4465]],[[12640,12640],"mapped",[4466]],[[12641,12641],"mapped",[4467]],[[12642,12642],"mapped",[4468]],[[12643,12643],"mapped",[4469]],[[12644,12644],"disallowed"],[[12645,12645],"mapped",[4372]],[[12646,12646],"mapped",[4373]],[[12647,12647],"mapped",[4551]],[[12648,12648],"mapped",[4552]],[[12649,12649],"mapped",[4556]],[[12650,12650],"mapped",[4558]],[[12651,12651],"mapped",[4563]],[[12652,12652],"mapped",[4567]],[[12653,12653],"mapped",[4569]],[[12654,12654],"mapped",[4380]],[[12655,12655],"mapped",[4573]],[[12656,12656],"mapped",[4575]],[[12657,12657],"mapped",[4381]],[[12658,12658],"mapped",[4382]],[[12659,12659],"mapped",[4384]],[[12660,12660],"mapped",[4386]],[[12661,12661],"mapped",[4387]],[[12662,12662],"mapped",[4391]],[[12663,12663],"mapped",[4393]],[[12664,12664],"mapped",[4395]],[[12665,12665],"mapped",[4396]],[[12666,12666],"mapped",[4397]],[[12667,12667],"mapped",[4398]],[[12668,12668],"mapped",[4399]],[[12669,12669],"mapped",[4402]],[[12670,12670],"mapped",[4406]],[[12671,12671],"mapped",[4416]],[[12672,12672],"mapped",[4423]],[[12673,12673],"mapped",[4428]],[[12674,12674],"mapped",[4593]],[[12675,12675],"mapped",[4594]],[[12676,12676],"mapped",[4439]],[[12677,12677],"mapped",[4440]],[[12678,12678],"mapped",[4441]],[[12679,12679],"mapped",[4484]],[[12680,12680],"mapped",[4485]],[[12681,12681],"mapped",[4488]],[[12682,12682],"mapped",[4497]],[[12683,12683],"mapped",[4498]],[[12684,12684],"mapped",[4500]],[[12685,12685],"mapped",[4510]],[[12686,12686],"mapped",[4513]],[[12687,12687],"disallowed"],[[12688,12689],"valid",[],"NV8"],[[12690,12690],"mapped",[19968]],[[12691,12691],"mapped",[20108]],[[12692,12692],"mapped",[19977]],[[12693,12693],"mapped",[22235]],[[12694,12694],"mapped",[19978]],[[12695,12695],"mapped",[20013]],[[12696,12696],"mapped",[19979]],[[12697,12697],"mapped",[30002]],[[12698,12698],"mapped",[20057]],[[12699,12699],"mapped",[19993]],[[12700,12700],"mapped",[19969]],[[12701,12701],"mapped",[22825]],[[12702,12702],"mapped",[22320]],[[12703,12703],"mapped",[20154]],[[12704,12727],"valid"],[[12728,12730],"valid"],[[12731,12735],"disallowed"],[[12736,12751],"valid",[],"NV8"],[[12752,12771],"valid",[],"NV8"],[[12772,12783],"disallowed"],[[12784,12799],"valid"],[[12800,12800],"disallowed_STD3_mapped",[40,4352,41]],[[12801,12801],"disallowed_STD3_mapped",[40,4354,41]],[[12802,12802],"disallowed_STD3_mapped",[40,4355,41]],[[12803,12803],"disallowed_STD3_mapped",[40,4357,41]],[[12804,12804],"disallowed_STD3_mapped",[40,4358,41]],[[12805,12805],"disallowed_STD3_mapped",[40,4359,41]],[[12806,12806],"disallowed_STD3_mapped",[40,4361,41]],[[12807,12807],"disallowed_STD3_mapped",[40,4363,41]],[[12808,12808],"disallowed_STD3_mapped",[40,4364,41]],[[12809,12809],"disallowed_STD3_mapped",[40,4366,41]],[[12810,12810],"disallowed_STD3_mapped",[40,4367,41]],[[12811,12811],"disallowed_STD3_mapped",[40,4368,41]],[[12812,12812],"disallowed_STD3_mapped",[40,4369,41]],[[12813,12813],"disallowed_STD3_mapped",[40,4370,41]],[[12814,12814],"disallowed_STD3_mapped",[40,44032,41]],[[12815,12815],"disallowed_STD3_mapped",[40,45208,41]],[[12816,12816],"disallowed_STD3_mapped",[40,45796,41]],[[12817,12817],"disallowed_STD3_mapped",[40,46972,41]],[[12818,12818],"disallowed_STD3_mapped",[40,47560,41]],[[12819,12819],"disallowed_STD3_mapped",[40,48148,41]],[[12820,12820],"disallowed_STD3_mapped",[40,49324,41]],[[12821,12821],"disallowed_STD3_mapped",[40,50500,41]],[[12822,12822],"disallowed_STD3_mapped",[40,51088,41]],[[12823,12823],"disallowed_STD3_mapped",[40,52264,41]],[[12824,12824],"disallowed_STD3_mapped",[40,52852,41]],[[12825,12825],"disallowed_STD3_mapped",[40,53440,41]],[[12826,12826],"disallowed_STD3_mapped",[40,54028,41]],[[12827,12827],"disallowed_STD3_mapped",[40,54616,41]],[[12828,12828],"disallowed_STD3_mapped",[40,51452,41]],[[12829,12829],"disallowed_STD3_mapped",[40,50724,51204,41]],[[12830,12830],"disallowed_STD3_mapped",[40,50724,54980,41]],[[12831,12831],"disallowed"],[[12832,12832],"disallowed_STD3_mapped",[40,19968,41]],[[12833,12833],"disallowed_STD3_mapped",[40,20108,41]],[[12834,12834],"disallowed_STD3_mapped",[40,19977,41]],[[12835,12835],"disallowed_STD3_mapped",[40,22235,41]],[[12836,12836],"disallowed_STD3_mapped",[40,20116,41]],[[12837,12837],"disallowed_STD3_mapped",[40,20845,41]],[[12838,12838],"disallowed_STD3_mapped",[40,19971,41]],[[12839,12839],"disallowed_STD3_mapped",[40,20843,41]],[[12840,12840],"disallowed_STD3_mapped",[40,20061,41]],[[12841,12841],"disallowed_STD3_mapped",[40,21313,41]],[[12842,12842],"disallowed_STD3_mapped",[40,26376,41]],[[12843,12843],"disallowed_STD3_mapped",[40,28779,41]],[[12844,12844],"disallowed_STD3_mapped",[40,27700,41]],[[12845,12845],"disallowed_STD3_mapped",[40,26408,41]],[[12846,12846],"disallowed_STD3_mapped",[40,37329,41]],[[12847,12847],"disallowed_STD3_mapped",[40,22303,41]],[[12848,12848],"disallowed_STD3_mapped",[40,26085,41]],[[12849,12849],"disallowed_STD3_mapped",[40,26666,41]],[[12850,12850],"disallowed_STD3_mapped",[40,26377,41]],[[12851,12851],"disallowed_STD3_mapped",[40,31038,41]],[[12852,12852],"disallowed_STD3_mapped",[40,21517,41]],[[12853,12853],"disallowed_STD3_mapped",[40,29305,41]],[[12854,12854],"disallowed_STD3_mapped",[40,36001,41]],[[12855,12855],"disallowed_STD3_mapped",[40,31069,41]],[[12856,12856],"disallowed_STD3_mapped",[40,21172,41]],[[12857,12857],"disallowed_STD3_mapped",[40,20195,41]],[[12858,12858],"disallowed_STD3_mapped",[40,21628,41]],[[12859,12859],"disallowed_STD3_mapped",[40,23398,41]],[[12860,12860],"disallowed_STD3_mapped",[40,30435,41]],[[12861,12861],"disallowed_STD3_mapped",[40,20225,41]],[[12862,12862],"disallowed_STD3_mapped",[40,36039,41]],[[12863,12863],"disallowed_STD3_mapped",[40,21332,41]],[[12864,12864],"disallowed_STD3_mapped",[40,31085,41]],[[12865,12865],"disallowed_STD3_mapped",[40,20241,41]],[[12866,12866],"disallowed_STD3_mapped",[40,33258,41]],[[12867,12867],"disallowed_STD3_mapped",[40,33267,41]],[[12868,12868],"mapped",[21839]],[[12869,12869],"mapped",[24188]],[[12870,12870],"mapped",[25991]],[[12871,12871],"mapped",[31631]],[[12872,12879],"valid",[],"NV8"],[[12880,12880],"mapped",[112,116,101]],[[12881,12881],"mapped",[50,49]],[[12882,12882],"mapped",[50,50]],[[12883,12883],"mapped",[50,51]],[[12884,12884],"mapped",[50,52]],[[12885,12885],"mapped",[50,53]],[[12886,12886],"mapped",[50,54]],[[12887,12887],"mapped",[50,55]],[[12888,12888],"mapped",[50,56]],[[12889,12889],"mapped",[50,57]],[[12890,12890],"mapped",[51,48]],[[12891,12891],"mapped",[51,49]],[[12892,12892],"mapped",[51,50]],[[12893,12893],"mapped",[51,51]],[[12894,12894],"mapped",[51,52]],[[12895,12895],"mapped",[51,53]],[[12896,12896],"mapped",[4352]],[[12897,12897],"mapped",[4354]],[[12898,12898],"mapped",[4355]],[[12899,12899],"mapped",[4357]],[[12900,12900],"mapped",[4358]],[[12901,12901],"mapped",[4359]],[[12902,12902],"mapped",[4361]],[[12903,12903],"mapped",[4363]],[[12904,12904],"mapped",[4364]],[[12905,12905],"mapped",[4366]],[[12906,12906],"mapped",[4367]],[[12907,12907],"mapped",[4368]],[[12908,12908],"mapped",[4369]],[[12909,12909],"mapped",[4370]],[[12910,12910],"mapped",[44032]],[[12911,12911],"mapped",[45208]],[[12912,12912],"mapped",[45796]],[[12913,12913],"mapped",[46972]],[[12914,12914],"mapped",[47560]],[[12915,12915],"mapped",[48148]],[[12916,12916],"mapped",[49324]],[[12917,12917],"mapped",[50500]],[[12918,12918],"mapped",[51088]],[[12919,12919],"mapped",[52264]],[[12920,12920],"mapped",[52852]],[[12921,12921],"mapped",[53440]],[[12922,12922],"mapped",[54028]],[[12923,12923],"mapped",[54616]],[[12924,12924],"mapped",[52280,44256]],[[12925,12925],"mapped",[51452,51032]],[[12926,12926],"mapped",[50864]],[[12927,12927],"valid",[],"NV8"],[[12928,12928],"mapped",[19968]],[[12929,12929],"mapped",[20108]],[[12930,12930],"mapped",[19977]],[[12931,12931],"mapped",[22235]],[[12932,12932],"mapped",[20116]],[[12933,12933],"mapped",[20845]],[[12934,12934],"mapped",[19971]],[[12935,12935],"mapped",[20843]],[[12936,12936],"mapped",[20061]],[[12937,12937],"mapped",[21313]],[[12938,12938],"mapped",[26376]],[[12939,12939],"mapped",[28779]],[[12940,12940],"mapped",[27700]],[[12941,12941],"mapped",[26408]],[[12942,12942],"mapped",[37329]],[[12943,12943],"mapped",[22303]],[[12944,12944],"mapped",[26085]],[[12945,12945],"mapped",[26666]],[[12946,12946],"mapped",[26377]],[[12947,12947],"mapped",[31038]],[[12948,12948],"mapped",[21517]],[[12949,12949],"mapped",[29305]],[[12950,12950],"mapped",[36001]],[[12951,12951],"mapped",[31069]],[[12952,12952],"mapped",[21172]],[[12953,12953],"mapped",[31192]],[[12954,12954],"mapped",[30007]],[[12955,12955],"mapped",[22899]],[[12956,12956],"mapped",[36969]],[[12957,12957],"mapped",[20778]],[[12958,12958],"mapped",[21360]],[[12959,12959],"mapped",[27880]],[[12960,12960],"mapped",[38917]],[[12961,12961],"mapped",[20241]],[[12962,12962],"mapped",[20889]],[[12963,12963],"mapped",[27491]],[[12964,12964],"mapped",[19978]],[[12965,12965],"mapped",[20013]],[[12966,12966],"mapped",[19979]],[[12967,12967],"mapped",[24038]],[[12968,12968],"mapped",[21491]],[[12969,12969],"mapped",[21307]],[[12970,12970],"mapped",[23447]],[[12971,12971],"mapped",[23398]],[[12972,12972],"mapped",[30435]],[[12973,12973],"mapped",[20225]],[[12974,12974],"mapped",[36039]],[[12975,12975],"mapped",[21332]],[[12976,12976],"mapped",[22812]],[[12977,12977],"mapped",[51,54]],[[12978,12978],"mapped",[51,55]],[[12979,12979],"mapped",[51,56]],[[12980,12980],"mapped",[51,57]],[[12981,12981],"mapped",[52,48]],[[12982,12982],"mapped",[52,49]],[[12983,12983],"mapped",[52,50]],[[12984,12984],"mapped",[52,51]],[[12985,12985],"mapped",[52,52]],[[12986,12986],"mapped",[52,53]],[[12987,12987],"mapped",[52,54]],[[12988,12988],"mapped",[52,55]],[[12989,12989],"mapped",[52,56]],[[12990,12990],"mapped",[52,57]],[[12991,12991],"mapped",[53,48]],[[12992,12992],"mapped",[49,26376]],[[12993,12993],"mapped",[50,26376]],[[12994,12994],"mapped",[51,26376]],[[12995,12995],"mapped",[52,26376]],[[12996,12996],"mapped",[53,26376]],[[12997,12997],"mapped",[54,26376]],[[12998,12998],"mapped",[55,26376]],[[12999,12999],"mapped",[56,26376]],[[13000,13000],"mapped",[57,26376]],[[13001,13001],"mapped",[49,48,26376]],[[13002,13002],"mapped",[49,49,26376]],[[13003,13003],"mapped",[49,50,26376]],[[13004,13004],"mapped",[104,103]],[[13005,13005],"mapped",[101,114,103]],[[13006,13006],"mapped",[101,118]],[[13007,13007],"mapped",[108,116,100]],[[13008,13008],"mapped",[12450]],[[13009,13009],"mapped",[12452]],[[13010,13010],"mapped",[12454]],[[13011,13011],"mapped",[12456]],[[13012,13012],"mapped",[12458]],[[13013,13013],"mapped",[12459]],[[13014,13014],"mapped",[12461]],[[13015,13015],"mapped",[12463]],[[13016,13016],"mapped",[12465]],[[13017,13017],"mapped",[12467]],[[13018,13018],"mapped",[12469]],[[13019,13019],"mapped",[12471]],[[13020,13020],"mapped",[12473]],[[13021,13021],"mapped",[12475]],[[13022,13022],"mapped",[12477]],[[13023,13023],"mapped",[12479]],[[13024,13024],"mapped",[12481]],[[13025,13025],"mapped",[12484]],[[13026,13026],"mapped",[12486]],[[13027,13027],"mapped",[12488]],[[13028,13028],"mapped",[12490]],[[13029,13029],"mapped",[12491]],[[13030,13030],"mapped",[12492]],[[13031,13031],"mapped",[12493]],[[13032,13032],"mapped",[12494]],[[13033,13033],"mapped",[12495]],[[13034,13034],"mapped",[12498]],[[13035,13035],"mapped",[12501]],[[13036,13036],"mapped",[12504]],[[13037,13037],"mapped",[12507]],[[13038,13038],"mapped",[12510]],[[13039,13039],"mapped",[12511]],[[13040,13040],"mapped",[12512]],[[13041,13041],"mapped",[12513]],[[13042,13042],"mapped",[12514]],[[13043,13043],"mapped",[12516]],[[13044,13044],"mapped",[12518]],[[13045,13045],"mapped",[12520]],[[13046,13046],"mapped",[12521]],[[13047,13047],"mapped",[12522]],[[13048,13048],"mapped",[12523]],[[13049,13049],"mapped",[12524]],[[13050,13050],"mapped",[12525]],[[13051,13051],"mapped",[12527]],[[13052,13052],"mapped",[12528]],[[13053,13053],"mapped",[12529]],[[13054,13054],"mapped",[12530]],[[13055,13055],"disallowed"],[[13056,13056],"mapped",[12450,12497,12540,12488]],[[13057,13057],"mapped",[12450,12523,12501,12449]],[[13058,13058],"mapped",[12450,12531,12506,12450]],[[13059,13059],"mapped",[12450,12540,12523]],[[13060,13060],"mapped",[12452,12491,12531,12464]],[[13061,13061],"mapped",[12452,12531,12481]],[[13062,13062],"mapped",[12454,12457,12531]],[[13063,13063],"mapped",[12456,12473,12463,12540,12489]],[[13064,13064],"mapped",[12456,12540,12459,12540]],[[13065,13065],"mapped",[12458,12531,12473]],[[13066,13066],"mapped",[12458,12540,12512]],[[13067,13067],"mapped",[12459,12452,12522]],[[13068,13068],"mapped",[12459,12521,12483,12488]],[[13069,13069],"mapped",[12459,12525,12522,12540]],[[13070,13070],"mapped",[12460,12525,12531]],[[13071,13071],"mapped",[12460,12531,12510]],[[13072,13072],"mapped",[12462,12460]],[[13073,13073],"mapped",[12462,12491,12540]],[[13074,13074],"mapped",[12461,12517,12522,12540]],[[13075,13075],"mapped",[12462,12523,12480,12540]],[[13076,13076],"mapped",[12461,12525]],[[13077,13077],"mapped",[12461,12525,12464,12521,12512]],[[13078,13078],"mapped",[12461,12525,12513,12540,12488,12523]],[[13079,13079],"mapped",[12461,12525,12527,12483,12488]],[[13080,13080],"mapped",[12464,12521,12512]],[[13081,13081],"mapped",[12464,12521,12512,12488,12531]],[[13082,13082],"mapped",[12463,12523,12476,12452,12525]],[[13083,13083],"mapped",[12463,12525,12540,12493]],[[13084,13084],"mapped",[12465,12540,12473]],[[13085,13085],"mapped",[12467,12523,12490]],[[13086,13086],"mapped",[12467,12540,12509]],[[13087,13087],"mapped",[12469,12452,12463,12523]],[[13088,13088],"mapped",[12469,12531,12481,12540,12512]],[[13089,13089],"mapped",[12471,12522,12531,12464]],[[13090,13090],"mapped",[12475,12531,12481]],[[13091,13091],"mapped",[12475,12531,12488]],[[13092,13092],"mapped",[12480,12540,12473]],[[13093,13093],"mapped",[12487,12471]],[[13094,13094],"mapped",[12489,12523]],[[13095,13095],"mapped",[12488,12531]],[[13096,13096],"mapped",[12490,12494]],[[13097,13097],"mapped",[12494,12483,12488]],[[13098,13098],"mapped",[12495,12452,12484]],[[13099,13099],"mapped",[12497,12540,12475,12531,12488]],[[13100,13100],"mapped",[12497,12540,12484]],[[13101,13101],"mapped",[12496,12540,12524,12523]],[[13102,13102],"mapped",[12500,12450,12473,12488,12523]],[[13103,13103],"mapped",[12500,12463,12523]],[[13104,13104],"mapped",[12500,12467]],[[13105,13105],"mapped",[12499,12523]],[[13106,13106],"mapped",[12501,12449,12521,12483,12489]],[[13107,13107],"mapped",[12501,12451,12540,12488]],[[13108,13108],"mapped",[12502,12483,12471,12455,12523]],[[13109,13109],"mapped",[12501,12521,12531]],[[13110,13110],"mapped",[12504,12463,12479,12540,12523]],[[13111,13111],"mapped",[12506,12477]],[[13112,13112],"mapped",[12506,12491,12498]],[[13113,13113],"mapped",[12504,12523,12484]],[[13114,13114],"mapped",[12506,12531,12473]],[[13115,13115],"mapped",[12506,12540,12472]],[[13116,13116],"mapped",[12505,12540,12479]],[[13117,13117],"mapped",[12509,12452,12531,12488]],[[13118,13118],"mapped",[12508,12523,12488]],[[13119,13119],"mapped",[12507,12531]],[[13120,13120],"mapped",[12509,12531,12489]],[[13121,13121],"mapped",[12507,12540,12523]],[[13122,13122],"mapped",[12507,12540,12531]],[[13123,13123],"mapped",[12510,12452,12463,12525]],[[13124,13124],"mapped",[12510,12452,12523]],[[13125,13125],"mapped",[12510,12483,12495]],[[13126,13126],"mapped",[12510,12523,12463]],[[13127,13127],"mapped",[12510,12531,12471,12519,12531]],[[13128,13128],"mapped",[12511,12463,12525,12531]],[[13129,13129],"mapped",[12511,12522]],[[13130,13130],"mapped",[12511,12522,12496,12540,12523]],[[13131,13131],"mapped",[12513,12460]],[[13132,13132],"mapped",[12513,12460,12488,12531]],[[13133,13133],"mapped",[12513,12540,12488,12523]],[[13134,13134],"mapped",[12516,12540,12489]],[[13135,13135],"mapped",[12516,12540,12523]],[[13136,13136],"mapped",[12518,12450,12531]],[[13137,13137],"mapped",[12522,12483,12488,12523]],[[13138,13138],"mapped",[12522,12521]],[[13139,13139],"mapped",[12523,12500,12540]],[[13140,13140],"mapped",[12523,12540,12502,12523]],[[13141,13141],"mapped",[12524,12512]],[[13142,13142],"mapped",[12524,12531,12488,12466,12531]],[[13143,13143],"mapped",[12527,12483,12488]],[[13144,13144],"mapped",[48,28857]],[[13145,13145],"mapped",[49,28857]],[[13146,13146],"mapped",[50,28857]],[[13147,13147],"mapped",[51,28857]],[[13148,13148],"mapped",[52,28857]],[[13149,13149],"mapped",[53,28857]],[[13150,13150],"mapped",[54,28857]],[[13151,13151],"mapped",[55,28857]],[[13152,13152],"mapped",[56,28857]],[[13153,13153],"mapped",[57,28857]],[[13154,13154],"mapped",[49,48,28857]],[[13155,13155],"mapped",[49,49,28857]],[[13156,13156],"mapped",[49,50,28857]],[[13157,13157],"mapped",[49,51,28857]],[[13158,13158],"mapped",[49,52,28857]],[[13159,13159],"mapped",[49,53,28857]],[[13160,13160],"mapped",[49,54,28857]],[[13161,13161],"mapped",[49,55,28857]],[[13162,13162],"mapped",[49,56,28857]],[[13163,13163],"mapped",[49,57,28857]],[[13164,13164],"mapped",[50,48,28857]],[[13165,13165],"mapped",[50,49,28857]],[[13166,13166],"mapped",[50,50,28857]],[[13167,13167],"mapped",[50,51,28857]],[[13168,13168],"mapped",[50,52,28857]],[[13169,13169],"mapped",[104,112,97]],[[13170,13170],"mapped",[100,97]],[[13171,13171],"mapped",[97,117]],[[13172,13172],"mapped",[98,97,114]],[[13173,13173],"mapped",[111,118]],[[13174,13174],"mapped",[112,99]],[[13175,13175],"mapped",[100,109]],[[13176,13176],"mapped",[100,109,50]],[[13177,13177],"mapped",[100,109,51]],[[13178,13178],"mapped",[105,117]],[[13179,13179],"mapped",[24179,25104]],[[13180,13180],"mapped",[26157,21644]],[[13181,13181],"mapped",[22823,27491]],[[13182,13182],"mapped",[26126,27835]],[[13183,13183],"mapped",[26666,24335,20250,31038]],[[13184,13184],"mapped",[112,97]],[[13185,13185],"mapped",[110,97]],[[13186,13186],"mapped",[956,97]],[[13187,13187],"mapped",[109,97]],[[13188,13188],"mapped",[107,97]],[[13189,13189],"mapped",[107,98]],[[13190,13190],"mapped",[109,98]],[[13191,13191],"mapped",[103,98]],[[13192,13192],"mapped",[99,97,108]],[[13193,13193],"mapped",[107,99,97,108]],[[13194,13194],"mapped",[112,102]],[[13195,13195],"mapped",[110,102]],[[13196,13196],"mapped",[956,102]],[[13197,13197],"mapped",[956,103]],[[13198,13198],"mapped",[109,103]],[[13199,13199],"mapped",[107,103]],[[13200,13200],"mapped",[104,122]],[[13201,13201],"mapped",[107,104,122]],[[13202,13202],"mapped",[109,104,122]],[[13203,13203],"mapped",[103,104,122]],[[13204,13204],"mapped",[116,104,122]],[[13205,13205],"mapped",[956,108]],[[13206,13206],"mapped",[109,108]],[[13207,13207],"mapped",[100,108]],[[13208,13208],"mapped",[107,108]],[[13209,13209],"mapped",[102,109]],[[13210,13210],"mapped",[110,109]],[[13211,13211],"mapped",[956,109]],[[13212,13212],"mapped",[109,109]],[[13213,13213],"mapped",[99,109]],[[13214,13214],"mapped",[107,109]],[[13215,13215],"mapped",[109,109,50]],[[13216,13216],"mapped",[99,109,50]],[[13217,13217],"mapped",[109,50]],[[13218,13218],"mapped",[107,109,50]],[[13219,13219],"mapped",[109,109,51]],[[13220,13220],"mapped",[99,109,51]],[[13221,13221],"mapped",[109,51]],[[13222,13222],"mapped",[107,109,51]],[[13223,13223],"mapped",[109,8725,115]],[[13224,13224],"mapped",[109,8725,115,50]],[[13225,13225],"mapped",[112,97]],[[13226,13226],"mapped",[107,112,97]],[[13227,13227],"mapped",[109,112,97]],[[13228,13228],"mapped",[103,112,97]],[[13229,13229],"mapped",[114,97,100]],[[13230,13230],"mapped",[114,97,100,8725,115]],[[13231,13231],"mapped",[114,97,100,8725,115,50]],[[13232,13232],"mapped",[112,115]],[[13233,13233],"mapped",[110,115]],[[13234,13234],"mapped",[956,115]],[[13235,13235],"mapped",[109,115]],[[13236,13236],"mapped",[112,118]],[[13237,13237],"mapped",[110,118]],[[13238,13238],"mapped",[956,118]],[[13239,13239],"mapped",[109,118]],[[13240,13240],"mapped",[107,118]],[[13241,13241],"mapped",[109,118]],[[13242,13242],"mapped",[112,119]],[[13243,13243],"mapped",[110,119]],[[13244,13244],"mapped",[956,119]],[[13245,13245],"mapped",[109,119]],[[13246,13246],"mapped",[107,119]],[[13247,13247],"mapped",[109,119]],[[13248,13248],"mapped",[107,969]],[[13249,13249],"mapped",[109,969]],[[13250,13250],"disallowed"],[[13251,13251],"mapped",[98,113]],[[13252,13252],"mapped",[99,99]],[[13253,13253],"mapped",[99,100]],[[13254,13254],"mapped",[99,8725,107,103]],[[13255,13255],"disallowed"],[[13256,13256],"mapped",[100,98]],[[13257,13257],"mapped",[103,121]],[[13258,13258],"mapped",[104,97]],[[13259,13259],"mapped",[104,112]],[[13260,13260],"mapped",[105,110]],[[13261,13261],"mapped",[107,107]],[[13262,13262],"mapped",[107,109]],[[13263,13263],"mapped",[107,116]],[[13264,13264],"mapped",[108,109]],[[13265,13265],"mapped",[108,110]],[[13266,13266],"mapped",[108,111,103]],[[13267,13267],"mapped",[108,120]],[[13268,13268],"mapped",[109,98]],[[13269,13269],"mapped",[109,105,108]],[[13270,13270],"mapped",[109,111,108]],[[13271,13271],"mapped",[112,104]],[[13272,13272],"disallowed"],[[13273,13273],"mapped",[112,112,109]],[[13274,13274],"mapped",[112,114]],[[13275,13275],"mapped",[115,114]],[[13276,13276],"mapped",[115,118]],[[13277,13277],"mapped",[119,98]],[[13278,13278],"mapped",[118,8725,109]],[[13279,13279],"mapped",[97,8725,109]],[[13280,13280],"mapped",[49,26085]],[[13281,13281],"mapped",[50,26085]],[[13282,13282],"mapped",[51,26085]],[[13283,13283],"mapped",[52,26085]],[[13284,13284],"mapped",[53,26085]],[[13285,13285],"mapped",[54,26085]],[[13286,13286],"mapped",[55,26085]],[[13287,13287],"mapped",[56,26085]],[[13288,13288],"mapped",[57,26085]],[[13289,13289],"mapped",[49,48,26085]],[[13290,13290],"mapped",[49,49,26085]],[[13291,13291],"mapped",[49,50,26085]],[[13292,13292],"mapped",[49,51,26085]],[[13293,13293],"mapped",[49,52,26085]],[[13294,13294],"mapped",[49,53,26085]],[[13295,13295],"mapped",[49,54,26085]],[[13296,13296],"mapped",[49,55,26085]],[[13297,13297],"mapped",[49,56,26085]],[[13298,13298],"mapped",[49,57,26085]],[[13299,13299],"mapped",[50,48,26085]],[[13300,13300],"mapped",[50,49,26085]],[[13301,13301],"mapped",[50,50,26085]],[[13302,13302],"mapped",[50,51,26085]],[[13303,13303],"mapped",[50,52,26085]],[[13304,13304],"mapped",[50,53,26085]],[[13305,13305],"mapped",[50,54,26085]],[[13306,13306],"mapped",[50,55,26085]],[[13307,13307],"mapped",[50,56,26085]],[[13308,13308],"mapped",[50,57,26085]],[[13309,13309],"mapped",[51,48,26085]],[[13310,13310],"mapped",[51,49,26085]],[[13311,13311],"mapped",[103,97,108]],[[13312,19893],"valid"],[[19894,19903],"disallowed"],[[19904,19967],"valid",[],"NV8"],[[19968,40869],"valid"],[[40870,40891],"valid"],[[40892,40899],"valid"],[[40900,40907],"valid"],[[40908,40908],"valid"],[[40909,40917],"valid"],[[40918,40959],"disallowed"],[[40960,42124],"valid"],[[42125,42127],"disallowed"],[[42128,42145],"valid",[],"NV8"],[[42146,42147],"valid",[],"NV8"],[[42148,42163],"valid",[],"NV8"],[[42164,42164],"valid",[],"NV8"],[[42165,42176],"valid",[],"NV8"],[[42177,42177],"valid",[],"NV8"],[[42178,42180],"valid",[],"NV8"],[[42181,42181],"valid",[],"NV8"],[[42182,42182],"valid",[],"NV8"],[[42183,42191],"disallowed"],[[42192,42237],"valid"],[[42238,42239],"valid",[],"NV8"],[[42240,42508],"valid"],[[42509,42511],"valid",[],"NV8"],[[42512,42539],"valid"],[[42540,42559],"disallowed"],[[42560,42560],"mapped",[42561]],[[42561,42561],"valid"],[[42562,42562],"mapped",[42563]],[[42563,42563],"valid"],[[42564,42564],"mapped",[42565]],[[42565,42565],"valid"],[[42566,42566],"mapped",[42567]],[[42567,42567],"valid"],[[42568,42568],"mapped",[42569]],[[42569,42569],"valid"],[[42570,42570],"mapped",[42571]],[[42571,42571],"valid"],[[42572,42572],"mapped",[42573]],[[42573,42573],"valid"],[[42574,42574],"mapped",[42575]],[[42575,42575],"valid"],[[42576,42576],"mapped",[42577]],[[42577,42577],"valid"],[[42578,42578],"mapped",[42579]],[[42579,42579],"valid"],[[42580,42580],"mapped",[42581]],[[42581,42581],"valid"],[[42582,42582],"mapped",[42583]],[[42583,42583],"valid"],[[42584,42584],"mapped",[42585]],[[42585,42585],"valid"],[[42586,42586],"mapped",[42587]],[[42587,42587],"valid"],[[42588,42588],"mapped",[42589]],[[42589,42589],"valid"],[[42590,42590],"mapped",[42591]],[[42591,42591],"valid"],[[42592,42592],"mapped",[42593]],[[42593,42593],"valid"],[[42594,42594],"mapped",[42595]],[[42595,42595],"valid"],[[42596,42596],"mapped",[42597]],[[42597,42597],"valid"],[[42598,42598],"mapped",[42599]],[[42599,42599],"valid"],[[42600,42600],"mapped",[42601]],[[42601,42601],"valid"],[[42602,42602],"mapped",[42603]],[[42603,42603],"valid"],[[42604,42604],"mapped",[42605]],[[42605,42607],"valid"],[[42608,42611],"valid",[],"NV8"],[[42612,42619],"valid"],[[42620,42621],"valid"],[[42622,42622],"valid",[],"NV8"],[[42623,42623],"valid"],[[42624,42624],"mapped",[42625]],[[42625,42625],"valid"],[[42626,42626],"mapped",[42627]],[[42627,42627],"valid"],[[42628,42628],"mapped",[42629]],[[42629,42629],"valid"],[[42630,42630],"mapped",[42631]],[[42631,42631],"valid"],[[42632,42632],"mapped",[42633]],[[42633,42633],"valid"],[[42634,42634],"mapped",[42635]],[[42635,42635],"valid"],[[42636,42636],"mapped",[42637]],[[42637,42637],"valid"],[[42638,42638],"mapped",[42639]],[[42639,42639],"valid"],[[42640,42640],"mapped",[42641]],[[42641,42641],"valid"],[[42642,42642],"mapped",[42643]],[[42643,42643],"valid"],[[42644,42644],"mapped",[42645]],[[42645,42645],"valid"],[[42646,42646],"mapped",[42647]],[[42647,42647],"valid"],[[42648,42648],"mapped",[42649]],[[42649,42649],"valid"],[[42650,42650],"mapped",[42651]],[[42651,42651],"valid"],[[42652,42652],"mapped",[1098]],[[42653,42653],"mapped",[1100]],[[42654,42654],"valid"],[[42655,42655],"valid"],[[42656,42725],"valid"],[[42726,42735],"valid",[],"NV8"],[[42736,42737],"valid"],[[42738,42743],"valid",[],"NV8"],[[42744,42751],"disallowed"],[[42752,42774],"valid",[],"NV8"],[[42775,42778],"valid"],[[42779,42783],"valid"],[[42784,42785],"valid",[],"NV8"],[[42786,42786],"mapped",[42787]],[[42787,42787],"valid"],[[42788,42788],"mapped",[42789]],[[42789,42789],"valid"],[[42790,42790],"mapped",[42791]],[[42791,42791],"valid"],[[42792,42792],"mapped",[42793]],[[42793,42793],"valid"],[[42794,42794],"mapped",[42795]],[[42795,42795],"valid"],[[42796,42796],"mapped",[42797]],[[42797,42797],"valid"],[[42798,42798],"mapped",[42799]],[[42799,42801],"valid"],[[42802,42802],"mapped",[42803]],[[42803,42803],"valid"],[[42804,42804],"mapped",[42805]],[[42805,42805],"valid"],[[42806,42806],"mapped",[42807]],[[42807,42807],"valid"],[[42808,42808],"mapped",[42809]],[[42809,42809],"valid"],[[42810,42810],"mapped",[42811]],[[42811,42811],"valid"],[[42812,42812],"mapped",[42813]],[[42813,42813],"valid"],[[42814,42814],"mapped",[42815]],[[42815,42815],"valid"],[[42816,42816],"mapped",[42817]],[[42817,42817],"valid"],[[42818,42818],"mapped",[42819]],[[42819,42819],"valid"],[[42820,42820],"mapped",[42821]],[[42821,42821],"valid"],[[42822,42822],"mapped",[42823]],[[42823,42823],"valid"],[[42824,42824],"mapped",[42825]],[[42825,42825],"valid"],[[42826,42826],"mapped",[42827]],[[42827,42827],"valid"],[[42828,42828],"mapped",[42829]],[[42829,42829],"valid"],[[42830,42830],"mapped",[42831]],[[42831,42831],"valid"],[[42832,42832],"mapped",[42833]],[[42833,42833],"valid"],[[42834,42834],"mapped",[42835]],[[42835,42835],"valid"],[[42836,42836],"mapped",[42837]],[[42837,42837],"valid"],[[42838,42838],"mapped",[42839]],[[42839,42839],"valid"],[[42840,42840],"mapped",[42841]],[[42841,42841],"valid"],[[42842,42842],"mapped",[42843]],[[42843,42843],"valid"],[[42844,42844],"mapped",[42845]],[[42845,42845],"valid"],[[42846,42846],"mapped",[42847]],[[42847,42847],"valid"],[[42848,42848],"mapped",[42849]],[[42849,42849],"valid"],[[42850,42850],"mapped",[42851]],[[42851,42851],"valid"],[[42852,42852],"mapped",[42853]],[[42853,42853],"valid"],[[42854,42854],"mapped",[42855]],[[42855,42855],"valid"],[[42856,42856],"mapped",[42857]],[[42857,42857],"valid"],[[42858,42858],"mapped",[42859]],[[42859,42859],"valid"],[[42860,42860],"mapped",[42861]],[[42861,42861],"valid"],[[42862,42862],"mapped",[42863]],[[42863,42863],"valid"],[[42864,42864],"mapped",[42863]],[[42865,42872],"valid"],[[42873,42873],"mapped",[42874]],[[42874,42874],"valid"],[[42875,42875],"mapped",[42876]],[[42876,42876],"valid"],[[42877,42877],"mapped",[7545]],[[42878,42878],"mapped",[42879]],[[42879,42879],"valid"],[[42880,42880],"mapped",[42881]],[[42881,42881],"valid"],[[42882,42882],"mapped",[42883]],[[42883,42883],"valid"],[[42884,42884],"mapped",[42885]],[[42885,42885],"valid"],[[42886,42886],"mapped",[42887]],[[42887,42888],"valid"],[[42889,42890],"valid",[],"NV8"],[[42891,42891],"mapped",[42892]],[[42892,42892],"valid"],[[42893,42893],"mapped",[613]],[[42894,42894],"valid"],[[42895,42895],"valid"],[[42896,42896],"mapped",[42897]],[[42897,42897],"valid"],[[42898,42898],"mapped",[42899]],[[42899,42899],"valid"],[[42900,42901],"valid"],[[42902,42902],"mapped",[42903]],[[42903,42903],"valid"],[[42904,42904],"mapped",[42905]],[[42905,42905],"valid"],[[42906,42906],"mapped",[42907]],[[42907,42907],"valid"],[[42908,42908],"mapped",[42909]],[[42909,42909],"valid"],[[42910,42910],"mapped",[42911]],[[42911,42911],"valid"],[[42912,42912],"mapped",[42913]],[[42913,42913],"valid"],[[42914,42914],"mapped",[42915]],[[42915,42915],"valid"],[[42916,42916],"mapped",[42917]],[[42917,42917],"valid"],[[42918,42918],"mapped",[42919]],[[42919,42919],"valid"],[[42920,42920],"mapped",[42921]],[[42921,42921],"valid"],[[42922,42922],"mapped",[614]],[[42923,42923],"mapped",[604]],[[42924,42924],"mapped",[609]],[[42925,42925],"mapped",[620]],[[42926,42927],"disallowed"],[[42928,42928],"mapped",[670]],[[42929,42929],"mapped",[647]],[[42930,42930],"mapped",[669]],[[42931,42931],"mapped",[43859]],[[42932,42932],"mapped",[42933]],[[42933,42933],"valid"],[[42934,42934],"mapped",[42935]],[[42935,42935],"valid"],[[42936,42998],"disallowed"],[[42999,42999],"valid"],[[43000,43000],"mapped",[295]],[[43001,43001],"mapped",[339]],[[43002,43002],"valid"],[[43003,43007],"valid"],[[43008,43047],"valid"],[[43048,43051],"valid",[],"NV8"],[[43052,43055],"disallowed"],[[43056,43065],"valid",[],"NV8"],[[43066,43071],"disallowed"],[[43072,43123],"valid"],[[43124,43127],"valid",[],"NV8"],[[43128,43135],"disallowed"],[[43136,43204],"valid"],[[43205,43213],"disallowed"],[[43214,43215],"valid",[],"NV8"],[[43216,43225],"valid"],[[43226,43231],"disallowed"],[[43232,43255],"valid"],[[43256,43258],"valid",[],"NV8"],[[43259,43259],"valid"],[[43260,43260],"valid",[],"NV8"],[[43261,43261],"valid"],[[43262,43263],"disallowed"],[[43264,43309],"valid"],[[43310,43311],"valid",[],"NV8"],[[43312,43347],"valid"],[[43348,43358],"disallowed"],[[43359,43359],"valid",[],"NV8"],[[43360,43388],"valid",[],"NV8"],[[43389,43391],"disallowed"],[[43392,43456],"valid"],[[43457,43469],"valid",[],"NV8"],[[43470,43470],"disallowed"],[[43471,43481],"valid"],[[43482,43485],"disallowed"],[[43486,43487],"valid",[],"NV8"],[[43488,43518],"valid"],[[43519,43519],"disallowed"],[[43520,43574],"valid"],[[43575,43583],"disallowed"],[[43584,43597],"valid"],[[43598,43599],"disallowed"],[[43600,43609],"valid"],[[43610,43611],"disallowed"],[[43612,43615],"valid",[],"NV8"],[[43616,43638],"valid"],[[43639,43641],"valid",[],"NV8"],[[43642,43643],"valid"],[[43644,43647],"valid"],[[43648,43714],"valid"],[[43715,43738],"disallowed"],[[43739,43741],"valid"],[[43742,43743],"valid",[],"NV8"],[[43744,43759],"valid"],[[43760,43761],"valid",[],"NV8"],[[43762,43766],"valid"],[[43767,43776],"disallowed"],[[43777,43782],"valid"],[[43783,43784],"disallowed"],[[43785,43790],"valid"],[[43791,43792],"disallowed"],[[43793,43798],"valid"],[[43799,43807],"disallowed"],[[43808,43814],"valid"],[[43815,43815],"disallowed"],[[43816,43822],"valid"],[[43823,43823],"disallowed"],[[43824,43866],"valid"],[[43867,43867],"valid",[],"NV8"],[[43868,43868],"mapped",[42791]],[[43869,43869],"mapped",[43831]],[[43870,43870],"mapped",[619]],[[43871,43871],"mapped",[43858]],[[43872,43875],"valid"],[[43876,43877],"valid"],[[43878,43887],"disallowed"],[[43888,43888],"mapped",[5024]],[[43889,43889],"mapped",[5025]],[[43890,43890],"mapped",[5026]],[[43891,43891],"mapped",[5027]],[[43892,43892],"mapped",[5028]],[[43893,43893],"mapped",[5029]],[[43894,43894],"mapped",[5030]],[[43895,43895],"mapped",[5031]],[[43896,43896],"mapped",[5032]],[[43897,43897],"mapped",[5033]],[[43898,43898],"mapped",[5034]],[[43899,43899],"mapped",[5035]],[[43900,43900],"mapped",[5036]],[[43901,43901],"mapped",[5037]],[[43902,43902],"mapped",[5038]],[[43903,43903],"mapped",[5039]],[[43904,43904],"mapped",[5040]],[[43905,43905],"mapped",[5041]],[[43906,43906],"mapped",[5042]],[[43907,43907],"mapped",[5043]],[[43908,43908],"mapped",[5044]],[[43909,43909],"mapped",[5045]],[[43910,43910],"mapped",[5046]],[[43911,43911],"mapped",[5047]],[[43912,43912],"mapped",[5048]],[[43913,43913],"mapped",[5049]],[[43914,43914],"mapped",[5050]],[[43915,43915],"mapped",[5051]],[[43916,43916],"mapped",[5052]],[[43917,43917],"mapped",[5053]],[[43918,43918],"mapped",[5054]],[[43919,43919],"mapped",[5055]],[[43920,43920],"mapped",[5056]],[[43921,43921],"mapped",[5057]],[[43922,43922],"mapped",[5058]],[[43923,43923],"mapped",[5059]],[[43924,43924],"mapped",[5060]],[[43925,43925],"mapped",[5061]],[[43926,43926],"mapped",[5062]],[[43927,43927],"mapped",[5063]],[[43928,43928],"mapped",[5064]],[[43929,43929],"mapped",[5065]],[[43930,43930],"mapped",[5066]],[[43931,43931],"mapped",[5067]],[[43932,43932],"mapped",[5068]],[[43933,43933],"mapped",[5069]],[[43934,43934],"mapped",[5070]],[[43935,43935],"mapped",[5071]],[[43936,43936],"mapped",[5072]],[[43937,43937],"mapped",[5073]],[[43938,43938],"mapped",[5074]],[[43939,43939],"mapped",[5075]],[[43940,43940],"mapped",[5076]],[[43941,43941],"mapped",[5077]],[[43942,43942],"mapped",[5078]],[[43943,43943],"mapped",[5079]],[[43944,43944],"mapped",[5080]],[[43945,43945],"mapped",[5081]],[[43946,43946],"mapped",[5082]],[[43947,43947],"mapped",[5083]],[[43948,43948],"mapped",[5084]],[[43949,43949],"mapped",[5085]],[[43950,43950],"mapped",[5086]],[[43951,43951],"mapped",[5087]],[[43952,43952],"mapped",[5088]],[[43953,43953],"mapped",[5089]],[[43954,43954],"mapped",[5090]],[[43955,43955],"mapped",[5091]],[[43956,43956],"mapped",[5092]],[[43957,43957],"mapped",[5093]],[[43958,43958],"mapped",[5094]],[[43959,43959],"mapped",[5095]],[[43960,43960],"mapped",[5096]],[[43961,43961],"mapped",[5097]],[[43962,43962],"mapped",[5098]],[[43963,43963],"mapped",[5099]],[[43964,43964],"mapped",[5100]],[[43965,43965],"mapped",[5101]],[[43966,43966],"mapped",[5102]],[[43967,43967],"mapped",[5103]],[[43968,44010],"valid"],[[44011,44011],"valid",[],"NV8"],[[44012,44013],"valid"],[[44014,44015],"disallowed"],[[44016,44025],"valid"],[[44026,44031],"disallowed"],[[44032,55203],"valid"],[[55204,55215],"disallowed"],[[55216,55238],"valid",[],"NV8"],[[55239,55242],"disallowed"],[[55243,55291],"valid",[],"NV8"],[[55292,55295],"disallowed"],[[55296,57343],"disallowed"],[[57344,63743],"disallowed"],[[63744,63744],"mapped",[35912]],[[63745,63745],"mapped",[26356]],[[63746,63746],"mapped",[36554]],[[63747,63747],"mapped",[36040]],[[63748,63748],"mapped",[28369]],[[63749,63749],"mapped",[20018]],[[63750,63750],"mapped",[21477]],[[63751,63752],"mapped",[40860]],[[63753,63753],"mapped",[22865]],[[63754,63754],"mapped",[37329]],[[63755,63755],"mapped",[21895]],[[63756,63756],"mapped",[22856]],[[63757,63757],"mapped",[25078]],[[63758,63758],"mapped",[30313]],[[63759,63759],"mapped",[32645]],[[63760,63760],"mapped",[34367]],[[63761,63761],"mapped",[34746]],[[63762,63762],"mapped",[35064]],[[63763,63763],"mapped",[37007]],[[63764,63764],"mapped",[27138]],[[63765,63765],"mapped",[27931]],[[63766,63766],"mapped",[28889]],[[63767,63767],"mapped",[29662]],[[63768,63768],"mapped",[33853]],[[63769,63769],"mapped",[37226]],[[63770,63770],"mapped",[39409]],[[63771,63771],"mapped",[20098]],[[63772,63772],"mapped",[21365]],[[63773,63773],"mapped",[27396]],[[63774,63774],"mapped",[29211]],[[63775,63775],"mapped",[34349]],[[63776,63776],"mapped",[40478]],[[63777,63777],"mapped",[23888]],[[63778,63778],"mapped",[28651]],[[63779,63779],"mapped",[34253]],[[63780,63780],"mapped",[35172]],[[63781,63781],"mapped",[25289]],[[63782,63782],"mapped",[33240]],[[63783,63783],"mapped",[34847]],[[63784,63784],"mapped",[24266]],[[63785,63785],"mapped",[26391]],[[63786,63786],"mapped",[28010]],[[63787,63787],"mapped",[29436]],[[63788,63788],"mapped",[37070]],[[63789,63789],"mapped",[20358]],[[63790,63790],"mapped",[20919]],[[63791,63791],"mapped",[21214]],[[63792,63792],"mapped",[25796]],[[63793,63793],"mapped",[27347]],[[63794,63794],"mapped",[29200]],[[63795,63795],"mapped",[30439]],[[63796,63796],"mapped",[32769]],[[63797,63797],"mapped",[34310]],[[63798,63798],"mapped",[34396]],[[63799,63799],"mapped",[36335]],[[63800,63800],"mapped",[38706]],[[63801,63801],"mapped",[39791]],[[63802,63802],"mapped",[40442]],[[63803,63803],"mapped",[30860]],[[63804,63804],"mapped",[31103]],[[63805,63805],"mapped",[32160]],[[63806,63806],"mapped",[33737]],[[63807,63807],"mapped",[37636]],[[63808,63808],"mapped",[40575]],[[63809,63809],"mapped",[35542]],[[63810,63810],"mapped",[22751]],[[63811,63811],"mapped",[24324]],[[63812,63812],"mapped",[31840]],[[63813,63813],"mapped",[32894]],[[63814,63814],"mapped",[29282]],[[63815,63815],"mapped",[30922]],[[63816,63816],"mapped",[36034]],[[63817,63817],"mapped",[38647]],[[63818,63818],"mapped",[22744]],[[63819,63819],"mapped",[23650]],[[63820,63820],"mapped",[27155]],[[63821,63821],"mapped",[28122]],[[63822,63822],"mapped",[28431]],[[63823,63823],"mapped",[32047]],[[63824,63824],"mapped",[32311]],[[63825,63825],"mapped",[38475]],[[63826,63826],"mapped",[21202]],[[63827,63827],"mapped",[32907]],[[63828,63828],"mapped",[20956]],[[63829,63829],"mapped",[20940]],[[63830,63830],"mapped",[31260]],[[63831,63831],"mapped",[32190]],[[63832,63832],"mapped",[33777]],[[63833,63833],"mapped",[38517]],[[63834,63834],"mapped",[35712]],[[63835,63835],"mapped",[25295]],[[63836,63836],"mapped",[27138]],[[63837,63837],"mapped",[35582]],[[63838,63838],"mapped",[20025]],[[63839,63839],"mapped",[23527]],[[63840,63840],"mapped",[24594]],[[63841,63841],"mapped",[29575]],[[63842,63842],"mapped",[30064]],[[63843,63843],"mapped",[21271]],[[63844,63844],"mapped",[30971]],[[63845,63845],"mapped",[20415]],[[63846,63846],"mapped",[24489]],[[63847,63847],"mapped",[19981]],[[63848,63848],"mapped",[27852]],[[63849,63849],"mapped",[25976]],[[63850,63850],"mapped",[32034]],[[63851,63851],"mapped",[21443]],[[63852,63852],"mapped",[22622]],[[63853,63853],"mapped",[30465]],[[63854,63854],"mapped",[33865]],[[63855,63855],"mapped",[35498]],[[63856,63856],"mapped",[27578]],[[63857,63857],"mapped",[36784]],[[63858,63858],"mapped",[27784]],[[63859,63859],"mapped",[25342]],[[63860,63860],"mapped",[33509]],[[63861,63861],"mapped",[25504]],[[63862,63862],"mapped",[30053]],[[63863,63863],"mapped",[20142]],[[63864,63864],"mapped",[20841]],[[63865,63865],"mapped",[20937]],[[63866,63866],"mapped",[26753]],[[63867,63867],"mapped",[31975]],[[63868,63868],"mapped",[33391]],[[63869,63869],"mapped",[35538]],[[63870,63870],"mapped",[37327]],[[63871,63871],"mapped",[21237]],[[63872,63872],"mapped",[21570]],[[63873,63873],"mapped",[22899]],[[63874,63874],"mapped",[24300]],[[63875,63875],"mapped",[26053]],[[63876,63876],"mapped",[28670]],[[63877,63877],"mapped",[31018]],[[63878,63878],"mapped",[38317]],[[63879,63879],"mapped",[39530]],[[63880,63880],"mapped",[40599]],[[63881,63881],"mapped",[40654]],[[63882,63882],"mapped",[21147]],[[63883,63883],"mapped",[26310]],[[63884,63884],"mapped",[27511]],[[63885,63885],"mapped",[36706]],[[63886,63886],"mapped",[24180]],[[63887,63887],"mapped",[24976]],[[63888,63888],"mapped",[25088]],[[63889,63889],"mapped",[25754]],[[63890,63890],"mapped",[28451]],[[63891,63891],"mapped",[29001]],[[63892,63892],"mapped",[29833]],[[63893,63893],"mapped",[31178]],[[63894,63894],"mapped",[32244]],[[63895,63895],"mapped",[32879]],[[63896,63896],"mapped",[36646]],[[63897,63897],"mapped",[34030]],[[63898,63898],"mapped",[36899]],[[63899,63899],"mapped",[37706]],[[63900,63900],"mapped",[21015]],[[63901,63901],"mapped",[21155]],[[63902,63902],"mapped",[21693]],[[63903,63903],"mapped",[28872]],[[63904,63904],"mapped",[35010]],[[63905,63905],"mapped",[35498]],[[63906,63906],"mapped",[24265]],[[63907,63907],"mapped",[24565]],[[63908,63908],"mapped",[25467]],[[63909,63909],"mapped",[27566]],[[63910,63910],"mapped",[31806]],[[63911,63911],"mapped",[29557]],[[63912,63912],"mapped",[20196]],[[63913,63913],"mapped",[22265]],[[63914,63914],"mapped",[23527]],[[63915,63915],"mapped",[23994]],[[63916,63916],"mapped",[24604]],[[63917,63917],"mapped",[29618]],[[63918,63918],"mapped",[29801]],[[63919,63919],"mapped",[32666]],[[63920,63920],"mapped",[32838]],[[63921,63921],"mapped",[37428]],[[63922,63922],"mapped",[38646]],[[63923,63923],"mapped",[38728]],[[63924,63924],"mapped",[38936]],[[63925,63925],"mapped",[20363]],[[63926,63926],"mapped",[31150]],[[63927,63927],"mapped",[37300]],[[63928,63928],"mapped",[38584]],[[63929,63929],"mapped",[24801]],[[63930,63930],"mapped",[20102]],[[63931,63931],"mapped",[20698]],[[63932,63932],"mapped",[23534]],[[63933,63933],"mapped",[23615]],[[63934,63934],"mapped",[26009]],[[63935,63935],"mapped",[27138]],[[63936,63936],"mapped",[29134]],[[63937,63937],"mapped",[30274]],[[63938,63938],"mapped",[34044]],[[63939,63939],"mapped",[36988]],[[63940,63940],"mapped",[40845]],[[63941,63941],"mapped",[26248]],[[63942,63942],"mapped",[38446]],[[63943,63943],"mapped",[21129]],[[63944,63944],"mapped",[26491]],[[63945,63945],"mapped",[26611]],[[63946,63946],"mapped",[27969]],[[63947,63947],"mapped",[28316]],[[63948,63948],"mapped",[29705]],[[63949,63949],"mapped",[30041]],[[63950,63950],"mapped",[30827]],[[63951,63951],"mapped",[32016]],[[63952,63952],"mapped",[39006]],[[63953,63953],"mapped",[20845]],[[63954,63954],"mapped",[25134]],[[63955,63955],"mapped",[38520]],[[63956,63956],"mapped",[20523]],[[63957,63957],"mapped",[23833]],[[63958,63958],"mapped",[28138]],[[63959,63959],"mapped",[36650]],[[63960,63960],"mapped",[24459]],[[63961,63961],"mapped",[24900]],[[63962,63962],"mapped",[26647]],[[63963,63963],"mapped",[29575]],[[63964,63964],"mapped",[38534]],[[63965,63965],"mapped",[21033]],[[63966,63966],"mapped",[21519]],[[63967,63967],"mapped",[23653]],[[63968,63968],"mapped",[26131]],[[63969,63969],"mapped",[26446]],[[63970,63970],"mapped",[26792]],[[63971,63971],"mapped",[27877]],[[63972,63972],"mapped",[29702]],[[63973,63973],"mapped",[30178]],[[63974,63974],"mapped",[32633]],[[63975,63975],"mapped",[35023]],[[63976,63976],"mapped",[35041]],[[63977,63977],"mapped",[37324]],[[63978,63978],"mapped",[38626]],[[63979,63979],"mapped",[21311]],[[63980,63980],"mapped",[28346]],[[63981,63981],"mapped",[21533]],[[63982,63982],"mapped",[29136]],[[63983,63983],"mapped",[29848]],[[63984,63984],"mapped",[34298]],[[63985,63985],"mapped",[38563]],[[63986,63986],"mapped",[40023]],[[63987,63987],"mapped",[40607]],[[63988,63988],"mapped",[26519]],[[63989,63989],"mapped",[28107]],[[63990,63990],"mapped",[33256]],[[63991,63991],"mapped",[31435]],[[63992,63992],"mapped",[31520]],[[63993,63993],"mapped",[31890]],[[63994,63994],"mapped",[29376]],[[63995,63995],"mapped",[28825]],[[63996,63996],"mapped",[35672]],[[63997,63997],"mapped",[20160]],[[63998,63998],"mapped",[33590]],[[63999,63999],"mapped",[21050]],[[64000,64000],"mapped",[20999]],[[64001,64001],"mapped",[24230]],[[64002,64002],"mapped",[25299]],[[64003,64003],"mapped",[31958]],[[64004,64004],"mapped",[23429]],[[64005,64005],"mapped",[27934]],[[64006,64006],"mapped",[26292]],[[64007,64007],"mapped",[36667]],[[64008,64008],"mapped",[34892]],[[64009,64009],"mapped",[38477]],[[64010,64010],"mapped",[35211]],[[64011,64011],"mapped",[24275]],[[64012,64012],"mapped",[20800]],[[64013,64013],"mapped",[21952]],[[64014,64015],"valid"],[[64016,64016],"mapped",[22618]],[[64017,64017],"valid"],[[64018,64018],"mapped",[26228]],[[64019,64020],"valid"],[[64021,64021],"mapped",[20958]],[[64022,64022],"mapped",[29482]],[[64023,64023],"mapped",[30410]],[[64024,64024],"mapped",[31036]],[[64025,64025],"mapped",[31070]],[[64026,64026],"mapped",[31077]],[[64027,64027],"mapped",[31119]],[[64028,64028],"mapped",[38742]],[[64029,64029],"mapped",[31934]],[[64030,64030],"mapped",[32701]],[[64031,64031],"valid"],[[64032,64032],"mapped",[34322]],[[64033,64033],"valid"],[[64034,64034],"mapped",[35576]],[[64035,64036],"valid"],[[64037,64037],"mapped",[36920]],[[64038,64038],"mapped",[37117]],[[64039,64041],"valid"],[[64042,64042],"mapped",[39151]],[[64043,64043],"mapped",[39164]],[[64044,64044],"mapped",[39208]],[[64045,64045],"mapped",[40372]],[[64046,64046],"mapped",[37086]],[[64047,64047],"mapped",[38583]],[[64048,64048],"mapped",[20398]],[[64049,64049],"mapped",[20711]],[[64050,64050],"mapped",[20813]],[[64051,64051],"mapped",[21193]],[[64052,64052],"mapped",[21220]],[[64053,64053],"mapped",[21329]],[[64054,64054],"mapped",[21917]],[[64055,64055],"mapped",[22022]],[[64056,64056],"mapped",[22120]],[[64057,64057],"mapped",[22592]],[[64058,64058],"mapped",[22696]],[[64059,64059],"mapped",[23652]],[[64060,64060],"mapped",[23662]],[[64061,64061],"mapped",[24724]],[[64062,64062],"mapped",[24936]],[[64063,64063],"mapped",[24974]],[[64064,64064],"mapped",[25074]],[[64065,64065],"mapped",[25935]],[[64066,64066],"mapped",[26082]],[[64067,64067],"mapped",[26257]],[[64068,64068],"mapped",[26757]],[[64069,64069],"mapped",[28023]],[[64070,64070],"mapped",[28186]],[[64071,64071],"mapped",[28450]],[[64072,64072],"mapped",[29038]],[[64073,64073],"mapped",[29227]],[[64074,64074],"mapped",[29730]],[[64075,64075],"mapped",[30865]],[[64076,64076],"mapped",[31038]],[[64077,64077],"mapped",[31049]],[[64078,64078],"mapped",[31048]],[[64079,64079],"mapped",[31056]],[[64080,64080],"mapped",[31062]],[[64081,64081],"mapped",[31069]],[[64082,64082],"mapped",[31117]],[[64083,64083],"mapped",[31118]],[[64084,64084],"mapped",[31296]],[[64085,64085],"mapped",[31361]],[[64086,64086],"mapped",[31680]],[[64087,64087],"mapped",[32244]],[[64088,64088],"mapped",[32265]],[[64089,64089],"mapped",[32321]],[[64090,64090],"mapped",[32626]],[[64091,64091],"mapped",[32773]],[[64092,64092],"mapped",[33261]],[[64093,64094],"mapped",[33401]],[[64095,64095],"mapped",[33879]],[[64096,64096],"mapped",[35088]],[[64097,64097],"mapped",[35222]],[[64098,64098],"mapped",[35585]],[[64099,64099],"mapped",[35641]],[[64100,64100],"mapped",[36051]],[[64101,64101],"mapped",[36104]],[[64102,64102],"mapped",[36790]],[[64103,64103],"mapped",[36920]],[[64104,64104],"mapped",[38627]],[[64105,64105],"mapped",[38911]],[[64106,64106],"mapped",[38971]],[[64107,64107],"mapped",[24693]],[[64108,64108],"mapped",[148206]],[[64109,64109],"mapped",[33304]],[[64110,64111],"disallowed"],[[64112,64112],"mapped",[20006]],[[64113,64113],"mapped",[20917]],[[64114,64114],"mapped",[20840]],[[64115,64115],"mapped",[20352]],[[64116,64116],"mapped",[20805]],[[64117,64117],"mapped",[20864]],[[64118,64118],"mapped",[21191]],[[64119,64119],"mapped",[21242]],[[64120,64120],"mapped",[21917]],[[64121,64121],"mapped",[21845]],[[64122,64122],"mapped",[21913]],[[64123,64123],"mapped",[21986]],[[64124,64124],"mapped",[22618]],[[64125,64125],"mapped",[22707]],[[64126,64126],"mapped",[22852]],[[64127,64127],"mapped",[22868]],[[64128,64128],"mapped",[23138]],[[64129,64129],"mapped",[23336]],[[64130,64130],"mapped",[24274]],[[64131,64131],"mapped",[24281]],[[64132,64132],"mapped",[24425]],[[64133,64133],"mapped",[24493]],[[64134,64134],"mapped",[24792]],[[64135,64135],"mapped",[24910]],[[64136,64136],"mapped",[24840]],[[64137,64137],"mapped",[24974]],[[64138,64138],"mapped",[24928]],[[64139,64139],"mapped",[25074]],[[64140,64140],"mapped",[25140]],[[64141,64141],"mapped",[25540]],[[64142,64142],"mapped",[25628]],[[64143,64143],"mapped",[25682]],[[64144,64144],"mapped",[25942]],[[64145,64145],"mapped",[26228]],[[64146,64146],"mapped",[26391]],[[64147,64147],"mapped",[26395]],[[64148,64148],"mapped",[26454]],[[64149,64149],"mapped",[27513]],[[64150,64150],"mapped",[27578]],[[64151,64151],"mapped",[27969]],[[64152,64152],"mapped",[28379]],[[64153,64153],"mapped",[28363]],[[64154,64154],"mapped",[28450]],[[64155,64155],"mapped",[28702]],[[64156,64156],"mapped",[29038]],[[64157,64157],"mapped",[30631]],[[64158,64158],"mapped",[29237]],[[64159,64159],"mapped",[29359]],[[64160,64160],"mapped",[29482]],[[64161,64161],"mapped",[29809]],[[64162,64162],"mapped",[29958]],[[64163,64163],"mapped",[30011]],[[64164,64164],"mapped",[30237]],[[64165,64165],"mapped",[30239]],[[64166,64166],"mapped",[30410]],[[64167,64167],"mapped",[30427]],[[64168,64168],"mapped",[30452]],[[64169,64169],"mapped",[30538]],[[64170,64170],"mapped",[30528]],[[64171,64171],"mapped",[30924]],[[64172,64172],"mapped",[31409]],[[64173,64173],"mapped",[31680]],[[64174,64174],"mapped",[31867]],[[64175,64175],"mapped",[32091]],[[64176,64176],"mapped",[32244]],[[64177,64177],"mapped",[32574]],[[64178,64178],"mapped",[32773]],[[64179,64179],"mapped",[33618]],[[64180,64180],"mapped",[33775]],[[64181,64181],"mapped",[34681]],[[64182,64182],"mapped",[35137]],[[64183,64183],"mapped",[35206]],[[64184,64184],"mapped",[35222]],[[64185,64185],"mapped",[35519]],[[64186,64186],"mapped",[35576]],[[64187,64187],"mapped",[35531]],[[64188,64188],"mapped",[35585]],[[64189,64189],"mapped",[35582]],[[64190,64190],"mapped",[35565]],[[64191,64191],"mapped",[35641]],[[64192,64192],"mapped",[35722]],[[64193,64193],"mapped",[36104]],[[64194,64194],"mapped",[36664]],[[64195,64195],"mapped",[36978]],[[64196,64196],"mapped",[37273]],[[64197,64197],"mapped",[37494]],[[64198,64198],"mapped",[38524]],[[64199,64199],"mapped",[38627]],[[64200,64200],"mapped",[38742]],[[64201,64201],"mapped",[38875]],[[64202,64202],"mapped",[38911]],[[64203,64203],"mapped",[38923]],[[64204,64204],"mapped",[38971]],[[64205,64205],"mapped",[39698]],[[64206,64206],"mapped",[40860]],[[64207,64207],"mapped",[141386]],[[64208,64208],"mapped",[141380]],[[64209,64209],"mapped",[144341]],[[64210,64210],"mapped",[15261]],[[64211,64211],"mapped",[16408]],[[64212,64212],"mapped",[16441]],[[64213,64213],"mapped",[152137]],[[64214,64214],"mapped",[154832]],[[64215,64215],"mapped",[163539]],[[64216,64216],"mapped",[40771]],[[64217,64217],"mapped",[40846]],[[64218,64255],"disallowed"],[[64256,64256],"mapped",[102,102]],[[64257,64257],"mapped",[102,105]],[[64258,64258],"mapped",[102,108]],[[64259,64259],"mapped",[102,102,105]],[[64260,64260],"mapped",[102,102,108]],[[64261,64262],"mapped",[115,116]],[[64263,64274],"disallowed"],[[64275,64275],"mapped",[1396,1398]],[[64276,64276],"mapped",[1396,1381]],[[64277,64277],"mapped",[1396,1387]],[[64278,64278],"mapped",[1406,1398]],[[64279,64279],"mapped",[1396,1389]],[[64280,64284],"disallowed"],[[64285,64285],"mapped",[1497,1460]],[[64286,64286],"valid"],[[64287,64287],"mapped",[1522,1463]],[[64288,64288],"mapped",[1506]],[[64289,64289],"mapped",[1488]],[[64290,64290],"mapped",[1491]],[[64291,64291],"mapped",[1492]],[[64292,64292],"mapped",[1499]],[[64293,64293],"mapped",[1500]],[[64294,64294],"mapped",[1501]],[[64295,64295],"mapped",[1512]],[[64296,64296],"mapped",[1514]],[[64297,64297],"disallowed_STD3_mapped",[43]],[[64298,64298],"mapped",[1513,1473]],[[64299,64299],"mapped",[1513,1474]],[[64300,64300],"mapped",[1513,1468,1473]],[[64301,64301],"mapped",[1513,1468,1474]],[[64302,64302],"mapped",[1488,1463]],[[64303,64303],"mapped",[1488,1464]],[[64304,64304],"mapped",[1488,1468]],[[64305,64305],"mapped",[1489,1468]],[[64306,64306],"mapped",[1490,1468]],[[64307,64307],"mapped",[1491,1468]],[[64308,64308],"mapped",[1492,1468]],[[64309,64309],"mapped",[1493,1468]],[[64310,64310],"mapped",[1494,1468]],[[64311,64311],"disallowed"],[[64312,64312],"mapped",[1496,1468]],[[64313,64313],"mapped",[1497,1468]],[[64314,64314],"mapped",[1498,1468]],[[64315,64315],"mapped",[1499,1468]],[[64316,64316],"mapped",[1500,1468]],[[64317,64317],"disallowed"],[[64318,64318],"mapped",[1502,1468]],[[64319,64319],"disallowed"],[[64320,64320],"mapped",[1504,1468]],[[64321,64321],"mapped",[1505,1468]],[[64322,64322],"disallowed"],[[64323,64323],"mapped",[1507,1468]],[[64324,64324],"mapped",[1508,1468]],[[64325,64325],"disallowed"],[[64326,64326],"mapped",[1510,1468]],[[64327,64327],"mapped",[1511,1468]],[[64328,64328],"mapped",[1512,1468]],[[64329,64329],"mapped",[1513,1468]],[[64330,64330],"mapped",[1514,1468]],[[64331,64331],"mapped",[1493,1465]],[[64332,64332],"mapped",[1489,1471]],[[64333,64333],"mapped",[1499,1471]],[[64334,64334],"mapped",[1508,1471]],[[64335,64335],"mapped",[1488,1500]],[[64336,64337],"mapped",[1649]],[[64338,64341],"mapped",[1659]],[[64342,64345],"mapped",[1662]],[[64346,64349],"mapped",[1664]],[[64350,64353],"mapped",[1658]],[[64354,64357],"mapped",[1663]],[[64358,64361],"mapped",[1657]],[[64362,64365],"mapped",[1700]],[[64366,64369],"mapped",[1702]],[[64370,64373],"mapped",[1668]],[[64374,64377],"mapped",[1667]],[[64378,64381],"mapped",[1670]],[[64382,64385],"mapped",[1671]],[[64386,64387],"mapped",[1677]],[[64388,64389],"mapped",[1676]],[[64390,64391],"mapped",[1678]],[[64392,64393],"mapped",[1672]],[[64394,64395],"mapped",[1688]],[[64396,64397],"mapped",[1681]],[[64398,64401],"mapped",[1705]],[[64402,64405],"mapped",[1711]],[[64406,64409],"mapped",[1715]],[[64410,64413],"mapped",[1713]],[[64414,64415],"mapped",[1722]],[[64416,64419],"mapped",[1723]],[[64420,64421],"mapped",[1728]],[[64422,64425],"mapped",[1729]],[[64426,64429],"mapped",[1726]],[[64430,64431],"mapped",[1746]],[[64432,64433],"mapped",[1747]],[[64434,64449],"valid",[],"NV8"],[[64450,64466],"disallowed"],[[64467,64470],"mapped",[1709]],[[64471,64472],"mapped",[1735]],[[64473,64474],"mapped",[1734]],[[64475,64476],"mapped",[1736]],[[64477,64477],"mapped",[1735,1652]],[[64478,64479],"mapped",[1739]],[[64480,64481],"mapped",[1733]],[[64482,64483],"mapped",[1737]],[[64484,64487],"mapped",[1744]],[[64488,64489],"mapped",[1609]],[[64490,64491],"mapped",[1574,1575]],[[64492,64493],"mapped",[1574,1749]],[[64494,64495],"mapped",[1574,1608]],[[64496,64497],"mapped",[1574,1735]],[[64498,64499],"mapped",[1574,1734]],[[64500,64501],"mapped",[1574,1736]],[[64502,64504],"mapped",[1574,1744]],[[64505,64507],"mapped",[1574,1609]],[[64508,64511],"mapped",[1740]],[[64512,64512],"mapped",[1574,1580]],[[64513,64513],"mapped",[1574,1581]],[[64514,64514],"mapped",[1574,1605]],[[64515,64515],"mapped",[1574,1609]],[[64516,64516],"mapped",[1574,1610]],[[64517,64517],"mapped",[1576,1580]],[[64518,64518],"mapped",[1576,1581]],[[64519,64519],"mapped",[1576,1582]],[[64520,64520],"mapped",[1576,1605]],[[64521,64521],"mapped",[1576,1609]],[[64522,64522],"mapped",[1576,1610]],[[64523,64523],"mapped",[1578,1580]],[[64524,64524],"mapped",[1578,1581]],[[64525,64525],"mapped",[1578,1582]],[[64526,64526],"mapped",[1578,1605]],[[64527,64527],"mapped",[1578,1609]],[[64528,64528],"mapped",[1578,1610]],[[64529,64529],"mapped",[1579,1580]],[[64530,64530],"mapped",[1579,1605]],[[64531,64531],"mapped",[1579,1609]],[[64532,64532],"mapped",[1579,1610]],[[64533,64533],"mapped",[1580,1581]],[[64534,64534],"mapped",[1580,1605]],[[64535,64535],"mapped",[1581,1580]],[[64536,64536],"mapped",[1581,1605]],[[64537,64537],"mapped",[1582,1580]],[[64538,64538],"mapped",[1582,1581]],[[64539,64539],"mapped",[1582,1605]],[[64540,64540],"mapped",[1587,1580]],[[64541,64541],"mapped",[1587,1581]],[[64542,64542],"mapped",[1587,1582]],[[64543,64543],"mapped",[1587,1605]],[[64544,64544],"mapped",[1589,1581]],[[64545,64545],"mapped",[1589,1605]],[[64546,64546],"mapped",[1590,1580]],[[64547,64547],"mapped",[1590,1581]],[[64548,64548],"mapped",[1590,1582]],[[64549,64549],"mapped",[1590,1605]],[[64550,64550],"mapped",[1591,1581]],[[64551,64551],"mapped",[1591,1605]],[[64552,64552],"mapped",[1592,1605]],[[64553,64553],"mapped",[1593,1580]],[[64554,64554],"mapped",[1593,1605]],[[64555,64555],"mapped",[1594,1580]],[[64556,64556],"mapped",[1594,1605]],[[64557,64557],"mapped",[1601,1580]],[[64558,64558],"mapped",[1601,1581]],[[64559,64559],"mapped",[1601,1582]],[[64560,64560],"mapped",[1601,1605]],[[64561,64561],"mapped",[1601,1609]],[[64562,64562],"mapped",[1601,1610]],[[64563,64563],"mapped",[1602,1581]],[[64564,64564],"mapped",[1602,1605]],[[64565,64565],"mapped",[1602,1609]],[[64566,64566],"mapped",[1602,1610]],[[64567,64567],"mapped",[1603,1575]],[[64568,64568],"mapped",[1603,1580]],[[64569,64569],"mapped",[1603,1581]],[[64570,64570],"mapped",[1603,1582]],[[64571,64571],"mapped",[1603,1604]],[[64572,64572],"mapped",[1603,1605]],[[64573,64573],"mapped",[1603,1609]],[[64574,64574],"mapped",[1603,1610]],[[64575,64575],"mapped",[1604,1580]],[[64576,64576],"mapped",[1604,1581]],[[64577,64577],"mapped",[1604,1582]],[[64578,64578],"mapped",[1604,1605]],[[64579,64579],"mapped",[1604,1609]],[[64580,64580],"mapped",[1604,1610]],[[64581,64581],"mapped",[1605,1580]],[[64582,64582],"mapped",[1605,1581]],[[64583,64583],"mapped",[1605,1582]],[[64584,64584],"mapped",[1605,1605]],[[64585,64585],"mapped",[1605,1609]],[[64586,64586],"mapped",[1605,1610]],[[64587,64587],"mapped",[1606,1580]],[[64588,64588],"mapped",[1606,1581]],[[64589,64589],"mapped",[1606,1582]],[[64590,64590],"mapped",[1606,1605]],[[64591,64591],"mapped",[1606,1609]],[[64592,64592],"mapped",[1606,1610]],[[64593,64593],"mapped",[1607,1580]],[[64594,64594],"mapped",[1607,1605]],[[64595,64595],"mapped",[1607,1609]],[[64596,64596],"mapped",[1607,1610]],[[64597,64597],"mapped",[1610,1580]],[[64598,64598],"mapped",[1610,1581]],[[64599,64599],"mapped",[1610,1582]],[[64600,64600],"mapped",[1610,1605]],[[64601,64601],"mapped",[1610,1609]],[[64602,64602],"mapped",[1610,1610]],[[64603,64603],"mapped",[1584,1648]],[[64604,64604],"mapped",[1585,1648]],[[64605,64605],"mapped",[1609,1648]],[[64606,64606],"disallowed_STD3_mapped",[32,1612,1617]],[[64607,64607],"disallowed_STD3_mapped",[32,1613,1617]],[[64608,64608],"disallowed_STD3_mapped",[32,1614,1617]],[[64609,64609],"disallowed_STD3_mapped",[32,1615,1617]],[[64610,64610],"disallowed_STD3_mapped",[32,1616,1617]],[[64611,64611],"disallowed_STD3_mapped",[32,1617,1648]],[[64612,64612],"mapped",[1574,1585]],[[64613,64613],"mapped",[1574,1586]],[[64614,64614],"mapped",[1574,1605]],[[64615,64615],"mapped",[1574,1606]],[[64616,64616],"mapped",[1574,1609]],[[64617,64617],"mapped",[1574,1610]],[[64618,64618],"mapped",[1576,1585]],[[64619,64619],"mapped",[1576,1586]],[[64620,64620],"mapped",[1576,1605]],[[64621,64621],"mapped",[1576,1606]],[[64622,64622],"mapped",[1576,1609]],[[64623,64623],"mapped",[1576,1610]],[[64624,64624],"mapped",[1578,1585]],[[64625,64625],"mapped",[1578,1586]],[[64626,64626],"mapped",[1578,1605]],[[64627,64627],"mapped",[1578,1606]],[[64628,64628],"mapped",[1578,1609]],[[64629,64629],"mapped",[1578,1610]],[[64630,64630],"mapped",[1579,1585]],[[64631,64631],"mapped",[1579,1586]],[[64632,64632],"mapped",[1579,1605]],[[64633,64633],"mapped",[1579,1606]],[[64634,64634],"mapped",[1579,1609]],[[64635,64635],"mapped",[1579,1610]],[[64636,64636],"mapped",[1601,1609]],[[64637,64637],"mapped",[1601,1610]],[[64638,64638],"mapped",[1602,1609]],[[64639,64639],"mapped",[1602,1610]],[[64640,64640],"mapped",[1603,1575]],[[64641,64641],"mapped",[1603,1604]],[[64642,64642],"mapped",[1603,1605]],[[64643,64643],"mapped",[1603,1609]],[[64644,64644],"mapped",[1603,1610]],[[64645,64645],"mapped",[1604,1605]],[[64646,64646],"mapped",[1604,1609]],[[64647,64647],"mapped",[1604,1610]],[[64648,64648],"mapped",[1605,1575]],[[64649,64649],"mapped",[1605,1605]],[[64650,64650],"mapped",[1606,1585]],[[64651,64651],"mapped",[1606,1586]],[[64652,64652],"mapped",[1606,1605]],[[64653,64653],"mapped",[1606,1606]],[[64654,64654],"mapped",[1606,1609]],[[64655,64655],"mapped",[1606,1610]],[[64656,64656],"mapped",[1609,1648]],[[64657,64657],"mapped",[1610,1585]],[[64658,64658],"mapped",[1610,1586]],[[64659,64659],"mapped",[1610,1605]],[[64660,64660],"mapped",[1610,1606]],[[64661,64661],"mapped",[1610,1609]],[[64662,64662],"mapped",[1610,1610]],[[64663,64663],"mapped",[1574,1580]],[[64664,64664],"mapped",[1574,1581]],[[64665,64665],"mapped",[1574,1582]],[[64666,64666],"mapped",[1574,1605]],[[64667,64667],"mapped",[1574,1607]],[[64668,64668],"mapped",[1576,1580]],[[64669,64669],"mapped",[1576,1581]],[[64670,64670],"mapped",[1576,1582]],[[64671,64671],"mapped",[1576,1605]],[[64672,64672],"mapped",[1576,1607]],[[64673,64673],"mapped",[1578,1580]],[[64674,64674],"mapped",[1578,1581]],[[64675,64675],"mapped",[1578,1582]],[[64676,64676],"mapped",[1578,1605]],[[64677,64677],"mapped",[1578,1607]],[[64678,64678],"mapped",[1579,1605]],[[64679,64679],"mapped",[1580,1581]],[[64680,64680],"mapped",[1580,1605]],[[64681,64681],"mapped",[1581,1580]],[[64682,64682],"mapped",[1581,1605]],[[64683,64683],"mapped",[1582,1580]],[[64684,64684],"mapped",[1582,1605]],[[64685,64685],"mapped",[1587,1580]],[[64686,64686],"mapped",[1587,1581]],[[64687,64687],"mapped",[1587,1582]],[[64688,64688],"mapped",[1587,1605]],[[64689,64689],"mapped",[1589,1581]],[[64690,64690],"mapped",[1589,1582]],[[64691,64691],"mapped",[1589,1605]],[[64692,64692],"mapped",[1590,1580]],[[64693,64693],"mapped",[1590,1581]],[[64694,64694],"mapped",[1590,1582]],[[64695,64695],"mapped",[1590,1605]],[[64696,64696],"mapped",[1591,1581]],[[64697,64697],"mapped",[1592,1605]],[[64698,64698],"mapped",[1593,1580]],[[64699,64699],"mapped",[1593,1605]],[[64700,64700],"mapped",[1594,1580]],[[64701,64701],"mapped",[1594,1605]],[[64702,64702],"mapped",[1601,1580]],[[64703,64703],"mapped",[1601,1581]],[[64704,64704],"mapped",[1601,1582]],[[64705,64705],"mapped",[1601,1605]],[[64706,64706],"mapped",[1602,1581]],[[64707,64707],"mapped",[1602,1605]],[[64708,64708],"mapped",[1603,1580]],[[64709,64709],"mapped",[1603,1581]],[[64710,64710],"mapped",[1603,1582]],[[64711,64711],"mapped",[1603,1604]],[[64712,64712],"mapped",[1603,1605]],[[64713,64713],"mapped",[1604,1580]],[[64714,64714],"mapped",[1604,1581]],[[64715,64715],"mapped",[1604,1582]],[[64716,64716],"mapped",[1604,1605]],[[64717,64717],"mapped",[1604,1607]],[[64718,64718],"mapped",[1605,1580]],[[64719,64719],"mapped",[1605,1581]],[[64720,64720],"mapped",[1605,1582]],[[64721,64721],"mapped",[1605,1605]],[[64722,64722],"mapped",[1606,1580]],[[64723,64723],"mapped",[1606,1581]],[[64724,64724],"mapped",[1606,1582]],[[64725,64725],"mapped",[1606,1605]],[[64726,64726],"mapped",[1606,1607]],[[64727,64727],"mapped",[1607,1580]],[[64728,64728],"mapped",[1607,1605]],[[64729,64729],"mapped",[1607,1648]],[[64730,64730],"mapped",[1610,1580]],[[64731,64731],"mapped",[1610,1581]],[[64732,64732],"mapped",[1610,1582]],[[64733,64733],"mapped",[1610,1605]],[[64734,64734],"mapped",[1610,1607]],[[64735,64735],"mapped",[1574,1605]],[[64736,64736],"mapped",[1574,1607]],[[64737,64737],"mapped",[1576,1605]],[[64738,64738],"mapped",[1576,1607]],[[64739,64739],"mapped",[1578,1605]],[[64740,64740],"mapped",[1578,1607]],[[64741,64741],"mapped",[1579,1605]],[[64742,64742],"mapped",[1579,1607]],[[64743,64743],"mapped",[1587,1605]],[[64744,64744],"mapped",[1587,1607]],[[64745,64745],"mapped",[1588,1605]],[[64746,64746],"mapped",[1588,1607]],[[64747,64747],"mapped",[1603,1604]],[[64748,64748],"mapped",[1603,1605]],[[64749,64749],"mapped",[1604,1605]],[[64750,64750],"mapped",[1606,1605]],[[64751,64751],"mapped",[1606,1607]],[[64752,64752],"mapped",[1610,1605]],[[64753,64753],"mapped",[1610,1607]],[[64754,64754],"mapped",[1600,1614,1617]],[[64755,64755],"mapped",[1600,1615,1617]],[[64756,64756],"mapped",[1600,1616,1617]],[[64757,64757],"mapped",[1591,1609]],[[64758,64758],"mapped",[1591,1610]],[[64759,64759],"mapped",[1593,1609]],[[64760,64760],"mapped",[1593,1610]],[[64761,64761],"mapped",[1594,1609]],[[64762,64762],"mapped",[1594,1610]],[[64763,64763],"mapped",[1587,1609]],[[64764,64764],"mapped",[1587,1610]],[[64765,64765],"mapped",[1588,1609]],[[64766,64766],"mapped",[1588,1610]],[[64767,64767],"mapped",[1581,1609]],[[64768,64768],"mapped",[1581,1610]],[[64769,64769],"mapped",[1580,1609]],[[64770,64770],"mapped",[1580,1610]],[[64771,64771],"mapped",[1582,1609]],[[64772,64772],"mapped",[1582,1610]],[[64773,64773],"mapped",[1589,1609]],[[64774,64774],"mapped",[1589,1610]],[[64775,64775],"mapped",[1590,1609]],[[64776,64776],"mapped",[1590,1610]],[[64777,64777],"mapped",[1588,1580]],[[64778,64778],"mapped",[1588,1581]],[[64779,64779],"mapped",[1588,1582]],[[64780,64780],"mapped",[1588,1605]],[[64781,64781],"mapped",[1588,1585]],[[64782,64782],"mapped",[1587,1585]],[[64783,64783],"mapped",[1589,1585]],[[64784,64784],"mapped",[1590,1585]],[[64785,64785],"mapped",[1591,1609]],[[64786,64786],"mapped",[1591,1610]],[[64787,64787],"mapped",[1593,1609]],[[64788,64788],"mapped",[1593,1610]],[[64789,64789],"mapped",[1594,1609]],[[64790,64790],"mapped",[1594,1610]],[[64791,64791],"mapped",[1587,1609]],[[64792,64792],"mapped",[1587,1610]],[[64793,64793],"mapped",[1588,1609]],[[64794,64794],"mapped",[1588,1610]],[[64795,64795],"mapped",[1581,1609]],[[64796,64796],"mapped",[1581,1610]],[[64797,64797],"mapped",[1580,1609]],[[64798,64798],"mapped",[1580,1610]],[[64799,64799],"mapped",[1582,1609]],[[64800,64800],"mapped",[1582,1610]],[[64801,64801],"mapped",[1589,1609]],[[64802,64802],"mapped",[1589,1610]],[[64803,64803],"mapped",[1590,1609]],[[64804,64804],"mapped",[1590,1610]],[[64805,64805],"mapped",[1588,1580]],[[64806,64806],"mapped",[1588,1581]],[[64807,64807],"mapped",[1588,1582]],[[64808,64808],"mapped",[1588,1605]],[[64809,64809],"mapped",[1588,1585]],[[64810,64810],"mapped",[1587,1585]],[[64811,64811],"mapped",[1589,1585]],[[64812,64812],"mapped",[1590,1585]],[[64813,64813],"mapped",[1588,1580]],[[64814,64814],"mapped",[1588,1581]],[[64815,64815],"mapped",[1588,1582]],[[64816,64816],"mapped",[1588,1605]],[[64817,64817],"mapped",[1587,1607]],[[64818,64818],"mapped",[1588,1607]],[[64819,64819],"mapped",[1591,1605]],[[64820,64820],"mapped",[1587,1580]],[[64821,64821],"mapped",[1587,1581]],[[64822,64822],"mapped",[1587,1582]],[[64823,64823],"mapped",[1588,1580]],[[64824,64824],"mapped",[1588,1581]],[[64825,64825],"mapped",[1588,1582]],[[64826,64826],"mapped",[1591,1605]],[[64827,64827],"mapped",[1592,1605]],[[64828,64829],"mapped",[1575,1611]],[[64830,64831],"valid",[],"NV8"],[[64832,64847],"disallowed"],[[64848,64848],"mapped",[1578,1580,1605]],[[64849,64850],"mapped",[1578,1581,1580]],[[64851,64851],"mapped",[1578,1581,1605]],[[64852,64852],"mapped",[1578,1582,1605]],[[64853,64853],"mapped",[1578,1605,1580]],[[64854,64854],"mapped",[1578,1605,1581]],[[64855,64855],"mapped",[1578,1605,1582]],[[64856,64857],"mapped",[1580,1605,1581]],[[64858,64858],"mapped",[1581,1605,1610]],[[64859,64859],"mapped",[1581,1605,1609]],[[64860,64860],"mapped",[1587,1581,1580]],[[64861,64861],"mapped",[1587,1580,1581]],[[64862,64862],"mapped",[1587,1580,1609]],[[64863,64864],"mapped",[1587,1605,1581]],[[64865,64865],"mapped",[1587,1605,1580]],[[64866,64867],"mapped",[1587,1605,1605]],[[64868,64869],"mapped",[1589,1581,1581]],[[64870,64870],"mapped",[1589,1605,1605]],[[64871,64872],"mapped",[1588,1581,1605]],[[64873,64873],"mapped",[1588,1580,1610]],[[64874,64875],"mapped",[1588,1605,1582]],[[64876,64877],"mapped",[1588,1605,1605]],[[64878,64878],"mapped",[1590,1581,1609]],[[64879,64880],"mapped",[1590,1582,1605]],[[64881,64882],"mapped",[1591,1605,1581]],[[64883,64883],"mapped",[1591,1605,1605]],[[64884,64884],"mapped",[1591,1605,1610]],[[64885,64885],"mapped",[1593,1580,1605]],[[64886,64887],"mapped",[1593,1605,1605]],[[64888,64888],"mapped",[1593,1605,1609]],[[64889,64889],"mapped",[1594,1605,1605]],[[64890,64890],"mapped",[1594,1605,1610]],[[64891,64891],"mapped",[1594,1605,1609]],[[64892,64893],"mapped",[1601,1582,1605]],[[64894,64894],"mapped",[1602,1605,1581]],[[64895,64895],"mapped",[1602,1605,1605]],[[64896,64896],"mapped",[1604,1581,1605]],[[64897,64897],"mapped",[1604,1581,1610]],[[64898,64898],"mapped",[1604,1581,1609]],[[64899,64900],"mapped",[1604,1580,1580]],[[64901,64902],"mapped",[1604,1582,1605]],[[64903,64904],"mapped",[1604,1605,1581]],[[64905,64905],"mapped",[1605,1581,1580]],[[64906,64906],"mapped",[1605,1581,1605]],[[64907,64907],"mapped",[1605,1581,1610]],[[64908,64908],"mapped",[1605,1580,1581]],[[64909,64909],"mapped",[1605,1580,1605]],[[64910,64910],"mapped",[1605,1582,1580]],[[64911,64911],"mapped",[1605,1582,1605]],[[64912,64913],"disallowed"],[[64914,64914],"mapped",[1605,1580,1582]],[[64915,64915],"mapped",[1607,1605,1580]],[[64916,64916],"mapped",[1607,1605,1605]],[[64917,64917],"mapped",[1606,1581,1605]],[[64918,64918],"mapped",[1606,1581,1609]],[[64919,64920],"mapped",[1606,1580,1605]],[[64921,64921],"mapped",[1606,1580,1609]],[[64922,64922],"mapped",[1606,1605,1610]],[[64923,64923],"mapped",[1606,1605,1609]],[[64924,64925],"mapped",[1610,1605,1605]],[[64926,64926],"mapped",[1576,1582,1610]],[[64927,64927],"mapped",[1578,1580,1610]],[[64928,64928],"mapped",[1578,1580,1609]],[[64929,64929],"mapped",[1578,1582,1610]],[[64930,64930],"mapped",[1578,1582,1609]],[[64931,64931],"mapped",[1578,1605,1610]],[[64932,64932],"mapped",[1578,1605,1609]],[[64933,64933],"mapped",[1580,1605,1610]],[[64934,64934],"mapped",[1580,1581,1609]],[[64935,64935],"mapped",[1580,1605,1609]],[[64936,64936],"mapped",[1587,1582,1609]],[[64937,64937],"mapped",[1589,1581,1610]],[[64938,64938],"mapped",[1588,1581,1610]],[[64939,64939],"mapped",[1590,1581,1610]],[[64940,64940],"mapped",[1604,1580,1610]],[[64941,64941],"mapped",[1604,1605,1610]],[[64942,64942],"mapped",[1610,1581,1610]],[[64943,64943],"mapped",[1610,1580,1610]],[[64944,64944],"mapped",[1610,1605,1610]],[[64945,64945],"mapped",[1605,1605,1610]],[[64946,64946],"mapped",[1602,1605,1610]],[[64947,64947],"mapped",[1606,1581,1610]],[[64948,64948],"mapped",[1602,1605,1581]],[[64949,64949],"mapped",[1604,1581,1605]],[[64950,64950],"mapped",[1593,1605,1610]],[[64951,64951],"mapped",[1603,1605,1610]],[[64952,64952],"mapped",[1606,1580,1581]],[[64953,64953],"mapped",[1605,1582,1610]],[[64954,64954],"mapped",[1604,1580,1605]],[[64955,64955],"mapped",[1603,1605,1605]],[[64956,64956],"mapped",[1604,1580,1605]],[[64957,64957],"mapped",[1606,1580,1581]],[[64958,64958],"mapped",[1580,1581,1610]],[[64959,64959],"mapped",[1581,1580,1610]],[[64960,64960],"mapped",[1605,1580,1610]],[[64961,64961],"mapped",[1601,1605,1610]],[[64962,64962],"mapped",[1576,1581,1610]],[[64963,64963],"mapped",[1603,1605,1605]],[[64964,64964],"mapped",[1593,1580,1605]],[[64965,64965],"mapped",[1589,1605,1605]],[[64966,64966],"mapped",[1587,1582,1610]],[[64967,64967],"mapped",[1606,1580,1610]],[[64968,64975],"disallowed"],[[64976,65007],"disallowed"],[[65008,65008],"mapped",[1589,1604,1746]],[[65009,65009],"mapped",[1602,1604,1746]],[[65010,65010],"mapped",[1575,1604,1604,1607]],[[65011,65011],"mapped",[1575,1603,1576,1585]],[[65012,65012],"mapped",[1605,1581,1605,1583]],[[65013,65013],"mapped",[1589,1604,1593,1605]],[[65014,65014],"mapped",[1585,1587,1608,1604]],[[65015,65015],"mapped",[1593,1604,1610,1607]],[[65016,65016],"mapped",[1608,1587,1604,1605]],[[65017,65017],"mapped",[1589,1604,1609]],[[65018,65018],"disallowed_STD3_mapped",[1589,1604,1609,32,1575,1604,1604,1607,32,1593,1604,1610,1607,32,1608,1587,1604,1605]],[[65019,65019],"disallowed_STD3_mapped",[1580,1604,32,1580,1604,1575,1604,1607]],[[65020,65020],"mapped",[1585,1740,1575,1604]],[[65021,65021],"valid",[],"NV8"],[[65022,65023],"disallowed"],[[65024,65039],"ignored"],[[65040,65040],"disallowed_STD3_mapped",[44]],[[65041,65041],"mapped",[12289]],[[65042,65042],"disallowed"],[[65043,65043],"disallowed_STD3_mapped",[58]],[[65044,65044],"disallowed_STD3_mapped",[59]],[[65045,65045],"disallowed_STD3_mapped",[33]],[[65046,65046],"disallowed_STD3_mapped",[63]],[[65047,65047],"mapped",[12310]],[[65048,65048],"mapped",[12311]],[[65049,65049],"disallowed"],[[65050,65055],"disallowed"],[[65056,65059],"valid"],[[65060,65062],"valid"],[[65063,65069],"valid"],[[65070,65071],"valid"],[[65072,65072],"disallowed"],[[65073,65073],"mapped",[8212]],[[65074,65074],"mapped",[8211]],[[65075,65076],"disallowed_STD3_mapped",[95]],[[65077,65077],"disallowed_STD3_mapped",[40]],[[65078,65078],"disallowed_STD3_mapped",[41]],[[65079,65079],"disallowed_STD3_mapped",[123]],[[65080,65080],"disallowed_STD3_mapped",[125]],[[65081,65081],"mapped",[12308]],[[65082,65082],"mapped",[12309]],[[65083,65083],"mapped",[12304]],[[65084,65084],"mapped",[12305]],[[65085,65085],"mapped",[12298]],[[65086,65086],"mapped",[12299]],[[65087,65087],"mapped",[12296]],[[65088,65088],"mapped",[12297]],[[65089,65089],"mapped",[12300]],[[65090,65090],"mapped",[12301]],[[65091,65091],"mapped",[12302]],[[65092,65092],"mapped",[12303]],[[65093,65094],"valid",[],"NV8"],[[65095,65095],"disallowed_STD3_mapped",[91]],[[65096,65096],"disallowed_STD3_mapped",[93]],[[65097,65100],"disallowed_STD3_mapped",[32,773]],[[65101,65103],"disallowed_STD3_mapped",[95]],[[65104,65104],"disallowed_STD3_mapped",[44]],[[65105,65105],"mapped",[12289]],[[65106,65106],"disallowed"],[[65107,65107],"disallowed"],[[65108,65108],"disallowed_STD3_mapped",[59]],[[65109,65109],"disallowed_STD3_mapped",[58]],[[65110,65110],"disallowed_STD3_mapped",[63]],[[65111,65111],"disallowed_STD3_mapped",[33]],[[65112,65112],"mapped",[8212]],[[65113,65113],"disallowed_STD3_mapped",[40]],[[65114,65114],"disallowed_STD3_mapped",[41]],[[65115,65115],"disallowed_STD3_mapped",[123]],[[65116,65116],"disallowed_STD3_mapped",[125]],[[65117,65117],"mapped",[12308]],[[65118,65118],"mapped",[12309]],[[65119,65119],"disallowed_STD3_mapped",[35]],[[65120,65120],"disallowed_STD3_mapped",[38]],[[65121,65121],"disallowed_STD3_mapped",[42]],[[65122,65122],"disallowed_STD3_mapped",[43]],[[65123,65123],"mapped",[45]],[[65124,65124],"disallowed_STD3_mapped",[60]],[[65125,65125],"disallowed_STD3_mapped",[62]],[[65126,65126],"disallowed_STD3_mapped",[61]],[[65127,65127],"disallowed"],[[65128,65128],"disallowed_STD3_mapped",[92]],[[65129,65129],"disallowed_STD3_mapped",[36]],[[65130,65130],"disallowed_STD3_mapped",[37]],[[65131,65131],"disallowed_STD3_mapped",[64]],[[65132,65135],"disallowed"],[[65136,65136],"disallowed_STD3_mapped",[32,1611]],[[65137,65137],"mapped",[1600,1611]],[[65138,65138],"disallowed_STD3_mapped",[32,1612]],[[65139,65139],"valid"],[[65140,65140],"disallowed_STD3_mapped",[32,1613]],[[65141,65141],"disallowed"],[[65142,65142],"disallowed_STD3_mapped",[32,1614]],[[65143,65143],"mapped",[1600,1614]],[[65144,65144],"disallowed_STD3_mapped",[32,1615]],[[65145,65145],"mapped",[1600,1615]],[[65146,65146],"disallowed_STD3_mapped",[32,1616]],[[65147,65147],"mapped",[1600,1616]],[[65148,65148],"disallowed_STD3_mapped",[32,1617]],[[65149,65149],"mapped",[1600,1617]],[[65150,65150],"disallowed_STD3_mapped",[32,1618]],[[65151,65151],"mapped",[1600,1618]],[[65152,65152],"mapped",[1569]],[[65153,65154],"mapped",[1570]],[[65155,65156],"mapped",[1571]],[[65157,65158],"mapped",[1572]],[[65159,65160],"mapped",[1573]],[[65161,65164],"mapped",[1574]],[[65165,65166],"mapped",[1575]],[[65167,65170],"mapped",[1576]],[[65171,65172],"mapped",[1577]],[[65173,65176],"mapped",[1578]],[[65177,65180],"mapped",[1579]],[[65181,65184],"mapped",[1580]],[[65185,65188],"mapped",[1581]],[[65189,65192],"mapped",[1582]],[[65193,65194],"mapped",[1583]],[[65195,65196],"mapped",[1584]],[[65197,65198],"mapped",[1585]],[[65199,65200],"mapped",[1586]],[[65201,65204],"mapped",[1587]],[[65205,65208],"mapped",[1588]],[[65209,65212],"mapped",[1589]],[[65213,65216],"mapped",[1590]],[[65217,65220],"mapped",[1591]],[[65221,65224],"mapped",[1592]],[[65225,65228],"mapped",[1593]],[[65229,65232],"mapped",[1594]],[[65233,65236],"mapped",[1601]],[[65237,65240],"mapped",[1602]],[[65241,65244],"mapped",[1603]],[[65245,65248],"mapped",[1604]],[[65249,65252],"mapped",[1605]],[[65253,65256],"mapped",[1606]],[[65257,65260],"mapped",[1607]],[[65261,65262],"mapped",[1608]],[[65263,65264],"mapped",[1609]],[[65265,65268],"mapped",[1610]],[[65269,65270],"mapped",[1604,1570]],[[65271,65272],"mapped",[1604,1571]],[[65273,65274],"mapped",[1604,1573]],[[65275,65276],"mapped",[1604,1575]],[[65277,65278],"disallowed"],[[65279,65279],"ignored"],[[65280,65280],"disallowed"],[[65281,65281],"disallowed_STD3_mapped",[33]],[[65282,65282],"disallowed_STD3_mapped",[34]],[[65283,65283],"disallowed_STD3_mapped",[35]],[[65284,65284],"disallowed_STD3_mapped",[36]],[[65285,65285],"disallowed_STD3_mapped",[37]],[[65286,65286],"disallowed_STD3_mapped",[38]],[[65287,65287],"disallowed_STD3_mapped",[39]],[[65288,65288],"disallowed_STD3_mapped",[40]],[[65289,65289],"disallowed_STD3_mapped",[41]],[[65290,65290],"disallowed_STD3_mapped",[42]],[[65291,65291],"disallowed_STD3_mapped",[43]],[[65292,65292],"disallowed_STD3_mapped",[44]],[[65293,65293],"mapped",[45]],[[65294,65294],"mapped",[46]],[[65295,65295],"disallowed_STD3_mapped",[47]],[[65296,65296],"mapped",[48]],[[65297,65297],"mapped",[49]],[[65298,65298],"mapped",[50]],[[65299,65299],"mapped",[51]],[[65300,65300],"mapped",[52]],[[65301,65301],"mapped",[53]],[[65302,65302],"mapped",[54]],[[65303,65303],"mapped",[55]],[[65304,65304],"mapped",[56]],[[65305,65305],"mapped",[57]],[[65306,65306],"disallowed_STD3_mapped",[58]],[[65307,65307],"disallowed_STD3_mapped",[59]],[[65308,65308],"disallowed_STD3_mapped",[60]],[[65309,65309],"disallowed_STD3_mapped",[61]],[[65310,65310],"disallowed_STD3_mapped",[62]],[[65311,65311],"disallowed_STD3_mapped",[63]],[[65312,65312],"disallowed_STD3_mapped",[64]],[[65313,65313],"mapped",[97]],[[65314,65314],"mapped",[98]],[[65315,65315],"mapped",[99]],[[65316,65316],"mapped",[100]],[[65317,65317],"mapped",[101]],[[65318,65318],"mapped",[102]],[[65319,65319],"mapped",[103]],[[65320,65320],"mapped",[104]],[[65321,65321],"mapped",[105]],[[65322,65322],"mapped",[106]],[[65323,65323],"mapped",[107]],[[65324,65324],"mapped",[108]],[[65325,65325],"mapped",[109]],[[65326,65326],"mapped",[110]],[[65327,65327],"mapped",[111]],[[65328,65328],"mapped",[112]],[[65329,65329],"mapped",[113]],[[65330,65330],"mapped",[114]],[[65331,65331],"mapped",[115]],[[65332,65332],"mapped",[116]],[[65333,65333],"mapped",[117]],[[65334,65334],"mapped",[118]],[[65335,65335],"mapped",[119]],[[65336,65336],"mapped",[120]],[[65337,65337],"mapped",[121]],[[65338,65338],"mapped",[122]],[[65339,65339],"disallowed_STD3_mapped",[91]],[[65340,65340],"disallowed_STD3_mapped",[92]],[[65341,65341],"disallowed_STD3_mapped",[93]],[[65342,65342],"disallowed_STD3_mapped",[94]],[[65343,65343],"disallowed_STD3_mapped",[95]],[[65344,65344],"disallowed_STD3_mapped",[96]],[[65345,65345],"mapped",[97]],[[65346,65346],"mapped",[98]],[[65347,65347],"mapped",[99]],[[65348,65348],"mapped",[100]],[[65349,65349],"mapped",[101]],[[65350,65350],"mapped",[102]],[[65351,65351],"mapped",[103]],[[65352,65352],"mapped",[104]],[[65353,65353],"mapped",[105]],[[65354,65354],"mapped",[106]],[[65355,65355],"mapped",[107]],[[65356,65356],"mapped",[108]],[[65357,65357],"mapped",[109]],[[65358,65358],"mapped",[110]],[[65359,65359],"mapped",[111]],[[65360,65360],"mapped",[112]],[[65361,65361],"mapped",[113]],[[65362,65362],"mapped",[114]],[[65363,65363],"mapped",[115]],[[65364,65364],"mapped",[116]],[[65365,65365],"mapped",[117]],[[65366,65366],"mapped",[118]],[[65367,65367],"mapped",[119]],[[65368,65368],"mapped",[120]],[[65369,65369],"mapped",[121]],[[65370,65370],"mapped",[122]],[[65371,65371],"disallowed_STD3_mapped",[123]],[[65372,65372],"disallowed_STD3_mapped",[124]],[[65373,65373],"disallowed_STD3_mapped",[125]],[[65374,65374],"disallowed_STD3_mapped",[126]],[[65375,65375],"mapped",[10629]],[[65376,65376],"mapped",[10630]],[[65377,65377],"mapped",[46]],[[65378,65378],"mapped",[12300]],[[65379,65379],"mapped",[12301]],[[65380,65380],"mapped",[12289]],[[65381,65381],"mapped",[12539]],[[65382,65382],"mapped",[12530]],[[65383,65383],"mapped",[12449]],[[65384,65384],"mapped",[12451]],[[65385,65385],"mapped",[12453]],[[65386,65386],"mapped",[12455]],[[65387,65387],"mapped",[12457]],[[65388,65388],"mapped",[12515]],[[65389,65389],"mapped",[12517]],[[65390,65390],"mapped",[12519]],[[65391,65391],"mapped",[12483]],[[65392,65392],"mapped",[12540]],[[65393,65393],"mapped",[12450]],[[65394,65394],"mapped",[12452]],[[65395,65395],"mapped",[12454]],[[65396,65396],"mapped",[12456]],[[65397,65397],"mapped",[12458]],[[65398,65398],"mapped",[12459]],[[65399,65399],"mapped",[12461]],[[65400,65400],"mapped",[12463]],[[65401,65401],"mapped",[12465]],[[65402,65402],"mapped",[12467]],[[65403,65403],"mapped",[12469]],[[65404,65404],"mapped",[12471]],[[65405,65405],"mapped",[12473]],[[65406,65406],"mapped",[12475]],[[65407,65407],"mapped",[12477]],[[65408,65408],"mapped",[12479]],[[65409,65409],"mapped",[12481]],[[65410,65410],"mapped",[12484]],[[65411,65411],"mapped",[12486]],[[65412,65412],"mapped",[12488]],[[65413,65413],"mapped",[12490]],[[65414,65414],"mapped",[12491]],[[65415,65415],"mapped",[12492]],[[65416,65416],"mapped",[12493]],[[65417,65417],"mapped",[12494]],[[65418,65418],"mapped",[12495]],[[65419,65419],"mapped",[12498]],[[65420,65420],"mapped",[12501]],[[65421,65421],"mapped",[12504]],[[65422,65422],"mapped",[12507]],[[65423,65423],"mapped",[12510]],[[65424,65424],"mapped",[12511]],[[65425,65425],"mapped",[12512]],[[65426,65426],"mapped",[12513]],[[65427,65427],"mapped",[12514]],[[65428,65428],"mapped",[12516]],[[65429,65429],"mapped",[12518]],[[65430,65430],"mapped",[12520]],[[65431,65431],"mapped",[12521]],[[65432,65432],"mapped",[12522]],[[65433,65433],"mapped",[12523]],[[65434,65434],"mapped",[12524]],[[65435,65435],"mapped",[12525]],[[65436,65436],"mapped",[12527]],[[65437,65437],"mapped",[12531]],[[65438,65438],"mapped",[12441]],[[65439,65439],"mapped",[12442]],[[65440,65440],"disallowed"],[[65441,65441],"mapped",[4352]],[[65442,65442],"mapped",[4353]],[[65443,65443],"mapped",[4522]],[[65444,65444],"mapped",[4354]],[[65445,65445],"mapped",[4524]],[[65446,65446],"mapped",[4525]],[[65447,65447],"mapped",[4355]],[[65448,65448],"mapped",[4356]],[[65449,65449],"mapped",[4357]],[[65450,65450],"mapped",[4528]],[[65451,65451],"mapped",[4529]],[[65452,65452],"mapped",[4530]],[[65453,65453],"mapped",[4531]],[[65454,65454],"mapped",[4532]],[[65455,65455],"mapped",[4533]],[[65456,65456],"mapped",[4378]],[[65457,65457],"mapped",[4358]],[[65458,65458],"mapped",[4359]],[[65459,65459],"mapped",[4360]],[[65460,65460],"mapped",[4385]],[[65461,65461],"mapped",[4361]],[[65462,65462],"mapped",[4362]],[[65463,65463],"mapped",[4363]],[[65464,65464],"mapped",[4364]],[[65465,65465],"mapped",[4365]],[[65466,65466],"mapped",[4366]],[[65467,65467],"mapped",[4367]],[[65468,65468],"mapped",[4368]],[[65469,65469],"mapped",[4369]],[[65470,65470],"mapped",[4370]],[[65471,65473],"disallowed"],[[65474,65474],"mapped",[4449]],[[65475,65475],"mapped",[4450]],[[65476,65476],"mapped",[4451]],[[65477,65477],"mapped",[4452]],[[65478,65478],"mapped",[4453]],[[65479,65479],"mapped",[4454]],[[65480,65481],"disallowed"],[[65482,65482],"mapped",[4455]],[[65483,65483],"mapped",[4456]],[[65484,65484],"mapped",[4457]],[[65485,65485],"mapped",[4458]],[[65486,65486],"mapped",[4459]],[[65487,65487],"mapped",[4460]],[[65488,65489],"disallowed"],[[65490,65490],"mapped",[4461]],[[65491,65491],"mapped",[4462]],[[65492,65492],"mapped",[4463]],[[65493,65493],"mapped",[4464]],[[65494,65494],"mapped",[4465]],[[65495,65495],"mapped",[4466]],[[65496,65497],"disallowed"],[[65498,65498],"mapped",[4467]],[[65499,65499],"mapped",[4468]],[[65500,65500],"mapped",[4469]],[[65501,65503],"disallowed"],[[65504,65504],"mapped",[162]],[[65505,65505],"mapped",[163]],[[65506,65506],"mapped",[172]],[[65507,65507],"disallowed_STD3_mapped",[32,772]],[[65508,65508],"mapped",[166]],[[65509,65509],"mapped",[165]],[[65510,65510],"mapped",[8361]],[[65511,65511],"disallowed"],[[65512,65512],"mapped",[9474]],[[65513,65513],"mapped",[8592]],[[65514,65514],"mapped",[8593]],[[65515,65515],"mapped",[8594]],[[65516,65516],"mapped",[8595]],[[65517,65517],"mapped",[9632]],[[65518,65518],"mapped",[9675]],[[65519,65528],"disallowed"],[[65529,65531],"disallowed"],[[65532,65532],"disallowed"],[[65533,65533],"disallowed"],[[65534,65535],"disallowed"],[[65536,65547],"valid"],[[65548,65548],"disallowed"],[[65549,65574],"valid"],[[65575,65575],"disallowed"],[[65576,65594],"valid"],[[65595,65595],"disallowed"],[[65596,65597],"valid"],[[65598,65598],"disallowed"],[[65599,65613],"valid"],[[65614,65615],"disallowed"],[[65616,65629],"valid"],[[65630,65663],"disallowed"],[[65664,65786],"valid"],[[65787,65791],"disallowed"],[[65792,65794],"valid",[],"NV8"],[[65795,65798],"disallowed"],[[65799,65843],"valid",[],"NV8"],[[65844,65846],"disallowed"],[[65847,65855],"valid",[],"NV8"],[[65856,65930],"valid",[],"NV8"],[[65931,65932],"valid",[],"NV8"],[[65933,65935],"disallowed"],[[65936,65947],"valid",[],"NV8"],[[65948,65951],"disallowed"],[[65952,65952],"valid",[],"NV8"],[[65953,65999],"disallowed"],[[66000,66044],"valid",[],"NV8"],[[66045,66045],"valid"],[[66046,66175],"disallowed"],[[66176,66204],"valid"],[[66205,66207],"disallowed"],[[66208,66256],"valid"],[[66257,66271],"disallowed"],[[66272,66272],"valid"],[[66273,66299],"valid",[],"NV8"],[[66300,66303],"disallowed"],[[66304,66334],"valid"],[[66335,66335],"valid"],[[66336,66339],"valid",[],"NV8"],[[66340,66351],"disallowed"],[[66352,66368],"valid"],[[66369,66369],"valid",[],"NV8"],[[66370,66377],"valid"],[[66378,66378],"valid",[],"NV8"],[[66379,66383],"disallowed"],[[66384,66426],"valid"],[[66427,66431],"disallowed"],[[66432,66461],"valid"],[[66462,66462],"disallowed"],[[66463,66463],"valid",[],"NV8"],[[66464,66499],"valid"],[[66500,66503],"disallowed"],[[66504,66511],"valid"],[[66512,66517],"valid",[],"NV8"],[[66518,66559],"disallowed"],[[66560,66560],"mapped",[66600]],[[66561,66561],"mapped",[66601]],[[66562,66562],"mapped",[66602]],[[66563,66563],"mapped",[66603]],[[66564,66564],"mapped",[66604]],[[66565,66565],"mapped",[66605]],[[66566,66566],"mapped",[66606]],[[66567,66567],"mapped",[66607]],[[66568,66568],"mapped",[66608]],[[66569,66569],"mapped",[66609]],[[66570,66570],"mapped",[66610]],[[66571,66571],"mapped",[66611]],[[66572,66572],"mapped",[66612]],[[66573,66573],"mapped",[66613]],[[66574,66574],"mapped",[66614]],[[66575,66575],"mapped",[66615]],[[66576,66576],"mapped",[66616]],[[66577,66577],"mapped",[66617]],[[66578,66578],"mapped",[66618]],[[66579,66579],"mapped",[66619]],[[66580,66580],"mapped",[66620]],[[66581,66581],"mapped",[66621]],[[66582,66582],"mapped",[66622]],[[66583,66583],"mapped",[66623]],[[66584,66584],"mapped",[66624]],[[66585,66585],"mapped",[66625]],[[66586,66586],"mapped",[66626]],[[66587,66587],"mapped",[66627]],[[66588,66588],"mapped",[66628]],[[66589,66589],"mapped",[66629]],[[66590,66590],"mapped",[66630]],[[66591,66591],"mapped",[66631]],[[66592,66592],"mapped",[66632]],[[66593,66593],"mapped",[66633]],[[66594,66594],"mapped",[66634]],[[66595,66595],"mapped",[66635]],[[66596,66596],"mapped",[66636]],[[66597,66597],"mapped",[66637]],[[66598,66598],"mapped",[66638]],[[66599,66599],"mapped",[66639]],[[66600,66637],"valid"],[[66638,66717],"valid"],[[66718,66719],"disallowed"],[[66720,66729],"valid"],[[66730,66815],"disallowed"],[[66816,66855],"valid"],[[66856,66863],"disallowed"],[[66864,66915],"valid"],[[66916,66926],"disallowed"],[[66927,66927],"valid",[],"NV8"],[[66928,67071],"disallowed"],[[67072,67382],"valid"],[[67383,67391],"disallowed"],[[67392,67413],"valid"],[[67414,67423],"disallowed"],[[67424,67431],"valid"],[[67432,67583],"disallowed"],[[67584,67589],"valid"],[[67590,67591],"disallowed"],[[67592,67592],"valid"],[[67593,67593],"disallowed"],[[67594,67637],"valid"],[[67638,67638],"disallowed"],[[67639,67640],"valid"],[[67641,67643],"disallowed"],[[67644,67644],"valid"],[[67645,67646],"disallowed"],[[67647,67647],"valid"],[[67648,67669],"valid"],[[67670,67670],"disallowed"],[[67671,67679],"valid",[],"NV8"],[[67680,67702],"valid"],[[67703,67711],"valid",[],"NV8"],[[67712,67742],"valid"],[[67743,67750],"disallowed"],[[67751,67759],"valid",[],"NV8"],[[67760,67807],"disallowed"],[[67808,67826],"valid"],[[67827,67827],"disallowed"],[[67828,67829],"valid"],[[67830,67834],"disallowed"],[[67835,67839],"valid",[],"NV8"],[[67840,67861],"valid"],[[67862,67865],"valid",[],"NV8"],[[67866,67867],"valid",[],"NV8"],[[67868,67870],"disallowed"],[[67871,67871],"valid",[],"NV8"],[[67872,67897],"valid"],[[67898,67902],"disallowed"],[[67903,67903],"valid",[],"NV8"],[[67904,67967],"disallowed"],[[67968,68023],"valid"],[[68024,68027],"disallowed"],[[68028,68029],"valid",[],"NV8"],[[68030,68031],"valid"],[[68032,68047],"valid",[],"NV8"],[[68048,68049],"disallowed"],[[68050,68095],"valid",[],"NV8"],[[68096,68099],"valid"],[[68100,68100],"disallowed"],[[68101,68102],"valid"],[[68103,68107],"disallowed"],[[68108,68115],"valid"],[[68116,68116],"disallowed"],[[68117,68119],"valid"],[[68120,68120],"disallowed"],[[68121,68147],"valid"],[[68148,68151],"disallowed"],[[68152,68154],"valid"],[[68155,68158],"disallowed"],[[68159,68159],"valid"],[[68160,68167],"valid",[],"NV8"],[[68168,68175],"disallowed"],[[68176,68184],"valid",[],"NV8"],[[68185,68191],"disallowed"],[[68192,68220],"valid"],[[68221,68223],"valid",[],"NV8"],[[68224,68252],"valid"],[[68253,68255],"valid",[],"NV8"],[[68256,68287],"disallowed"],[[68288,68295],"valid"],[[68296,68296],"valid",[],"NV8"],[[68297,68326],"valid"],[[68327,68330],"disallowed"],[[68331,68342],"valid",[],"NV8"],[[68343,68351],"disallowed"],[[68352,68405],"valid"],[[68406,68408],"disallowed"],[[68409,68415],"valid",[],"NV8"],[[68416,68437],"valid"],[[68438,68439],"disallowed"],[[68440,68447],"valid",[],"NV8"],[[68448,68466],"valid"],[[68467,68471],"disallowed"],[[68472,68479],"valid",[],"NV8"],[[68480,68497],"valid"],[[68498,68504],"disallowed"],[[68505,68508],"valid",[],"NV8"],[[68509,68520],"disallowed"],[[68521,68527],"valid",[],"NV8"],[[68528,68607],"disallowed"],[[68608,68680],"valid"],[[68681,68735],"disallowed"],[[68736,68736],"mapped",[68800]],[[68737,68737],"mapped",[68801]],[[68738,68738],"mapped",[68802]],[[68739,68739],"mapped",[68803]],[[68740,68740],"mapped",[68804]],[[68741,68741],"mapped",[68805]],[[68742,68742],"mapped",[68806]],[[68743,68743],"mapped",[68807]],[[68744,68744],"mapped",[68808]],[[68745,68745],"mapped",[68809]],[[68746,68746],"mapped",[68810]],[[68747,68747],"mapped",[68811]],[[68748,68748],"mapped",[68812]],[[68749,68749],"mapped",[68813]],[[68750,68750],"mapped",[68814]],[[68751,68751],"mapped",[68815]],[[68752,68752],"mapped",[68816]],[[68753,68753],"mapped",[68817]],[[68754,68754],"mapped",[68818]],[[68755,68755],"mapped",[68819]],[[68756,68756],"mapped",[68820]],[[68757,68757],"mapped",[68821]],[[68758,68758],"mapped",[68822]],[[68759,68759],"mapped",[68823]],[[68760,68760],"mapped",[68824]],[[68761,68761],"mapped",[68825]],[[68762,68762],"mapped",[68826]],[[68763,68763],"mapped",[68827]],[[68764,68764],"mapped",[68828]],[[68765,68765],"mapped",[68829]],[[68766,68766],"mapped",[68830]],[[68767,68767],"mapped",[68831]],[[68768,68768],"mapped",[68832]],[[68769,68769],"mapped",[68833]],[[68770,68770],"mapped",[68834]],[[68771,68771],"mapped",[68835]],[[68772,68772],"mapped",[68836]],[[68773,68773],"mapped",[68837]],[[68774,68774],"mapped",[68838]],[[68775,68775],"mapped",[68839]],[[68776,68776],"mapped",[68840]],[[68777,68777],"mapped",[68841]],[[68778,68778],"mapped",[68842]],[[68779,68779],"mapped",[68843]],[[68780,68780],"mapped",[68844]],[[68781,68781],"mapped",[68845]],[[68782,68782],"mapped",[68846]],[[68783,68783],"mapped",[68847]],[[68784,68784],"mapped",[68848]],[[68785,68785],"mapped",[68849]],[[68786,68786],"mapped",[68850]],[[68787,68799],"disallowed"],[[68800,68850],"valid"],[[68851,68857],"disallowed"],[[68858,68863],"valid",[],"NV8"],[[68864,69215],"disallowed"],[[69216,69246],"valid",[],"NV8"],[[69247,69631],"disallowed"],[[69632,69702],"valid"],[[69703,69709],"valid",[],"NV8"],[[69710,69713],"disallowed"],[[69714,69733],"valid",[],"NV8"],[[69734,69743],"valid"],[[69744,69758],"disallowed"],[[69759,69759],"valid"],[[69760,69818],"valid"],[[69819,69820],"valid",[],"NV8"],[[69821,69821],"disallowed"],[[69822,69825],"valid",[],"NV8"],[[69826,69839],"disallowed"],[[69840,69864],"valid"],[[69865,69871],"disallowed"],[[69872,69881],"valid"],[[69882,69887],"disallowed"],[[69888,69940],"valid"],[[69941,69941],"disallowed"],[[69942,69951],"valid"],[[69952,69955],"valid",[],"NV8"],[[69956,69967],"disallowed"],[[69968,70003],"valid"],[[70004,70005],"valid",[],"NV8"],[[70006,70006],"valid"],[[70007,70015],"disallowed"],[[70016,70084],"valid"],[[70085,70088],"valid",[],"NV8"],[[70089,70089],"valid",[],"NV8"],[[70090,70092],"valid"],[[70093,70093],"valid",[],"NV8"],[[70094,70095],"disallowed"],[[70096,70105],"valid"],[[70106,70106],"valid"],[[70107,70107],"valid",[],"NV8"],[[70108,70108],"valid"],[[70109,70111],"valid",[],"NV8"],[[70112,70112],"disallowed"],[[70113,70132],"valid",[],"NV8"],[[70133,70143],"disallowed"],[[70144,70161],"valid"],[[70162,70162],"disallowed"],[[70163,70199],"valid"],[[70200,70205],"valid",[],"NV8"],[[70206,70271],"disallowed"],[[70272,70278],"valid"],[[70279,70279],"disallowed"],[[70280,70280],"valid"],[[70281,70281],"disallowed"],[[70282,70285],"valid"],[[70286,70286],"disallowed"],[[70287,70301],"valid"],[[70302,70302],"disallowed"],[[70303,70312],"valid"],[[70313,70313],"valid",[],"NV8"],[[70314,70319],"disallowed"],[[70320,70378],"valid"],[[70379,70383],"disallowed"],[[70384,70393],"valid"],[[70394,70399],"disallowed"],[[70400,70400],"valid"],[[70401,70403],"valid"],[[70404,70404],"disallowed"],[[70405,70412],"valid"],[[70413,70414],"disallowed"],[[70415,70416],"valid"],[[70417,70418],"disallowed"],[[70419,70440],"valid"],[[70441,70441],"disallowed"],[[70442,70448],"valid"],[[70449,70449],"disallowed"],[[70450,70451],"valid"],[[70452,70452],"disallowed"],[[70453,70457],"valid"],[[70458,70459],"disallowed"],[[70460,70468],"valid"],[[70469,70470],"disallowed"],[[70471,70472],"valid"],[[70473,70474],"disallowed"],[[70475,70477],"valid"],[[70478,70479],"disallowed"],[[70480,70480],"valid"],[[70481,70486],"disallowed"],[[70487,70487],"valid"],[[70488,70492],"disallowed"],[[70493,70499],"valid"],[[70500,70501],"disallowed"],[[70502,70508],"valid"],[[70509,70511],"disallowed"],[[70512,70516],"valid"],[[70517,70783],"disallowed"],[[70784,70853],"valid"],[[70854,70854],"valid",[],"NV8"],[[70855,70855],"valid"],[[70856,70863],"disallowed"],[[70864,70873],"valid"],[[70874,71039],"disallowed"],[[71040,71093],"valid"],[[71094,71095],"disallowed"],[[71096,71104],"valid"],[[71105,71113],"valid",[],"NV8"],[[71114,71127],"valid",[],"NV8"],[[71128,71133],"valid"],[[71134,71167],"disallowed"],[[71168,71232],"valid"],[[71233,71235],"valid",[],"NV8"],[[71236,71236],"valid"],[[71237,71247],"disallowed"],[[71248,71257],"valid"],[[71258,71295],"disallowed"],[[71296,71351],"valid"],[[71352,71359],"disallowed"],[[71360,71369],"valid"],[[71370,71423],"disallowed"],[[71424,71449],"valid"],[[71450,71452],"disallowed"],[[71453,71467],"valid"],[[71468,71471],"disallowed"],[[71472,71481],"valid"],[[71482,71487],"valid",[],"NV8"],[[71488,71839],"disallowed"],[[71840,71840],"mapped",[71872]],[[71841,71841],"mapped",[71873]],[[71842,71842],"mapped",[71874]],[[71843,71843],"mapped",[71875]],[[71844,71844],"mapped",[71876]],[[71845,71845],"mapped",[71877]],[[71846,71846],"mapped",[71878]],[[71847,71847],"mapped",[71879]],[[71848,71848],"mapped",[71880]],[[71849,71849],"mapped",[71881]],[[71850,71850],"mapped",[71882]],[[71851,71851],"mapped",[71883]],[[71852,71852],"mapped",[71884]],[[71853,71853],"mapped",[71885]],[[71854,71854],"mapped",[71886]],[[71855,71855],"mapped",[71887]],[[71856,71856],"mapped",[71888]],[[71857,71857],"mapped",[71889]],[[71858,71858],"mapped",[71890]],[[71859,71859],"mapped",[71891]],[[71860,71860],"mapped",[71892]],[[71861,71861],"mapped",[71893]],[[71862,71862],"mapped",[71894]],[[71863,71863],"mapped",[71895]],[[71864,71864],"mapped",[71896]],[[71865,71865],"mapped",[71897]],[[71866,71866],"mapped",[71898]],[[71867,71867],"mapped",[71899]],[[71868,71868],"mapped",[71900]],[[71869,71869],"mapped",[71901]],[[71870,71870],"mapped",[71902]],[[71871,71871],"mapped",[71903]],[[71872,71913],"valid"],[[71914,71922],"valid",[],"NV8"],[[71923,71934],"disallowed"],[[71935,71935],"valid"],[[71936,72383],"disallowed"],[[72384,72440],"valid"],[[72441,73727],"disallowed"],[[73728,74606],"valid"],[[74607,74648],"valid"],[[74649,74649],"valid"],[[74650,74751],"disallowed"],[[74752,74850],"valid",[],"NV8"],[[74851,74862],"valid",[],"NV8"],[[74863,74863],"disallowed"],[[74864,74867],"valid",[],"NV8"],[[74868,74868],"valid",[],"NV8"],[[74869,74879],"disallowed"],[[74880,75075],"valid"],[[75076,77823],"disallowed"],[[77824,78894],"valid"],[[78895,82943],"disallowed"],[[82944,83526],"valid"],[[83527,92159],"disallowed"],[[92160,92728],"valid"],[[92729,92735],"disallowed"],[[92736,92766],"valid"],[[92767,92767],"disallowed"],[[92768,92777],"valid"],[[92778,92781],"disallowed"],[[92782,92783],"valid",[],"NV8"],[[92784,92879],"disallowed"],[[92880,92909],"valid"],[[92910,92911],"disallowed"],[[92912,92916],"valid"],[[92917,92917],"valid",[],"NV8"],[[92918,92927],"disallowed"],[[92928,92982],"valid"],[[92983,92991],"valid",[],"NV8"],[[92992,92995],"valid"],[[92996,92997],"valid",[],"NV8"],[[92998,93007],"disallowed"],[[93008,93017],"valid"],[[93018,93018],"disallowed"],[[93019,93025],"valid",[],"NV8"],[[93026,93026],"disallowed"],[[93027,93047],"valid"],[[93048,93052],"disallowed"],[[93053,93071],"valid"],[[93072,93951],"disallowed"],[[93952,94020],"valid"],[[94021,94031],"disallowed"],[[94032,94078],"valid"],[[94079,94094],"disallowed"],[[94095,94111],"valid"],[[94112,110591],"disallowed"],[[110592,110593],"valid"],[[110594,113663],"disallowed"],[[113664,113770],"valid"],[[113771,113775],"disallowed"],[[113776,113788],"valid"],[[113789,113791],"disallowed"],[[113792,113800],"valid"],[[113801,113807],"disallowed"],[[113808,113817],"valid"],[[113818,113819],"disallowed"],[[113820,113820],"valid",[],"NV8"],[[113821,113822],"valid"],[[113823,113823],"valid",[],"NV8"],[[113824,113827],"ignored"],[[113828,118783],"disallowed"],[[118784,119029],"valid",[],"NV8"],[[119030,119039],"disallowed"],[[119040,119078],"valid",[],"NV8"],[[119079,119080],"disallowed"],[[119081,119081],"valid",[],"NV8"],[[119082,119133],"valid",[],"NV8"],[[119134,119134],"mapped",[119127,119141]],[[119135,119135],"mapped",[119128,119141]],[[119136,119136],"mapped",[119128,119141,119150]],[[119137,119137],"mapped",[119128,119141,119151]],[[119138,119138],"mapped",[119128,119141,119152]],[[119139,119139],"mapped",[119128,119141,119153]],[[119140,119140],"mapped",[119128,119141,119154]],[[119141,119154],"valid",[],"NV8"],[[119155,119162],"disallowed"],[[119163,119226],"valid",[],"NV8"],[[119227,119227],"mapped",[119225,119141]],[[119228,119228],"mapped",[119226,119141]],[[119229,119229],"mapped",[119225,119141,119150]],[[119230,119230],"mapped",[119226,119141,119150]],[[119231,119231],"mapped",[119225,119141,119151]],[[119232,119232],"mapped",[119226,119141,119151]],[[119233,119261],"valid",[],"NV8"],[[119262,119272],"valid",[],"NV8"],[[119273,119295],"disallowed"],[[119296,119365],"valid",[],"NV8"],[[119366,119551],"disallowed"],[[119552,119638],"valid",[],"NV8"],[[119639,119647],"disallowed"],[[119648,119665],"valid",[],"NV8"],[[119666,119807],"disallowed"],[[119808,119808],"mapped",[97]],[[119809,119809],"mapped",[98]],[[119810,119810],"mapped",[99]],[[119811,119811],"mapped",[100]],[[119812,119812],"mapped",[101]],[[119813,119813],"mapped",[102]],[[119814,119814],"mapped",[103]],[[119815,119815],"mapped",[104]],[[119816,119816],"mapped",[105]],[[119817,119817],"mapped",[106]],[[119818,119818],"mapped",[107]],[[119819,119819],"mapped",[108]],[[119820,119820],"mapped",[109]],[[119821,119821],"mapped",[110]],[[119822,119822],"mapped",[111]],[[119823,119823],"mapped",[112]],[[119824,119824],"mapped",[113]],[[119825,119825],"mapped",[114]],[[119826,119826],"mapped",[115]],[[119827,119827],"mapped",[116]],[[119828,119828],"mapped",[117]],[[119829,119829],"mapped",[118]],[[119830,119830],"mapped",[119]],[[119831,119831],"mapped",[120]],[[119832,119832],"mapped",[121]],[[119833,119833],"mapped",[122]],[[119834,119834],"mapped",[97]],[[119835,119835],"mapped",[98]],[[119836,119836],"mapped",[99]],[[119837,119837],"mapped",[100]],[[119838,119838],"mapped",[101]],[[119839,119839],"mapped",[102]],[[119840,119840],"mapped",[103]],[[119841,119841],"mapped",[104]],[[119842,119842],"mapped",[105]],[[119843,119843],"mapped",[106]],[[119844,119844],"mapped",[107]],[[119845,119845],"mapped",[108]],[[119846,119846],"mapped",[109]],[[119847,119847],"mapped",[110]],[[119848,119848],"mapped",[111]],[[119849,119849],"mapped",[112]],[[119850,119850],"mapped",[113]],[[119851,119851],"mapped",[114]],[[119852,119852],"mapped",[115]],[[119853,119853],"mapped",[116]],[[119854,119854],"mapped",[117]],[[119855,119855],"mapped",[118]],[[119856,119856],"mapped",[119]],[[119857,119857],"mapped",[120]],[[119858,119858],"mapped",[121]],[[119859,119859],"mapped",[122]],[[119860,119860],"mapped",[97]],[[119861,119861],"mapped",[98]],[[119862,119862],"mapped",[99]],[[119863,119863],"mapped",[100]],[[119864,119864],"mapped",[101]],[[119865,119865],"mapped",[102]],[[119866,119866],"mapped",[103]],[[119867,119867],"mapped",[104]],[[119868,119868],"mapped",[105]],[[119869,119869],"mapped",[106]],[[119870,119870],"mapped",[107]],[[119871,119871],"mapped",[108]],[[119872,119872],"mapped",[109]],[[119873,119873],"mapped",[110]],[[119874,119874],"mapped",[111]],[[119875,119875],"mapped",[112]],[[119876,119876],"mapped",[113]],[[119877,119877],"mapped",[114]],[[119878,119878],"mapped",[115]],[[119879,119879],"mapped",[116]],[[119880,119880],"mapped",[117]],[[119881,119881],"mapped",[118]],[[119882,119882],"mapped",[119]],[[119883,119883],"mapped",[120]],[[119884,119884],"mapped",[121]],[[119885,119885],"mapped",[122]],[[119886,119886],"mapped",[97]],[[119887,119887],"mapped",[98]],[[119888,119888],"mapped",[99]],[[119889,119889],"mapped",[100]],[[119890,119890],"mapped",[101]],[[119891,119891],"mapped",[102]],[[119892,119892],"mapped",[103]],[[119893,119893],"disallowed"],[[119894,119894],"mapped",[105]],[[119895,119895],"mapped",[106]],[[119896,119896],"mapped",[107]],[[119897,119897],"mapped",[108]],[[119898,119898],"mapped",[109]],[[119899,119899],"mapped",[110]],[[119900,119900],"mapped",[111]],[[119901,119901],"mapped",[112]],[[119902,119902],"mapped",[113]],[[119903,119903],"mapped",[114]],[[119904,119904],"mapped",[115]],[[119905,119905],"mapped",[116]],[[119906,119906],"mapped",[117]],[[119907,119907],"mapped",[118]],[[119908,119908],"mapped",[119]],[[119909,119909],"mapped",[120]],[[119910,119910],"mapped",[121]],[[119911,119911],"mapped",[122]],[[119912,119912],"mapped",[97]],[[119913,119913],"mapped",[98]],[[119914,119914],"mapped",[99]],[[119915,119915],"mapped",[100]],[[119916,119916],"mapped",[101]],[[119917,119917],"mapped",[102]],[[119918,119918],"mapped",[103]],[[119919,119919],"mapped",[104]],[[119920,119920],"mapped",[105]],[[119921,119921],"mapped",[106]],[[119922,119922],"mapped",[107]],[[119923,119923],"mapped",[108]],[[119924,119924],"mapped",[109]],[[119925,119925],"mapped",[110]],[[119926,119926],"mapped",[111]],[[119927,119927],"mapped",[112]],[[119928,119928],"mapped",[113]],[[119929,119929],"mapped",[114]],[[119930,119930],"mapped",[115]],[[119931,119931],"mapped",[116]],[[119932,119932],"mapped",[117]],[[119933,119933],"mapped",[118]],[[119934,119934],"mapped",[119]],[[119935,119935],"mapped",[120]],[[119936,119936],"mapped",[121]],[[119937,119937],"mapped",[122]],[[119938,119938],"mapped",[97]],[[119939,119939],"mapped",[98]],[[119940,119940],"mapped",[99]],[[119941,119941],"mapped",[100]],[[119942,119942],"mapped",[101]],[[119943,119943],"mapped",[102]],[[119944,119944],"mapped",[103]],[[119945,119945],"mapped",[104]],[[119946,119946],"mapped",[105]],[[119947,119947],"mapped",[106]],[[119948,119948],"mapped",[107]],[[119949,119949],"mapped",[108]],[[119950,119950],"mapped",[109]],[[119951,119951],"mapped",[110]],[[119952,119952],"mapped",[111]],[[119953,119953],"mapped",[112]],[[119954,119954],"mapped",[113]],[[119955,119955],"mapped",[114]],[[119956,119956],"mapped",[115]],[[119957,119957],"mapped",[116]],[[119958,119958],"mapped",[117]],[[119959,119959],"mapped",[118]],[[119960,119960],"mapped",[119]],[[119961,119961],"mapped",[120]],[[119962,119962],"mapped",[121]],[[119963,119963],"mapped",[122]],[[119964,119964],"mapped",[97]],[[119965,119965],"disallowed"],[[119966,119966],"mapped",[99]],[[119967,119967],"mapped",[100]],[[119968,119969],"disallowed"],[[119970,119970],"mapped",[103]],[[119971,119972],"disallowed"],[[119973,119973],"mapped",[106]],[[119974,119974],"mapped",[107]],[[119975,119976],"disallowed"],[[119977,119977],"mapped",[110]],[[119978,119978],"mapped",[111]],[[119979,119979],"mapped",[112]],[[119980,119980],"mapped",[113]],[[119981,119981],"disallowed"],[[119982,119982],"mapped",[115]],[[119983,119983],"mapped",[116]],[[119984,119984],"mapped",[117]],[[119985,119985],"mapped",[118]],[[119986,119986],"mapped",[119]],[[119987,119987],"mapped",[120]],[[119988,119988],"mapped",[121]],[[119989,119989],"mapped",[122]],[[119990,119990],"mapped",[97]],[[119991,119991],"mapped",[98]],[[119992,119992],"mapped",[99]],[[119993,119993],"mapped",[100]],[[119994,119994],"disallowed"],[[119995,119995],"mapped",[102]],[[119996,119996],"disallowed"],[[119997,119997],"mapped",[104]],[[119998,119998],"mapped",[105]],[[119999,119999],"mapped",[106]],[[120000,120000],"mapped",[107]],[[120001,120001],"mapped",[108]],[[120002,120002],"mapped",[109]],[[120003,120003],"mapped",[110]],[[120004,120004],"disallowed"],[[120005,120005],"mapped",[112]],[[120006,120006],"mapped",[113]],[[120007,120007],"mapped",[114]],[[120008,120008],"mapped",[115]],[[120009,120009],"mapped",[116]],[[120010,120010],"mapped",[117]],[[120011,120011],"mapped",[118]],[[120012,120012],"mapped",[119]],[[120013,120013],"mapped",[120]],[[120014,120014],"mapped",[121]],[[120015,120015],"mapped",[122]],[[120016,120016],"mapped",[97]],[[120017,120017],"mapped",[98]],[[120018,120018],"mapped",[99]],[[120019,120019],"mapped",[100]],[[120020,120020],"mapped",[101]],[[120021,120021],"mapped",[102]],[[120022,120022],"mapped",[103]],[[120023,120023],"mapped",[104]],[[120024,120024],"mapped",[105]],[[120025,120025],"mapped",[106]],[[120026,120026],"mapped",[107]],[[120027,120027],"mapped",[108]],[[120028,120028],"mapped",[109]],[[120029,120029],"mapped",[110]],[[120030,120030],"mapped",[111]],[[120031,120031],"mapped",[112]],[[120032,120032],"mapped",[113]],[[120033,120033],"mapped",[114]],[[120034,120034],"mapped",[115]],[[120035,120035],"mapped",[116]],[[120036,120036],"mapped",[117]],[[120037,120037],"mapped",[118]],[[120038,120038],"mapped",[119]],[[120039,120039],"mapped",[120]],[[120040,120040],"mapped",[121]],[[120041,120041],"mapped",[122]],[[120042,120042],"mapped",[97]],[[120043,120043],"mapped",[98]],[[120044,120044],"mapped",[99]],[[120045,120045],"mapped",[100]],[[120046,120046],"mapped",[101]],[[120047,120047],"mapped",[102]],[[120048,120048],"mapped",[103]],[[120049,120049],"mapped",[104]],[[120050,120050],"mapped",[105]],[[120051,120051],"mapped",[106]],[[120052,120052],"mapped",[107]],[[120053,120053],"mapped",[108]],[[120054,120054],"mapped",[109]],[[120055,120055],"mapped",[110]],[[120056,120056],"mapped",[111]],[[120057,120057],"mapped",[112]],[[120058,120058],"mapped",[113]],[[120059,120059],"mapped",[114]],[[120060,120060],"mapped",[115]],[[120061,120061],"mapped",[116]],[[120062,120062],"mapped",[117]],[[120063,120063],"mapped",[118]],[[120064,120064],"mapped",[119]],[[120065,120065],"mapped",[120]],[[120066,120066],"mapped",[121]],[[120067,120067],"mapped",[122]],[[120068,120068],"mapped",[97]],[[120069,120069],"mapped",[98]],[[120070,120070],"disallowed"],[[120071,120071],"mapped",[100]],[[120072,120072],"mapped",[101]],[[120073,120073],"mapped",[102]],[[120074,120074],"mapped",[103]],[[120075,120076],"disallowed"],[[120077,120077],"mapped",[106]],[[120078,120078],"mapped",[107]],[[120079,120079],"mapped",[108]],[[120080,120080],"mapped",[109]],[[120081,120081],"mapped",[110]],[[120082,120082],"mapped",[111]],[[120083,120083],"mapped",[112]],[[120084,120084],"mapped",[113]],[[120085,120085],"disallowed"],[[120086,120086],"mapped",[115]],[[120087,120087],"mapped",[116]],[[120088,120088],"mapped",[117]],[[120089,120089],"mapped",[118]],[[120090,120090],"mapped",[119]],[[120091,120091],"mapped",[120]],[[120092,120092],"mapped",[121]],[[120093,120093],"disallowed"],[[120094,120094],"mapped",[97]],[[120095,120095],"mapped",[98]],[[120096,120096],"mapped",[99]],[[120097,120097],"mapped",[100]],[[120098,120098],"mapped",[101]],[[120099,120099],"mapped",[102]],[[120100,120100],"mapped",[103]],[[120101,120101],"mapped",[104]],[[120102,120102],"mapped",[105]],[[120103,120103],"mapped",[106]],[[120104,120104],"mapped",[107]],[[120105,120105],"mapped",[108]],[[120106,120106],"mapped",[109]],[[120107,120107],"mapped",[110]],[[120108,120108],"mapped",[111]],[[120109,120109],"mapped",[112]],[[120110,120110],"mapped",[113]],[[120111,120111],"mapped",[114]],[[120112,120112],"mapped",[115]],[[120113,120113],"mapped",[116]],[[120114,120114],"mapped",[117]],[[120115,120115],"mapped",[118]],[[120116,120116],"mapped",[119]],[[120117,120117],"mapped",[120]],[[120118,120118],"mapped",[121]],[[120119,120119],"mapped",[122]],[[120120,120120],"mapped",[97]],[[120121,120121],"mapped",[98]],[[120122,120122],"disallowed"],[[120123,120123],"mapped",[100]],[[120124,120124],"mapped",[101]],[[120125,120125],"mapped",[102]],[[120126,120126],"mapped",[103]],[[120127,120127],"disallowed"],[[120128,120128],"mapped",[105]],[[120129,120129],"mapped",[106]],[[120130,120130],"mapped",[107]],[[120131,120131],"mapped",[108]],[[120132,120132],"mapped",[109]],[[120133,120133],"disallowed"],[[120134,120134],"mapped",[111]],[[120135,120137],"disallowed"],[[120138,120138],"mapped",[115]],[[120139,120139],"mapped",[116]],[[120140,120140],"mapped",[117]],[[120141,120141],"mapped",[118]],[[120142,120142],"mapped",[119]],[[120143,120143],"mapped",[120]],[[120144,120144],"mapped",[121]],[[120145,120145],"disallowed"],[[120146,120146],"mapped",[97]],[[120147,120147],"mapped",[98]],[[120148,120148],"mapped",[99]],[[120149,120149],"mapped",[100]],[[120150,120150],"mapped",[101]],[[120151,120151],"mapped",[102]],[[120152,120152],"mapped",[103]],[[120153,120153],"mapped",[104]],[[120154,120154],"mapped",[105]],[[120155,120155],"mapped",[106]],[[120156,120156],"mapped",[107]],[[120157,120157],"mapped",[108]],[[120158,120158],"mapped",[109]],[[120159,120159],"mapped",[110]],[[120160,120160],"mapped",[111]],[[120161,120161],"mapped",[112]],[[120162,120162],"mapped",[113]],[[120163,120163],"mapped",[114]],[[120164,120164],"mapped",[115]],[[120165,120165],"mapped",[116]],[[120166,120166],"mapped",[117]],[[120167,120167],"mapped",[118]],[[120168,120168],"mapped",[119]],[[120169,120169],"mapped",[120]],[[120170,120170],"mapped",[121]],[[120171,120171],"mapped",[122]],[[120172,120172],"mapped",[97]],[[120173,120173],"mapped",[98]],[[120174,120174],"mapped",[99]],[[120175,120175],"mapped",[100]],[[120176,120176],"mapped",[101]],[[120177,120177],"mapped",[102]],[[120178,120178],"mapped",[103]],[[120179,120179],"mapped",[104]],[[120180,120180],"mapped",[105]],[[120181,120181],"mapped",[106]],[[120182,120182],"mapped",[107]],[[120183,120183],"mapped",[108]],[[120184,120184],"mapped",[109]],[[120185,120185],"mapped",[110]],[[120186,120186],"mapped",[111]],[[120187,120187],"mapped",[112]],[[120188,120188],"mapped",[113]],[[120189,120189],"mapped",[114]],[[120190,120190],"mapped",[115]],[[120191,120191],"mapped",[116]],[[120192,120192],"mapped",[117]],[[120193,120193],"mapped",[118]],[[120194,120194],"mapped",[119]],[[120195,120195],"mapped",[120]],[[120196,120196],"mapped",[121]],[[120197,120197],"mapped",[122]],[[120198,120198],"mapped",[97]],[[120199,120199],"mapped",[98]],[[120200,120200],"mapped",[99]],[[120201,120201],"mapped",[100]],[[120202,120202],"mapped",[101]],[[120203,120203],"mapped",[102]],[[120204,120204],"mapped",[103]],[[120205,120205],"mapped",[104]],[[120206,120206],"mapped",[105]],[[120207,120207],"mapped",[106]],[[120208,120208],"mapped",[107]],[[120209,120209],"mapped",[108]],[[120210,120210],"mapped",[109]],[[120211,120211],"mapped",[110]],[[120212,120212],"mapped",[111]],[[120213,120213],"mapped",[112]],[[120214,120214],"mapped",[113]],[[120215,120215],"mapped",[114]],[[120216,120216],"mapped",[115]],[[120217,120217],"mapped",[116]],[[120218,120218],"mapped",[117]],[[120219,120219],"mapped",[118]],[[120220,120220],"mapped",[119]],[[120221,120221],"mapped",[120]],[[120222,120222],"mapped",[121]],[[120223,120223],"mapped",[122]],[[120224,120224],"mapped",[97]],[[120225,120225],"mapped",[98]],[[120226,120226],"mapped",[99]],[[120227,120227],"mapped",[100]],[[120228,120228],"mapped",[101]],[[120229,120229],"mapped",[102]],[[120230,120230],"mapped",[103]],[[120231,120231],"mapped",[104]],[[120232,120232],"mapped",[105]],[[120233,120233],"mapped",[106]],[[120234,120234],"mapped",[107]],[[120235,120235],"mapped",[108]],[[120236,120236],"mapped",[109]],[[120237,120237],"mapped",[110]],[[120238,120238],"mapped",[111]],[[120239,120239],"mapped",[112]],[[120240,120240],"mapped",[113]],[[120241,120241],"mapped",[114]],[[120242,120242],"mapped",[115]],[[120243,120243],"mapped",[116]],[[120244,120244],"mapped",[117]],[[120245,120245],"mapped",[118]],[[120246,120246],"mapped",[119]],[[120247,120247],"mapped",[120]],[[120248,120248],"mapped",[121]],[[120249,120249],"mapped",[122]],[[120250,120250],"mapped",[97]],[[120251,120251],"mapped",[98]],[[120252,120252],"mapped",[99]],[[120253,120253],"mapped",[100]],[[120254,120254],"mapped",[101]],[[120255,120255],"mapped",[102]],[[120256,120256],"mapped",[103]],[[120257,120257],"mapped",[104]],[[120258,120258],"mapped",[105]],[[120259,120259],"mapped",[106]],[[120260,120260],"mapped",[107]],[[120261,120261],"mapped",[108]],[[120262,120262],"mapped",[109]],[[120263,120263],"mapped",[110]],[[120264,120264],"mapped",[111]],[[120265,120265],"mapped",[112]],[[120266,120266],"mapped",[113]],[[120267,120267],"mapped",[114]],[[120268,120268],"mapped",[115]],[[120269,120269],"mapped",[116]],[[120270,120270],"mapped",[117]],[[120271,120271],"mapped",[118]],[[120272,120272],"mapped",[119]],[[120273,120273],"mapped",[120]],[[120274,120274],"mapped",[121]],[[120275,120275],"mapped",[122]],[[120276,120276],"mapped",[97]],[[120277,120277],"mapped",[98]],[[120278,120278],"mapped",[99]],[[120279,120279],"mapped",[100]],[[120280,120280],"mapped",[101]],[[120281,120281],"mapped",[102]],[[120282,120282],"mapped",[103]],[[120283,120283],"mapped",[104]],[[120284,120284],"mapped",[105]],[[120285,120285],"mapped",[106]],[[120286,120286],"mapped",[107]],[[120287,120287],"mapped",[108]],[[120288,120288],"mapped",[109]],[[120289,120289],"mapped",[110]],[[120290,120290],"mapped",[111]],[[120291,120291],"mapped",[112]],[[120292,120292],"mapped",[113]],[[120293,120293],"mapped",[114]],[[120294,120294],"mapped",[115]],[[120295,120295],"mapped",[116]],[[120296,120296],"mapped",[117]],[[120297,120297],"mapped",[118]],[[120298,120298],"mapped",[119]],[[120299,120299],"mapped",[120]],[[120300,120300],"mapped",[121]],[[120301,120301],"mapped",[122]],[[120302,120302],"mapped",[97]],[[120303,120303],"mapped",[98]],[[120304,120304],"mapped",[99]],[[120305,120305],"mapped",[100]],[[120306,120306],"mapped",[101]],[[120307,120307],"mapped",[102]],[[120308,120308],"mapped",[103]],[[120309,120309],"mapped",[104]],[[120310,120310],"mapped",[105]],[[120311,120311],"mapped",[106]],[[120312,120312],"mapped",[107]],[[120313,120313],"mapped",[108]],[[120314,120314],"mapped",[109]],[[120315,120315],"mapped",[110]],[[120316,120316],"mapped",[111]],[[120317,120317],"mapped",[112]],[[120318,120318],"mapped",[113]],[[120319,120319],"mapped",[114]],[[120320,120320],"mapped",[115]],[[120321,120321],"mapped",[116]],[[120322,120322],"mapped",[117]],[[120323,120323],"mapped",[118]],[[120324,120324],"mapped",[119]],[[120325,120325],"mapped",[120]],[[120326,120326],"mapped",[121]],[[120327,120327],"mapped",[122]],[[120328,120328],"mapped",[97]],[[120329,120329],"mapped",[98]],[[120330,120330],"mapped",[99]],[[120331,120331],"mapped",[100]],[[120332,120332],"mapped",[101]],[[120333,120333],"mapped",[102]],[[120334,120334],"mapped",[103]],[[120335,120335],"mapped",[104]],[[120336,120336],"mapped",[105]],[[120337,120337],"mapped",[106]],[[120338,120338],"mapped",[107]],[[120339,120339],"mapped",[108]],[[120340,120340],"mapped",[109]],[[120341,120341],"mapped",[110]],[[120342,120342],"mapped",[111]],[[120343,120343],"mapped",[112]],[[120344,120344],"mapped",[113]],[[120345,120345],"mapped",[114]],[[120346,120346],"mapped",[115]],[[120347,120347],"mapped",[116]],[[120348,120348],"mapped",[117]],[[120349,120349],"mapped",[118]],[[120350,120350],"mapped",[119]],[[120351,120351],"mapped",[120]],[[120352,120352],"mapped",[121]],[[120353,120353],"mapped",[122]],[[120354,120354],"mapped",[97]],[[120355,120355],"mapped",[98]],[[120356,120356],"mapped",[99]],[[120357,120357],"mapped",[100]],[[120358,120358],"mapped",[101]],[[120359,120359],"mapped",[102]],[[120360,120360],"mapped",[103]],[[120361,120361],"mapped",[104]],[[120362,120362],"mapped",[105]],[[120363,120363],"mapped",[106]],[[120364,120364],"mapped",[107]],[[120365,120365],"mapped",[108]],[[120366,120366],"mapped",[109]],[[120367,120367],"mapped",[110]],[[120368,120368],"mapped",[111]],[[120369,120369],"mapped",[112]],[[120370,120370],"mapped",[113]],[[120371,120371],"mapped",[114]],[[120372,120372],"mapped",[115]],[[120373,120373],"mapped",[116]],[[120374,120374],"mapped",[117]],[[120375,120375],"mapped",[118]],[[120376,120376],"mapped",[119]],[[120377,120377],"mapped",[120]],[[120378,120378],"mapped",[121]],[[120379,120379],"mapped",[122]],[[120380,120380],"mapped",[97]],[[120381,120381],"mapped",[98]],[[120382,120382],"mapped",[99]],[[120383,120383],"mapped",[100]],[[120384,120384],"mapped",[101]],[[120385,120385],"mapped",[102]],[[120386,120386],"mapped",[103]],[[120387,120387],"mapped",[104]],[[120388,120388],"mapped",[105]],[[120389,120389],"mapped",[106]],[[120390,120390],"mapped",[107]],[[120391,120391],"mapped",[108]],[[120392,120392],"mapped",[109]],[[120393,120393],"mapped",[110]],[[120394,120394],"mapped",[111]],[[120395,120395],"mapped",[112]],[[120396,120396],"mapped",[113]],[[120397,120397],"mapped",[114]],[[120398,120398],"mapped",[115]],[[120399,120399],"mapped",[116]],[[120400,120400],"mapped",[117]],[[120401,120401],"mapped",[118]],[[120402,120402],"mapped",[119]],[[120403,120403],"mapped",[120]],[[120404,120404],"mapped",[121]],[[120405,120405],"mapped",[122]],[[120406,120406],"mapped",[97]],[[120407,120407],"mapped",[98]],[[120408,120408],"mapped",[99]],[[120409,120409],"mapped",[100]],[[120410,120410],"mapped",[101]],[[120411,120411],"mapped",[102]],[[120412,120412],"mapped",[103]],[[120413,120413],"mapped",[104]],[[120414,120414],"mapped",[105]],[[120415,120415],"mapped",[106]],[[120416,120416],"mapped",[107]],[[120417,120417],"mapped",[108]],[[120418,120418],"mapped",[109]],[[120419,120419],"mapped",[110]],[[120420,120420],"mapped",[111]],[[120421,120421],"mapped",[112]],[[120422,120422],"mapped",[113]],[[120423,120423],"mapped",[114]],[[120424,120424],"mapped",[115]],[[120425,120425],"mapped",[116]],[[120426,120426],"mapped",[117]],[[120427,120427],"mapped",[118]],[[120428,120428],"mapped",[119]],[[120429,120429],"mapped",[120]],[[120430,120430],"mapped",[121]],[[120431,120431],"mapped",[122]],[[120432,120432],"mapped",[97]],[[120433,120433],"mapped",[98]],[[120434,120434],"mapped",[99]],[[120435,120435],"mapped",[100]],[[120436,120436],"mapped",[101]],[[120437,120437],"mapped",[102]],[[120438,120438],"mapped",[103]],[[120439,120439],"mapped",[104]],[[120440,120440],"mapped",[105]],[[120441,120441],"mapped",[106]],[[120442,120442],"mapped",[107]],[[120443,120443],"mapped",[108]],[[120444,120444],"mapped",[109]],[[120445,120445],"mapped",[110]],[[120446,120446],"mapped",[111]],[[120447,120447],"mapped",[112]],[[120448,120448],"mapped",[113]],[[120449,120449],"mapped",[114]],[[120450,120450],"mapped",[115]],[[120451,120451],"mapped",[116]],[[120452,120452],"mapped",[117]],[[120453,120453],"mapped",[118]],[[120454,120454],"mapped",[119]],[[120455,120455],"mapped",[120]],[[120456,120456],"mapped",[121]],[[120457,120457],"mapped",[122]],[[120458,120458],"mapped",[97]],[[120459,120459],"mapped",[98]],[[120460,120460],"mapped",[99]],[[120461,120461],"mapped",[100]],[[120462,120462],"mapped",[101]],[[120463,120463],"mapped",[102]],[[120464,120464],"mapped",[103]],[[120465,120465],"mapped",[104]],[[120466,120466],"mapped",[105]],[[120467,120467],"mapped",[106]],[[120468,120468],"mapped",[107]],[[120469,120469],"mapped",[108]],[[120470,120470],"mapped",[109]],[[120471,120471],"mapped",[110]],[[120472,120472],"mapped",[111]],[[120473,120473],"mapped",[112]],[[120474,120474],"mapped",[113]],[[120475,120475],"mapped",[114]],[[120476,120476],"mapped",[115]],[[120477,120477],"mapped",[116]],[[120478,120478],"mapped",[117]],[[120479,120479],"mapped",[118]],[[120480,120480],"mapped",[119]],[[120481,120481],"mapped",[120]],[[120482,120482],"mapped",[121]],[[120483,120483],"mapped",[122]],[[120484,120484],"mapped",[305]],[[120485,120485],"mapped",[567]],[[120486,120487],"disallowed"],[[120488,120488],"mapped",[945]],[[120489,120489],"mapped",[946]],[[120490,120490],"mapped",[947]],[[120491,120491],"mapped",[948]],[[120492,120492],"mapped",[949]],[[120493,120493],"mapped",[950]],[[120494,120494],"mapped",[951]],[[120495,120495],"mapped",[952]],[[120496,120496],"mapped",[953]],[[120497,120497],"mapped",[954]],[[120498,120498],"mapped",[955]],[[120499,120499],"mapped",[956]],[[120500,120500],"mapped",[957]],[[120501,120501],"mapped",[958]],[[120502,120502],"mapped",[959]],[[120503,120503],"mapped",[960]],[[120504,120504],"mapped",[961]],[[120505,120505],"mapped",[952]],[[120506,120506],"mapped",[963]],[[120507,120507],"mapped",[964]],[[120508,120508],"mapped",[965]],[[120509,120509],"mapped",[966]],[[120510,120510],"mapped",[967]],[[120511,120511],"mapped",[968]],[[120512,120512],"mapped",[969]],[[120513,120513],"mapped",[8711]],[[120514,120514],"mapped",[945]],[[120515,120515],"mapped",[946]],[[120516,120516],"mapped",[947]],[[120517,120517],"mapped",[948]],[[120518,120518],"mapped",[949]],[[120519,120519],"mapped",[950]],[[120520,120520],"mapped",[951]],[[120521,120521],"mapped",[952]],[[120522,120522],"mapped",[953]],[[120523,120523],"mapped",[954]],[[120524,120524],"mapped",[955]],[[120525,120525],"mapped",[956]],[[120526,120526],"mapped",[957]],[[120527,120527],"mapped",[958]],[[120528,120528],"mapped",[959]],[[120529,120529],"mapped",[960]],[[120530,120530],"mapped",[961]],[[120531,120532],"mapped",[963]],[[120533,120533],"mapped",[964]],[[120534,120534],"mapped",[965]],[[120535,120535],"mapped",[966]],[[120536,120536],"mapped",[967]],[[120537,120537],"mapped",[968]],[[120538,120538],"mapped",[969]],[[120539,120539],"mapped",[8706]],[[120540,120540],"mapped",[949]],[[120541,120541],"mapped",[952]],[[120542,120542],"mapped",[954]],[[120543,120543],"mapped",[966]],[[120544,120544],"mapped",[961]],[[120545,120545],"mapped",[960]],[[120546,120546],"mapped",[945]],[[120547,120547],"mapped",[946]],[[120548,120548],"mapped",[947]],[[120549,120549],"mapped",[948]],[[120550,120550],"mapped",[949]],[[120551,120551],"mapped",[950]],[[120552,120552],"mapped",[951]],[[120553,120553],"mapped",[952]],[[120554,120554],"mapped",[953]],[[120555,120555],"mapped",[954]],[[120556,120556],"mapped",[955]],[[120557,120557],"mapped",[956]],[[120558,120558],"mapped",[957]],[[120559,120559],"mapped",[958]],[[120560,120560],"mapped",[959]],[[120561,120561],"mapped",[960]],[[120562,120562],"mapped",[961]],[[120563,120563],"mapped",[952]],[[120564,120564],"mapped",[963]],[[120565,120565],"mapped",[964]],[[120566,120566],"mapped",[965]],[[120567,120567],"mapped",[966]],[[120568,120568],"mapped",[967]],[[120569,120569],"mapped",[968]],[[120570,120570],"mapped",[969]],[[120571,120571],"mapped",[8711]],[[120572,120572],"mapped",[945]],[[120573,120573],"mapped",[946]],[[120574,120574],"mapped",[947]],[[120575,120575],"mapped",[948]],[[120576,120576],"mapped",[949]],[[120577,120577],"mapped",[950]],[[120578,120578],"mapped",[951]],[[120579,120579],"mapped",[952]],[[120580,120580],"mapped",[953]],[[120581,120581],"mapped",[954]],[[120582,120582],"mapped",[955]],[[120583,120583],"mapped",[956]],[[120584,120584],"mapped",[957]],[[120585,120585],"mapped",[958]],[[120586,120586],"mapped",[959]],[[120587,120587],"mapped",[960]],[[120588,120588],"mapped",[961]],[[120589,120590],"mapped",[963]],[[120591,120591],"mapped",[964]],[[120592,120592],"mapped",[965]],[[120593,120593],"mapped",[966]],[[120594,120594],"mapped",[967]],[[120595,120595],"mapped",[968]],[[120596,120596],"mapped",[969]],[[120597,120597],"mapped",[8706]],[[120598,120598],"mapped",[949]],[[120599,120599],"mapped",[952]],[[120600,120600],"mapped",[954]],[[120601,120601],"mapped",[966]],[[120602,120602],"mapped",[961]],[[120603,120603],"mapped",[960]],[[120604,120604],"mapped",[945]],[[120605,120605],"mapped",[946]],[[120606,120606],"mapped",[947]],[[120607,120607],"mapped",[948]],[[120608,120608],"mapped",[949]],[[120609,120609],"mapped",[950]],[[120610,120610],"mapped",[951]],[[120611,120611],"mapped",[952]],[[120612,120612],"mapped",[953]],[[120613,120613],"mapped",[954]],[[120614,120614],"mapped",[955]],[[120615,120615],"mapped",[956]],[[120616,120616],"mapped",[957]],[[120617,120617],"mapped",[958]],[[120618,120618],"mapped",[959]],[[120619,120619],"mapped",[960]],[[120620,120620],"mapped",[961]],[[120621,120621],"mapped",[952]],[[120622,120622],"mapped",[963]],[[120623,120623],"mapped",[964]],[[120624,120624],"mapped",[965]],[[120625,120625],"mapped",[966]],[[120626,120626],"mapped",[967]],[[120627,120627],"mapped",[968]],[[120628,120628],"mapped",[969]],[[120629,120629],"mapped",[8711]],[[120630,120630],"mapped",[945]],[[120631,120631],"mapped",[946]],[[120632,120632],"mapped",[947]],[[120633,120633],"mapped",[948]],[[120634,120634],"mapped",[949]],[[120635,120635],"mapped",[950]],[[120636,120636],"mapped",[951]],[[120637,120637],"mapped",[952]],[[120638,120638],"mapped",[953]],[[120639,120639],"mapped",[954]],[[120640,120640],"mapped",[955]],[[120641,120641],"mapped",[956]],[[120642,120642],"mapped",[957]],[[120643,120643],"mapped",[958]],[[120644,120644],"mapped",[959]],[[120645,120645],"mapped",[960]],[[120646,120646],"mapped",[961]],[[120647,120648],"mapped",[963]],[[120649,120649],"mapped",[964]],[[120650,120650],"mapped",[965]],[[120651,120651],"mapped",[966]],[[120652,120652],"mapped",[967]],[[120653,120653],"mapped",[968]],[[120654,120654],"mapped",[969]],[[120655,120655],"mapped",[8706]],[[120656,120656],"mapped",[949]],[[120657,120657],"mapped",[952]],[[120658,120658],"mapped",[954]],[[120659,120659],"mapped",[966]],[[120660,120660],"mapped",[961]],[[120661,120661],"mapped",[960]],[[120662,120662],"mapped",[945]],[[120663,120663],"mapped",[946]],[[120664,120664],"mapped",[947]],[[120665,120665],"mapped",[948]],[[120666,120666],"mapped",[949]],[[120667,120667],"mapped",[950]],[[120668,120668],"mapped",[951]],[[120669,120669],"mapped",[952]],[[120670,120670],"mapped",[953]],[[120671,120671],"mapped",[954]],[[120672,120672],"mapped",[955]],[[120673,120673],"mapped",[956]],[[120674,120674],"mapped",[957]],[[120675,120675],"mapped",[958]],[[120676,120676],"mapped",[959]],[[120677,120677],"mapped",[960]],[[120678,120678],"mapped",[961]],[[120679,120679],"mapped",[952]],[[120680,120680],"mapped",[963]],[[120681,120681],"mapped",[964]],[[120682,120682],"mapped",[965]],[[120683,120683],"mapped",[966]],[[120684,120684],"mapped",[967]],[[120685,120685],"mapped",[968]],[[120686,120686],"mapped",[969]],[[120687,120687],"mapped",[8711]],[[120688,120688],"mapped",[945]],[[120689,120689],"mapped",[946]],[[120690,120690],"mapped",[947]],[[120691,120691],"mapped",[948]],[[120692,120692],"mapped",[949]],[[120693,120693],"mapped",[950]],[[120694,120694],"mapped",[951]],[[120695,120695],"mapped",[952]],[[120696,120696],"mapped",[953]],[[120697,120697],"mapped",[954]],[[120698,120698],"mapped",[955]],[[120699,120699],"mapped",[956]],[[120700,120700],"mapped",[957]],[[120701,120701],"mapped",[958]],[[120702,120702],"mapped",[959]],[[120703,120703],"mapped",[960]],[[120704,120704],"mapped",[961]],[[120705,120706],"mapped",[963]],[[120707,120707],"mapped",[964]],[[120708,120708],"mapped",[965]],[[120709,120709],"mapped",[966]],[[120710,120710],"mapped",[967]],[[120711,120711],"mapped",[968]],[[120712,120712],"mapped",[969]],[[120713,120713],"mapped",[8706]],[[120714,120714],"mapped",[949]],[[120715,120715],"mapped",[952]],[[120716,120716],"mapped",[954]],[[120717,120717],"mapped",[966]],[[120718,120718],"mapped",[961]],[[120719,120719],"mapped",[960]],[[120720,120720],"mapped",[945]],[[120721,120721],"mapped",[946]],[[120722,120722],"mapped",[947]],[[120723,120723],"mapped",[948]],[[120724,120724],"mapped",[949]],[[120725,120725],"mapped",[950]],[[120726,120726],"mapped",[951]],[[120727,120727],"mapped",[952]],[[120728,120728],"mapped",[953]],[[120729,120729],"mapped",[954]],[[120730,120730],"mapped",[955]],[[120731,120731],"mapped",[956]],[[120732,120732],"mapped",[957]],[[120733,120733],"mapped",[958]],[[120734,120734],"mapped",[959]],[[120735,120735],"mapped",[960]],[[120736,120736],"mapped",[961]],[[120737,120737],"mapped",[952]],[[120738,120738],"mapped",[963]],[[120739,120739],"mapped",[964]],[[120740,120740],"mapped",[965]],[[120741,120741],"mapped",[966]],[[120742,120742],"mapped",[967]],[[120743,120743],"mapped",[968]],[[120744,120744],"mapped",[969]],[[120745,120745],"mapped",[8711]],[[120746,120746],"mapped",[945]],[[120747,120747],"mapped",[946]],[[120748,120748],"mapped",[947]],[[120749,120749],"mapped",[948]],[[120750,120750],"mapped",[949]],[[120751,120751],"mapped",[950]],[[120752,120752],"mapped",[951]],[[120753,120753],"mapped",[952]],[[120754,120754],"mapped",[953]],[[120755,120755],"mapped",[954]],[[120756,120756],"mapped",[955]],[[120757,120757],"mapped",[956]],[[120758,120758],"mapped",[957]],[[120759,120759],"mapped",[958]],[[120760,120760],"mapped",[959]],[[120761,120761],"mapped",[960]],[[120762,120762],"mapped",[961]],[[120763,120764],"mapped",[963]],[[120765,120765],"mapped",[964]],[[120766,120766],"mapped",[965]],[[120767,120767],"mapped",[966]],[[120768,120768],"mapped",[967]],[[120769,120769],"mapped",[968]],[[120770,120770],"mapped",[969]],[[120771,120771],"mapped",[8706]],[[120772,120772],"mapped",[949]],[[120773,120773],"mapped",[952]],[[120774,120774],"mapped",[954]],[[120775,120775],"mapped",[966]],[[120776,120776],"mapped",[961]],[[120777,120777],"mapped",[960]],[[120778,120779],"mapped",[989]],[[120780,120781],"disallowed"],[[120782,120782],"mapped",[48]],[[120783,120783],"mapped",[49]],[[120784,120784],"mapped",[50]],[[120785,120785],"mapped",[51]],[[120786,120786],"mapped",[52]],[[120787,120787],"mapped",[53]],[[120788,120788],"mapped",[54]],[[120789,120789],"mapped",[55]],[[120790,120790],"mapped",[56]],[[120791,120791],"mapped",[57]],[[120792,120792],"mapped",[48]],[[120793,120793],"mapped",[49]],[[120794,120794],"mapped",[50]],[[120795,120795],"mapped",[51]],[[120796,120796],"mapped",[52]],[[120797,120797],"mapped",[53]],[[120798,120798],"mapped",[54]],[[120799,120799],"mapped",[55]],[[120800,120800],"mapped",[56]],[[120801,120801],"mapped",[57]],[[120802,120802],"mapped",[48]],[[120803,120803],"mapped",[49]],[[120804,120804],"mapped",[50]],[[120805,120805],"mapped",[51]],[[120806,120806],"mapped",[52]],[[120807,120807],"mapped",[53]],[[120808,120808],"mapped",[54]],[[120809,120809],"mapped",[55]],[[120810,120810],"mapped",[56]],[[120811,120811],"mapped",[57]],[[120812,120812],"mapped",[48]],[[120813,120813],"mapped",[49]],[[120814,120814],"mapped",[50]],[[120815,120815],"mapped",[51]],[[120816,120816],"mapped",[52]],[[120817,120817],"mapped",[53]],[[120818,120818],"mapped",[54]],[[120819,120819],"mapped",[55]],[[120820,120820],"mapped",[56]],[[120821,120821],"mapped",[57]],[[120822,120822],"mapped",[48]],[[120823,120823],"mapped",[49]],[[120824,120824],"mapped",[50]],[[120825,120825],"mapped",[51]],[[120826,120826],"mapped",[52]],[[120827,120827],"mapped",[53]],[[120828,120828],"mapped",[54]],[[120829,120829],"mapped",[55]],[[120830,120830],"mapped",[56]],[[120831,120831],"mapped",[57]],[[120832,121343],"valid",[],"NV8"],[[121344,121398],"valid"],[[121399,121402],"valid",[],"NV8"],[[121403,121452],"valid"],[[121453,121460],"valid",[],"NV8"],[[121461,121461],"valid"],[[121462,121475],"valid",[],"NV8"],[[121476,121476],"valid"],[[121477,121483],"valid",[],"NV8"],[[121484,121498],"disallowed"],[[121499,121503],"valid"],[[121504,121504],"disallowed"],[[121505,121519],"valid"],[[121520,124927],"disallowed"],[[124928,125124],"valid"],[[125125,125126],"disallowed"],[[125127,125135],"valid",[],"NV8"],[[125136,125142],"valid"],[[125143,126463],"disallowed"],[[126464,126464],"mapped",[1575]],[[126465,126465],"mapped",[1576]],[[126466,126466],"mapped",[1580]],[[126467,126467],"mapped",[1583]],[[126468,126468],"disallowed"],[[126469,126469],"mapped",[1608]],[[126470,126470],"mapped",[1586]],[[126471,126471],"mapped",[1581]],[[126472,126472],"mapped",[1591]],[[126473,126473],"mapped",[1610]],[[126474,126474],"mapped",[1603]],[[126475,126475],"mapped",[1604]],[[126476,126476],"mapped",[1605]],[[126477,126477],"mapped",[1606]],[[126478,126478],"mapped",[1587]],[[126479,126479],"mapped",[1593]],[[126480,126480],"mapped",[1601]],[[126481,126481],"mapped",[1589]],[[126482,126482],"mapped",[1602]],[[126483,126483],"mapped",[1585]],[[126484,126484],"mapped",[1588]],[[126485,126485],"mapped",[1578]],[[126486,126486],"mapped",[1579]],[[126487,126487],"mapped",[1582]],[[126488,126488],"mapped",[1584]],[[126489,126489],"mapped",[1590]],[[126490,126490],"mapped",[1592]],[[126491,126491],"mapped",[1594]],[[126492,126492],"mapped",[1646]],[[126493,126493],"mapped",[1722]],[[126494,126494],"mapped",[1697]],[[126495,126495],"mapped",[1647]],[[126496,126496],"disallowed"],[[126497,126497],"mapped",[1576]],[[126498,126498],"mapped",[1580]],[[126499,126499],"disallowed"],[[126500,126500],"mapped",[1607]],[[126501,126502],"disallowed"],[[126503,126503],"mapped",[1581]],[[126504,126504],"disallowed"],[[126505,126505],"mapped",[1610]],[[126506,126506],"mapped",[1603]],[[126507,126507],"mapped",[1604]],[[126508,126508],"mapped",[1605]],[[126509,126509],"mapped",[1606]],[[126510,126510],"mapped",[1587]],[[126511,126511],"mapped",[1593]],[[126512,126512],"mapped",[1601]],[[126513,126513],"mapped",[1589]],[[126514,126514],"mapped",[1602]],[[126515,126515],"disallowed"],[[126516,126516],"mapped",[1588]],[[126517,126517],"mapped",[1578]],[[126518,126518],"mapped",[1579]],[[126519,126519],"mapped",[1582]],[[126520,126520],"disallowed"],[[126521,126521],"mapped",[1590]],[[126522,126522],"disallowed"],[[126523,126523],"mapped",[1594]],[[126524,126529],"disallowed"],[[126530,126530],"mapped",[1580]],[[126531,126534],"disallowed"],[[126535,126535],"mapped",[1581]],[[126536,126536],"disallowed"],[[126537,126537],"mapped",[1610]],[[126538,126538],"disallowed"],[[126539,126539],"mapped",[1604]],[[126540,126540],"disallowed"],[[126541,126541],"mapped",[1606]],[[126542,126542],"mapped",[1587]],[[126543,126543],"mapped",[1593]],[[126544,126544],"disallowed"],[[126545,126545],"mapped",[1589]],[[126546,126546],"mapped",[1602]],[[126547,126547],"disallowed"],[[126548,126548],"mapped",[1588]],[[126549,126550],"disallowed"],[[126551,126551],"mapped",[1582]],[[126552,126552],"disallowed"],[[126553,126553],"mapped",[1590]],[[126554,126554],"disallowed"],[[126555,126555],"mapped",[1594]],[[126556,126556],"disallowed"],[[126557,126557],"mapped",[1722]],[[126558,126558],"disallowed"],[[126559,126559],"mapped",[1647]],[[126560,126560],"disallowed"],[[126561,126561],"mapped",[1576]],[[126562,126562],"mapped",[1580]],[[126563,126563],"disallowed"],[[126564,126564],"mapped",[1607]],[[126565,126566],"disallowed"],[[126567,126567],"mapped",[1581]],[[126568,126568],"mapped",[1591]],[[126569,126569],"mapped",[1610]],[[126570,126570],"mapped",[1603]],[[126571,126571],"disallowed"],[[126572,126572],"mapped",[1605]],[[126573,126573],"mapped",[1606]],[[126574,126574],"mapped",[1587]],[[126575,126575],"mapped",[1593]],[[126576,126576],"mapped",[1601]],[[126577,126577],"mapped",[1589]],[[126578,126578],"mapped",[1602]],[[126579,126579],"disallowed"],[[126580,126580],"mapped",[1588]],[[126581,126581],"mapped",[1578]],[[126582,126582],"mapped",[1579]],[[126583,126583],"mapped",[1582]],[[126584,126584],"disallowed"],[[126585,126585],"mapped",[1590]],[[126586,126586],"mapped",[1592]],[[126587,126587],"mapped",[1594]],[[126588,126588],"mapped",[1646]],[[126589,126589],"disallowed"],[[126590,126590],"mapped",[1697]],[[126591,126591],"disallowed"],[[126592,126592],"mapped",[1575]],[[126593,126593],"mapped",[1576]],[[126594,126594],"mapped",[1580]],[[126595,126595],"mapped",[1583]],[[126596,126596],"mapped",[1607]],[[126597,126597],"mapped",[1608]],[[126598,126598],"mapped",[1586]],[[126599,126599],"mapped",[1581]],[[126600,126600],"mapped",[1591]],[[126601,126601],"mapped",[1610]],[[126602,126602],"disallowed"],[[126603,126603],"mapped",[1604]],[[126604,126604],"mapped",[1605]],[[126605,126605],"mapped",[1606]],[[126606,126606],"mapped",[1587]],[[126607,126607],"mapped",[1593]],[[126608,126608],"mapped",[1601]],[[126609,126609],"mapped",[1589]],[[126610,126610],"mapped",[1602]],[[126611,126611],"mapped",[1585]],[[126612,126612],"mapped",[1588]],[[126613,126613],"mapped",[1578]],[[126614,126614],"mapped",[1579]],[[126615,126615],"mapped",[1582]],[[126616,126616],"mapped",[1584]],[[126617,126617],"mapped",[1590]],[[126618,126618],"mapped",[1592]],[[126619,126619],"mapped",[1594]],[[126620,126624],"disallowed"],[[126625,126625],"mapped",[1576]],[[126626,126626],"mapped",[1580]],[[126627,126627],"mapped",[1583]],[[126628,126628],"disallowed"],[[126629,126629],"mapped",[1608]],[[126630,126630],"mapped",[1586]],[[126631,126631],"mapped",[1581]],[[126632,126632],"mapped",[1591]],[[126633,126633],"mapped",[1610]],[[126634,126634],"disallowed"],[[126635,126635],"mapped",[1604]],[[126636,126636],"mapped",[1605]],[[126637,126637],"mapped",[1606]],[[126638,126638],"mapped",[1587]],[[126639,126639],"mapped",[1593]],[[126640,126640],"mapped",[1601]],[[126641,126641],"mapped",[1589]],[[126642,126642],"mapped",[1602]],[[126643,126643],"mapped",[1585]],[[126644,126644],"mapped",[1588]],[[126645,126645],"mapped",[1578]],[[126646,126646],"mapped",[1579]],[[126647,126647],"mapped",[1582]],[[126648,126648],"mapped",[1584]],[[126649,126649],"mapped",[1590]],[[126650,126650],"mapped",[1592]],[[126651,126651],"mapped",[1594]],[[126652,126703],"disallowed"],[[126704,126705],"valid",[],"NV8"],[[126706,126975],"disallowed"],[[126976,127019],"valid",[],"NV8"],[[127020,127023],"disallowed"],[[127024,127123],"valid",[],"NV8"],[[127124,127135],"disallowed"],[[127136,127150],"valid",[],"NV8"],[[127151,127152],"disallowed"],[[127153,127166],"valid",[],"NV8"],[[127167,127167],"valid",[],"NV8"],[[127168,127168],"disallowed"],[[127169,127183],"valid",[],"NV8"],[[127184,127184],"disallowed"],[[127185,127199],"valid",[],"NV8"],[[127200,127221],"valid",[],"NV8"],[[127222,127231],"disallowed"],[[127232,127232],"disallowed"],[[127233,127233],"disallowed_STD3_mapped",[48,44]],[[127234,127234],"disallowed_STD3_mapped",[49,44]],[[127235,127235],"disallowed_STD3_mapped",[50,44]],[[127236,127236],"disallowed_STD3_mapped",[51,44]],[[127237,127237],"disallowed_STD3_mapped",[52,44]],[[127238,127238],"disallowed_STD3_mapped",[53,44]],[[127239,127239],"disallowed_STD3_mapped",[54,44]],[[127240,127240],"disallowed_STD3_mapped",[55,44]],[[127241,127241],"disallowed_STD3_mapped",[56,44]],[[127242,127242],"disallowed_STD3_mapped",[57,44]],[[127243,127244],"valid",[],"NV8"],[[127245,127247],"disallowed"],[[127248,127248],"disallowed_STD3_mapped",[40,97,41]],[[127249,127249],"disallowed_STD3_mapped",[40,98,41]],[[127250,127250],"disallowed_STD3_mapped",[40,99,41]],[[127251,127251],"disallowed_STD3_mapped",[40,100,41]],[[127252,127252],"disallowed_STD3_mapped",[40,101,41]],[[127253,127253],"disallowed_STD3_mapped",[40,102,41]],[[127254,127254],"disallowed_STD3_mapped",[40,103,41]],[[127255,127255],"disallowed_STD3_mapped",[40,104,41]],[[127256,127256],"disallowed_STD3_mapped",[40,105,41]],[[127257,127257],"disallowed_STD3_mapped",[40,106,41]],[[127258,127258],"disallowed_STD3_mapped",[40,107,41]],[[127259,127259],"disallowed_STD3_mapped",[40,108,41]],[[127260,127260],"disallowed_STD3_mapped",[40,109,41]],[[127261,127261],"disallowed_STD3_mapped",[40,110,41]],[[127262,127262],"disallowed_STD3_mapped",[40,111,41]],[[127263,127263],"disallowed_STD3_mapped",[40,112,41]],[[127264,127264],"disallowed_STD3_mapped",[40,113,41]],[[127265,127265],"disallowed_STD3_mapped",[40,114,41]],[[127266,127266],"disallowed_STD3_mapped",[40,115,41]],[[127267,127267],"disallowed_STD3_mapped",[40,116,41]],[[127268,127268],"disallowed_STD3_mapped",[40,117,41]],[[127269,127269],"disallowed_STD3_mapped",[40,118,41]],[[127270,127270],"disallowed_STD3_mapped",[40,119,41]],[[127271,127271],"disallowed_STD3_mapped",[40,120,41]],[[127272,127272],"disallowed_STD3_mapped",[40,121,41]],[[127273,127273],"disallowed_STD3_mapped",[40,122,41]],[[127274,127274],"mapped",[12308,115,12309]],[[127275,127275],"mapped",[99]],[[127276,127276],"mapped",[114]],[[127277,127277],"mapped",[99,100]],[[127278,127278],"mapped",[119,122]],[[127279,127279],"disallowed"],[[127280,127280],"mapped",[97]],[[127281,127281],"mapped",[98]],[[127282,127282],"mapped",[99]],[[127283,127283],"mapped",[100]],[[127284,127284],"mapped",[101]],[[127285,127285],"mapped",[102]],[[127286,127286],"mapped",[103]],[[127287,127287],"mapped",[104]],[[127288,127288],"mapped",[105]],[[127289,127289],"mapped",[106]],[[127290,127290],"mapped",[107]],[[127291,127291],"mapped",[108]],[[127292,127292],"mapped",[109]],[[127293,127293],"mapped",[110]],[[127294,127294],"mapped",[111]],[[127295,127295],"mapped",[112]],[[127296,127296],"mapped",[113]],[[127297,127297],"mapped",[114]],[[127298,127298],"mapped",[115]],[[127299,127299],"mapped",[116]],[[127300,127300],"mapped",[117]],[[127301,127301],"mapped",[118]],[[127302,127302],"mapped",[119]],[[127303,127303],"mapped",[120]],[[127304,127304],"mapped",[121]],[[127305,127305],"mapped",[122]],[[127306,127306],"mapped",[104,118]],[[127307,127307],"mapped",[109,118]],[[127308,127308],"mapped",[115,100]],[[127309,127309],"mapped",[115,115]],[[127310,127310],"mapped",[112,112,118]],[[127311,127311],"mapped",[119,99]],[[127312,127318],"valid",[],"NV8"],[[127319,127319],"valid",[],"NV8"],[[127320,127326],"valid",[],"NV8"],[[127327,127327],"valid",[],"NV8"],[[127328,127337],"valid",[],"NV8"],[[127338,127338],"mapped",[109,99]],[[127339,127339],"mapped",[109,100]],[[127340,127343],"disallowed"],[[127344,127352],"valid",[],"NV8"],[[127353,127353],"valid",[],"NV8"],[[127354,127354],"valid",[],"NV8"],[[127355,127356],"valid",[],"NV8"],[[127357,127358],"valid",[],"NV8"],[[127359,127359],"valid",[],"NV8"],[[127360,127369],"valid",[],"NV8"],[[127370,127373],"valid",[],"NV8"],[[127374,127375],"valid",[],"NV8"],[[127376,127376],"mapped",[100,106]],[[127377,127386],"valid",[],"NV8"],[[127387,127461],"disallowed"],[[127462,127487],"valid",[],"NV8"],[[127488,127488],"mapped",[12411,12363]],[[127489,127489],"mapped",[12467,12467]],[[127490,127490],"mapped",[12469]],[[127491,127503],"disallowed"],[[127504,127504],"mapped",[25163]],[[127505,127505],"mapped",[23383]],[[127506,127506],"mapped",[21452]],[[127507,127507],"mapped",[12487]],[[127508,127508],"mapped",[20108]],[[127509,127509],"mapped",[22810]],[[127510,127510],"mapped",[35299]],[[127511,127511],"mapped",[22825]],[[127512,127512],"mapped",[20132]],[[127513,127513],"mapped",[26144]],[[127514,127514],"mapped",[28961]],[[127515,127515],"mapped",[26009]],[[127516,127516],"mapped",[21069]],[[127517,127517],"mapped",[24460]],[[127518,127518],"mapped",[20877]],[[127519,127519],"mapped",[26032]],[[127520,127520],"mapped",[21021]],[[127521,127521],"mapped",[32066]],[[127522,127522],"mapped",[29983]],[[127523,127523],"mapped",[36009]],[[127524,127524],"mapped",[22768]],[[127525,127525],"mapped",[21561]],[[127526,127526],"mapped",[28436]],[[127527,127527],"mapped",[25237]],[[127528,127528],"mapped",[25429]],[[127529,127529],"mapped",[19968]],[[127530,127530],"mapped",[19977]],[[127531,127531],"mapped",[36938]],[[127532,127532],"mapped",[24038]],[[127533,127533],"mapped",[20013]],[[127534,127534],"mapped",[21491]],[[127535,127535],"mapped",[25351]],[[127536,127536],"mapped",[36208]],[[127537,127537],"mapped",[25171]],[[127538,127538],"mapped",[31105]],[[127539,127539],"mapped",[31354]],[[127540,127540],"mapped",[21512]],[[127541,127541],"mapped",[28288]],[[127542,127542],"mapped",[26377]],[[127543,127543],"mapped",[26376]],[[127544,127544],"mapped",[30003]],[[127545,127545],"mapped",[21106]],[[127546,127546],"mapped",[21942]],[[127547,127551],"disallowed"],[[127552,127552],"mapped",[12308,26412,12309]],[[127553,127553],"mapped",[12308,19977,12309]],[[127554,127554],"mapped",[12308,20108,12309]],[[127555,127555],"mapped",[12308,23433,12309]],[[127556,127556],"mapped",[12308,28857,12309]],[[127557,127557],"mapped",[12308,25171,12309]],[[127558,127558],"mapped",[12308,30423,12309]],[[127559,127559],"mapped",[12308,21213,12309]],[[127560,127560],"mapped",[12308,25943,12309]],[[127561,127567],"disallowed"],[[127568,127568],"mapped",[24471]],[[127569,127569],"mapped",[21487]],[[127570,127743],"disallowed"],[[127744,127776],"valid",[],"NV8"],[[127777,127788],"valid",[],"NV8"],[[127789,127791],"valid",[],"NV8"],[[127792,127797],"valid",[],"NV8"],[[127798,127798],"valid",[],"NV8"],[[127799,127868],"valid",[],"NV8"],[[127869,127869],"valid",[],"NV8"],[[127870,127871],"valid",[],"NV8"],[[127872,127891],"valid",[],"NV8"],[[127892,127903],"valid",[],"NV8"],[[127904,127940],"valid",[],"NV8"],[[127941,127941],"valid",[],"NV8"],[[127942,127946],"valid",[],"NV8"],[[127947,127950],"valid",[],"NV8"],[[127951,127955],"valid",[],"NV8"],[[127956,127967],"valid",[],"NV8"],[[127968,127984],"valid",[],"NV8"],[[127985,127991],"valid",[],"NV8"],[[127992,127999],"valid",[],"NV8"],[[128000,128062],"valid",[],"NV8"],[[128063,128063],"valid",[],"NV8"],[[128064,128064],"valid",[],"NV8"],[[128065,128065],"valid",[],"NV8"],[[128066,128247],"valid",[],"NV8"],[[128248,128248],"valid",[],"NV8"],[[128249,128252],"valid",[],"NV8"],[[128253,128254],"valid",[],"NV8"],[[128255,128255],"valid",[],"NV8"],[[128256,128317],"valid",[],"NV8"],[[128318,128319],"valid",[],"NV8"],[[128320,128323],"valid",[],"NV8"],[[128324,128330],"valid",[],"NV8"],[[128331,128335],"valid",[],"NV8"],[[128336,128359],"valid",[],"NV8"],[[128360,128377],"valid",[],"NV8"],[[128378,128378],"disallowed"],[[128379,128419],"valid",[],"NV8"],[[128420,128420],"disallowed"],[[128421,128506],"valid",[],"NV8"],[[128507,128511],"valid",[],"NV8"],[[128512,128512],"valid",[],"NV8"],[[128513,128528],"valid",[],"NV8"],[[128529,128529],"valid",[],"NV8"],[[128530,128532],"valid",[],"NV8"],[[128533,128533],"valid",[],"NV8"],[[128534,128534],"valid",[],"NV8"],[[128535,128535],"valid",[],"NV8"],[[128536,128536],"valid",[],"NV8"],[[128537,128537],"valid",[],"NV8"],[[128538,128538],"valid",[],"NV8"],[[128539,128539],"valid",[],"NV8"],[[128540,128542],"valid",[],"NV8"],[[128543,128543],"valid",[],"NV8"],[[128544,128549],"valid",[],"NV8"],[[128550,128551],"valid",[],"NV8"],[[128552,128555],"valid",[],"NV8"],[[128556,128556],"valid",[],"NV8"],[[128557,128557],"valid",[],"NV8"],[[128558,128559],"valid",[],"NV8"],[[128560,128563],"valid",[],"NV8"],[[128564,128564],"valid",[],"NV8"],[[128565,128576],"valid",[],"NV8"],[[128577,128578],"valid",[],"NV8"],[[128579,128580],"valid",[],"NV8"],[[128581,128591],"valid",[],"NV8"],[[128592,128639],"valid",[],"NV8"],[[128640,128709],"valid",[],"NV8"],[[128710,128719],"valid",[],"NV8"],[[128720,128720],"valid",[],"NV8"],[[128721,128735],"disallowed"],[[128736,128748],"valid",[],"NV8"],[[128749,128751],"disallowed"],[[128752,128755],"valid",[],"NV8"],[[128756,128767],"disallowed"],[[128768,128883],"valid",[],"NV8"],[[128884,128895],"disallowed"],[[128896,128980],"valid",[],"NV8"],[[128981,129023],"disallowed"],[[129024,129035],"valid",[],"NV8"],[[129036,129039],"disallowed"],[[129040,129095],"valid",[],"NV8"],[[129096,129103],"disallowed"],[[129104,129113],"valid",[],"NV8"],[[129114,129119],"disallowed"],[[129120,129159],"valid",[],"NV8"],[[129160,129167],"disallowed"],[[129168,129197],"valid",[],"NV8"],[[129198,129295],"disallowed"],[[129296,129304],"valid",[],"NV8"],[[129305,129407],"disallowed"],[[129408,129412],"valid",[],"NV8"],[[129413,129471],"disallowed"],[[129472,129472],"valid",[],"NV8"],[[129473,131069],"disallowed"],[[131070,131071],"disallowed"],[[131072,173782],"valid"],[[173783,173823],"disallowed"],[[173824,177972],"valid"],[[177973,177983],"disallowed"],[[177984,178205],"valid"],[[178206,178207],"disallowed"],[[178208,183969],"valid"],[[183970,194559],"disallowed"],[[194560,194560],"mapped",[20029]],[[194561,194561],"mapped",[20024]],[[194562,194562],"mapped",[20033]],[[194563,194563],"mapped",[131362]],[[194564,194564],"mapped",[20320]],[[194565,194565],"mapped",[20398]],[[194566,194566],"mapped",[20411]],[[194567,194567],"mapped",[20482]],[[194568,194568],"mapped",[20602]],[[194569,194569],"mapped",[20633]],[[194570,194570],"mapped",[20711]],[[194571,194571],"mapped",[20687]],[[194572,194572],"mapped",[13470]],[[194573,194573],"mapped",[132666]],[[194574,194574],"mapped",[20813]],[[194575,194575],"mapped",[20820]],[[194576,194576],"mapped",[20836]],[[194577,194577],"mapped",[20855]],[[194578,194578],"mapped",[132380]],[[194579,194579],"mapped",[13497]],[[194580,194580],"mapped",[20839]],[[194581,194581],"mapped",[20877]],[[194582,194582],"mapped",[132427]],[[194583,194583],"mapped",[20887]],[[194584,194584],"mapped",[20900]],[[194585,194585],"mapped",[20172]],[[194586,194586],"mapped",[20908]],[[194587,194587],"mapped",[20917]],[[194588,194588],"mapped",[168415]],[[194589,194589],"mapped",[20981]],[[194590,194590],"mapped",[20995]],[[194591,194591],"mapped",[13535]],[[194592,194592],"mapped",[21051]],[[194593,194593],"mapped",[21062]],[[194594,194594],"mapped",[21106]],[[194595,194595],"mapped",[21111]],[[194596,194596],"mapped",[13589]],[[194597,194597],"mapped",[21191]],[[194598,194598],"mapped",[21193]],[[194599,194599],"mapped",[21220]],[[194600,194600],"mapped",[21242]],[[194601,194601],"mapped",[21253]],[[194602,194602],"mapped",[21254]],[[194603,194603],"mapped",[21271]],[[194604,194604],"mapped",[21321]],[[194605,194605],"mapped",[21329]],[[194606,194606],"mapped",[21338]],[[194607,194607],"mapped",[21363]],[[194608,194608],"mapped",[21373]],[[194609,194611],"mapped",[21375]],[[194612,194612],"mapped",[133676]],[[194613,194613],"mapped",[28784]],[[194614,194614],"mapped",[21450]],[[194615,194615],"mapped",[21471]],[[194616,194616],"mapped",[133987]],[[194617,194617],"mapped",[21483]],[[194618,194618],"mapped",[21489]],[[194619,194619],"mapped",[21510]],[[194620,194620],"mapped",[21662]],[[194621,194621],"mapped",[21560]],[[194622,194622],"mapped",[21576]],[[194623,194623],"mapped",[21608]],[[194624,194624],"mapped",[21666]],[[194625,194625],"mapped",[21750]],[[194626,194626],"mapped",[21776]],[[194627,194627],"mapped",[21843]],[[194628,194628],"mapped",[21859]],[[194629,194630],"mapped",[21892]],[[194631,194631],"mapped",[21913]],[[194632,194632],"mapped",[21931]],[[194633,194633],"mapped",[21939]],[[194634,194634],"mapped",[21954]],[[194635,194635],"mapped",[22294]],[[194636,194636],"mapped",[22022]],[[194637,194637],"mapped",[22295]],[[194638,194638],"mapped",[22097]],[[194639,194639],"mapped",[22132]],[[194640,194640],"mapped",[20999]],[[194641,194641],"mapped",[22766]],[[194642,194642],"mapped",[22478]],[[194643,194643],"mapped",[22516]],[[194644,194644],"mapped",[22541]],[[194645,194645],"mapped",[22411]],[[194646,194646],"mapped",[22578]],[[194647,194647],"mapped",[22577]],[[194648,194648],"mapped",[22700]],[[194649,194649],"mapped",[136420]],[[194650,194650],"mapped",[22770]],[[194651,194651],"mapped",[22775]],[[194652,194652],"mapped",[22790]],[[194653,194653],"mapped",[22810]],[[194654,194654],"mapped",[22818]],[[194655,194655],"mapped",[22882]],[[194656,194656],"mapped",[136872]],[[194657,194657],"mapped",[136938]],[[194658,194658],"mapped",[23020]],[[194659,194659],"mapped",[23067]],[[194660,194660],"mapped",[23079]],[[194661,194661],"mapped",[23000]],[[194662,194662],"mapped",[23142]],[[194663,194663],"mapped",[14062]],[[194664,194664],"disallowed"],[[194665,194665],"mapped",[23304]],[[194666,194667],"mapped",[23358]],[[194668,194668],"mapped",[137672]],[[194669,194669],"mapped",[23491]],[[194670,194670],"mapped",[23512]],[[194671,194671],"mapped",[23527]],[[194672,194672],"mapped",[23539]],[[194673,194673],"mapped",[138008]],[[194674,194674],"mapped",[23551]],[[194675,194675],"mapped",[23558]],[[194676,194676],"disallowed"],[[194677,194677],"mapped",[23586]],[[194678,194678],"mapped",[14209]],[[194679,194679],"mapped",[23648]],[[194680,194680],"mapped",[23662]],[[194681,194681],"mapped",[23744]],[[194682,194682],"mapped",[23693]],[[194683,194683],"mapped",[138724]],[[194684,194684],"mapped",[23875]],[[194685,194685],"mapped",[138726]],[[194686,194686],"mapped",[23918]],[[194687,194687],"mapped",[23915]],[[194688,194688],"mapped",[23932]],[[194689,194689],"mapped",[24033]],[[194690,194690],"mapped",[24034]],[[194691,194691],"mapped",[14383]],[[194692,194692],"mapped",[24061]],[[194693,194693],"mapped",[24104]],[[194694,194694],"mapped",[24125]],[[194695,194695],"mapped",[24169]],[[194696,194696],"mapped",[14434]],[[194697,194697],"mapped",[139651]],[[194698,194698],"mapped",[14460]],[[194699,194699],"mapped",[24240]],[[194700,194700],"mapped",[24243]],[[194701,194701],"mapped",[24246]],[[194702,194702],"mapped",[24266]],[[194703,194703],"mapped",[172946]],[[194704,194704],"mapped",[24318]],[[194705,194706],"mapped",[140081]],[[194707,194707],"mapped",[33281]],[[194708,194709],"mapped",[24354]],[[194710,194710],"mapped",[14535]],[[194711,194711],"mapped",[144056]],[[194712,194712],"mapped",[156122]],[[194713,194713],"mapped",[24418]],[[194714,194714],"mapped",[24427]],[[194715,194715],"mapped",[14563]],[[194716,194716],"mapped",[24474]],[[194717,194717],"mapped",[24525]],[[194718,194718],"mapped",[24535]],[[194719,194719],"mapped",[24569]],[[194720,194720],"mapped",[24705]],[[194721,194721],"mapped",[14650]],[[194722,194722],"mapped",[14620]],[[194723,194723],"mapped",[24724]],[[194724,194724],"mapped",[141012]],[[194725,194725],"mapped",[24775]],[[194726,194726],"mapped",[24904]],[[194727,194727],"mapped",[24908]],[[194728,194728],"mapped",[24910]],[[194729,194729],"mapped",[24908]],[[194730,194730],"mapped",[24954]],[[194731,194731],"mapped",[24974]],[[194732,194732],"mapped",[25010]],[[194733,194733],"mapped",[24996]],[[194734,194734],"mapped",[25007]],[[194735,194735],"mapped",[25054]],[[194736,194736],"mapped",[25074]],[[194737,194737],"mapped",[25078]],[[194738,194738],"mapped",[25104]],[[194739,194739],"mapped",[25115]],[[194740,194740],"mapped",[25181]],[[194741,194741],"mapped",[25265]],[[194742,194742],"mapped",[25300]],[[194743,194743],"mapped",[25424]],[[194744,194744],"mapped",[142092]],[[194745,194745],"mapped",[25405]],[[194746,194746],"mapped",[25340]],[[194747,194747],"mapped",[25448]],[[194748,194748],"mapped",[25475]],[[194749,194749],"mapped",[25572]],[[194750,194750],"mapped",[142321]],[[194751,194751],"mapped",[25634]],[[194752,194752],"mapped",[25541]],[[194753,194753],"mapped",[25513]],[[194754,194754],"mapped",[14894]],[[194755,194755],"mapped",[25705]],[[194756,194756],"mapped",[25726]],[[194757,194757],"mapped",[25757]],[[194758,194758],"mapped",[25719]],[[194759,194759],"mapped",[14956]],[[194760,194760],"mapped",[25935]],[[194761,194761],"mapped",[25964]],[[194762,194762],"mapped",[143370]],[[194763,194763],"mapped",[26083]],[[194764,194764],"mapped",[26360]],[[194765,194765],"mapped",[26185]],[[194766,194766],"mapped",[15129]],[[194767,194767],"mapped",[26257]],[[194768,194768],"mapped",[15112]],[[194769,194769],"mapped",[15076]],[[194770,194770],"mapped",[20882]],[[194771,194771],"mapped",[20885]],[[194772,194772],"mapped",[26368]],[[194773,194773],"mapped",[26268]],[[194774,194774],"mapped",[32941]],[[194775,194775],"mapped",[17369]],[[194776,194776],"mapped",[26391]],[[194777,194777],"mapped",[26395]],[[194778,194778],"mapped",[26401]],[[194779,194779],"mapped",[26462]],[[194780,194780],"mapped",[26451]],[[194781,194781],"mapped",[144323]],[[194782,194782],"mapped",[15177]],[[194783,194783],"mapped",[26618]],[[194784,194784],"mapped",[26501]],[[194785,194785],"mapped",[26706]],[[194786,194786],"mapped",[26757]],[[194787,194787],"mapped",[144493]],[[194788,194788],"mapped",[26766]],[[194789,194789],"mapped",[26655]],[[194790,194790],"mapped",[26900]],[[194791,194791],"mapped",[15261]],[[194792,194792],"mapped",[26946]],[[194793,194793],"mapped",[27043]],[[194794,194794],"mapped",[27114]],[[194795,194795],"mapped",[27304]],[[194796,194796],"mapped",[145059]],[[194797,194797],"mapped",[27355]],[[194798,194798],"mapped",[15384]],[[194799,194799],"mapped",[27425]],[[194800,194800],"mapped",[145575]],[[194801,194801],"mapped",[27476]],[[194802,194802],"mapped",[15438]],[[194803,194803],"mapped",[27506]],[[194804,194804],"mapped",[27551]],[[194805,194805],"mapped",[27578]],[[194806,194806],"mapped",[27579]],[[194807,194807],"mapped",[146061]],[[194808,194808],"mapped",[138507]],[[194809,194809],"mapped",[146170]],[[194810,194810],"mapped",[27726]],[[194811,194811],"mapped",[146620]],[[194812,194812],"mapped",[27839]],[[194813,194813],"mapped",[27853]],[[194814,194814],"mapped",[27751]],[[194815,194815],"mapped",[27926]],[[194816,194816],"mapped",[27966]],[[194817,194817],"mapped",[28023]],[[194818,194818],"mapped",[27969]],[[194819,194819],"mapped",[28009]],[[194820,194820],"mapped",[28024]],[[194821,194821],"mapped",[28037]],[[194822,194822],"mapped",[146718]],[[194823,194823],"mapped",[27956]],[[194824,194824],"mapped",[28207]],[[194825,194825],"mapped",[28270]],[[194826,194826],"mapped",[15667]],[[194827,194827],"mapped",[28363]],[[194828,194828],"mapped",[28359]],[[194829,194829],"mapped",[147153]],[[194830,194830],"mapped",[28153]],[[194831,194831],"mapped",[28526]],[[194832,194832],"mapped",[147294]],[[194833,194833],"mapped",[147342]],[[194834,194834],"mapped",[28614]],[[194835,194835],"mapped",[28729]],[[194836,194836],"mapped",[28702]],[[194837,194837],"mapped",[28699]],[[194838,194838],"mapped",[15766]],[[194839,194839],"mapped",[28746]],[[194840,194840],"mapped",[28797]],[[194841,194841],"mapped",[28791]],[[194842,194842],"mapped",[28845]],[[194843,194843],"mapped",[132389]],[[194844,194844],"mapped",[28997]],[[194845,194845],"mapped",[148067]],[[194846,194846],"mapped",[29084]],[[194847,194847],"disallowed"],[[194848,194848],"mapped",[29224]],[[194849,194849],"mapped",[29237]],[[194850,194850],"mapped",[29264]],[[194851,194851],"mapped",[149000]],[[194852,194852],"mapped",[29312]],[[194853,194853],"mapped",[29333]],[[194854,194854],"mapped",[149301]],[[194855,194855],"mapped",[149524]],[[194856,194856],"mapped",[29562]],[[194857,194857],"mapped",[29579]],[[194858,194858],"mapped",[16044]],[[194859,194859],"mapped",[29605]],[[194860,194861],"mapped",[16056]],[[194862,194862],"mapped",[29767]],[[194863,194863],"mapped",[29788]],[[194864,194864],"mapped",[29809]],[[194865,194865],"mapped",[29829]],[[194866,194866],"mapped",[29898]],[[194867,194867],"mapped",[16155]],[[194868,194868],"mapped",[29988]],[[194869,194869],"mapped",[150582]],[[194870,194870],"mapped",[30014]],[[194871,194871],"mapped",[150674]],[[194872,194872],"mapped",[30064]],[[194873,194873],"mapped",[139679]],[[194874,194874],"mapped",[30224]],[[194875,194875],"mapped",[151457]],[[194876,194876],"mapped",[151480]],[[194877,194877],"mapped",[151620]],[[194878,194878],"mapped",[16380]],[[194879,194879],"mapped",[16392]],[[194880,194880],"mapped",[30452]],[[194881,194881],"mapped",[151795]],[[194882,194882],"mapped",[151794]],[[194883,194883],"mapped",[151833]],[[194884,194884],"mapped",[151859]],[[194885,194885],"mapped",[30494]],[[194886,194887],"mapped",[30495]],[[194888,194888],"mapped",[30538]],[[194889,194889],"mapped",[16441]],[[194890,194890],"mapped",[30603]],[[194891,194891],"mapped",[16454]],[[194892,194892],"mapped",[16534]],[[194893,194893],"mapped",[152605]],[[194894,194894],"mapped",[30798]],[[194895,194895],"mapped",[30860]],[[194896,194896],"mapped",[30924]],[[194897,194897],"mapped",[16611]],[[194898,194898],"mapped",[153126]],[[194899,194899],"mapped",[31062]],[[194900,194900],"mapped",[153242]],[[194901,194901],"mapped",[153285]],[[194902,194902],"mapped",[31119]],[[194903,194903],"mapped",[31211]],[[194904,194904],"mapped",[16687]],[[194905,194905],"mapped",[31296]],[[194906,194906],"mapped",[31306]],[[194907,194907],"mapped",[31311]],[[194908,194908],"mapped",[153980]],[[194909,194910],"mapped",[154279]],[[194911,194911],"disallowed"],[[194912,194912],"mapped",[16898]],[[194913,194913],"mapped",[154539]],[[194914,194914],"mapped",[31686]],[[194915,194915],"mapped",[31689]],[[194916,194916],"mapped",[16935]],[[194917,194917],"mapped",[154752]],[[194918,194918],"mapped",[31954]],[[194919,194919],"mapped",[17056]],[[194920,194920],"mapped",[31976]],[[194921,194921],"mapped",[31971]],[[194922,194922],"mapped",[32000]],[[194923,194923],"mapped",[155526]],[[194924,194924],"mapped",[32099]],[[194925,194925],"mapped",[17153]],[[194926,194926],"mapped",[32199]],[[194927,194927],"mapped",[32258]],[[194928,194928],"mapped",[32325]],[[194929,194929],"mapped",[17204]],[[194930,194930],"mapped",[156200]],[[194931,194931],"mapped",[156231]],[[194932,194932],"mapped",[17241]],[[194933,194933],"mapped",[156377]],[[194934,194934],"mapped",[32634]],[[194935,194935],"mapped",[156478]],[[194936,194936],"mapped",[32661]],[[194937,194937],"mapped",[32762]],[[194938,194938],"mapped",[32773]],[[194939,194939],"mapped",[156890]],[[194940,194940],"mapped",[156963]],[[194941,194941],"mapped",[32864]],[[194942,194942],"mapped",[157096]],[[194943,194943],"mapped",[32880]],[[194944,194944],"mapped",[144223]],[[194945,194945],"mapped",[17365]],[[194946,194946],"mapped",[32946]],[[194947,194947],"mapped",[33027]],[[194948,194948],"mapped",[17419]],[[194949,194949],"mapped",[33086]],[[194950,194950],"mapped",[23221]],[[194951,194951],"mapped",[157607]],[[194952,194952],"mapped",[157621]],[[194953,194953],"mapped",[144275]],[[194954,194954],"mapped",[144284]],[[194955,194955],"mapped",[33281]],[[194956,194956],"mapped",[33284]],[[194957,194957],"mapped",[36766]],[[194958,194958],"mapped",[17515]],[[194959,194959],"mapped",[33425]],[[194960,194960],"mapped",[33419]],[[194961,194961],"mapped",[33437]],[[194962,194962],"mapped",[21171]],[[194963,194963],"mapped",[33457]],[[194964,194964],"mapped",[33459]],[[194965,194965],"mapped",[33469]],[[194966,194966],"mapped",[33510]],[[194967,194967],"mapped",[158524]],[[194968,194968],"mapped",[33509]],[[194969,194969],"mapped",[33565]],[[194970,194970],"mapped",[33635]],[[194971,194971],"mapped",[33709]],[[194972,194972],"mapped",[33571]],[[194973,194973],"mapped",[33725]],[[194974,194974],"mapped",[33767]],[[194975,194975],"mapped",[33879]],[[194976,194976],"mapped",[33619]],[[194977,194977],"mapped",[33738]],[[194978,194978],"mapped",[33740]],[[194979,194979],"mapped",[33756]],[[194980,194980],"mapped",[158774]],[[194981,194981],"mapped",[159083]],[[194982,194982],"mapped",[158933]],[[194983,194983],"mapped",[17707]],[[194984,194984],"mapped",[34033]],[[194985,194985],"mapped",[34035]],[[194986,194986],"mapped",[34070]],[[194987,194987],"mapped",[160714]],[[194988,194988],"mapped",[34148]],[[194989,194989],"mapped",[159532]],[[194990,194990],"mapped",[17757]],[[194991,194991],"mapped",[17761]],[[194992,194992],"mapped",[159665]],[[194993,194993],"mapped",[159954]],[[194994,194994],"mapped",[17771]],[[194995,194995],"mapped",[34384]],[[194996,194996],"mapped",[34396]],[[194997,194997],"mapped",[34407]],[[194998,194998],"mapped",[34409]],[[194999,194999],"mapped",[34473]],[[195000,195000],"mapped",[34440]],[[195001,195001],"mapped",[34574]],[[195002,195002],"mapped",[34530]],[[195003,195003],"mapped",[34681]],[[195004,195004],"mapped",[34600]],[[195005,195005],"mapped",[34667]],[[195006,195006],"mapped",[34694]],[[195007,195007],"disallowed"],[[195008,195008],"mapped",[34785]],[[195009,195009],"mapped",[34817]],[[195010,195010],"mapped",[17913]],[[195011,195011],"mapped",[34912]],[[195012,195012],"mapped",[34915]],[[195013,195013],"mapped",[161383]],[[195014,195014],"mapped",[35031]],[[195015,195015],"mapped",[35038]],[[195016,195016],"mapped",[17973]],[[195017,195017],"mapped",[35066]],[[195018,195018],"mapped",[13499]],[[195019,195019],"mapped",[161966]],[[195020,195020],"mapped",[162150]],[[195021,195021],"mapped",[18110]],[[195022,195022],"mapped",[18119]],[[195023,195023],"mapped",[35488]],[[195024,195024],"mapped",[35565]],[[195025,195025],"mapped",[35722]],[[195026,195026],"mapped",[35925]],[[195027,195027],"mapped",[162984]],[[195028,195028],"mapped",[36011]],[[195029,195029],"mapped",[36033]],[[195030,195030],"mapped",[36123]],[[195031,195031],"mapped",[36215]],[[195032,195032],"mapped",[163631]],[[195033,195033],"mapped",[133124]],[[195034,195034],"mapped",[36299]],[[195035,195035],"mapped",[36284]],[[195036,195036],"mapped",[36336]],[[195037,195037],"mapped",[133342]],[[195038,195038],"mapped",[36564]],[[195039,195039],"mapped",[36664]],[[195040,195040],"mapped",[165330]],[[195041,195041],"mapped",[165357]],[[195042,195042],"mapped",[37012]],[[195043,195043],"mapped",[37105]],[[195044,195044],"mapped",[37137]],[[195045,195045],"mapped",[165678]],[[195046,195046],"mapped",[37147]],[[195047,195047],"mapped",[37432]],[[195048,195048],"mapped",[37591]],[[195049,195049],"mapped",[37592]],[[195050,195050],"mapped",[37500]],[[195051,195051],"mapped",[37881]],[[195052,195052],"mapped",[37909]],[[195053,195053],"mapped",[166906]],[[195054,195054],"mapped",[38283]],[[195055,195055],"mapped",[18837]],[[195056,195056],"mapped",[38327]],[[195057,195057],"mapped",[167287]],[[195058,195058],"mapped",[18918]],[[195059,195059],"mapped",[38595]],[[195060,195060],"mapped",[23986]],[[195061,195061],"mapped",[38691]],[[195062,195062],"mapped",[168261]],[[195063,195063],"mapped",[168474]],[[195064,195064],"mapped",[19054]],[[195065,195065],"mapped",[19062]],[[195066,195066],"mapped",[38880]],[[195067,195067],"mapped",[168970]],[[195068,195068],"mapped",[19122]],[[195069,195069],"mapped",[169110]],[[195070,195071],"mapped",[38923]],[[195072,195072],"mapped",[38953]],[[195073,195073],"mapped",[169398]],[[195074,195074],"mapped",[39138]],[[195075,195075],"mapped",[19251]],[[195076,195076],"mapped",[39209]],[[195077,195077],"mapped",[39335]],[[195078,195078],"mapped",[39362]],[[195079,195079],"mapped",[39422]],[[195080,195080],"mapped",[19406]],[[195081,195081],"mapped",[170800]],[[195082,195082],"mapped",[39698]],[[195083,195083],"mapped",[40000]],[[195084,195084],"mapped",[40189]],[[195085,195085],"mapped",[19662]],[[195086,195086],"mapped",[19693]],[[195087,195087],"mapped",[40295]],[[195088,195088],"mapped",[172238]],[[195089,195089],"mapped",[19704]],[[195090,195090],"mapped",[172293]],[[195091,195091],"mapped",[172558]],[[195092,195092],"mapped",[172689]],[[195093,195093],"mapped",[40635]],[[195094,195094],"mapped",[19798]],[[195095,195095],"mapped",[40697]],[[195096,195096],"mapped",[40702]],[[195097,195097],"mapped",[40709]],[[195098,195098],"mapped",[40719]],[[195099,195099],"mapped",[40726]],[[195100,195100],"mapped",[40763]],[[195101,195101],"mapped",[173568]],[[195102,196605],"disallowed"],[[196606,196607],"disallowed"],[[196608,262141],"disallowed"],[[262142,262143],"disallowed"],[[262144,327677],"disallowed"],[[327678,327679],"disallowed"],[[327680,393213],"disallowed"],[[393214,393215],"disallowed"],[[393216,458749],"disallowed"],[[458750,458751],"disallowed"],[[458752,524285],"disallowed"],[[524286,524287],"disallowed"],[[524288,589821],"disallowed"],[[589822,589823],"disallowed"],[[589824,655357],"disallowed"],[[655358,655359],"disallowed"],[[655360,720893],"disallowed"],[[720894,720895],"disallowed"],[[720896,786429],"disallowed"],[[786430,786431],"disallowed"],[[786432,851965],"disallowed"],[[851966,851967],"disallowed"],[[851968,917501],"disallowed"],[[917502,917503],"disallowed"],[[917504,917504],"disallowed"],[[917505,917505],"disallowed"],[[917506,917535],"disallowed"],[[917536,917631],"disallowed"],[[917632,917759],"disallowed"],[[917760,917999],"ignored"],[[918000,983037],"disallowed"],[[983038,983039],"disallowed"],[[983040,1048573],"disallowed"],[[1048574,1048575],"disallowed"],[[1048576,1114109],"disallowed"],[[1114110,1114111],"disallowed"]]'); - -/***/ }) - -/******/ }); -/************************************************************************/ -/******/ // The module cache -/******/ var __webpack_module_cache__ = {}; -/******/ -/******/ // The require function -/******/ function __nccwpck_require__(moduleId) { -/******/ // Check if module is in cache -/******/ var cachedModule = __webpack_module_cache__[moduleId]; -/******/ if (cachedModule !== undefined) { -/******/ return cachedModule.exports; -/******/ } -/******/ // Create a new module (and put it into the cache) -/******/ var module = __webpack_module_cache__[moduleId] = { -/******/ id: moduleId, -/******/ loaded: false, -/******/ exports: {} -/******/ }; -/******/ -/******/ // Execute the module function -/******/ var threw = true; -/******/ try { -/******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __nccwpck_require__); -/******/ threw = false; -/******/ } finally { -/******/ if(threw) delete __webpack_module_cache__[moduleId]; -/******/ } -/******/ -/******/ // Flag the module as loaded -/******/ module.loaded = true; -/******/ -/******/ // Return the exports of the module -/******/ return module.exports; -/******/ } -/******/ -/******/ // expose the modules object (__webpack_modules__) -/******/ __nccwpck_require__.m = __webpack_modules__; -/******/ -/************************************************************************/ -/******/ /* webpack/runtime/create fake namespace object */ -/******/ (() => { -/******/ var getProto = Object.getPrototypeOf ? (obj) => (Object.getPrototypeOf(obj)) : (obj) => (obj.__proto__); -/******/ var leafPrototypes; -/******/ // create a fake namespace object -/******/ // mode & 1: value is a module id, require it -/******/ // mode & 2: merge all properties of value into the ns -/******/ // mode & 4: return value when already ns object -/******/ // mode & 16: return value when it's Promise-like -/******/ // mode & 8|1: behave like require -/******/ __nccwpck_require__.t = function(value, mode) { -/******/ if(mode & 1) value = this(value); -/******/ if(mode & 8) return value; -/******/ if(typeof value === 'object' && value) { -/******/ if((mode & 4) && value.__esModule) return value; -/******/ if((mode & 16) && typeof value.then === 'function') return value; -/******/ } -/******/ var ns = Object.create(null); -/******/ __nccwpck_require__.r(ns); -/******/ var def = {}; -/******/ leafPrototypes = leafPrototypes || [null, getProto({}), getProto([]), getProto(getProto)]; -/******/ for(var current = mode & 2 && value; typeof current == 'object' && !~leafPrototypes.indexOf(current); current = getProto(current)) { -/******/ Object.getOwnPropertyNames(current).forEach((key) => (def[key] = () => (value[key]))); -/******/ } -/******/ def['default'] = () => (value); -/******/ __nccwpck_require__.d(ns, def); -/******/ return ns; -/******/ }; -/******/ })(); -/******/ -/******/ /* webpack/runtime/define property getters */ -/******/ (() => { -/******/ // define getter functions for harmony exports -/******/ __nccwpck_require__.d = (exports, definition) => { -/******/ for(var key in definition) { -/******/ if(__nccwpck_require__.o(definition, key) && !__nccwpck_require__.o(exports, key)) { -/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] }); -/******/ } -/******/ } -/******/ }; -/******/ })(); -/******/ -/******/ /* webpack/runtime/ensure chunk */ -/******/ (() => { -/******/ __nccwpck_require__.f = {}; -/******/ // This file contains only the entry chunk. -/******/ // The chunk loading function for additional chunks -/******/ __nccwpck_require__.e = (chunkId) => { -/******/ return Promise.all(Object.keys(__nccwpck_require__.f).reduce((promises, key) => { -/******/ __nccwpck_require__.f[key](chunkId, promises); -/******/ return promises; -/******/ }, [])); -/******/ }; -/******/ })(); -/******/ -/******/ /* webpack/runtime/get javascript chunk filename */ -/******/ (() => { -/******/ // This function allow to reference async chunks -/******/ __nccwpck_require__.u = (chunkId) => { -/******/ // return url for filenames based on template -/******/ return "" + chunkId + ".index.js"; -/******/ }; -/******/ })(); -/******/ -/******/ /* webpack/runtime/hasOwnProperty shorthand */ -/******/ (() => { -/******/ __nccwpck_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) -/******/ })(); -/******/ -/******/ /* webpack/runtime/make namespace object */ -/******/ (() => { -/******/ // define __esModule on exports -/******/ __nccwpck_require__.r = (exports) => { -/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { -/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); -/******/ } -/******/ Object.defineProperty(exports, '__esModule', { value: true }); -/******/ }; -/******/ })(); -/******/ -/******/ /* webpack/runtime/node module decorator */ -/******/ (() => { -/******/ __nccwpck_require__.nmd = (module) => { -/******/ module.paths = []; -/******/ if (!module.children) module.children = []; -/******/ return module; -/******/ }; -/******/ })(); -/******/ -/******/ /* webpack/runtime/compat */ -/******/ -/******/ if (typeof __nccwpck_require__ !== 'undefined') __nccwpck_require__.ab = new URL('.', import.meta.url).pathname.slice(import.meta.url.match(/^file:\/\/\/\w:/) ? 1 : 0, -1) + "/"; -/******/ -/******/ /* webpack/runtime/import chunk loading */ -/******/ (() => { -/******/ // no baseURI -/******/ -/******/ // object to store loaded and loading chunks -/******/ // undefined = chunk not loaded, null = chunk preloaded/prefetched -/******/ // [resolve, Promise] = chunk loading, 0 = chunk loaded -/******/ var installedChunks = { -/******/ 792: 0 -/******/ }; -/******/ -/******/ var installChunk = (data) => { -/******/ var {ids, modules, runtime} = data; -/******/ // add "modules" to the modules object, -/******/ // then flag all "ids" as loaded and fire callback -/******/ var moduleId, chunkId, i = 0; -/******/ for(moduleId in modules) { -/******/ if(__nccwpck_require__.o(modules, moduleId)) { -/******/ __nccwpck_require__.m[moduleId] = modules[moduleId]; -/******/ } -/******/ } -/******/ if(runtime) runtime(__nccwpck_require__); -/******/ for(;i < ids.length; i++) { -/******/ chunkId = ids[i]; -/******/ if(__nccwpck_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) { -/******/ installedChunks[chunkId][0](); -/******/ } -/******/ installedChunks[ids[i]] = 0; -/******/ } -/******/ -/******/ } -/******/ -/******/ __nccwpck_require__.f.j = (chunkId, promises) => { -/******/ // import() chunk loading for javascript -/******/ var installedChunkData = __nccwpck_require__.o(installedChunks, chunkId) ? installedChunks[chunkId] : undefined; -/******/ if(installedChunkData !== 0) { // 0 means "already installed". -/******/ -/******/ // a Promise means "currently loading". -/******/ if(installedChunkData) { -/******/ promises.push(installedChunkData[1]); -/******/ } else { -/******/ if(true) { // all chunks have JS -/******/ // setup Promise in chunk cache -/******/ var promise = import("./" + __nccwpck_require__.u(chunkId)).then(installChunk, (e) => { -/******/ if(installedChunks[chunkId] !== 0) installedChunks[chunkId] = undefined; -/******/ throw e; -/******/ }); -/******/ var promise = Promise.race([promise, new Promise((resolve) => (installedChunkData = installedChunks[chunkId] = [resolve]))]) -/******/ promises.push(installedChunkData[1] = promise); -/******/ } -/******/ } -/******/ } -/******/ }; -/******/ -/******/ // no prefetching -/******/ -/******/ // no preloaded -/******/ -/******/ // no external install chunk -/******/ -/******/ // no on chunks loaded -/******/ })(); -/******/ -/************************************************************************/ -var __webpack_exports__ = {}; - -// NAMESPACE OBJECT: ./node_modules/@langchain/core/dist/utils/fast-json-patch/src/core.js -var src_core_namespaceObject = {}; -__nccwpck_require__.r(src_core_namespaceObject); -__nccwpck_require__.d(src_core_namespaceObject, { - JsonPatchError: () => (JsonPatchError), - _areEquals: () => (_areEquals), - applyOperation: () => (applyOperation), - applyPatch: () => (core_applyPatch), - applyReducer: () => (applyReducer), - deepClone: () => (deepClone), - getValueByPointer: () => (getValueByPointer), - validate: () => (core_validate), - validator: () => (validator) -}); - -// EXTERNAL MODULE: ./node_modules/@actions/core/lib/core.js -var core = __nccwpck_require__(7484); -// EXTERNAL MODULE: ./node_modules/@actions/github/lib/github.js -var github = __nccwpck_require__(3228); +//# sourceMappingURL=shims.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/internal/request-options.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +const FallbackEncoder = ({ headers, body }) => { + return { + bodyHeaders: { + 'content-type': 'application/json', + }, + body: JSON.stringify(body), + }; +}; +//# sourceMappingURL=request-options.mjs.map ;// CONCATENATED MODULE: ./node_modules/openai/internal/qs/formats.mjs const default_format = 'RFC3986'; +const default_formatter = (v) => String(v); const formatters = { RFC1738: (v) => String(v).replace(/%20/g, '+'), - RFC3986: (v) => String(v), + RFC3986: default_formatter, }; const RFC1738 = 'RFC1738'; const RFC3986 = 'RFC3986'; //# sourceMappingURL=formats.mjs.map ;// CONCATENATED MODULE: ./node_modules/openai/internal/qs/utils.mjs -const has = Object.prototype.hasOwnProperty; -const is_array = Array.isArray; -const hex_table = (() => { + +let has = (obj, key) => ((has = Object.hasOwn ?? Function.prototype.call.bind(Object.prototype.hasOwnProperty)), + has(obj, key)); +const hex_table = /* @__PURE__ */ (() => { const array = []; for (let i = 0; i < 256; ++i) { array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase()); @@ -68330,7 +62835,7 @@ function compact_queue(queue) { if (!item) continue; const obj = item.obj[item.prop]; - if (is_array(obj)) { + if (isArray(obj)) { const compacted = []; for (let j = 0; j < obj.length; ++j) { if (typeof obj[j] !== 'undefined') { @@ -68356,12 +62861,11 @@ function merge(target, source, options = {}) { return target; } if (typeof source !== 'object') { - if (is_array(target)) { + if (isArray(target)) { target.push(source); } else if (target && typeof target === 'object') { - if ((options && (options.plainObjects || options.allowPrototypes)) || - !has.call(Object.prototype, source)) { + if ((options && (options.plainObjects || options.allowPrototypes)) || !has(Object.prototype, source)) { target[source] = true; } } @@ -68374,13 +62878,13 @@ function merge(target, source, options = {}) { return [target].concat(source); } let mergeTarget = target; - if (is_array(target) && !is_array(source)) { + if (isArray(target) && !isArray(source)) { // @ts-ignore mergeTarget = array_to_object(target, options); } - if (is_array(target) && is_array(source)) { + if (isArray(target) && isArray(source)) { source.forEach(function (item, i) { - if (has.call(target, i)) { + if (has(target, i)) { const targetItem = target[i]; if (targetItem && typeof targetItem === 'object' && item && typeof item === 'object') { target[i] = merge(targetItem, item, options); @@ -68397,7 +62901,7 @@ function merge(target, source, options = {}) { } return Object.keys(source).reduce(function (acc, key) { const value = source[key]; - if (has.call(acc, key)) { + if (has(acc, key)) { acc[key] = merge(acc[key], value, options); } else { @@ -68521,7 +63025,7 @@ function combine(a, b) { return [].concat(a, b); } function maybe_map(val, fn) { - if (is_array(val)) { + if (values_isArray(val)) { const mapped = []; for (let i = 0; i < val.length; i += 1) { mapped.push(fn(val[i])); @@ -68534,7 +63038,7 @@ function maybe_map(val, fn) { ;// CONCATENATED MODULE: ./node_modules/openai/internal/qs/stringify.mjs -const stringify_has = Object.prototype.hasOwnProperty; + const array_prefix_generators = { brackets(prefix) { return String(prefix) + '[]'; @@ -68547,12 +63051,10 @@ const array_prefix_generators = { return String(prefix); }, }; -const stringify_is_array = Array.isArray; -const push = Array.prototype.push; const push_to_array = function (arr, value_or_array) { - push.apply(arr, stringify_is_array(value_or_array) ? value_or_array : [value_or_array]); + Array.prototype.push.apply(arr, values_isArray(value_or_array) ? value_or_array : [value_or_array]); }; -const to_ISO = Date.prototype.toISOString; +let toISOString; const defaults = { addQueryPrefix: false, allowDots: false, @@ -68566,11 +63068,11 @@ const defaults = { encoder: encode, encodeValuesOnly: false, format: default_format, - formatter: formatters[default_format], + formatter: default_formatter, /** @deprecated */ indices: false, serializeDate(date) { - return to_ISO.call(date); + return (toISOString ?? (toISOString = Function.prototype.call.bind(Date.prototype.toISOString)))(date); }, skipNulls: false, strictNullHandling: false, @@ -68610,7 +63112,7 @@ function inner_stringify(object, prefix, generateArrayPrefix, commaRoundTrip, al else if (obj instanceof Date) { obj = serializeDate?.(obj); } - else if (generateArrayPrefix === 'comma' && stringify_is_array(obj)) { + else if (generateArrayPrefix === 'comma' && values_isArray(obj)) { obj = maybe_map(obj, function (value) { if (value instanceof Date) { return serializeDate?.(value); @@ -68646,7 +63148,7 @@ function inner_stringify(object, prefix, generateArrayPrefix, commaRoundTrip, al return values; } let obj_keys; - if (generateArrayPrefix === 'comma' && stringify_is_array(obj)) { + if (generateArrayPrefix === 'comma' && values_isArray(obj)) { // we need to join elements in if (encodeValuesOnly && encoder) { // @ts-expect-error values only @@ -68654,7 +63156,7 @@ function inner_stringify(object, prefix, generateArrayPrefix, commaRoundTrip, al } obj_keys = [{ value: obj.length > 0 ? obj.join(',') || null : void undefined }]; } - else if (stringify_is_array(filter)) { + else if (values_isArray(filter)) { obj_keys = filter; } else { @@ -68662,8 +63164,8 @@ function inner_stringify(object, prefix, generateArrayPrefix, commaRoundTrip, al obj_keys = sort ? keys.sort(sort) : keys; } const encoded_prefix = encodeDotInKeys ? String(prefix).replace(/\./g, '%2E') : String(prefix); - const adjusted_prefix = commaRoundTrip && stringify_is_array(obj) && obj.length === 1 ? encoded_prefix + '[]' : encoded_prefix; - if (allowEmptyArrays && stringify_is_array(obj) && obj.length === 0) { + const adjusted_prefix = commaRoundTrip && values_isArray(obj) && obj.length === 1 ? encoded_prefix + '[]' : encoded_prefix; + if (allowEmptyArrays && values_isArray(obj) && obj.length === 0) { return adjusted_prefix + '[]'; } for (let j = 0; j < obj_keys.length; ++j) { @@ -68676,7 +63178,7 @@ function inner_stringify(object, prefix, generateArrayPrefix, commaRoundTrip, al } // @ts-ignore const encoded_key = allowDots && encodeDotInKeys ? key.replace(/\./g, '%2E') : key; - const key_prefix = stringify_is_array(obj) ? + const key_prefix = values_isArray(obj) ? typeof generateArrayPrefix === 'function' ? generateArrayPrefix(adjusted_prefix, encoded_key) : adjusted_prefix @@ -68686,7 +63188,7 @@ function inner_stringify(object, prefix, generateArrayPrefix, commaRoundTrip, al valueSideChannel.set(sentinel, sideChannel); push_to_array(values, inner_stringify(value, key_prefix, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, // @ts-ignore - generateArrayPrefix === 'comma' && encodeValuesOnly && stringify_is_array(obj) ? null : encoder, filter, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, valueSideChannel)); + generateArrayPrefix === 'comma' && encodeValuesOnly && values_isArray(obj) ? null : encoder, filter, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, valueSideChannel)); } return values; } @@ -68700,745 +63202,155 @@ function normalize_stringify_options(opts = defaults) { if (opts.encoder !== null && typeof opts.encoder !== 'undefined' && typeof opts.encoder !== 'function') { throw new TypeError('Encoder has to be a function.'); } - const charset = opts.charset || defaults.charset; - if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') { - throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined'); - } - let format = default_format; - if (typeof opts.format !== 'undefined') { - if (!stringify_has.call(formatters, opts.format)) { - throw new TypeError('Unknown format option provided.'); - } - format = opts.format; - } - const formatter = formatters[format]; - let filter = defaults.filter; - if (typeof opts.filter === 'function' || stringify_is_array(opts.filter)) { - filter = opts.filter; - } - let arrayFormat; - if (opts.arrayFormat && opts.arrayFormat in array_prefix_generators) { - arrayFormat = opts.arrayFormat; - } - else if ('indices' in opts) { - arrayFormat = opts.indices ? 'indices' : 'repeat'; - } - else { - arrayFormat = defaults.arrayFormat; - } - if ('commaRoundTrip' in opts && typeof opts.commaRoundTrip !== 'boolean') { - throw new TypeError('`commaRoundTrip` must be a boolean, or absent'); - } - const allowDots = typeof opts.allowDots === 'undefined' ? - !!opts.encodeDotInKeys === true ? - true - : defaults.allowDots - : !!opts.allowDots; - return { - addQueryPrefix: typeof opts.addQueryPrefix === 'boolean' ? opts.addQueryPrefix : defaults.addQueryPrefix, - // @ts-ignore - allowDots: allowDots, - allowEmptyArrays: typeof opts.allowEmptyArrays === 'boolean' ? !!opts.allowEmptyArrays : defaults.allowEmptyArrays, - arrayFormat: arrayFormat, - charset: charset, - charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel, - commaRoundTrip: !!opts.commaRoundTrip, - delimiter: typeof opts.delimiter === 'undefined' ? defaults.delimiter : opts.delimiter, - encode: typeof opts.encode === 'boolean' ? opts.encode : defaults.encode, - encodeDotInKeys: typeof opts.encodeDotInKeys === 'boolean' ? opts.encodeDotInKeys : defaults.encodeDotInKeys, - encoder: typeof opts.encoder === 'function' ? opts.encoder : defaults.encoder, - encodeValuesOnly: typeof opts.encodeValuesOnly === 'boolean' ? opts.encodeValuesOnly : defaults.encodeValuesOnly, - filter: filter, - format: format, - formatter: formatter, - serializeDate: typeof opts.serializeDate === 'function' ? opts.serializeDate : defaults.serializeDate, - skipNulls: typeof opts.skipNulls === 'boolean' ? opts.skipNulls : defaults.skipNulls, - // @ts-ignore - sort: typeof opts.sort === 'function' ? opts.sort : null, - strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling, - }; -} -function stringify(object, opts = {}) { - let obj = object; - const options = normalize_stringify_options(opts); - let obj_keys; - let filter; - if (typeof options.filter === 'function') { - filter = options.filter; - obj = filter('', obj); - } - else if (stringify_is_array(options.filter)) { - filter = options.filter; - obj_keys = filter; - } - const keys = []; - if (typeof obj !== 'object' || obj === null) { - return ''; - } - const generateArrayPrefix = array_prefix_generators[options.arrayFormat]; - const commaRoundTrip = generateArrayPrefix === 'comma' && options.commaRoundTrip; - if (!obj_keys) { - obj_keys = Object.keys(obj); - } - if (options.sort) { - obj_keys.sort(options.sort); - } - const sideChannel = new WeakMap(); - for (let i = 0; i < obj_keys.length; ++i) { - const key = obj_keys[i]; - if (options.skipNulls && obj[key] === null) { - continue; - } - push_to_array(keys, inner_stringify(obj[key], key, - // @ts-expect-error - generateArrayPrefix, commaRoundTrip, options.allowEmptyArrays, options.strictNullHandling, options.skipNulls, options.encodeDotInKeys, options.encode ? options.encoder : null, options.filter, options.sort, options.allowDots, options.serializeDate, options.format, options.formatter, options.encodeValuesOnly, options.charset, sideChannel)); - } - const joined = keys.join(options.delimiter); - let prefix = options.addQueryPrefix === true ? '?' : ''; - if (options.charsetSentinel) { - if (options.charset === 'iso-8859-1') { - // encodeURIComponent('✓'), the "numeric entity" representation of a checkmark - prefix += 'utf8=%26%2310003%3B&'; - } - else { - // encodeURIComponent('✓') - prefix += 'utf8=%E2%9C%93&'; - } - } - return joined.length > 0 ? prefix + joined : ''; -} -//# sourceMappingURL=stringify.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/version.mjs -const VERSION = '4.98.0'; // x-release-please-version -//# sourceMappingURL=version.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_shims/registry.mjs -let auto = false; -let kind = undefined; -let registry_fetch = undefined; -let index_Request = (/* unused pure expression or super */ null && (undefined)); -let registry_Response = (/* unused pure expression or super */ null && (undefined)); -let registry_Headers = (/* unused pure expression or super */ null && (undefined)); -let registry_FormData = undefined; -let registry_Blob = (/* unused pure expression or super */ null && (undefined)); -let registry_File = undefined; -let registry_ReadableStream = undefined; -let registry_getMultipartRequestOptions = undefined; -let getDefaultAgent = undefined; -let fileFromPath = undefined; -let isFsReadStream = undefined; -function setShims(shims, options = { auto: false }) { - if (auto) { - throw new Error(`you must \`import 'openai/shims/${shims.kind}'\` before importing anything else from openai`); - } - if (kind) { - throw new Error(`can't \`import 'openai/shims/${shims.kind}'\` after \`import 'openai/shims/${kind}'\``); - } - auto = options.auto; - kind = shims.kind; - registry_fetch = shims.fetch; - index_Request = shims.Request; - registry_Response = shims.Response; - registry_Headers = shims.Headers; - registry_FormData = shims.FormData; - registry_Blob = shims.Blob; - registry_File = shims.File; - registry_ReadableStream = shims.ReadableStream; - registry_getMultipartRequestOptions = shims.getMultipartRequestOptions; - getDefaultAgent = shims.getDefaultAgent; - fileFromPath = shims.fileFromPath; - isFsReadStream = shims.isFsReadStream; -} -//# sourceMappingURL=registry.mjs.map -// EXTERNAL MODULE: ./node_modules/node-fetch/lib/index.js -var lib = __nccwpck_require__(6705); -// EXTERNAL MODULE: external "util" -var external_util_ = __nccwpck_require__(9023); -// EXTERNAL MODULE: ./node_modules/formdata-node/lib/esm/File.js -var esm_File = __nccwpck_require__(2928); -// EXTERNAL MODULE: ./node_modules/formdata-node/lib/esm/isFile.js -var isFile = __nccwpck_require__(928); -// EXTERNAL MODULE: ./node_modules/formdata-node/lib/esm/Blob.js + 2 modules -var esm_Blob = __nccwpck_require__(6220); -;// CONCATENATED MODULE: ./node_modules/formdata-node/lib/esm/isBlob.js - -const isBlob = (value) => value instanceof esm_Blob/* Blob */.Y; - -// EXTERNAL MODULE: ./node_modules/formdata-node/lib/esm/isFunction.js -var isFunction = __nccwpck_require__(5122); -;// CONCATENATED MODULE: ./node_modules/formdata-node/lib/esm/deprecateConstructorEntries.js - -const deprecateConstructorEntries = (0,external_util_.deprecate)(() => { }, "Constructor \"entries\" argument is not spec-compliant " - + "and will be removed in next major release."); - -;// CONCATENATED MODULE: ./node_modules/formdata-node/lib/esm/FormData.js -var __classPrivateFieldGet = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) { - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); -}; -var _FormData_instances, _FormData_entries, _FormData_setEntry; - - - - - - -class FormData_FormData { - constructor(entries) { - _FormData_instances.add(this); - _FormData_entries.set(this, new Map()); - if (entries) { - deprecateConstructorEntries(); - entries.forEach(({ name, value, fileName }) => this.append(name, value, fileName)); - } - } - static [(_FormData_entries = new WeakMap(), _FormData_instances = new WeakSet(), Symbol.hasInstance)](value) { - return Boolean(value - && (0,isFunction/* isFunction */.T)(value.constructor) - && value[Symbol.toStringTag] === "FormData" - && (0,isFunction/* isFunction */.T)(value.append) - && (0,isFunction/* isFunction */.T)(value.set) - && (0,isFunction/* isFunction */.T)(value.get) - && (0,isFunction/* isFunction */.T)(value.getAll) - && (0,isFunction/* isFunction */.T)(value.has) - && (0,isFunction/* isFunction */.T)(value.delete) - && (0,isFunction/* isFunction */.T)(value.entries) - && (0,isFunction/* isFunction */.T)(value.values) - && (0,isFunction/* isFunction */.T)(value.keys) - && (0,isFunction/* isFunction */.T)(value[Symbol.iterator]) - && (0,isFunction/* isFunction */.T)(value.forEach)); - } - append(name, value, fileName) { - __classPrivateFieldGet(this, _FormData_instances, "m", _FormData_setEntry).call(this, { - name, - fileName, - append: true, - rawValue: value, - argsLength: arguments.length - }); - } - set(name, value, fileName) { - __classPrivateFieldGet(this, _FormData_instances, "m", _FormData_setEntry).call(this, { - name, - fileName, - append: false, - rawValue: value, - argsLength: arguments.length - }); - } - get(name) { - const field = __classPrivateFieldGet(this, _FormData_entries, "f").get(String(name)); - if (!field) { - return null; - } - return field[0]; - } - getAll(name) { - const field = __classPrivateFieldGet(this, _FormData_entries, "f").get(String(name)); - if (!field) { - return []; - } - return field.slice(); - } - has(name) { - return __classPrivateFieldGet(this, _FormData_entries, "f").has(String(name)); - } - delete(name) { - __classPrivateFieldGet(this, _FormData_entries, "f").delete(String(name)); - } - *keys() { - for (const key of __classPrivateFieldGet(this, _FormData_entries, "f").keys()) { - yield key; - } - } - *entries() { - for (const name of this.keys()) { - const values = this.getAll(name); - for (const value of values) { - yield [name, value]; - } - } - } - *values() { - for (const [, value] of this) { - yield value; - } - } - [(_FormData_setEntry = function _FormData_setEntry({ name, rawValue, append, fileName, argsLength }) { - const methodName = append ? "append" : "set"; - if (argsLength < 2) { - throw new TypeError(`Failed to execute '${methodName}' on 'FormData': ` - + `2 arguments required, but only ${argsLength} present.`); - } - name = String(name); - let value; - if ((0,isFile/* isFile */.f)(rawValue)) { - value = fileName === undefined - ? rawValue - : new esm_File/* File */.Z([rawValue], fileName, { - type: rawValue.type, - lastModified: rawValue.lastModified - }); - } - else if (isBlob(rawValue)) { - value = new esm_File/* File */.Z([rawValue], fileName === undefined ? "blob" : fileName, { - type: rawValue.type - }); - } - else if (fileName) { - throw new TypeError(`Failed to execute '${methodName}' on 'FormData': ` - + "parameter 2 is not of type 'Blob'."); - } - else { - value = String(rawValue); - } - const values = __classPrivateFieldGet(this, _FormData_entries, "f").get(name); - if (!values) { - return void __classPrivateFieldGet(this, _FormData_entries, "f").set(name, [value]); - } - if (!append) { - return void __classPrivateFieldGet(this, _FormData_entries, "f").set(name, [value]); - } - values.push(value); - }, Symbol.iterator)]() { - return this.entries(); - } - forEach(callback, thisArg) { - for (const [name, value] of this) { - callback.call(thisArg, value, name, this); - } - } - get [Symbol.toStringTag]() { - return "FormData"; - } - [external_util_.inspect.custom]() { - return this[Symbol.toStringTag]; - } -} - -;// CONCATENATED MODULE: ./node_modules/formdata-node/lib/esm/index.js - - - - -// EXTERNAL MODULE: ./node_modules/agentkeepalive/index.js -var agentkeepalive = __nccwpck_require__(3873); -// EXTERNAL MODULE: ./node_modules/abort-controller/dist/abort-controller.js -var abort_controller = __nccwpck_require__(7413); -;// CONCATENATED MODULE: external "node:fs" -const external_node_fs_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:fs"); -;// CONCATENATED MODULE: ./node_modules/form-data-encoder/lib/esm/util/createBoundary.js -const alphabet = "abcdefghijklmnopqrstuvwxyz0123456789"; -function createBoundary() { - let size = 16; - let res = ""; - while (size--) { - res += alphabet[(Math.random() * alphabet.length) << 0]; - } - return res; -} -/* harmony default export */ const util_createBoundary = (createBoundary); - -;// CONCATENATED MODULE: ./node_modules/form-data-encoder/lib/esm/util/isPlainObject.js -const getType = (value) => (Object.prototype.toString.call(value).slice(8, -1).toLowerCase()); -function isPlainObject(value) { - if (getType(value) !== "object") { - return false; - } - const pp = Object.getPrototypeOf(value); - if (pp === null || pp === undefined) { - return true; - } - const Ctor = pp.constructor && pp.constructor.toString(); - return Ctor === Object.toString(); -} -/* harmony default export */ const util_isPlainObject = (isPlainObject); - -;// CONCATENATED MODULE: ./node_modules/form-data-encoder/lib/esm/util/normalizeValue.js -const normalizeValue = (value) => String(value) - .replace(/\r|\n/g, (match, i, str) => { - if ((match === "\r" && str[i + 1] !== "\n") - || (match === "\n" && str[i - 1] !== "\r")) { - return "\r\n"; - } - return match; -}); -/* harmony default export */ const util_normalizeValue = (normalizeValue); - -;// CONCATENATED MODULE: ./node_modules/form-data-encoder/lib/esm/util/escapeName.js -const escapeName = (name) => String(name) - .replace(/\r/g, "%0D") - .replace(/\n/g, "%0A") - .replace(/"/g, "%22"); -/* harmony default export */ const util_escapeName = (escapeName); - -;// CONCATENATED MODULE: ./node_modules/form-data-encoder/lib/esm/util/isFunction.js -const isFunction_isFunction = (value) => (typeof value === "function"); -/* harmony default export */ const util_isFunction = (isFunction_isFunction); - -;// CONCATENATED MODULE: ./node_modules/form-data-encoder/lib/esm/util/isFileLike.js - -const isFileLike = (value) => Boolean(value - && typeof value === "object" - && util_isFunction(value.constructor) - && value[Symbol.toStringTag] === "File" - && util_isFunction(value.stream) - && value.name != null - && value.size != null - && value.lastModified != null); - -;// CONCATENATED MODULE: ./node_modules/form-data-encoder/lib/esm/util/isFormData.js - -const isFormData = (value) => Boolean(value - && util_isFunction(value.constructor) - && value[Symbol.toStringTag] === "FormData" - && util_isFunction(value.append) - && util_isFunction(value.getAll) - && util_isFunction(value.entries) - && util_isFunction(value[Symbol.iterator])); -const isFormDataLike = (/* unused pure expression or super */ null && (isFormData)); - -;// CONCATENATED MODULE: ./node_modules/form-data-encoder/lib/esm/FormDataEncoder.js -var __classPrivateFieldSet = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { - if (kind === "m") throw new TypeError("Private method is not writable"); - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); - return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; -}; -var FormDataEncoder_classPrivateFieldGet = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) { - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); -}; -var _FormDataEncoder_instances, _FormDataEncoder_CRLF, _FormDataEncoder_CRLF_BYTES, _FormDataEncoder_CRLF_BYTES_LENGTH, _FormDataEncoder_DASHES, _FormDataEncoder_encoder, _FormDataEncoder_footer, _FormDataEncoder_form, _FormDataEncoder_options, _FormDataEncoder_getFieldHeader; - - - - - - -const defaultOptions = { - enableAdditionalHeaders: false -}; -class FormDataEncoder { - constructor(form, boundaryOrOptions, options) { - _FormDataEncoder_instances.add(this); - _FormDataEncoder_CRLF.set(this, "\r\n"); - _FormDataEncoder_CRLF_BYTES.set(this, void 0); - _FormDataEncoder_CRLF_BYTES_LENGTH.set(this, void 0); - _FormDataEncoder_DASHES.set(this, "-".repeat(2)); - _FormDataEncoder_encoder.set(this, new TextEncoder()); - _FormDataEncoder_footer.set(this, void 0); - _FormDataEncoder_form.set(this, void 0); - _FormDataEncoder_options.set(this, void 0); - if (!isFormData(form)) { - throw new TypeError("Expected first argument to be a FormData instance."); - } - let boundary; - if (util_isPlainObject(boundaryOrOptions)) { - options = boundaryOrOptions; - } - else { - boundary = boundaryOrOptions; - } - if (!boundary) { - boundary = util_createBoundary(); - } - if (typeof boundary !== "string") { - throw new TypeError("Expected boundary argument to be a string."); - } - if (options && !util_isPlainObject(options)) { - throw new TypeError("Expected options argument to be an object."); - } - __classPrivateFieldSet(this, _FormDataEncoder_form, form, "f"); - __classPrivateFieldSet(this, _FormDataEncoder_options, { ...defaultOptions, ...options }, "f"); - __classPrivateFieldSet(this, _FormDataEncoder_CRLF_BYTES, FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_encoder, "f").encode(FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_CRLF, "f")), "f"); - __classPrivateFieldSet(this, _FormDataEncoder_CRLF_BYTES_LENGTH, FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_CRLF_BYTES, "f").byteLength, "f"); - this.boundary = `form-data-boundary-${boundary}`; - this.contentType = `multipart/form-data; boundary=${this.boundary}`; - __classPrivateFieldSet(this, _FormDataEncoder_footer, FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_encoder, "f").encode(`${FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_DASHES, "f")}${this.boundary}${FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_DASHES, "f")}${FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_CRLF, "f").repeat(2)}`), "f"); - this.contentLength = String(this.getContentLength()); - this.headers = Object.freeze({ - "Content-Type": this.contentType, - "Content-Length": this.contentLength - }); - Object.defineProperties(this, { - boundary: { writable: false, configurable: false }, - contentType: { writable: false, configurable: false }, - contentLength: { writable: false, configurable: false }, - headers: { writable: false, configurable: false } - }); - } - getContentLength() { - let length = 0; - for (const [name, raw] of FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_form, "f")) { - const value = isFileLike(raw) ? raw : FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_encoder, "f").encode(util_normalizeValue(raw)); - length += FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_instances, "m", _FormDataEncoder_getFieldHeader).call(this, name, value).byteLength; - length += isFileLike(value) ? value.size : value.byteLength; - length += FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_CRLF_BYTES_LENGTH, "f"); - } - return length + FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_footer, "f").byteLength; - } - *values() { - for (const [name, raw] of FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_form, "f").entries()) { - const value = isFileLike(raw) ? raw : FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_encoder, "f").encode(util_normalizeValue(raw)); - yield FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_instances, "m", _FormDataEncoder_getFieldHeader).call(this, name, value); - yield value; - yield FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_CRLF_BYTES, "f"); - } - yield FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_footer, "f"); - } - async *encode() { - for (const part of this.values()) { - if (isFileLike(part)) { - yield* part.stream(); - } - else { - yield part; - } - } + const charset = opts.charset || defaults.charset; + if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') { + throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined'); } - [(_FormDataEncoder_CRLF = new WeakMap(), _FormDataEncoder_CRLF_BYTES = new WeakMap(), _FormDataEncoder_CRLF_BYTES_LENGTH = new WeakMap(), _FormDataEncoder_DASHES = new WeakMap(), _FormDataEncoder_encoder = new WeakMap(), _FormDataEncoder_footer = new WeakMap(), _FormDataEncoder_form = new WeakMap(), _FormDataEncoder_options = new WeakMap(), _FormDataEncoder_instances = new WeakSet(), _FormDataEncoder_getFieldHeader = function _FormDataEncoder_getFieldHeader(name, value) { - let header = ""; - header += `${FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_DASHES, "f")}${this.boundary}${FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_CRLF, "f")}`; - header += `Content-Disposition: form-data; name="${util_escapeName(name)}"`; - if (isFileLike(value)) { - header += `; filename="${util_escapeName(value.name)}"${FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_CRLF, "f")}`; - header += `Content-Type: ${value.type || "application/octet-stream"}`; - } - if (FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_options, "f").enableAdditionalHeaders === true) { - header += `${FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_CRLF, "f")}Content-Length: ${isFileLike(value) ? value.size : value.byteLength}`; + let format = default_format; + if (typeof opts.format !== 'undefined') { + if (!has(formatters, opts.format)) { + throw new TypeError('Unknown format option provided.'); } - return FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_encoder, "f").encode(`${header}${FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_CRLF, "f").repeat(2)}`); - }, Symbol.iterator)]() { - return this.values(); + format = opts.format; } - [Symbol.asyncIterator]() { - return this.encode(); + const formatter = formatters[format]; + let filter = defaults.filter; + if (typeof opts.filter === 'function' || values_isArray(opts.filter)) { + filter = opts.filter; } -} -const Encoder = (/* unused pure expression or super */ null && (FormDataEncoder)); - -;// CONCATENATED MODULE: ./node_modules/form-data-encoder/lib/esm/index.js - - - - - - -// EXTERNAL MODULE: external "node:stream" -var external_node_stream_ = __nccwpck_require__(7075); -;// CONCATENATED MODULE: ./node_modules/openai/_shims/MultipartBody.mjs -/** - * Disclaimer: modules in _shims aren't intended to be imported by SDK users. - */ -class MultipartBody { - constructor(body) { - this.body = body; + let arrayFormat; + if (opts.arrayFormat && opts.arrayFormat in array_prefix_generators) { + arrayFormat = opts.arrayFormat; } - get [Symbol.toStringTag]() { - return 'MultipartBody'; + else if ('indices' in opts) { + arrayFormat = opts.indices ? 'indices' : 'repeat'; } -} -//# sourceMappingURL=MultipartBody.mjs.map -;// CONCATENATED MODULE: external "node:stream/web" -const web_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:stream/web"); -;// CONCATENATED MODULE: ./node_modules/openai/_shims/node-runtime.mjs - - - - - - - - - -let fileFromPathWarned = false; -async function node_runtime_fileFromPath(path, ...args) { - // this import fails in environments that don't handle export maps correctly, like old versions of Jest - const { fileFromPath: _fileFromPath } = await __nccwpck_require__.e(/* import() */ 33).then(__nccwpck_require__.bind(__nccwpck_require__, 2033)); - if (!fileFromPathWarned) { - console.warn(`fileFromPath is deprecated; use fs.createReadStream(${JSON.stringify(path)}) instead`); - fileFromPathWarned = true; + else { + arrayFormat = defaults.arrayFormat; } - // @ts-ignore - return await _fileFromPath(path, ...args); -} -const defaultHttpAgent = new agentkeepalive({ keepAlive: true, timeout: 5 * 60 * 1000 }); -const defaultHttpsAgent = new agentkeepalive.HttpsAgent({ keepAlive: true, timeout: 5 * 60 * 1000 }); -async function node_runtime_getMultipartRequestOptions(form, opts) { - const encoder = new FormDataEncoder(form); - const readable = external_node_stream_.Readable.from(encoder); - const body = new MultipartBody(readable); - const headers = { - ...opts.headers, - ...encoder.headers, - 'Content-Length': encoder.contentLength, - }; - return { ...opts, body: body, headers }; -} -function getRuntime() { - // Polyfill global object if needed. - if (typeof AbortController === 'undefined') { - // @ts-expect-error (the types are subtly different, but compatible in practice) - globalThis.AbortController = abort_controller.AbortController; + if ('commaRoundTrip' in opts && typeof opts.commaRoundTrip !== 'boolean') { + throw new TypeError('`commaRoundTrip` must be a boolean, or absent'); } + const allowDots = typeof opts.allowDots === 'undefined' ? + !!opts.encodeDotInKeys === true ? + true + : defaults.allowDots + : !!opts.allowDots; return { - kind: 'node', - fetch: lib, - Request: lib.Request, - Response: lib.Response, - Headers: lib.Headers, - FormData: FormData_FormData, - Blob: esm_Blob/* Blob */.Y, - File: esm_File/* File */.Z, - ReadableStream: web_namespaceObject.ReadableStream, - getMultipartRequestOptions: node_runtime_getMultipartRequestOptions, - getDefaultAgent: (url) => (url.startsWith('https') ? defaultHttpsAgent : defaultHttpAgent), - fileFromPath: node_runtime_fileFromPath, - isFsReadStream: (value) => value instanceof external_node_fs_namespaceObject.ReadStream, + addQueryPrefix: typeof opts.addQueryPrefix === 'boolean' ? opts.addQueryPrefix : defaults.addQueryPrefix, + // @ts-ignore + allowDots: allowDots, + allowEmptyArrays: typeof opts.allowEmptyArrays === 'boolean' ? !!opts.allowEmptyArrays : defaults.allowEmptyArrays, + arrayFormat: arrayFormat, + charset: charset, + charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel, + commaRoundTrip: !!opts.commaRoundTrip, + delimiter: typeof opts.delimiter === 'undefined' ? defaults.delimiter : opts.delimiter, + encode: typeof opts.encode === 'boolean' ? opts.encode : defaults.encode, + encodeDotInKeys: typeof opts.encodeDotInKeys === 'boolean' ? opts.encodeDotInKeys : defaults.encodeDotInKeys, + encoder: typeof opts.encoder === 'function' ? opts.encoder : defaults.encoder, + encodeValuesOnly: typeof opts.encodeValuesOnly === 'boolean' ? opts.encodeValuesOnly : defaults.encodeValuesOnly, + filter: filter, + format: format, + formatter: formatter, + serializeDate: typeof opts.serializeDate === 'function' ? opts.serializeDate : defaults.serializeDate, + skipNulls: typeof opts.skipNulls === 'boolean' ? opts.skipNulls : defaults.skipNulls, + // @ts-ignore + sort: typeof opts.sort === 'function' ? opts.sort : null, + strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling, }; } -//# sourceMappingURL=node-runtime.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_shims/index.mjs -/** - * Disclaimer: modules in _shims aren't intended to be imported by SDK users. - */ - - -const init = () => { - if (!kind) setShims(getRuntime(), { auto: true }); -}; - - -init(); - -;// CONCATENATED MODULE: ./node_modules/openai/error.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -class error_OpenAIError extends Error { -} -class APIError extends error_OpenAIError { - constructor(status, error, message, headers) { - super(`${APIError.makeMessage(status, error, message)}`); - this.status = status; - this.headers = headers; - this.request_id = headers?.['x-request-id']; - this.error = error; - const data = error; - this.code = data?.['code']; - this.param = data?.['param']; - this.type = data?.['type']; +function stringify(object, opts = {}) { + let obj = object; + const options = normalize_stringify_options(opts); + let obj_keys; + let filter; + if (typeof options.filter === 'function') { + filter = options.filter; + obj = filter('', obj); } - static makeMessage(status, error, message) { - const msg = error?.message ? - typeof error.message === 'string' ? - error.message - : JSON.stringify(error.message) - : error ? JSON.stringify(error) - : message; - if (status && msg) { - return `${status} ${msg}`; - } - if (status) { - return `${status} status code (no body)`; - } - if (msg) { - return msg; - } - return '(no status code or body)'; + else if (values_isArray(options.filter)) { + filter = options.filter; + obj_keys = filter; } - static generate(status, errorResponse, message, headers) { - if (!status || !headers) { - return new APIConnectionError({ message, cause: castToError(errorResponse) }); - } - const error = errorResponse?.['error']; - if (status === 400) { - return new BadRequestError(status, error, message, headers); - } - if (status === 401) { - return new AuthenticationError(status, error, message, headers); - } - if (status === 403) { - return new PermissionDeniedError(status, error, message, headers); - } - if (status === 404) { - return new NotFoundError(status, error, message, headers); - } - if (status === 409) { - return new ConflictError(status, error, message, headers); - } - if (status === 422) { - return new UnprocessableEntityError(status, error, message, headers); + const keys = []; + if (typeof obj !== 'object' || obj === null) { + return ''; + } + const generateArrayPrefix = array_prefix_generators[options.arrayFormat]; + const commaRoundTrip = generateArrayPrefix === 'comma' && options.commaRoundTrip; + if (!obj_keys) { + obj_keys = Object.keys(obj); + } + if (options.sort) { + obj_keys.sort(options.sort); + } + const sideChannel = new WeakMap(); + for (let i = 0; i < obj_keys.length; ++i) { + const key = obj_keys[i]; + if (options.skipNulls && obj[key] === null) { + continue; } - if (status === 429) { - return new RateLimitError(status, error, message, headers); + push_to_array(keys, inner_stringify(obj[key], key, + // @ts-expect-error + generateArrayPrefix, commaRoundTrip, options.allowEmptyArrays, options.strictNullHandling, options.skipNulls, options.encodeDotInKeys, options.encode ? options.encoder : null, options.filter, options.sort, options.allowDots, options.serializeDate, options.format, options.formatter, options.encodeValuesOnly, options.charset, sideChannel)); + } + const joined = keys.join(options.delimiter); + let prefix = options.addQueryPrefix === true ? '?' : ''; + if (options.charsetSentinel) { + if (options.charset === 'iso-8859-1') { + // encodeURIComponent('✓'), the "numeric entity" representation of a checkmark + prefix += 'utf8=%26%2310003%3B&'; } - if (status >= 500) { - return new InternalServerError(status, error, message, headers); + else { + // encodeURIComponent('✓') + prefix += 'utf8=%E2%9C%93&'; } - return new APIError(status, error, message, headers); - } -} -class APIUserAbortError extends APIError { - constructor({ message } = {}) { - super(undefined, undefined, message || 'Request was aborted.', undefined); } + return joined.length > 0 ? prefix + joined : ''; } -class APIConnectionError extends APIError { - constructor({ message, cause }) { - super(undefined, undefined, message || 'Connection error.', undefined); - // in some environments the 'cause' property is already declared - // @ts-ignore - if (cause) - this.cause = cause; +//# sourceMappingURL=stringify.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/internal/qs/index.mjs + +const formats = { + formatters: formatters, + RFC1738: RFC1738, + RFC3986: RFC3986, + default: default_format, +}; + + +//# sourceMappingURL=index.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/internal/utils/bytes.mjs +function concatBytes(buffers) { + let length = 0; + for (const buffer of buffers) { + length += buffer.length; } -} -class APIConnectionTimeoutError extends APIConnectionError { - constructor({ message } = {}) { - super({ message: message ?? 'Request timed out.' }); + const output = new Uint8Array(length); + let index = 0; + for (const buffer of buffers) { + output.set(buffer, index); + index += buffer.length; } + return output; } -class BadRequestError extends APIError { -} -class AuthenticationError extends APIError { -} -class PermissionDeniedError extends APIError { -} -class NotFoundError extends APIError { -} -class ConflictError extends APIError { -} -class UnprocessableEntityError extends APIError { -} -class RateLimitError extends APIError { -} -class InternalServerError extends APIError { -} -class LengthFinishReasonError extends error_OpenAIError { - constructor() { - super(`Could not parse response content as the length limit was reached`); - } +let encodeUTF8_; +function bytes_encodeUTF8(str) { + let encoder; + return (encodeUTF8_ ?? + ((encoder = new globalThis.TextEncoder()), (encodeUTF8_ = encoder.encode.bind(encoder))))(str); } -class ContentFilterFinishReasonError extends error_OpenAIError { - constructor() { - super(`Could not parse response content as the request was rejected by the content filter`); - } +let decodeUTF8_; +function decodeUTF8(bytes) { + let decoder; + return (decodeUTF8_ ?? + ((decoder = new globalThis.TextDecoder()), (decodeUTF8_ = decoder.decode.bind(decoder))))(bytes); } -//# sourceMappingURL=error.mjs.map +//# sourceMappingURL=bytes.mjs.map ;// CONCATENATED MODULE: ./node_modules/openai/internal/decoders/line.mjs -var line_classPrivateFieldSet = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { - if (kind === "m") throw new TypeError("Private method is not writable"); - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); - return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; -}; -var line_classPrivateFieldGet = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) { - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); -}; -var _LineDecoder_carriageReturnIndex; +var _LineDecoder_buffer, _LineDecoder_carriageReturnIndex; + /** * A re-implementation of httpx's `LineDecoder` in Python that handles incrementally @@ -69448,78 +63360,51 @@ var _LineDecoder_carriageReturnIndex; */ class LineDecoder { constructor() { + _LineDecoder_buffer.set(this, void 0); _LineDecoder_carriageReturnIndex.set(this, void 0); - this.buffer = new Uint8Array(); - line_classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, "f"); + __classPrivateFieldSet(this, _LineDecoder_buffer, new Uint8Array(), "f"); + __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, "f"); } decode(chunk) { if (chunk == null) { return []; } const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) - : typeof chunk === 'string' ? new TextEncoder().encode(chunk) + : typeof chunk === 'string' ? bytes_encodeUTF8(chunk) : chunk; - let newData = new Uint8Array(this.buffer.length + binaryChunk.length); - newData.set(this.buffer); - newData.set(binaryChunk, this.buffer.length); - this.buffer = newData; + __classPrivateFieldSet(this, _LineDecoder_buffer, concatBytes([__classPrivateFieldGet(this, _LineDecoder_buffer, "f"), binaryChunk]), "f"); const lines = []; let patternIndex; - while ((patternIndex = findNewlineIndex(this.buffer, line_classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f"))) != null) { - if (patternIndex.carriage && line_classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") == null) { + while ((patternIndex = findNewlineIndex(__classPrivateFieldGet(this, _LineDecoder_buffer, "f"), __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f"))) != null) { + if (patternIndex.carriage && __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") == null) { // skip until we either get a corresponding `\n`, a new `\r` or nothing - line_classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, patternIndex.index, "f"); + __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, patternIndex.index, "f"); continue; } // we got double \r or \rtext\n - if (line_classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") != null && - (patternIndex.index !== line_classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") + 1 || patternIndex.carriage)) { - lines.push(this.decodeText(this.buffer.slice(0, line_classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") - 1))); - this.buffer = this.buffer.slice(line_classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f")); - line_classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, "f"); + if (__classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") != null && + (patternIndex.index !== __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") + 1 || patternIndex.carriage)) { + lines.push(decodeUTF8(__classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(0, __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") - 1))); + __classPrivateFieldSet(this, _LineDecoder_buffer, __classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(__classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f")), "f"); + __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, "f"); continue; } - const endIndex = line_classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") !== null ? patternIndex.preceding - 1 : patternIndex.preceding; - const line = this.decodeText(this.buffer.slice(0, endIndex)); + const endIndex = __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") !== null ? patternIndex.preceding - 1 : patternIndex.preceding; + const line = decodeUTF8(__classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(0, endIndex)); lines.push(line); - this.buffer = this.buffer.slice(patternIndex.index); - line_classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, "f"); + __classPrivateFieldSet(this, _LineDecoder_buffer, __classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(patternIndex.index), "f"); + __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, "f"); } return lines; } - decodeText(bytes) { - if (bytes == null) - return ''; - if (typeof bytes === 'string') - return bytes; - // Node: - if (typeof Buffer !== 'undefined') { - if (bytes instanceof Buffer) { - return bytes.toString(); - } - if (bytes instanceof Uint8Array) { - return Buffer.from(bytes).toString(); - } - throw new error_OpenAIError(`Unexpected: received non-Uint8Array (${bytes.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`); - } - // Browser - if (typeof TextDecoder !== 'undefined') { - if (bytes instanceof Uint8Array || bytes instanceof ArrayBuffer) { - this.textDecoder ?? (this.textDecoder = new TextDecoder('utf8')); - return this.textDecoder.decode(bytes); - } - throw new error_OpenAIError(`Unexpected: received non-Uint8Array/ArrayBuffer (${bytes.constructor.name}) in a web platform. Please report this error.`); - } - throw new error_OpenAIError(`Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.`); - } flush() { - if (!this.buffer.length) { + if (!__classPrivateFieldGet(this, _LineDecoder_buffer, "f").length) { return []; } return this.decode('\n'); } } -_LineDecoder_carriageReturnIndex = new WeakMap(); +_LineDecoder_buffer = new WeakMap(), _LineDecoder_carriageReturnIndex = new WeakMap(); // prettier-ignore LineDecoder.NEWLINE_CHARS = new Set(['\n', '\r']); LineDecoder.NEWLINE_REGEXP = /\r\n|[\n\r]/g; @@ -69572,43 +63457,91 @@ function findDoubleNewlineIndex(buffer) { return -1; } //# sourceMappingURL=line.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/internal/stream-utils.mjs -/** - * Most browsers don't yet have async iterable support for ReadableStream, - * and Node has a very different way of reading bytes from its "ReadableStream". - * - * This polyfill was pulled from https://github.com/MattiasBuelens/web-streams-polyfill/pull/122#issuecomment-1627354490 - */ -function ReadableStreamToAsyncIterable(stream) { - if (stream[Symbol.asyncIterator]) - return stream; - const reader = stream.getReader(); - return { - async next() { - try { - const result = await reader.read(); - if (result?.done) - reader.releaseLock(); // release lock when stream becomes closed - return result; - } - catch (e) { - reader.releaseLock(); // release lock when stream becomes errored - throw e; - } - }, - async return() { - const cancelPromise = reader.cancel(); - reader.releaseLock(); - await cancelPromise; - return { done: true, value: undefined }; - }, - [Symbol.asyncIterator]() { - return this; - }, +;// CONCATENATED MODULE: ./node_modules/openai/internal/utils/log.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +const levelNumbers = { + off: 0, + error: 200, + warn: 300, + info: 400, + debug: 500, +}; +const parseLogLevel = (maybeLevel, sourceName, client) => { + if (!maybeLevel) { + return undefined; + } + if (hasOwn(levelNumbers, maybeLevel)) { + return maybeLevel; + } + loggerFor(client).warn(`${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(Object.keys(levelNumbers))}`); + return undefined; +}; +function noop() { } +function makeLogFn(fnLevel, logger, logLevel) { + if (!logger || levelNumbers[fnLevel] > levelNumbers[logLevel]) { + return noop; + } + else { + // Don't wrap logger functions, we want the stacktrace intact! + return logger[fnLevel].bind(logger); + } +} +const noopLogger = { + error: noop, + warn: noop, + info: noop, + debug: noop, +}; +let cachedLoggers = /* @__PURE__ */ new WeakMap(); +function loggerFor(client) { + const logger = client.logger; + const logLevel = client.logLevel ?? 'off'; + if (!logger) { + return noopLogger; + } + const cachedLogger = cachedLoggers.get(logger); + if (cachedLogger && cachedLogger[0] === logLevel) { + return cachedLogger[1]; + } + const levelLogger = { + error: makeLogFn('error', logger, logLevel), + warn: makeLogFn('warn', logger, logLevel), + info: makeLogFn('info', logger, logLevel), + debug: makeLogFn('debug', logger, logLevel), }; + cachedLoggers.set(logger, [logLevel, levelLogger]); + return levelLogger; } -//# sourceMappingURL=stream-utils.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/streaming.mjs +const formatRequestDetails = (details) => { + if (details.options) { + details.options = { ...details.options }; + delete details.options['headers']; // redundant + leaks internals + } + if (details.headers) { + details.headers = Object.fromEntries((details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map(([name, value]) => [ + name, + (name.toLowerCase() === 'authorization' || + name.toLowerCase() === 'cookie' || + name.toLowerCase() === 'set-cookie') ? + '***' + : value, + ])); + } + if ('retryOfRequestLogID' in details) { + if (details.retryOfRequestLogID) { + details.retryOf = details.retryOfRequestLogID; + } + delete details.retryOfRequestLogID; + } + return details; +}; +//# sourceMappingURL=log.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/core/streaming.mjs +var _Stream_client; + + + @@ -69616,15 +63549,18 @@ function ReadableStreamToAsyncIterable(stream) { class Stream { - constructor(iterator, controller) { + constructor(iterator, controller, client) { this.iterator = iterator; + _Stream_client.set(this, void 0); this.controller = controller; + __classPrivateFieldSet(this, _Stream_client, client, "f"); } - static fromSSEResponse(response, controller) { + static fromSSEResponse(response, controller, client) { let consumed = false; + const logger = client ? loggerFor(client) : console; async function* iterator() { if (consumed) { - throw new Error('Cannot iterate over a consumed stream, use `.tee()` to split the stream.'); + throw new error_OpenAIError('Cannot iterate over a consumed stream, use `.tee()` to split the stream.'); } consumed = true; let done = false; @@ -69636,20 +63572,18 @@ class Stream { done = true; continue; } - if (sse.event === null || - sse.event.startsWith('response.') || - sse.event.startsWith('transcript.')) { + if (sse.event === null || !sse.event.startsWith('thread.')) { let data; try { data = JSON.parse(sse.data); } catch (e) { - console.error(`Could not parse message into JSON:`, sse.data); - console.error(`From chunk:`, sse.raw); + logger.error(`Could not parse message into JSON:`, sse.data); + logger.error(`From chunk:`, sse.raw); throw e; } if (data && data.error) { - throw new APIError(undefined, data.error, undefined, createResponseHeaders(response.headers)); + throw new APIError(undefined, data.error, undefined, response.headers); } yield data; } @@ -69674,7 +63608,7 @@ class Stream { } catch (e) { // If the user calls `stream.controller.abort()`, we should exit without throwing. - if (e instanceof Error && e.name === 'AbortError') + if (isAbortError(e)) return; throw e; } @@ -69684,13 +63618,13 @@ class Stream { controller.abort(); } } - return new Stream(iterator, controller); + return new Stream(iterator, controller, client); } /** * Generates a Stream from a newline-separated ReadableStream * where each item is a JSON value. */ - static fromReadableStream(readableStream, controller) { + static fromReadableStream(readableStream, controller, client) { let consumed = false; async function* iterLines() { const lineDecoder = new LineDecoder(); @@ -69706,7 +63640,7 @@ class Stream { } async function* iterator() { if (consumed) { - throw new Error('Cannot iterate over a consumed stream, use `.tee()` to split the stream.'); + throw new error_OpenAIError('Cannot iterate over a consumed stream, use `.tee()` to split the stream.'); } consumed = true; let done = false; @@ -69721,7 +63655,7 @@ class Stream { } catch (e) { // If the user calls `stream.controller.abort()`, we should exit without throwing. - if (e instanceof Error && e.name === 'AbortError') + if (isAbortError(e)) return; throw e; } @@ -69731,9 +63665,9 @@ class Stream { controller.abort(); } } - return new Stream(iterator, controller); + return new Stream(iterator, controller, client); } - [Symbol.asyncIterator]() { + [(_Stream_client = new WeakMap(), Symbol.asyncIterator)]() { return this.iterator(); } /** @@ -69757,8 +63691,8 @@ class Stream { }; }; return [ - new Stream(() => teeIterator(left), this.controller), - new Stream(() => teeIterator(right), this.controller), + new Stream(() => teeIterator(left), this.controller, __classPrivateFieldGet(this, _Stream_client, "f")), + new Stream(() => teeIterator(right), this.controller, __classPrivateFieldGet(this, _Stream_client, "f")), ]; } /** @@ -69769,8 +63703,7 @@ class Stream { toReadableStream() { const self = this; let iter; - const encoder = new TextEncoder(); - return new registry_ReadableStream({ + return makeReadableStream({ async start() { iter = self[Symbol.asyncIterator](); }, @@ -69779,7 +63712,7 @@ class Stream { const { value, done } = await iter.next(); if (done) return ctrl.close(); - const bytes = encoder.encode(JSON.stringify(value) + '\n'); + const bytes = bytes_encodeUTF8(JSON.stringify(value) + '\n'); ctrl.enqueue(bytes); } catch (err) { @@ -69795,6 +63728,10 @@ class Stream { async function* _iterSSEMessages(response, controller) { if (!response.body) { controller.abort(); + if (typeof globalThis.navigator !== 'undefined' && + globalThis.navigator.product === 'ReactNative') { + throw new error_OpenAIError(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`); + } throw new error_OpenAIError(`Attempted to iterate over a response with no body`); } const sseDecoder = new SSEDecoder(); @@ -69824,7 +63761,7 @@ async function* iterSSEChunks(iterator) { continue; } const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) - : typeof chunk === 'string' ? new TextEncoder().encode(chunk) + : typeof chunk === 'string' ? bytes_encodeUTF8(chunk) : chunk; let newData = new Uint8Array(data.length + binaryChunk.length); newData.set(data); @@ -69869,238 +63806,69 @@ class SSEDecoder { return null; } let [fieldname, _, value] = partition(line, ':'); - if (value.startsWith(' ')) { - value = value.substring(1); - } - if (fieldname === 'event') { - this.event = value; - } - else if (fieldname === 'data') { - this.data.push(value); - } - return null; - } -} -function partition(str, delimiter) { - const index = str.indexOf(delimiter); - if (index !== -1) { - return [str.substring(0, index), delimiter, str.substring(index + delimiter.length)]; - } - return [str, '', '']; -} -//# sourceMappingURL=streaming.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/uploads.mjs - - -const isResponseLike = (value) => value != null && - typeof value === 'object' && - typeof value.url === 'string' && - typeof value.blob === 'function'; -const uploads_isFileLike = (value) => value != null && - typeof value === 'object' && - typeof value.name === 'string' && - typeof value.lastModified === 'number' && - isBlobLike(value); -/** - * The BlobLike type omits arrayBuffer() because @types/node-fetch@^2.6.4 lacks it; but this check - * adds the arrayBuffer() method type because it is available and used at runtime - */ -const isBlobLike = (value) => value != null && - typeof value === 'object' && - typeof value.size === 'number' && - typeof value.type === 'string' && - typeof value.text === 'function' && - typeof value.slice === 'function' && - typeof value.arrayBuffer === 'function'; -const isUploadable = (value) => { - return uploads_isFileLike(value) || isResponseLike(value) || isFsReadStream(value); -}; -/** - * Helper for creating a {@link File} to pass to an SDK upload method from a variety of different data formats - * @param value the raw content of the file. Can be an {@link Uploadable}, {@link BlobLikePart}, or {@link AsyncIterable} of {@link BlobLikePart}s - * @param {string=} name the name of the file. If omitted, toFile will try to determine a file name from bits if possible - * @param {Object=} options additional properties - * @param {string=} options.type the MIME type of the content - * @param {number=} options.lastModified the last modified timestamp - * @returns a {@link File} with the given properties - */ -async function toFile(value, name, options) { - // If it's a promise, resolve it. - value = await value; - // If we've been given a `File` we don't need to do anything - if (uploads_isFileLike(value)) { - return value; - } - if (isResponseLike(value)) { - const blob = await value.blob(); - name || (name = new URL(value.url).pathname.split(/[\\/]/).pop() ?? 'unknown_file'); - // we need to convert the `Blob` into an array buffer because the `Blob` class - // that `node-fetch` defines is incompatible with the web standard which results - // in `new File` interpreting it as a string instead of binary data. - const data = isBlobLike(blob) ? [(await blob.arrayBuffer())] : [blob]; - return new registry_File(data, name, options); - } - const bits = await getBytes(value); - name || (name = getName(value) ?? 'unknown_file'); - if (!options?.type) { - const type = bits[0]?.type; - if (typeof type === 'string') { - options = { ...options, type }; - } - } - return new registry_File(bits, name, options); -} -async function getBytes(value) { - let parts = []; - if (typeof value === 'string' || - ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc. - value instanceof ArrayBuffer) { - parts.push(value); - } - else if (isBlobLike(value)) { - parts.push(await value.arrayBuffer()); - } - else if (isAsyncIterableIterator(value) // includes Readable, ReadableStream, etc. - ) { - for await (const chunk of value) { - parts.push(chunk); // TODO, consider validating? - } - } - else { - throw new Error(`Unexpected data type: ${typeof value}; constructor: ${value?.constructor - ?.name}; props: ${propsForError(value)}`); - } - return parts; -} -function propsForError(value) { - const props = Object.getOwnPropertyNames(value); - return `[${props.map((p) => `"${p}"`).join(', ')}]`; -} -function getName(value) { - return (getStringFromMaybeBuffer(value.name) || - getStringFromMaybeBuffer(value.filename) || - // For fs.ReadStream - getStringFromMaybeBuffer(value.path)?.split(/[\\/]/).pop()); -} -const getStringFromMaybeBuffer = (x) => { - if (typeof x === 'string') - return x; - if (typeof Buffer !== 'undefined' && x instanceof Buffer) - return String(x); - return undefined; -}; -const isAsyncIterableIterator = (value) => value != null && typeof value === 'object' && typeof value[Symbol.asyncIterator] === 'function'; -const isMultipartBody = (body) => body && typeof body === 'object' && body.body && body[Symbol.toStringTag] === 'MultipartBody'; -/** - * Returns a multipart/form-data request if any part of the given request body contains a File / Blob value. - * Otherwise returns the request as is. - */ -const maybeMultipartFormRequestOptions = async (opts) => { - if (!hasUploadableValue(opts.body)) - return opts; - const form = await createForm(opts.body); - return getMultipartRequestOptions(form, opts); -}; -const multipartFormRequestOptions = async (opts) => { - const form = await createForm(opts.body); - return registry_getMultipartRequestOptions(form, opts); -}; -const createForm = async (body) => { - const form = new registry_FormData(); - await Promise.all(Object.entries(body || {}).map(([key, value]) => addFormValue(form, key, value))); - return form; -}; -const hasUploadableValue = (value) => { - if (isUploadable(value)) - return true; - if (Array.isArray(value)) - return value.some(hasUploadableValue); - if (value && typeof value === 'object') { - for (const k in value) { - if (hasUploadableValue(value[k])) - return true; - } - } - return false; -}; -const addFormValue = async (form, key, value) => { - if (value === undefined) - return; - if (value == null) { - throw new TypeError(`Received null for "${key}"; to pass null in FormData, you must use the string 'null'`); - } - // TODO: make nested formats configurable - if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { - form.append(key, String(value)); - } - else if (isUploadable(value)) { - const file = await toFile(value); - form.append(key, file); - } - else if (Array.isArray(value)) { - await Promise.all(value.map((entry) => addFormValue(form, key + '[]', entry))); - } - else if (typeof value === 'object') { - await Promise.all(Object.entries(value).map(([name, prop]) => addFormValue(form, `${key}[${name}]`, prop))); + if (value.startsWith(' ')) { + value = value.substring(1); + } + if (fieldname === 'event') { + this.event = value; + } + else if (fieldname === 'data') { + this.data.push(value); + } + return null; } - else { - throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`); +} +function partition(str, delimiter) { + const index = str.indexOf(delimiter); + if (index !== -1) { + return [str.substring(0, index), delimiter, str.substring(index + delimiter.length)]; } -}; -//# sourceMappingURL=uploads.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/core.mjs -var core_classPrivateFieldSet = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { - if (kind === "m") throw new TypeError("Private method is not writable"); - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); - return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; -}; -var core_classPrivateFieldGet = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) { - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); -}; -var _AbstractPage_client; - - - - -// try running side effects outside of _shims/index to workaround https://github.com/vercel/next.js/issues/76881 -init(); + return [str, '', '']; +} +//# sourceMappingURL=streaming.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/internal/parse.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -async function defaultParseResponse(props) { - const { response } = props; - if (props.options.stream) { - debug('response', response.status, response.url, response.headers, response.body); - // Note: there is an invariant here that isn't represented in the type system - // that if you set `stream: true` the response type must also be `Stream` - if (props.options.__streamClass) { - return props.options.__streamClass.fromSSEResponse(response, props.controller); +async function defaultParseResponse(client, props) { + const { response, requestLogID, retryOfRequestLogID, startTime } = props; + const body = await (async () => { + if (props.options.stream) { + loggerFor(client).debug('response', response.status, response.url, response.headers, response.body); + // Note: there is an invariant here that isn't represented in the type system + // that if you set `stream: true` the response type must also be `Stream` + if (props.options.__streamClass) { + return props.options.__streamClass.fromSSEResponse(response, props.controller, client); + } + return Stream.fromSSEResponse(response, props.controller, client); } - return Stream.fromSSEResponse(response, props.controller); - } - // fetch refuses to read the body when the status code is 204. - if (response.status === 204) { - return null; - } - if (props.options.__binaryResponse) { - return response; - } - const contentType = response.headers.get('content-type'); - const mediaType = contentType?.split(';')[0]?.trim(); - const isJSON = mediaType?.includes('application/json') || mediaType?.endsWith('+json'); - if (isJSON) { - const json = await response.json(); - debug('response', response.status, response.url, response.headers, json); - return _addRequestID(json, response); - } - const text = await response.text(); - debug('response', response.status, response.url, response.headers, text); - // TODO handle blob, arraybuffer, other content types, etc. - return text; + // fetch refuses to read the body when the status code is 204. + if (response.status === 204) { + return null; + } + if (props.options.__binaryResponse) { + return response; + } + const contentType = response.headers.get('content-type'); + const mediaType = contentType?.split(';')[0]?.trim(); + const isJSON = mediaType?.includes('application/json') || mediaType?.endsWith('+json'); + if (isJSON) { + const json = await response.json(); + return addRequestID(json, response); + } + const text = await response.text(); + return text; + })(); + loggerFor(client).debug(`[${requestLogID}] response parsed`, formatRequestDetails({ + retryOfRequestLogID, + url: response.url, + status: response.status, + body, + durationMs: Date.now() - startTime, + })); + return body; } -function _addRequestID(value, response) { +function addRequestID(value, response) { if (!value || typeof value !== 'object' || Array.isArray(value)) { return value; } @@ -70109,12 +63877,18 @@ function _addRequestID(value, response) { enumerable: false, }); } +//# sourceMappingURL=parse.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/core/api-promise.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +var _APIPromise_client; + + /** * A subclass of `Promise` providing additional helper methods * for interacting with the SDK. */ class APIPromise extends Promise { - constructor(responsePromise, parseResponse = defaultParseResponse) { + constructor(client, responsePromise, parseResponse = defaultParseResponse) { super((resolve) => { // this is maybe a bit weird but this has to be a no-op to not implicitly // parse the response body; instead .then, .catch, .finally are overridden @@ -70123,9 +63897,11 @@ class APIPromise extends Promise { }); this.responsePromise = responsePromise; this.parseResponse = parseResponse; + _APIPromise_client.set(this, void 0); + __classPrivateFieldSet(this, _APIPromise_client, client, "f"); } _thenUnwrap(transform) { - return new APIPromise(this.responsePromise, async (props) => _addRequestID(transform(await this.parseResponse(props), props), props.response)); + return new APIPromise(__classPrivateFieldGet(this, _APIPromise_client, "f"), this.responsePromise, async (client, props) => addRequestID(transform(await this.parseResponse(client, props), props), props.response)); } /** * Gets the raw `Response` instance instead of parsing the response @@ -70135,10 +63911,8 @@ class APIPromise extends Promise { * instance, you can use {@link withResponse()}. * * 👋 Getting the wrong TypeScript type for `Response`? - * Try setting `"moduleResolution": "NodeNext"` if you can, - * or add one of these imports before your first `import … from 'openai'`: - * - `import 'openai/shims/node'` (if you're running on Node) - * - `import 'openai/shims/web'` (otherwise) + * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]` + * to your `tsconfig.json`. */ asResponse() { return this.responsePromise.then((p) => p.response); @@ -70151,12 +63925,9 @@ class APIPromise extends Promise { * If you just want to get the raw `Response` instance without parsing it, * you can use {@link asResponse()}. * - * * 👋 Getting the wrong TypeScript type for `Response`? - * Try setting `"moduleResolution": "NodeNext"` if you can, - * or add one of these imports before your first `import … from 'openai'`: - * - `import 'openai/shims/node'` (if you're running on Node) - * - `import 'openai/shims/web'` (otherwise) + * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]` + * to your `tsconfig.json`. */ async withResponse() { const [data, response] = await Promise.all([this.parse(), this.asResponse()]); @@ -70164,7 +63935,7 @@ class APIPromise extends Promise { } parse() { if (!this.parsedPromise) { - this.parsedPromise = this.responsePromise.then(this.parseResponse); + this.parsedPromise = this.responsePromise.then((data) => this.parseResponse(__classPrivateFieldGet(this, _APIPromise_client, "f"), data)); } return this.parsedPromise; } @@ -70178,341 +63949,20 @@ class APIPromise extends Promise { return this.parse().finally(onfinally); } } -class APIClient { - constructor({ baseURL, maxRetries = 2, timeout = 600000, // 10 minutes - httpAgent, fetch: overriddenFetch, }) { - this.baseURL = baseURL; - this.maxRetries = validatePositiveInteger('maxRetries', maxRetries); - this.timeout = validatePositiveInteger('timeout', timeout); - this.httpAgent = httpAgent; - this.fetch = overriddenFetch ?? registry_fetch; - } - authHeaders(opts) { - return {}; - } - /** - * Override this to add your own default headers, for example: - * - * { - * ...super.defaultHeaders(), - * Authorization: 'Bearer 123', - * } - */ - defaultHeaders(opts) { - return { - Accept: 'application/json', - 'Content-Type': 'application/json', - 'User-Agent': this.getUserAgent(), - ...getPlatformHeaders(), - ...this.authHeaders(opts), - }; - } - /** - * Override this to add your own headers validation: - */ - validateHeaders(headers, customHeaders) { } - defaultIdempotencyKey() { - return `stainless-node-retry-${uuid4()}`; - } - get(path, opts) { - return this.methodRequest('get', path, opts); - } - post(path, opts) { - return this.methodRequest('post', path, opts); - } - patch(path, opts) { - return this.methodRequest('patch', path, opts); - } - put(path, opts) { - return this.methodRequest('put', path, opts); - } - delete(path, opts) { - return this.methodRequest('delete', path, opts); - } - methodRequest(method, path, opts) { - return this.request(Promise.resolve(opts).then(async (opts) => { - const body = opts && isBlobLike(opts?.body) ? new DataView(await opts.body.arrayBuffer()) - : opts?.body instanceof DataView ? opts.body - : opts?.body instanceof ArrayBuffer ? new DataView(opts.body) - : opts && ArrayBuffer.isView(opts?.body) ? new DataView(opts.body.buffer) - : opts?.body; - return { method, path, ...opts, body }; - })); - } - getAPIList(path, Page, opts) { - return this.requestAPIList(Page, { method: 'get', path, ...opts }); - } - calculateContentLength(body) { - if (typeof body === 'string') { - if (typeof Buffer !== 'undefined') { - return Buffer.byteLength(body, 'utf8').toString(); - } - if (typeof TextEncoder !== 'undefined') { - const encoder = new TextEncoder(); - const encoded = encoder.encode(body); - return encoded.length.toString(); - } - } - else if (ArrayBuffer.isView(body)) { - return body.byteLength.toString(); - } - return null; - } - buildRequest(inputOptions, { retryCount = 0 } = {}) { - const options = { ...inputOptions }; - const { method, path, query, headers: headers = {} } = options; - const body = ArrayBuffer.isView(options.body) || (options.__binaryRequest && typeof options.body === 'string') ? - options.body - : isMultipartBody(options.body) ? options.body.body - : options.body ? JSON.stringify(options.body, null, 2) - : null; - const contentLength = this.calculateContentLength(body); - const url = this.buildURL(path, query); - if ('timeout' in options) - validatePositiveInteger('timeout', options.timeout); - options.timeout = options.timeout ?? this.timeout; - const httpAgent = options.httpAgent ?? this.httpAgent ?? getDefaultAgent(url); - const minAgentTimeout = options.timeout + 1000; - if (typeof httpAgent?.options?.timeout === 'number' && - minAgentTimeout > (httpAgent.options.timeout ?? 0)) { - // Allow any given request to bump our agent active socket timeout. - // This may seem strange, but leaking active sockets should be rare and not particularly problematic, - // and without mutating agent we would need to create more of them. - // This tradeoff optimizes for performance. - httpAgent.options.timeout = minAgentTimeout; - } - if (this.idempotencyHeader && method !== 'get') { - if (!inputOptions.idempotencyKey) - inputOptions.idempotencyKey = this.defaultIdempotencyKey(); - headers[this.idempotencyHeader] = inputOptions.idempotencyKey; - } - const reqHeaders = this.buildHeaders({ options, headers, contentLength, retryCount }); - const req = { - method, - ...(body && { body: body }), - headers: reqHeaders, - ...(httpAgent && { agent: httpAgent }), - // @ts-ignore node-fetch uses a custom AbortSignal type that is - // not compatible with standard web types - signal: options.signal ?? null, - }; - return { req, url, timeout: options.timeout }; - } - buildHeaders({ options, headers, contentLength, retryCount, }) { - const reqHeaders = {}; - if (contentLength) { - reqHeaders['content-length'] = contentLength; - } - const defaultHeaders = this.defaultHeaders(options); - applyHeadersMut(reqHeaders, defaultHeaders); - applyHeadersMut(reqHeaders, headers); - // let builtin fetch set the Content-Type for multipart bodies - if (isMultipartBody(options.body) && kind !== 'node') { - delete reqHeaders['content-type']; - } - // Don't set theses headers if they were already set or removed through default headers or by the caller. - // We check `defaultHeaders` and `headers`, which can contain nulls, instead of `reqHeaders` to account - // for the removal case. - if (getHeader(defaultHeaders, 'x-stainless-retry-count') === undefined && - getHeader(headers, 'x-stainless-retry-count') === undefined) { - reqHeaders['x-stainless-retry-count'] = String(retryCount); - } - if (getHeader(defaultHeaders, 'x-stainless-timeout') === undefined && - getHeader(headers, 'x-stainless-timeout') === undefined && - options.timeout) { - reqHeaders['x-stainless-timeout'] = String(Math.trunc(options.timeout / 1000)); - } - this.validateHeaders(reqHeaders, headers); - return reqHeaders; - } - /** - * Used as a callback for mutating the given `FinalRequestOptions` object. - */ - async prepareOptions(options) { } - /** - * Used as a callback for mutating the given `RequestInit` object. - * - * This is useful for cases where you want to add certain headers based off of - * the request properties, e.g. `method` or `url`. - */ - async prepareRequest(request, { url, options }) { } - parseHeaders(headers) { - return (!headers ? {} - : Symbol.iterator in headers ? - Object.fromEntries(Array.from(headers).map((header) => [...header])) - : { ...headers }); - } - makeStatusError(status, error, message, headers) { - return APIError.generate(status, error, message, headers); - } - request(options, remainingRetries = null) { - return new APIPromise(this.makeRequest(options, remainingRetries)); - } - async makeRequest(optionsInput, retriesRemaining) { - const options = await optionsInput; - const maxRetries = options.maxRetries ?? this.maxRetries; - if (retriesRemaining == null) { - retriesRemaining = maxRetries; - } - await this.prepareOptions(options); - const { req, url, timeout } = this.buildRequest(options, { retryCount: maxRetries - retriesRemaining }); - await this.prepareRequest(req, { url, options }); - debug('request', url, options, req.headers); - if (options.signal?.aborted) { - throw new APIUserAbortError(); - } - const controller = new AbortController(); - const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError); - if (response instanceof Error) { - if (options.signal?.aborted) { - throw new APIUserAbortError(); - } - if (retriesRemaining) { - return this.retryRequest(options, retriesRemaining); - } - if (response.name === 'AbortError') { - throw new APIConnectionTimeoutError(); - } - throw new APIConnectionError({ cause: response }); - } - const responseHeaders = createResponseHeaders(response.headers); - if (!response.ok) { - if (retriesRemaining && this.shouldRetry(response)) { - const retryMessage = `retrying, ${retriesRemaining} attempts remaining`; - debug(`response (error; ${retryMessage})`, response.status, url, responseHeaders); - return this.retryRequest(options, retriesRemaining, responseHeaders); - } - const errText = await response.text().catch((e) => castToError(e).message); - const errJSON = safeJSON(errText); - const errMessage = errJSON ? undefined : errText; - const retryMessage = retriesRemaining ? `(error; no more retries left)` : `(error; not retryable)`; - debug(`response (error; ${retryMessage})`, response.status, url, responseHeaders, errMessage); - const err = this.makeStatusError(response.status, errJSON, errMessage, responseHeaders); - throw err; - } - return { response, options, controller }; - } - requestAPIList(Page, options) { - const request = this.makeRequest(options, null); - return new PagePromise(this, request, Page); - } - buildURL(path, query) { - const url = isAbsoluteURL(path) ? - new URL(path) - : new URL(this.baseURL + (this.baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path)); - const defaultQuery = this.defaultQuery(); - if (!isEmptyObj(defaultQuery)) { - query = { ...defaultQuery, ...query }; - } - if (typeof query === 'object' && query && !Array.isArray(query)) { - url.search = this.stringifyQuery(query); - } - return url.toString(); - } - stringifyQuery(query) { - return Object.entries(query) - .filter(([_, value]) => typeof value !== 'undefined') - .map(([key, value]) => { - if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { - return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`; - } - if (value === null) { - return `${encodeURIComponent(key)}=`; - } - throw new error_OpenAIError(`Cannot stringify type ${typeof value}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`); - }) - .join('&'); - } - async fetchWithTimeout(url, init, ms, controller) { - const { signal, ...options } = init || {}; - if (signal) - signal.addEventListener('abort', () => controller.abort()); - const timeout = setTimeout(() => controller.abort(), ms); - const fetchOptions = { - signal: controller.signal, - ...options, - }; - if (fetchOptions.method) { - // Custom methods like 'patch' need to be uppercased - // See https://github.com/nodejs/undici/issues/2294 - fetchOptions.method = fetchOptions.method.toUpperCase(); - } - return ( - // use undefined this binding; fetch errors if bound to something else in browser/cloudflare - this.fetch.call(undefined, url, fetchOptions).finally(() => { - clearTimeout(timeout); - })); - } - shouldRetry(response) { - // Note this is not a standard header. - const shouldRetryHeader = response.headers.get('x-should-retry'); - // If the server explicitly says whether or not to retry, obey. - if (shouldRetryHeader === 'true') - return true; - if (shouldRetryHeader === 'false') - return false; - // Retry on request timeouts. - if (response.status === 408) - return true; - // Retry on lock timeouts. - if (response.status === 409) - return true; - // Retry on rate limits. - if (response.status === 429) - return true; - // Retry internal errors. - if (response.status >= 500) - return true; - return false; - } - async retryRequest(options, retriesRemaining, responseHeaders) { - let timeoutMillis; - // Note the `retry-after-ms` header may not be standard, but is a good idea and we'd like proactive support for it. - const retryAfterMillisHeader = responseHeaders?.['retry-after-ms']; - if (retryAfterMillisHeader) { - const timeoutMs = parseFloat(retryAfterMillisHeader); - if (!Number.isNaN(timeoutMs)) { - timeoutMillis = timeoutMs; - } - } - // About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After - const retryAfterHeader = responseHeaders?.['retry-after']; - if (retryAfterHeader && !timeoutMillis) { - const timeoutSeconds = parseFloat(retryAfterHeader); - if (!Number.isNaN(timeoutSeconds)) { - timeoutMillis = timeoutSeconds * 1000; - } - else { - timeoutMillis = Date.parse(retryAfterHeader) - Date.now(); - } - } - // If the API asks us to wait a certain amount of time (and it's a reasonable amount), - // just do what it says, but otherwise calculate a default - if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1000)) { - const maxRetries = options.maxRetries ?? this.maxRetries; - timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries); - } - await sleep(timeoutMillis); - return this.makeRequest(options, retriesRemaining - 1); - } - calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) { - const initialRetryDelay = 0.5; - const maxRetryDelay = 8.0; - const numRetries = maxRetries - retriesRemaining; - // Apply exponential backoff, but not more than the max. - const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay); - // Apply some jitter, take up to at most 25 percent of the retry time. - const jitter = 1 - Math.random() * 0.25; - return sleepSeconds * jitter * 1000; - } - getUserAgent() { - return `${this.constructor.name}/JS ${VERSION}`; - } -} +_APIPromise_client = new WeakMap(); +//# sourceMappingURL=api-promise.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/core/pagination.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +var _AbstractPage_client; + + + + + class AbstractPage { constructor(client, response, body, options) { _AbstractPage_client.set(this, void 0); - core_classPrivateFieldSet(this, _AbstractPage_client, client, "f"); + __classPrivateFieldSet(this, _AbstractPage_client, client, "f"); this.options = options; this.response = response; this.body = body; @@ -70521,29 +63971,16 @@ class AbstractPage { const items = this.getPaginatedItems(); if (!items.length) return false; - return this.nextPageInfo() != null; + return this.nextPageRequestOptions() != null; } async getNextPage() { - const nextInfo = this.nextPageInfo(); - if (!nextInfo) { + const nextOptions = this.nextPageRequestOptions(); + if (!nextOptions) { throw new error_OpenAIError('No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.'); } - const nextOptions = { ...this.options }; - if ('params' in nextInfo && typeof nextOptions.query === 'object') { - nextOptions.query = { ...nextOptions.query, ...nextInfo.params }; - } - else if ('url' in nextInfo) { - const params = [...Object.entries(nextOptions.query || {}), ...nextInfo.url.searchParams.entries()]; - for (const [key, value] of params) { - nextInfo.url.searchParams.set(key, value); - } - nextOptions.query = undefined; - nextOptions.path = nextInfo.url.toString(); - } - return await core_classPrivateFieldGet(this, _AbstractPage_client, "f").requestAPIList(this.constructor, nextOptions); + return await __classPrivateFieldGet(this, _AbstractPage_client, "f").requestAPIList(this.constructor, nextOptions); } async *iterPages() { - // eslint-disable-next-line @typescript-eslint/no-this-alias let page = this; yield page; while (page.hasNextPage()) { @@ -70570,7 +64007,7 @@ class AbstractPage { */ class PagePromise extends APIPromise { constructor(client, request, Page) { - super(request, async (props) => new Page(client, props.response, await defaultParseResponse(props), props.options)); + super(client, request, async (client, props) => new Page(client, props.response, await defaultParseResponse(client, props), props.options)); } /** * Allow auto-paginating iteration on an unawaited list call, eg: @@ -70586,427 +64023,308 @@ class PagePromise extends APIPromise { } } } -const createResponseHeaders = (headers) => { - return new Proxy(Object.fromEntries( - // @ts-ignore - headers.entries()), { - get(target, name) { - const key = name.toString(); - return target[key.toLowerCase()] || target[key]; - }, - }); -}; -// This is required so that we can determine if a given object matches the RequestOptions -// type at runtime. While this requires duplication, it is enforced by the TypeScript -// compiler such that any missing / extraneous keys will cause an error. -const requestOptionsKeys = { - method: true, - path: true, - query: true, - body: true, - headers: true, - maxRetries: true, - stream: true, - timeout: true, - httpAgent: true, - signal: true, - idempotencyKey: true, - __metadata: true, - __binaryRequest: true, - __binaryResponse: true, - __streamClass: true, -}; -const isRequestOptions = (obj) => { - return (typeof obj === 'object' && - obj !== null && - !isEmptyObj(obj) && - Object.keys(obj).every((k) => hasOwn(requestOptionsKeys, k))); -}; -const getPlatformProperties = () => { - if (typeof Deno !== 'undefined' && Deno.build != null) { - return { - 'X-Stainless-Lang': 'js', - 'X-Stainless-Package-Version': VERSION, - 'X-Stainless-OS': normalizePlatform(Deno.build.os), - 'X-Stainless-Arch': normalizeArch(Deno.build.arch), - 'X-Stainless-Runtime': 'deno', - 'X-Stainless-Runtime-Version': typeof Deno.version === 'string' ? Deno.version : Deno.version?.deno ?? 'unknown', - }; - } - if (typeof EdgeRuntime !== 'undefined') { - return { - 'X-Stainless-Lang': 'js', - 'X-Stainless-Package-Version': VERSION, - 'X-Stainless-OS': 'Unknown', - 'X-Stainless-Arch': `other:${EdgeRuntime}`, - 'X-Stainless-Runtime': 'edge', - 'X-Stainless-Runtime-Version': process.version, - }; - } - // Check if Node.js - if (Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]') { - return { - 'X-Stainless-Lang': 'js', - 'X-Stainless-Package-Version': VERSION, - 'X-Stainless-OS': normalizePlatform(process.platform), - 'X-Stainless-Arch': normalizeArch(process.arch), - 'X-Stainless-Runtime': 'node', - 'X-Stainless-Runtime-Version': process.version, - }; - } - const browserInfo = getBrowserInfo(); - if (browserInfo) { - return { - 'X-Stainless-Lang': 'js', - 'X-Stainless-Package-Version': VERSION, - 'X-Stainless-OS': 'Unknown', - 'X-Stainless-Arch': 'unknown', - 'X-Stainless-Runtime': `browser:${browserInfo.browser}`, - 'X-Stainless-Runtime-Version': browserInfo.version, - }; - } - // TODO add support for Cloudflare workers, etc. - return { - 'X-Stainless-Lang': 'js', - 'X-Stainless-Package-Version': VERSION, - 'X-Stainless-OS': 'Unknown', - 'X-Stainless-Arch': 'unknown', - 'X-Stainless-Runtime': 'unknown', - 'X-Stainless-Runtime-Version': 'unknown', - }; -}; -// Note: modified from https://github.com/JS-DevTools/host-environment/blob/b1ab79ecde37db5d6e163c050e54fe7d287d7c92/src/isomorphic.browser.ts -function getBrowserInfo() { - if (typeof navigator === 'undefined' || !navigator) { - return null; - } - // NOTE: The order matters here! - const browserPatterns = [ - { key: 'edge', pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, - { key: 'ie', pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, - { key: 'ie', pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ }, - { key: 'chrome', pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, - { key: 'firefox', pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, - { key: 'safari', pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ }, - ]; - // Find the FIRST matching browser - for (const { key, pattern } of browserPatterns) { - const match = pattern.exec(navigator.userAgent); - if (match) { - const major = match[1] || 0; - const minor = match[2] || 0; - const patch = match[3] || 0; - return { browser: key, version: `${major}.${minor}.${patch}` }; - } - } - return null; -} -const normalizeArch = (arch) => { - // Node docs: - // - https://nodejs.org/api/process.html#processarch - // Deno docs: - // - https://doc.deno.land/deno/stable/~/Deno.build - if (arch === 'x32') - return 'x32'; - if (arch === 'x86_64' || arch === 'x64') - return 'x64'; - if (arch === 'arm') - return 'arm'; - if (arch === 'aarch64' || arch === 'arm64') - return 'arm64'; - if (arch) - return `other:${arch}`; - return 'unknown'; -}; -const normalizePlatform = (platform) => { - // Node platforms: - // - https://nodejs.org/api/process.html#processplatform - // Deno platforms: - // - https://doc.deno.land/deno/stable/~/Deno.build - // - https://github.com/denoland/deno/issues/14799 - platform = platform.toLowerCase(); - // NOTE: this iOS check is untested and may not work - // Node does not work natively on IOS, there is a fork at - // https://github.com/nodejs-mobile/nodejs-mobile - // however it is unknown at the time of writing how to detect if it is running - if (platform.includes('ios')) - return 'iOS'; - if (platform === 'android') - return 'Android'; - if (platform === 'darwin') - return 'MacOS'; - if (platform === 'win32') - return 'Windows'; - if (platform === 'freebsd') - return 'FreeBSD'; - if (platform === 'openbsd') - return 'OpenBSD'; - if (platform === 'linux') - return 'Linux'; - if (platform) - return `Other:${platform}`; - return 'Unknown'; -}; -let _platformHeaders; -const getPlatformHeaders = () => { - return (_platformHeaders ?? (_platformHeaders = getPlatformProperties())); -}; -const safeJSON = (text) => { - try { - return JSON.parse(text); - } - catch (err) { - return undefined; - } -}; -// https://url.spec.whatwg.org/#url-scheme-string -const startsWithSchemeRegexp = /^[a-z][a-z0-9+.-]*:/i; -const isAbsoluteURL = (url) => { - return startsWithSchemeRegexp.test(url); -}; -const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); -const validatePositiveInteger = (name, n) => { - if (typeof n !== 'number' || !Number.isInteger(n)) { - throw new error_OpenAIError(`${name} must be an integer`); - } - if (n < 0) { - throw new error_OpenAIError(`${name} must be a positive integer`); - } - return n; -}; -const castToError = (err) => { - if (err instanceof Error) - return err; - if (typeof err === 'object' && err !== null) { - try { - return new Error(JSON.stringify(err)); - } - catch { } - } - return new Error(err); -}; -const ensurePresent = (value) => { - if (value == null) - throw new OpenAIError(`Expected a value to be given but received ${value} instead.`); - return value; -}; /** - * Read an environment variable. - * - * Trims beginning and trailing whitespace. - * - * Will return undefined if the environment variable doesn't exist or cannot be accessed. - */ -const readEnv = (env) => { - if (typeof process !== 'undefined') { - return process.env?.[env]?.trim() ?? undefined; - } - if (typeof Deno !== 'undefined') { - return Deno.env?.get?.(env)?.trim(); - } - return undefined; -}; -const coerceInteger = (value) => { - if (typeof value === 'number') - return Math.round(value); - if (typeof value === 'string') - return parseInt(value, 10); - throw new OpenAIError(`Could not coerce ${value} (type: ${typeof value}) into a number`); -}; -const coerceFloat = (value) => { - if (typeof value === 'number') - return value; - if (typeof value === 'string') - return parseFloat(value); - throw new OpenAIError(`Could not coerce ${value} (type: ${typeof value}) into a number`); -}; -const coerceBoolean = (value) => { - if (typeof value === 'boolean') - return value; - if (typeof value === 'string') - return value === 'true'; - return Boolean(value); -}; -const maybeCoerceInteger = (value) => { - if (value === undefined) { - return undefined; + * Note: no pagination actually occurs yet, this is for forwards-compatibility. + */ +class Page extends AbstractPage { + constructor(client, response, body, options) { + super(client, response, body, options); + this.data = body.data || []; + this.object = body.object; } - return coerceInteger(value); -}; -const maybeCoerceFloat = (value) => { - if (value === undefined) { - return undefined; + getPaginatedItems() { + return this.data ?? []; } - return coerceFloat(value); -}; -const maybeCoerceBoolean = (value) => { - if (value === undefined) { - return undefined; + nextPageRequestOptions() { + return null; } - return coerceBoolean(value); -}; -// https://stackoverflow.com/a/34491287 -function isEmptyObj(obj) { - if (!obj) - return true; - for (const _k in obj) - return false; - return true; } -// https://eslint.org/docs/latest/rules/no-prototype-builtins -function hasOwn(obj, key) { - return Object.prototype.hasOwnProperty.call(obj, key); +class CursorPage extends AbstractPage { + constructor(client, response, body, options) { + super(client, response, body, options); + this.data = body.data || []; + this.has_more = body.has_more || false; + } + getPaginatedItems() { + return this.data ?? []; + } + hasNextPage() { + if (this.has_more === false) { + return false; + } + return super.hasNextPage(); + } + nextPageRequestOptions() { + const data = this.getPaginatedItems(); + const id = data[data.length - 1]?.id; + if (!id) { + return null; + } + return { + ...this.options, + query: { + ...maybeObj(this.options.query), + after: id, + }, + }; + } } -/** - * Copies headers from "newHeaders" onto "targetHeaders", - * using lower-case for all properties, - * ignoring any keys with undefined values, - * and deleting any keys with null values. - */ -function applyHeadersMut(targetHeaders, newHeaders) { - for (const k in newHeaders) { - if (!hasOwn(newHeaders, k)) - continue; - const lowerKey = k.toLowerCase(); - if (!lowerKey) - continue; - const val = newHeaders[k]; - if (val === null) { - delete targetHeaders[lowerKey]; +class ConversationCursorPage extends AbstractPage { + constructor(client, response, body, options) { + super(client, response, body, options); + this.data = body.data || []; + this.has_more = body.has_more || false; + this.last_id = body.last_id || ''; + } + getPaginatedItems() { + return this.data ?? []; + } + hasNextPage() { + if (this.has_more === false) { + return false; } - else if (val !== undefined) { - targetHeaders[lowerKey] = val; + return super.hasNextPage(); + } + nextPageRequestOptions() { + const cursor = this.last_id; + if (!cursor) { + return null; } + return { + ...this.options, + query: { + ...maybeObj(this.options.query), + after: cursor, + }, + }; } } -const SENSITIVE_HEADERS = new Set(['authorization', 'api-key']); -function debug(action, ...args) { - if (typeof process !== 'undefined' && process?.env?.['DEBUG'] === 'true') { - const modifiedArgs = args.map((arg) => { - if (!arg) { - return arg; - } - // Check for sensitive headers in request body 'headers' object - if (arg['headers']) { - // clone so we don't mutate - const modifiedArg = { ...arg, headers: { ...arg['headers'] } }; - for (const header in arg['headers']) { - if (SENSITIVE_HEADERS.has(header.toLowerCase())) { - modifiedArg['headers'][header] = 'REDACTED'; - } - } - return modifiedArg; - } - let modifiedArg = null; - // Check for sensitive headers in headers object - for (const header in arg) { - if (SENSITIVE_HEADERS.has(header.toLowerCase())) { - // avoid making a copy until we need to - modifiedArg ?? (modifiedArg = { ...arg }); - modifiedArg[header] = 'REDACTED'; - } - } - return modifiedArg ?? arg; - }); - console.log(`OpenAI:DEBUG:${action}`, ...modifiedArgs); +//# sourceMappingURL=pagination.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/internal/uploads.mjs + +const checkFileSupport = () => { + if (typeof File === 'undefined') { + const { process } = globalThis; + const isOldNode = typeof process?.versions?.node === 'string' && parseInt(process.versions.node.split('.')) < 20; + throw new Error('`File` is not defined as a global, which is required for file uploads.' + + (isOldNode ? + " Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`." + : '')); } +}; +/** + * Construct a `File` instance. This is used to ensure a helpful error is thrown + * for environments that don't define a global `File` yet. + */ +function makeFile(fileBits, fileName, options) { + checkFileSupport(); + return new File(fileBits, fileName ?? 'unknown_file', options); +} +function getName(value) { + return (((typeof value === 'object' && + value !== null && + (('name' in value && value.name && String(value.name)) || + ('url' in value && value.url && String(value.url)) || + ('filename' in value && value.filename && String(value.filename)) || + ('path' in value && value.path && String(value.path)))) || + '') + .split(/[\\/]/) + .pop() || undefined); } +const isAsyncIterable = (value) => value != null && typeof value === 'object' && typeof value[Symbol.asyncIterator] === 'function'; /** - * https://stackoverflow.com/a/2117523 + * Returns a multipart/form-data request if any part of the given request body contains a File / Blob value. + * Otherwise returns the request as is. */ -const uuid4 = () => { - return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => { - const r = (Math.random() * 16) | 0; - const v = c === 'x' ? r : (r & 0x3) | 0x8; - return v.toString(16); - }); +const maybeMultipartFormRequestOptions = async (opts, fetch) => { + if (!hasUploadableValue(opts.body)) + return opts; + return { ...opts, body: await createForm(opts.body, fetch) }; }; -const isRunningInBrowser = () => { - return ( - // @ts-ignore - typeof window !== 'undefined' && - // @ts-ignore - typeof window.document !== 'undefined' && - // @ts-ignore - typeof navigator !== 'undefined'); +const multipartFormRequestOptions = async (opts, fetch) => { + return { ...opts, body: await createForm(opts.body, fetch) }; }; -const isHeadersProtocol = (headers) => { - return typeof headers?.get === 'function'; -}; -const getRequiredHeader = (headers, header) => { - const foundHeader = getHeader(headers, header); - if (foundHeader === undefined) { - throw new Error(`Could not find ${header} header`); - } - return foundHeader; -}; -const getHeader = (headers, header) => { - const lowerCasedHeader = header.toLowerCase(); - if (isHeadersProtocol(headers)) { - // to deal with the case where the header looks like Stainless-Event-Id - const intercapsHeader = header[0]?.toUpperCase() + - header.substring(1).replace(/([^\w])(\w)/g, (_m, g1, g2) => g1 + g2.toUpperCase()); - for (const key of [header, lowerCasedHeader, header.toUpperCase(), intercapsHeader]) { - const value = headers.get(key); - if (value) { - return value; +const supportsFormDataMap = /* @__PURE__ */ new WeakMap(); +/** + * node-fetch doesn't support the global FormData object in recent node versions. Instead of sending + * properly-encoded form data, it just stringifies the object, resulting in a request body of "[object FormData]". + * This function detects if the fetch function provided supports the global FormData object to avoid + * confusing error messages later on. + */ +function supportsFormData(fetchObject) { + const fetch = typeof fetchObject === 'function' ? fetchObject : fetchObject.fetch; + const cached = supportsFormDataMap.get(fetch); + if (cached) + return cached; + const promise = (async () => { + try { + const FetchResponse = ('Response' in fetch ? + fetch.Response + : (await fetch('data:,')).constructor); + const data = new FormData(); + if (data.toString() === (await new FetchResponse(data).text())) { + return false; } + return true; } + catch { + // avoid false negatives + return true; + } + })(); + supportsFormDataMap.set(fetch, promise); + return promise; +} +const createForm = async (body, fetch) => { + if (!(await supportsFormData(fetch))) { + throw new TypeError('The provided fetch function does not support file uploads with the current global FormData class.'); } - for (const [key, value] of Object.entries(headers)) { - if (key.toLowerCase() === lowerCasedHeader) { - if (Array.isArray(value)) { - if (value.length <= 1) - return value[0]; - console.warn(`Received ${value.length} entries for the ${header} header, using the first entry.`); - return value[0]; - } - return value; + const form = new FormData(); + await Promise.all(Object.entries(body || {}).map(([key, value]) => addFormValue(form, key, value))); + return form; +}; +// We check for Blob not File because Bun.File doesn't inherit from File, +// but they both inherit from Blob and have a `name` property at runtime. +const isNamedBlob = (value) => value instanceof Blob && 'name' in value; +const isUploadable = (value) => typeof value === 'object' && + value !== null && + (value instanceof Response || isAsyncIterable(value) || isNamedBlob(value)); +const hasUploadableValue = (value) => { + if (isUploadable(value)) + return true; + if (Array.isArray(value)) + return value.some(hasUploadableValue); + if (value && typeof value === 'object') { + for (const k in value) { + if (hasUploadableValue(value[k])) + return true; } } - return undefined; + return false; }; -/** - * Encodes a string to Base64 format. - */ -const toBase64 = (str) => { - if (!str) - return ''; - if (typeof Buffer !== 'undefined') { - return Buffer.from(str).toString('base64'); +const addFormValue = async (form, key, value) => { + if (value === undefined) + return; + if (value == null) { + throw new TypeError(`Received null for "${key}"; to pass null in FormData, you must use the string 'null'`); } - if (typeof btoa !== 'undefined') { - return btoa(str); + // TODO: make nested formats configurable + if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { + form.append(key, String(value)); + } + else if (value instanceof Response) { + form.append(key, makeFile([await value.blob()], getName(value))); + } + else if (isAsyncIterable(value)) { + form.append(key, makeFile([await new Response(ReadableStreamFrom(value)).blob()], getName(value))); + } + else if (isNamedBlob(value)) { + form.append(key, value, getName(value)); + } + else if (Array.isArray(value)) { + await Promise.all(value.map((entry) => addFormValue(form, key + '[]', entry))); + } + else if (typeof value === 'object') { + await Promise.all(Object.entries(value).map(([name, prop]) => addFormValue(form, `${key}[${name}]`, prop))); + } + else { + throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`); } - throw new OpenAIError('Cannot generate b64 string; Expected `Buffer` or `btoa` to be defined'); }; +//# sourceMappingURL=uploads.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/internal/to-file.mjs + + /** - * Converts a Base64 encoded string to a Float32Array. - * @param base64Str - The Base64 encoded string. - * @returns An Array of numbers interpreted as Float32 values. + * This check adds the arrayBuffer() method type because it is available and used at runtime */ -const toFloat32Array = (base64Str) => { - if (typeof Buffer !== 'undefined') { - // for Node.js environment - const buf = Buffer.from(base64Str, 'base64'); - return Array.from(new Float32Array(buf.buffer, buf.byteOffset, buf.length / Float32Array.BYTES_PER_ELEMENT)); +const isBlobLike = (value) => value != null && + typeof value === 'object' && + typeof value.size === 'number' && + typeof value.type === 'string' && + typeof value.text === 'function' && + typeof value.slice === 'function' && + typeof value.arrayBuffer === 'function'; +/** + * This check adds the arrayBuffer() method type because it is available and used at runtime + */ +const isFileLike = (value) => value != null && + typeof value === 'object' && + typeof value.name === 'string' && + typeof value.lastModified === 'number' && + isBlobLike(value); +const isResponseLike = (value) => value != null && + typeof value === 'object' && + typeof value.url === 'string' && + typeof value.blob === 'function'; +/** + * Helper for creating a {@link File} to pass to an SDK upload method from a variety of different data formats + * @param value the raw content of the file. Can be an {@link Uploadable}, {@link BlobLikePart}, or {@link AsyncIterable} of {@link BlobLikePart}s + * @param {string=} name the name of the file. If omitted, toFile will try to determine a file name from bits if possible + * @param {Object=} options additional properties + * @param {string=} options.type the MIME type of the content + * @param {number=} options.lastModified the last modified timestamp + * @returns a {@link File} with the given properties + */ +async function toFile(value, name, options) { + checkFileSupport(); + // If it's a promise, resolve it. + value = await value; + // If we've been given a `File` we don't need to do anything + if (isFileLike(value)) { + if (value instanceof File) { + return value; + } + return makeFile([await value.arrayBuffer()], value.name); } - else { - // for legacy web platform APIs - const binaryStr = atob(base64Str); - const len = binaryStr.length; - const bytes = new Uint8Array(len); - for (let i = 0; i < len; i++) { - bytes[i] = binaryStr.charCodeAt(i); + if (isResponseLike(value)) { + const blob = await value.blob(); + name || (name = new URL(value.url).pathname.split(/[\\/]/).pop()); + return makeFile(await getBytes(blob), name, options); + } + const parts = await getBytes(value); + name || (name = getName(value)); + if (!options?.type) { + const type = parts.find((part) => typeof part === 'object' && 'type' in part && part.type); + if (typeof type === 'string') { + options = { ...options, type }; } - return Array.from(new Float32Array(bytes.buffer)); } -}; -function isObj(obj) { - return obj != null && typeof obj === 'object' && !Array.isArray(obj); + return makeFile(parts, name, options); +} +async function getBytes(value) { + let parts = []; + if (typeof value === 'string' || + ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc. + value instanceof ArrayBuffer) { + parts.push(value); + } + else if (isBlobLike(value)) { + parts.push(value instanceof Blob ? value : await value.arrayBuffer()); + } + else if (isAsyncIterable(value) // includes Readable, ReadableStream, etc. + ) { + for await (const chunk of value) { + parts.push(...(await getBytes(chunk))); // TODO, consider validating? + } + } + else { + const constructor = value?.constructor?.name; + throw new Error(`Unexpected data type: ${typeof value}${constructor ? `; constructor: ${constructor}` : ''}${propsForError(value)}`); + } + return parts; +} +function propsForError(value) { + if (typeof value !== 'object' || value === null) + return ''; + const props = Object.getOwnPropertyNames(value); + return `; props: [${props.map((p) => `"${p}"`).join(', ')}]`; } -//# sourceMappingURL=core.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resource.mjs +//# sourceMappingURL=to-file.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/core/uploads.mjs + +//# sourceMappingURL=uploads.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/core/resource.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. class APIResource { constructor(client) { @@ -71014,1103 +64332,1812 @@ class APIResource { } } //# sourceMappingURL=resource.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/completions.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +;// CONCATENATED MODULE: ./node_modules/openai/internal/utils/path.mjs -class Completions extends APIResource { - create(body, options) { - return this._client.post('/completions', { body, ...options, stream: body.stream ?? false }); - } +/** + * Percent-encode everything that isn't safe to have in a path without encoding safe chars. + * + * Taken from https://datatracker.ietf.org/doc/html/rfc3986#section-3.3: + * > unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" + * > sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "=" + * > pchar = unreserved / pct-encoded / sub-delims / ":" / "@" + */ +function encodeURIPath(str) { + return str.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g, encodeURIComponent); } -//# sourceMappingURL=completions.mjs.map +const EMPTY = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.create(null)); +const createPathTagFunction = (pathEncoder = encodeURIPath) => function path(statics, ...params) { + // If there are no params, no processing is needed. + if (statics.length === 1) + return statics[0]; + let postPath = false; + const invalidSegments = []; + const path = statics.reduce((previousValue, currentValue, index) => { + if (/[?#]/.test(currentValue)) { + postPath = true; + } + const value = params[index]; + let encoded = (postPath ? encodeURIComponent : pathEncoder)('' + value); + if (index !== params.length && + (value == null || + (typeof value === 'object' && + // handle values from other realms + value.toString === + Object.getPrototypeOf(Object.getPrototypeOf(value.hasOwnProperty ?? EMPTY) ?? EMPTY) + ?.toString))) { + encoded = value + ''; + invalidSegments.push({ + start: previousValue.length + currentValue.length, + length: encoded.length, + error: `Value of type ${Object.prototype.toString + .call(value) + .slice(8, -1)} is not a valid path parameter`, + }); + } + return previousValue + currentValue + (index === params.length ? '' : encoded); + }, ''); + const pathOnly = path.split(/[?#]/, 1)[0]; + const invalidSegmentPattern = /(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi; + let match; + // Find all invalid segments + while ((match = invalidSegmentPattern.exec(pathOnly)) !== null) { + invalidSegments.push({ + start: match.index, + length: match[0].length, + error: `Value "${match[0]}" can\'t be safely passed as a path parameter`, + }); + } + invalidSegments.sort((a, b) => a.start - b.start); + if (invalidSegments.length > 0) { + let lastEnd = 0; + const underline = invalidSegments.reduce((acc, segment) => { + const spaces = ' '.repeat(segment.start - lastEnd); + const arrows = '^'.repeat(segment.length); + lastEnd = segment.start + segment.length; + return acc + spaces + arrows; + }, ''); + throw new error_OpenAIError(`Path parameters result in path with invalid segments:\n${invalidSegments + .map((e) => e.error) + .join('\n')}\n${path}\n${underline}`); + } + return path; +}; +/** + * URI-encodes path params and ensures no unsafe /./ or /../ path segments are introduced. + */ +const path = /* @__PURE__ */ createPathTagFunction(encodeURIPath); +//# sourceMappingURL=path.mjs.map ;// CONCATENATED MODULE: ./node_modules/openai/resources/chat/completions/messages.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. class Messages extends APIResource { - list(completionId, query = {}, options) { - if (isRequestOptions(query)) { - return this.list(completionId, {}, query); - } - return this._client.getAPIList(`/chat/completions/${completionId}/messages`, ChatCompletionStoreMessagesPage, { query, ...options }); + /** + * Get the messages in a stored chat completion. Only Chat Completions that have + * been created with the `store` parameter set to `true` will be returned. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const chatCompletionStoreMessage of client.chat.completions.messages.list( + * 'completion_id', + * )) { + * // ... + * } + * ``` + */ + list(completionID, query = {}, options) { + return this._client.getAPIList(path `/chat/completions/${completionID}/messages`, (CursorPage), { query, ...options }); } } - //# sourceMappingURL=messages.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/pagination.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +;// CONCATENATED MODULE: ./node_modules/openai/error.mjs -/** - * Note: no pagination actually occurs yet, this is for forwards-compatibility. - */ -class Page extends AbstractPage { - constructor(client, response, body, options) { - super(client, response, body, options); - this.data = body.data || []; - this.object = body.object; - } - getPaginatedItems() { - return this.data ?? []; +//# sourceMappingURL=error.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/lib/parser.mjs + +function isChatCompletionFunctionTool(tool) { + return tool !== undefined && 'function' in tool && tool.function !== undefined; +} +function makeParseableResponseFormat(response_format, parser) { + const obj = { ...response_format }; + Object.defineProperties(obj, { + $brand: { + value: 'auto-parseable-response-format', + enumerable: false, + }, + $parseRaw: { + value: parser, + enumerable: false, + }, + }); + return obj; +} +function parser_makeParseableTextFormat(response_format, parser) { + const obj = { ...response_format }; + Object.defineProperties(obj, { + $brand: { + value: 'auto-parseable-response-format', + enumerable: false, + }, + $parseRaw: { + value: parser, + enumerable: false, + }, + }); + return obj; +} +function isAutoParsableResponseFormat(response_format) { + return response_format?.['$brand'] === 'auto-parseable-response-format'; +} +function parser_makeParseableTool(tool, { parser, callback, }) { + const obj = { ...tool }; + Object.defineProperties(obj, { + $brand: { + value: 'auto-parseable-tool', + enumerable: false, + }, + $parseRaw: { + value: parser, + enumerable: false, + }, + $callback: { + value: callback, + enumerable: false, + }, + }); + return obj; +} +function isAutoParsableTool(tool) { + return tool?.['$brand'] === 'auto-parseable-tool'; +} +function maybeParseChatCompletion(completion, params) { + if (!params || !hasAutoParseableInput(params)) { + return { + ...completion, + choices: completion.choices.map((choice) => { + assertToolCallsAreChatCompletionFunctionToolCalls(choice.message.tool_calls); + return { + ...choice, + message: { + ...choice.message, + parsed: null, + ...(choice.message.tool_calls ? + { + tool_calls: choice.message.tool_calls, + } + : undefined), + }, + }; + }), + }; } - // @deprecated Please use `nextPageInfo()` instead - /** - * This page represents a response that isn't actually paginated at the API level - * so there will never be any next page params. - */ - nextPageParams() { + return parseChatCompletion(completion, params); +} +function parseChatCompletion(completion, params) { + const choices = completion.choices.map((choice) => { + if (choice.finish_reason === 'length') { + throw new LengthFinishReasonError(); + } + if (choice.finish_reason === 'content_filter') { + throw new ContentFilterFinishReasonError(); + } + assertToolCallsAreChatCompletionFunctionToolCalls(choice.message.tool_calls); + return { + ...choice, + message: { + ...choice.message, + ...(choice.message.tool_calls ? + { + tool_calls: choice.message.tool_calls?.map((toolCall) => parseToolCall(params, toolCall)) ?? undefined, + } + : undefined), + parsed: choice.message.content && !choice.message.refusal ? + parseResponseFormat(params, choice.message.content) + : null, + }, + }; + }); + return { ...completion, choices }; +} +function parseResponseFormat(params, content) { + if (params.response_format?.type !== 'json_schema') { return null; } - nextPageInfo() { - return null; + if (params.response_format?.type === 'json_schema') { + if ('$parseRaw' in params.response_format) { + const response_format = params.response_format; + return response_format.$parseRaw(content); + } + return JSON.parse(content); } + return null; +} +function parseToolCall(params, toolCall) { + const inputTool = params.tools?.find((inputTool) => isChatCompletionFunctionTool(inputTool) && inputTool.function?.name === toolCall.function.name); // TS doesn't narrow based on isChatCompletionTool + return { + ...toolCall, + function: { + ...toolCall.function, + parsed_arguments: isAutoParsableTool(inputTool) ? inputTool.$parseRaw(toolCall.function.arguments) + : inputTool?.function.strict ? JSON.parse(toolCall.function.arguments) + : null, + }, + }; } -class CursorPage extends AbstractPage { - constructor(client, response, body, options) { - super(client, response, body, options); - this.data = body.data || []; - this.has_more = body.has_more || false; +function shouldParseToolCall(params, toolCall) { + if (!params || !('tools' in params) || !params.tools) { + return false; } - getPaginatedItems() { - return this.data ?? []; + const inputTool = params.tools?.find((inputTool) => isChatCompletionFunctionTool(inputTool) && inputTool.function?.name === toolCall.function.name); + return (isChatCompletionFunctionTool(inputTool) && + (isAutoParsableTool(inputTool) || inputTool?.function.strict || false)); +} +function hasAutoParseableInput(params) { + if (isAutoParsableResponseFormat(params.response_format)) { + return true; } - hasNextPage() { - if (this.has_more === false) { - return false; + return (params.tools?.some((t) => isAutoParsableTool(t) || (t.type === 'function' && t.function.strict === true)) ?? false); +} +function assertToolCallsAreChatCompletionFunctionToolCalls(toolCalls) { + for (const toolCall of toolCalls || []) { + if (toolCall.type !== 'function') { + throw new error_OpenAIError(`Currently only \`function\` tool calls are supported; Received \`${toolCall.type}\``); } - return super.hasNextPage(); } - // @deprecated Please use `nextPageInfo()` instead - nextPageParams() { - const info = this.nextPageInfo(); - if (!info) - return null; - if ('params' in info) - return info.params; - const params = Object.fromEntries(info.url.searchParams); - if (!Object.keys(params).length) - return null; - return params; - } - nextPageInfo() { - const data = this.getPaginatedItems(); - if (!data.length) { - return null; +} +function validateInputTools(tools) { + for (const tool of tools ?? []) { + if (tool.type !== 'function') { + throw new error_OpenAIError(`Currently only \`function\` tool types support auto-parsing; Received \`${tool.type}\``); } - const id = data[data.length - 1]?.id; - if (!id) { - return null; + if (tool.function.strict !== true) { + throw new error_OpenAIError(`The \`${tool.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`); } - return { params: { after: id } }; } } -//# sourceMappingURL=pagination.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/chat/completions/completions.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - +//# sourceMappingURL=parser.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/lib/chatCompletionUtils.mjs +const isAssistantMessage = (message) => { + return message?.role === 'assistant'; +}; +const isToolMessage = (message) => { + return message?.role === 'tool'; +}; +function isPresent(obj) { + return obj != null; +} +//# sourceMappingURL=chatCompletionUtils.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/lib/EventStream.mjs +var _EventStream_instances, _EventStream_connectedPromise, _EventStream_resolveConnectedPromise, _EventStream_rejectConnectedPromise, _EventStream_endPromise, _EventStream_resolveEndPromise, _EventStream_rejectEndPromise, _EventStream_listeners, _EventStream_ended, _EventStream_errored, _EventStream_aborted, _EventStream_catchingPromiseCreated, _EventStream_handleError; -class completions_Completions extends APIResource { +class EventStream { constructor() { - super(...arguments); - this.messages = new Messages(this._client); + _EventStream_instances.add(this); + this.controller = new AbortController(); + _EventStream_connectedPromise.set(this, void 0); + _EventStream_resolveConnectedPromise.set(this, () => { }); + _EventStream_rejectConnectedPromise.set(this, () => { }); + _EventStream_endPromise.set(this, void 0); + _EventStream_resolveEndPromise.set(this, () => { }); + _EventStream_rejectEndPromise.set(this, () => { }); + _EventStream_listeners.set(this, {}); + _EventStream_ended.set(this, false); + _EventStream_errored.set(this, false); + _EventStream_aborted.set(this, false); + _EventStream_catchingPromiseCreated.set(this, false); + __classPrivateFieldSet(this, _EventStream_connectedPromise, new Promise((resolve, reject) => { + __classPrivateFieldSet(this, _EventStream_resolveConnectedPromise, resolve, "f"); + __classPrivateFieldSet(this, _EventStream_rejectConnectedPromise, reject, "f"); + }), "f"); + __classPrivateFieldSet(this, _EventStream_endPromise, new Promise((resolve, reject) => { + __classPrivateFieldSet(this, _EventStream_resolveEndPromise, resolve, "f"); + __classPrivateFieldSet(this, _EventStream_rejectEndPromise, reject, "f"); + }), "f"); + // Don't let these promises cause unhandled rejection errors. + // we will manually cause an unhandled rejection error later + // if the user hasn't registered any error listener or called + // any promise-returning method. + __classPrivateFieldGet(this, _EventStream_connectedPromise, "f").catch(() => { }); + __classPrivateFieldGet(this, _EventStream_endPromise, "f").catch(() => { }); } - create(body, options) { - return this._client.post('/chat/completions', { body, ...options, stream: body.stream ?? false }); + _run(executor) { + // Unfortunately if we call `executor()` immediately we get runtime errors about + // references to `this` before the `super()` constructor call returns. + setTimeout(() => { + executor().then(() => { + this._emitFinal(); + this._emit('end'); + }, __classPrivateFieldGet(this, _EventStream_instances, "m", _EventStream_handleError).bind(this)); + }, 0); + } + _connected() { + if (this.ended) + return; + __classPrivateFieldGet(this, _EventStream_resolveConnectedPromise, "f").call(this); + this._emit('connect'); + } + get ended() { + return __classPrivateFieldGet(this, _EventStream_ended, "f"); + } + get errored() { + return __classPrivateFieldGet(this, _EventStream_errored, "f"); + } + get aborted() { + return __classPrivateFieldGet(this, _EventStream_aborted, "f"); + } + abort() { + this.controller.abort(); } /** - * Get a stored chat completion. Only Chat Completions that have been created with - * the `store` parameter set to `true` will be returned. - * - * @example - * ```ts - * const chatCompletion = - * await client.chat.completions.retrieve('completion_id'); - * ``` + * Adds the listener function to the end of the listeners array for the event. + * No checks are made to see if the listener has already been added. Multiple calls passing + * the same combination of event and listener will result in the listener being added, and + * called, multiple times. + * @returns this ChatCompletionStream, so that calls can be chained */ - retrieve(completionId, options) { - return this._client.get(`/chat/completions/${completionId}`, options); + on(event, listener) { + const listeners = __classPrivateFieldGet(this, _EventStream_listeners, "f")[event] || (__classPrivateFieldGet(this, _EventStream_listeners, "f")[event] = []); + listeners.push({ listener }); + return this; } /** - * Modify a stored chat completion. Only Chat Completions that have been created - * with the `store` parameter set to `true` can be modified. Currently, the only - * supported modification is to update the `metadata` field. - * - * @example - * ```ts - * const chatCompletion = await client.chat.completions.update( - * 'completion_id', - * { metadata: { foo: 'string' } }, - * ); - * ``` + * Removes the specified listener from the listener array for the event. + * off() will remove, at most, one instance of a listener from the listener array. If any single + * listener has been added multiple times to the listener array for the specified event, then + * off() must be called multiple times to remove each instance. + * @returns this ChatCompletionStream, so that calls can be chained */ - update(completionId, body, options) { - return this._client.post(`/chat/completions/${completionId}`, { body, ...options }); - } - list(query = {}, options) { - if (isRequestOptions(query)) { - return this.list({}, query); - } - return this._client.getAPIList('/chat/completions', ChatCompletionsPage, { query, ...options }); + off(event, listener) { + const listeners = __classPrivateFieldGet(this, _EventStream_listeners, "f")[event]; + if (!listeners) + return this; + const index = listeners.findIndex((l) => l.listener === listener); + if (index >= 0) + listeners.splice(index, 1); + return this; } /** - * Delete a stored chat completion. Only Chat Completions that have been created - * with the `store` parameter set to `true` can be deleted. - * - * @example - * ```ts - * const chatCompletionDeleted = - * await client.chat.completions.del('completion_id'); - * ``` + * Adds a one-time listener function for the event. The next time the event is triggered, + * this listener is removed and then invoked. + * @returns this ChatCompletionStream, so that calls can be chained */ - del(completionId, options) { - return this._client.delete(`/chat/completions/${completionId}`, options); - } -} -class ChatCompletionsPage extends CursorPage { -} -class ChatCompletionStoreMessagesPage extends CursorPage { -} -completions_Completions.ChatCompletionsPage = ChatCompletionsPage; -completions_Completions.Messages = Messages; -//# sourceMappingURL=completions.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/chat/chat.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - -class Chat extends APIResource { - constructor() { - super(...arguments); - this.completions = new completions_Completions(this._client); + once(event, listener) { + const listeners = __classPrivateFieldGet(this, _EventStream_listeners, "f")[event] || (__classPrivateFieldGet(this, _EventStream_listeners, "f")[event] = []); + listeners.push({ listener, once: true }); + return this; } -} -Chat.Completions = completions_Completions; -Chat.ChatCompletionsPage = ChatCompletionsPage; -//# sourceMappingURL=chat.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/embeddings.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - -class Embeddings extends APIResource { /** - * Creates an embedding vector representing the input text. + * This is similar to `.once()`, but returns a Promise that resolves the next time + * the event is triggered, instead of calling a listener callback. + * @returns a Promise that resolves the next time given event is triggered, + * or rejects if an error is emitted. (If you request the 'error' event, + * returns a promise that resolves with the error). * - * @example - * ```ts - * const createEmbeddingResponse = - * await client.embeddings.create({ - * input: 'The quick brown fox jumped over the lazy dog', - * model: 'text-embedding-3-small', - * }); - * ``` + * Example: + * + * const message = await stream.emitted('message') // rejects if the stream errors */ - create(body, options) { - const hasUserProvidedEncodingFormat = !!body.encoding_format; - // No encoding_format specified, defaulting to base64 for performance reasons - // See https://github.com/openai/openai-node/pull/1312 - let encoding_format = hasUserProvidedEncodingFormat ? body.encoding_format : 'base64'; - if (hasUserProvidedEncodingFormat) { - debug('Request', 'User defined encoding_format:', body.encoding_format); - } - const response = this._client.post('/embeddings', { - body: { - ...body, - encoding_format: encoding_format, - }, - ...options, + emitted(event) { + return new Promise((resolve, reject) => { + __classPrivateFieldSet(this, _EventStream_catchingPromiseCreated, true, "f"); + if (event !== 'error') + this.once('error', reject); + this.once(event, resolve); }); - // if the user specified an encoding_format, return the response as-is - if (hasUserProvidedEncodingFormat) { - return response; + } + async done() { + __classPrivateFieldSet(this, _EventStream_catchingPromiseCreated, true, "f"); + await __classPrivateFieldGet(this, _EventStream_endPromise, "f"); + } + _emit(event, ...args) { + // make sure we don't emit any events after end + if (__classPrivateFieldGet(this, _EventStream_ended, "f")) { + return; } - // in this stage, we are sure the user did not specify an encoding_format - // and we defaulted to base64 for performance reasons - // we are sure then that the response is base64 encoded, let's decode it - // the returned result will be a float32 array since this is OpenAI API's default encoding - debug('response', 'Decoding base64 embeddings to float32 array'); - return response._thenUnwrap((response) => { - if (response && response.data) { - response.data.forEach((embeddingBase64Obj) => { - const embeddingBase64Str = embeddingBase64Obj.embedding; - embeddingBase64Obj.embedding = toFloat32Array(embeddingBase64Str); - }); + if (event === 'end') { + __classPrivateFieldSet(this, _EventStream_ended, true, "f"); + __classPrivateFieldGet(this, _EventStream_resolveEndPromise, "f").call(this); + } + const listeners = __classPrivateFieldGet(this, _EventStream_listeners, "f")[event]; + if (listeners) { + __classPrivateFieldGet(this, _EventStream_listeners, "f")[event] = listeners.filter((l) => !l.once); + listeners.forEach(({ listener }) => listener(...args)); + } + if (event === 'abort') { + const error = args[0]; + if (!__classPrivateFieldGet(this, _EventStream_catchingPromiseCreated, "f") && !listeners?.length) { + Promise.reject(error); } - return response; - }); + __classPrivateFieldGet(this, _EventStream_rejectConnectedPromise, "f").call(this, error); + __classPrivateFieldGet(this, _EventStream_rejectEndPromise, "f").call(this, error); + this._emit('end'); + return; + } + if (event === 'error') { + // NOTE: _emit('error', error) should only be called from #handleError(). + const error = args[0]; + if (!__classPrivateFieldGet(this, _EventStream_catchingPromiseCreated, "f") && !listeners?.length) { + // Trigger an unhandled rejection if the user hasn't registered any error handlers. + // If you are seeing stack traces here, make sure to handle errors via either: + // - runner.on('error', () => ...) + // - await runner.done() + // - await runner.finalChatCompletion() + // - etc. + Promise.reject(error); + } + __classPrivateFieldGet(this, _EventStream_rejectConnectedPromise, "f").call(this, error); + __classPrivateFieldGet(this, _EventStream_rejectEndPromise, "f").call(this, error); + this._emit('end'); + } } + _emitFinal() { } } -//# sourceMappingURL=embeddings.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/files.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +_EventStream_connectedPromise = new WeakMap(), _EventStream_resolveConnectedPromise = new WeakMap(), _EventStream_rejectConnectedPromise = new WeakMap(), _EventStream_endPromise = new WeakMap(), _EventStream_resolveEndPromise = new WeakMap(), _EventStream_rejectEndPromise = new WeakMap(), _EventStream_listeners = new WeakMap(), _EventStream_ended = new WeakMap(), _EventStream_errored = new WeakMap(), _EventStream_aborted = new WeakMap(), _EventStream_catchingPromiseCreated = new WeakMap(), _EventStream_instances = new WeakSet(), _EventStream_handleError = function _EventStream_handleError(error) { + __classPrivateFieldSet(this, _EventStream_errored, true, "f"); + if (error instanceof Error && error.name === 'AbortError') { + error = new APIUserAbortError(); + } + if (error instanceof APIUserAbortError) { + __classPrivateFieldSet(this, _EventStream_aborted, true, "f"); + return this._emit('abort', error); + } + if (error instanceof error_OpenAIError) { + return this._emit('error', error); + } + if (error instanceof Error) { + const openAIError = new error_OpenAIError(error.message); + // @ts-ignore + openAIError.cause = error; + return this._emit('error', openAIError); + } + return this._emit('error', new error_OpenAIError(String(error))); +}; +//# sourceMappingURL=EventStream.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/lib/RunnableFunction.mjs +function isRunnableFunctionWithParse(fn) { + return typeof fn.parse === 'function'; +} +/** + * This is helper class for passing a `function` and `parse` where the `function` + * argument type matches the `parse` return type. + */ +class ParsingToolFunction { + constructor(input) { + this.type = 'function'; + this.function = input; + } +} +//# sourceMappingURL=RunnableFunction.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/lib/AbstractChatCompletionRunner.mjs +var _AbstractChatCompletionRunner_instances, _AbstractChatCompletionRunner_getFinalContent, _AbstractChatCompletionRunner_getFinalMessage, _AbstractChatCompletionRunner_getFinalFunctionToolCall, _AbstractChatCompletionRunner_getFinalFunctionToolCallResult, _AbstractChatCompletionRunner_calculateTotalUsage, _AbstractChatCompletionRunner_validateParams, _AbstractChatCompletionRunner_stringifyFunctionCallResult; -class Files extends APIResource { - /** - * Upload a file that can be used across various endpoints. Individual files can be - * up to 512 MB, and the size of all files uploaded by one organization can be up - * to 100 GB. - * - * The Assistants API supports files up to 2 million tokens and of specific file - * types. See the - * [Assistants Tools guide](https://platform.openai.com/docs/assistants/tools) for - * details. - * - * The Fine-tuning API only supports `.jsonl` files. The input also has certain - * required formats for fine-tuning - * [chat](https://platform.openai.com/docs/api-reference/fine-tuning/chat-input) or - * [completions](https://platform.openai.com/docs/api-reference/fine-tuning/completions-input) - * models. - * - * The Batch API only supports `.jsonl` files up to 200 MB in size. The input also - * has a specific required - * [format](https://platform.openai.com/docs/api-reference/batch/request-input). - * - * Please [contact us](https://help.openai.com/) if you need to increase these - * storage limits. - */ - create(body, options) { - return this._client.post('/files', multipartFormRequestOptions({ body, ...options })); +const DEFAULT_MAX_CHAT_COMPLETIONS = 10; +class AbstractChatCompletionRunner extends EventStream { + constructor() { + super(...arguments); + _AbstractChatCompletionRunner_instances.add(this); + this._chatCompletions = []; + this.messages = []; } - /** - * Returns information about a specific file. - */ - retrieve(fileId, options) { - return this._client.get(`/files/${fileId}`, options); + _addChatCompletion(chatCompletion) { + this._chatCompletions.push(chatCompletion); + this._emit('chatCompletion', chatCompletion); + const message = chatCompletion.choices[0]?.message; + if (message) + this._addMessage(message); + return chatCompletion; } - list(query = {}, options) { - if (isRequestOptions(query)) { - return this.list({}, query); + _addMessage(message, emit = true) { + if (!('content' in message)) + message.content = null; + this.messages.push(message); + if (emit) { + this._emit('message', message); + if (isToolMessage(message) && message.content) { + // Note, this assumes that {role: 'tool', content: …} is always the result of a call of tool of type=function. + this._emit('functionToolCallResult', message.content); + } + else if (isAssistantMessage(message) && message.tool_calls) { + for (const tool_call of message.tool_calls) { + if (tool_call.type === 'function') { + this._emit('functionToolCall', tool_call.function); + } + } + } } - return this._client.getAPIList('/files', FileObjectsPage, { query, ...options }); } /** - * Delete a file. + * @returns a promise that resolves with the final ChatCompletion, or rejects + * if an error occurred or the stream ended prematurely without producing a ChatCompletion. */ - del(fileId, options) { - return this._client.delete(`/files/${fileId}`, options); + async finalChatCompletion() { + await this.done(); + const completion = this._chatCompletions[this._chatCompletions.length - 1]; + if (!completion) + throw new error_OpenAIError('stream ended without producing a ChatCompletion'); + return completion; } /** - * Returns the contents of the specified file. + * @returns a promise that resolves with the content of the final ChatCompletionMessage, or rejects + * if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage. */ - content(fileId, options) { - return this._client.get(`/files/${fileId}/content`, { - ...options, - headers: { Accept: 'application/binary', ...options?.headers }, - __binaryResponse: true, - }); + async finalContent() { + await this.done(); + return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalContent).call(this); } /** - * Returns the contents of the specified file. - * - * @deprecated The `.content()` method should be used instead + * @returns a promise that resolves with the the final assistant ChatCompletionMessage response, + * or rejects if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage. */ - retrieveContent(fileId, options) { - return this._client.get(`/files/${fileId}/content`, options); + async finalMessage() { + await this.done(); + return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this); } /** - * Waits for the given file to be processed, default timeout is 30 mins. + * @returns a promise that resolves with the content of the final FunctionCall, or rejects + * if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage. */ - async waitForProcessing(id, { pollInterval = 5000, maxWait = 30 * 60 * 1000 } = {}) { - const TERMINAL_STATES = new Set(['processed', 'error', 'deleted']); - const start = Date.now(); - let file = await this.retrieve(id); - while (!file.status || !TERMINAL_STATES.has(file.status)) { - await sleep(pollInterval); - file = await this.retrieve(id); - if (Date.now() - start > maxWait) { - throw new APIConnectionTimeoutError({ - message: `Giving up on waiting for file ${id} to finish processing after ${maxWait} milliseconds.`, - }); + async finalFunctionToolCall() { + await this.done(); + return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionToolCall).call(this); + } + async finalFunctionToolCallResult() { + await this.done(); + return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionToolCallResult).call(this); + } + async totalUsage() { + await this.done(); + return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_calculateTotalUsage).call(this); + } + allChatCompletions() { + return [...this._chatCompletions]; + } + _emitFinal() { + const completion = this._chatCompletions[this._chatCompletions.length - 1]; + if (completion) + this._emit('finalChatCompletion', completion); + const finalMessage = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this); + if (finalMessage) + this._emit('finalMessage', finalMessage); + const finalContent = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalContent).call(this); + if (finalContent) + this._emit('finalContent', finalContent); + const finalFunctionCall = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionToolCall).call(this); + if (finalFunctionCall) + this._emit('finalFunctionToolCall', finalFunctionCall); + const finalFunctionCallResult = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionToolCallResult).call(this); + if (finalFunctionCallResult != null) + this._emit('finalFunctionToolCallResult', finalFunctionCallResult); + if (this._chatCompletions.some((c) => c.usage)) { + this._emit('totalUsage', __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_calculateTotalUsage).call(this)); + } + } + async _createChatCompletion(client, params, options) { + const signal = options?.signal; + if (signal) { + if (signal.aborted) + this.controller.abort(); + signal.addEventListener('abort', () => this.controller.abort()); + } + __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_validateParams).call(this, params); + const chatCompletion = await client.chat.completions.create({ ...params, stream: false }, { ...options, signal: this.controller.signal }); + this._connected(); + return this._addChatCompletion(parseChatCompletion(chatCompletion, params)); + } + async _runChatCompletion(client, params, options) { + for (const message of params.messages) { + this._addMessage(message, false); + } + return await this._createChatCompletion(client, params, options); + } + async _runTools(client, params, options) { + const role = 'tool'; + const { tool_choice = 'auto', stream, ...restParams } = params; + const singleFunctionToCall = typeof tool_choice !== 'string' && tool_choice.type === 'function' && tool_choice?.function?.name; + const { maxChatCompletions = DEFAULT_MAX_CHAT_COMPLETIONS } = options || {}; + // TODO(someday): clean this logic up + const inputTools = params.tools.map((tool) => { + if (isAutoParsableTool(tool)) { + if (!tool.$callback) { + throw new error_OpenAIError('Tool given to `.runTools()` that does not have an associated function'); + } + return { + type: 'function', + function: { + function: tool.$callback, + name: tool.function.name, + description: tool.function.description || '', + parameters: tool.function.parameters, + parse: tool.$parseRaw, + strict: true, + }, + }; + } + return tool; + }); + const functionsByName = {}; + for (const f of inputTools) { + if (f.type === 'function') { + functionsByName[f.function.name || f.function.function.name] = f.function; + } + } + const tools = 'tools' in params ? + inputTools.map((t) => t.type === 'function' ? + { + type: 'function', + function: { + name: t.function.name || t.function.function.name, + parameters: t.function.parameters, + description: t.function.description, + strict: t.function.strict, + }, + } + : t) + : undefined; + for (const message of params.messages) { + this._addMessage(message, false); + } + for (let i = 0; i < maxChatCompletions; ++i) { + const chatCompletion = await this._createChatCompletion(client, { + ...restParams, + tool_choice, + tools, + messages: [...this.messages], + }, options); + const message = chatCompletion.choices[0]?.message; + if (!message) { + throw new error_OpenAIError(`missing message in ChatCompletion response`); + } + if (!message.tool_calls?.length) { + return; + } + for (const tool_call of message.tool_calls) { + if (tool_call.type !== 'function') + continue; + const tool_call_id = tool_call.id; + const { name, arguments: args } = tool_call.function; + const fn = functionsByName[name]; + if (!fn) { + const content = `Invalid tool_call: ${JSON.stringify(name)}. Available options are: ${Object.keys(functionsByName) + .map((name) => JSON.stringify(name)) + .join(', ')}. Please try again`; + this._addMessage({ role, tool_call_id, content }); + continue; + } + else if (singleFunctionToCall && singleFunctionToCall !== name) { + const content = `Invalid tool_call: ${JSON.stringify(name)}. ${JSON.stringify(singleFunctionToCall)} requested. Please try again`; + this._addMessage({ role, tool_call_id, content }); + continue; + } + let parsed; + try { + parsed = isRunnableFunctionWithParse(fn) ? await fn.parse(args) : args; + } + catch (error) { + const content = error instanceof Error ? error.message : String(error); + this._addMessage({ role, tool_call_id, content }); + continue; + } + // @ts-expect-error it can't rule out `never` type. + const rawContent = await fn.function(parsed, this); + const content = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_stringifyFunctionCallResult).call(this, rawContent); + this._addMessage({ role, tool_call_id, content }); + if (singleFunctionToCall) { + return; + } } } - return file; + return; } } -class FileObjectsPage extends CursorPage { -} -Files.FileObjectsPage = FileObjectsPage; -//# sourceMappingURL=files.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/images.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - -class Images extends APIResource { - /** - * Creates a variation of a given image. This endpoint only supports `dall-e-2`. - * - * @example - * ```ts - * const imagesResponse = await client.images.createVariation({ - * image: fs.createReadStream('otter.png'), - * }); - * ``` - */ - createVariation(body, options) { - return this._client.post('/images/variations', multipartFormRequestOptions({ body, ...options })); +_AbstractChatCompletionRunner_instances = new WeakSet(), _AbstractChatCompletionRunner_getFinalContent = function _AbstractChatCompletionRunner_getFinalContent() { + return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this).content ?? null; +}, _AbstractChatCompletionRunner_getFinalMessage = function _AbstractChatCompletionRunner_getFinalMessage() { + let i = this.messages.length; + while (i-- > 0) { + const message = this.messages[i]; + if (isAssistantMessage(message)) { + // TODO: support audio here + const ret = { + ...message, + content: message.content ?? null, + refusal: message.refusal ?? null, + }; + return ret; + } } - /** - * Creates an edited or extended image given one or more source images and a - * prompt. This endpoint only supports `gpt-image-1` and `dall-e-2`. - * - * @example - * ```ts - * const imagesResponse = await client.images.edit({ - * image: fs.createReadStream('path/to/file'), - * prompt: 'A cute baby sea otter wearing a beret', - * }); - * ``` - */ - edit(body, options) { - return this._client.post('/images/edits', multipartFormRequestOptions({ body, ...options })); + throw new error_OpenAIError('stream ended without producing a ChatCompletionMessage with role=assistant'); +}, _AbstractChatCompletionRunner_getFinalFunctionToolCall = function _AbstractChatCompletionRunner_getFinalFunctionToolCall() { + for (let i = this.messages.length - 1; i >= 0; i--) { + const message = this.messages[i]; + if (isAssistantMessage(message) && message?.tool_calls?.length) { + return message.tool_calls.filter((x) => x.type === 'function').at(-1)?.function; + } } - /** - * Creates an image given a prompt. - * [Learn more](https://platform.openai.com/docs/guides/images). - * - * @example - * ```ts - * const imagesResponse = await client.images.generate({ - * prompt: 'A cute baby sea otter', - * }); - * ``` - */ - generate(body, options) { - return this._client.post('/images/generations', { body, ...options }); + return; +}, _AbstractChatCompletionRunner_getFinalFunctionToolCallResult = function _AbstractChatCompletionRunner_getFinalFunctionToolCallResult() { + for (let i = this.messages.length - 1; i >= 0; i--) { + const message = this.messages[i]; + if (isToolMessage(message) && + message.content != null && + typeof message.content === 'string' && + this.messages.some((x) => x.role === 'assistant' && + x.tool_calls?.some((y) => y.type === 'function' && y.id === message.tool_call_id))) { + return message.content; + } } -} -//# sourceMappingURL=images.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/audio/speech.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -class Speech extends APIResource { - /** - * Generates audio from the input text. - * - * @example - * ```ts - * const speech = await client.audio.speech.create({ - * input: 'input', - * model: 'string', - * voice: 'ash', - * }); - * - * const content = await speech.blob(); - * console.log(content); - * ``` - */ - create(body, options) { - return this._client.post('/audio/speech', { - body, - ...options, - headers: { Accept: 'application/octet-stream', ...options?.headers }, - __binaryResponse: true, - }); + return; +}, _AbstractChatCompletionRunner_calculateTotalUsage = function _AbstractChatCompletionRunner_calculateTotalUsage() { + const total = { + completion_tokens: 0, + prompt_tokens: 0, + total_tokens: 0, + }; + for (const { usage } of this._chatCompletions) { + if (usage) { + total.completion_tokens += usage.completion_tokens; + total.prompt_tokens += usage.prompt_tokens; + total.total_tokens += usage.total_tokens; + } } -} -//# sourceMappingURL=speech.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/audio/transcriptions.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - -class Transcriptions extends APIResource { - create(body, options) { - return this._client.post('/audio/transcriptions', multipartFormRequestOptions({ - body, - ...options, - stream: body.stream ?? false, - __metadata: { model: body.model }, - })); + return total; +}, _AbstractChatCompletionRunner_validateParams = function _AbstractChatCompletionRunner_validateParams(params) { + if (params.n != null && params.n > 1) { + throw new error_OpenAIError('ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.'); } -} -//# sourceMappingURL=transcriptions.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/audio/translations.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +}, _AbstractChatCompletionRunner_stringifyFunctionCallResult = function _AbstractChatCompletionRunner_stringifyFunctionCallResult(rawContent) { + return (typeof rawContent === 'string' ? rawContent + : rawContent === undefined ? 'undefined' + : JSON.stringify(rawContent)); +}; +//# sourceMappingURL=AbstractChatCompletionRunner.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/lib/ChatCompletionRunner.mjs -class Translations extends APIResource { - create(body, options) { - return this._client.post('/audio/translations', multipartFormRequestOptions({ body, ...options, __metadata: { model: body.model } })); +class ChatCompletionRunner extends AbstractChatCompletionRunner { + static runTools(client, params, options) { + const runner = new ChatCompletionRunner(); + const opts = { + ...options, + headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'runTools' }, + }; + runner._run(() => runner._runTools(client, params, opts)); + return runner; } -} -//# sourceMappingURL=translations.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/audio/audio.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - - - -class Audio extends APIResource { - constructor() { - super(...arguments); - this.transcriptions = new Transcriptions(this._client); - this.translations = new Translations(this._client); - this.speech = new Speech(this._client); + _addMessage(message, emit = true) { + super._addMessage(message, emit); + if (isAssistantMessage(message) && message.content) { + this._emit('content', message.content); + } } } -Audio.Transcriptions = Transcriptions; -Audio.Translations = Translations; -Audio.Speech = Speech; -//# sourceMappingURL=audio.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/moderations.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -class Moderations extends APIResource { - /** - * Classifies if text and/or image inputs are potentially harmful. Learn more in - * the [moderation guide](https://platform.openai.com/docs/guides/moderation). - */ - create(body, options) { - return this._client.post('/moderations', { body, ...options }); - } +//# sourceMappingURL=ChatCompletionRunner.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/_vendor/partial-json-parser/parser.mjs +const STR = 0b000000001; +const NUM = 0b000000010; +const ARR = 0b000000100; +const OBJ = 0b000001000; +const NULL = 0b000010000; +const BOOL = 0b000100000; +const NAN = 0b001000000; +const INFINITY = 0b010000000; +const MINUS_INFINITY = 0b100000000; +const INF = INFINITY | MINUS_INFINITY; +const SPECIAL = NULL | BOOL | INF | NAN; +const ATOM = STR | NUM | SPECIAL; +const COLLECTION = ARR | OBJ; +const ALL = ATOM | COLLECTION; +const Allow = { + STR, + NUM, + ARR, + OBJ, + NULL, + BOOL, + NAN, + INFINITY, + MINUS_INFINITY, + INF, + SPECIAL, + ATOM, + COLLECTION, + ALL, +}; +// The JSON string segment was unable to be parsed completely +class PartialJSON extends Error { } -//# sourceMappingURL=moderations.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/models.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - -class Models extends APIResource { - /** - * Retrieves a model instance, providing basic information about the model such as - * the owner and permissioning. - */ - retrieve(model, options) { - return this._client.get(`/models/${model}`, options); - } - /** - * Lists the currently available models, and provides basic information about each - * one such as the owner and availability. - */ - list(options) { - return this._client.getAPIList('/models', ModelsPage, options); - } - /** - * Delete a fine-tuned model. You must have the Owner role in your organization to - * delete a model. - */ - del(model, options) { - return this._client.delete(`/models/${model}`, options); - } +class MalformedJSON extends Error { } /** - * Note: no pagination actually occurs yet, this is for forwards-compatibility. + * Parse incomplete JSON + * @param {string} jsonString Partial JSON to be parsed + * @param {number} allowPartial Specify what types are allowed to be partial, see {@link Allow} for details + * @returns The parsed JSON + * @throws {PartialJSON} If the JSON is incomplete (related to the `allow` parameter) + * @throws {MalformedJSON} If the JSON is malformed */ -class ModelsPage extends Page { -} -Models.ModelsPage = ModelsPage; -//# sourceMappingURL=models.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/fine-tuning/methods.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -class Methods extends APIResource { -} -//# sourceMappingURL=methods.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/fine-tuning/alpha/graders.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -class Graders extends APIResource { - /** - * Run a grader. - * - * @example - * ```ts - * const response = await client.fineTuning.alpha.graders.run({ - * grader: { - * input: 'input', - * name: 'name', - * operation: 'eq', - * reference: 'reference', - * type: 'string_check', - * }, - * model_sample: 'model_sample', - * reference_answer: 'string', - * }); - * ``` - */ - run(body, options) { - return this._client.post('/fine_tuning/alpha/graders/run', { body, ...options }); +function parseJSON(jsonString, allowPartial = Allow.ALL) { + if (typeof jsonString !== 'string') { + throw new TypeError(`expecting str, got ${typeof jsonString}`); } - /** - * Validate a grader. - * - * @example - * ```ts - * const response = - * await client.fineTuning.alpha.graders.validate({ - * grader: { - * input: 'input', - * name: 'name', - * operation: 'eq', - * reference: 'reference', - * type: 'string_check', - * }, - * }); - * ``` - */ - validate(body, options) { - return this._client.post('/fine_tuning/alpha/graders/validate', { body, ...options }); + if (!jsonString.trim()) { + throw new Error(`${jsonString} is empty`); } + return _parseJSON(jsonString.trim(), allowPartial); } -//# sourceMappingURL=graders.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/fine-tuning/alpha/alpha.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +const _parseJSON = (jsonString, allow) => { + const length = jsonString.length; + let index = 0; + const markPartialJSON = (msg) => { + throw new PartialJSON(`${msg} at position ${index}`); + }; + const throwMalformedError = (msg) => { + throw new MalformedJSON(`${msg} at position ${index}`); + }; + const parseAny = () => { + skipBlank(); + if (index >= length) + markPartialJSON('Unexpected end of input'); + if (jsonString[index] === '"') + return parseStr(); + if (jsonString[index] === '{') + return parseObj(); + if (jsonString[index] === '[') + return parseArr(); + if (jsonString.substring(index, index + 4) === 'null' || + (Allow.NULL & allow && length - index < 4 && 'null'.startsWith(jsonString.substring(index)))) { + index += 4; + return null; + } + if (jsonString.substring(index, index + 4) === 'true' || + (Allow.BOOL & allow && length - index < 4 && 'true'.startsWith(jsonString.substring(index)))) { + index += 4; + return true; + } + if (jsonString.substring(index, index + 5) === 'false' || + (Allow.BOOL & allow && length - index < 5 && 'false'.startsWith(jsonString.substring(index)))) { + index += 5; + return false; + } + if (jsonString.substring(index, index + 8) === 'Infinity' || + (Allow.INFINITY & allow && length - index < 8 && 'Infinity'.startsWith(jsonString.substring(index)))) { + index += 8; + return Infinity; + } + if (jsonString.substring(index, index + 9) === '-Infinity' || + (Allow.MINUS_INFINITY & allow && + 1 < length - index && + length - index < 9 && + '-Infinity'.startsWith(jsonString.substring(index)))) { + index += 9; + return -Infinity; + } + if (jsonString.substring(index, index + 3) === 'NaN' || + (Allow.NAN & allow && length - index < 3 && 'NaN'.startsWith(jsonString.substring(index)))) { + index += 3; + return NaN; + } + return parseNum(); + }; + const parseStr = () => { + const start = index; + let escape = false; + index++; // skip initial quote + while (index < length && (jsonString[index] !== '"' || (escape && jsonString[index - 1] === '\\'))) { + escape = jsonString[index] === '\\' ? !escape : false; + index++; + } + if (jsonString.charAt(index) == '"') { + try { + return JSON.parse(jsonString.substring(start, ++index - Number(escape))); + } + catch (e) { + throwMalformedError(String(e)); + } + } + else if (Allow.STR & allow) { + try { + return JSON.parse(jsonString.substring(start, index - Number(escape)) + '"'); + } + catch (e) { + // SyntaxError: Invalid escape sequence + return JSON.parse(jsonString.substring(start, jsonString.lastIndexOf('\\')) + '"'); + } + } + markPartialJSON('Unterminated string literal'); + }; + const parseObj = () => { + index++; // skip initial brace + skipBlank(); + const obj = {}; + try { + while (jsonString[index] !== '}') { + skipBlank(); + if (index >= length && Allow.OBJ & allow) + return obj; + const key = parseStr(); + skipBlank(); + index++; // skip colon + try { + const value = parseAny(); + Object.defineProperty(obj, key, { value, writable: true, enumerable: true, configurable: true }); + } + catch (e) { + if (Allow.OBJ & allow) + return obj; + else + throw e; + } + skipBlank(); + if (jsonString[index] === ',') + index++; // skip comma + } + } + catch (e) { + if (Allow.OBJ & allow) + return obj; + else + markPartialJSON("Expected '}' at end of object"); + } + index++; // skip final brace + return obj; + }; + const parseArr = () => { + index++; // skip initial bracket + const arr = []; + try { + while (jsonString[index] !== ']') { + arr.push(parseAny()); + skipBlank(); + if (jsonString[index] === ',') { + index++; // skip comma + } + } + } + catch (e) { + if (Allow.ARR & allow) { + return arr; + } + markPartialJSON("Expected ']' at end of array"); + } + index++; // skip final bracket + return arr; + }; + const parseNum = () => { + if (index === 0) { + if (jsonString === '-' && Allow.NUM & allow) + markPartialJSON("Not sure what '-' is"); + try { + return JSON.parse(jsonString); + } + catch (e) { + if (Allow.NUM & allow) { + try { + if ('.' === jsonString[jsonString.length - 1]) + return JSON.parse(jsonString.substring(0, jsonString.lastIndexOf('.'))); + return JSON.parse(jsonString.substring(0, jsonString.lastIndexOf('e'))); + } + catch (e) { } + } + throwMalformedError(String(e)); + } + } + const start = index; + if (jsonString[index] === '-') + index++; + while (jsonString[index] && !',]}'.includes(jsonString[index])) + index++; + if (index == length && !(Allow.NUM & allow)) + markPartialJSON('Unterminated number literal'); + try { + return JSON.parse(jsonString.substring(start, index)); + } + catch (e) { + if (jsonString.substring(start, index) === '-' && Allow.NUM & allow) + markPartialJSON("Not sure what '-' is"); + try { + return JSON.parse(jsonString.substring(start, jsonString.lastIndexOf('e'))); + } + catch (e) { + throwMalformedError(String(e)); + } + } + }; + const skipBlank = () => { + while (index < length && ' \n\r\t'.includes(jsonString[index])) { + index++; + } + }; + return parseAny(); +}; +// using this function with malformed JSON is undefined behavior +const partialParse = (input) => parseJSON(input, Allow.ALL ^ Allow.NUM); + +//# sourceMappingURL=parser.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/streaming.mjs + +//# sourceMappingURL=streaming.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/lib/ChatCompletionStream.mjs +var _ChatCompletionStream_instances, _ChatCompletionStream_params, _ChatCompletionStream_choiceEventStates, _ChatCompletionStream_currentChatCompletionSnapshot, _ChatCompletionStream_beginRequest, _ChatCompletionStream_getChoiceEventState, _ChatCompletionStream_addChunk, _ChatCompletionStream_emitToolCallDoneEvent, _ChatCompletionStream_emitContentDoneEvents, _ChatCompletionStream_endRequest, _ChatCompletionStream_getAutoParseableResponseFormat, _ChatCompletionStream_accumulateChatCompletion; -class Alpha extends APIResource { - constructor() { - super(...arguments); - this.graders = new Graders(this._client); - } -} -Alpha.Graders = Graders; -//# sourceMappingURL=alpha.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/fine-tuning/checkpoints/permissions.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -class Permissions extends APIResource { +class ChatCompletionStream extends AbstractChatCompletionRunner { + constructor(params) { + super(); + _ChatCompletionStream_instances.add(this); + _ChatCompletionStream_params.set(this, void 0); + _ChatCompletionStream_choiceEventStates.set(this, void 0); + _ChatCompletionStream_currentChatCompletionSnapshot.set(this, void 0); + __classPrivateFieldSet(this, _ChatCompletionStream_params, params, "f"); + __classPrivateFieldSet(this, _ChatCompletionStream_choiceEventStates, [], "f"); + } + get currentChatCompletionSnapshot() { + return __classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f"); + } /** - * **NOTE:** Calling this endpoint requires an [admin API key](../admin-api-keys). - * - * This enables organization owners to share fine-tuned models with other projects - * in their organization. + * Intended for use on the frontend, consuming a stream produced with + * `.toReadableStream()` on the backend. * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const permissionCreateResponse of client.fineTuning.checkpoints.permissions.create( - * 'ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd', - * { project_ids: ['string'] }, - * )) { - * // ... - * } - * ``` + * Note that messages sent to the model do not appear in `.on('message')` + * in this context. */ - create(fineTunedModelCheckpoint, body, options) { - return this._client.getAPIList(`/fine_tuning/checkpoints/${fineTunedModelCheckpoint}/permissions`, PermissionCreateResponsesPage, { body, method: 'post', ...options }); + static fromReadableStream(stream) { + const runner = new ChatCompletionStream(null); + runner._run(() => runner._fromReadableStream(stream)); + return runner; } - retrieve(fineTunedModelCheckpoint, query = {}, options) { - if (isRequestOptions(query)) { - return this.retrieve(fineTunedModelCheckpoint, {}, query); + static createChatCompletion(client, params, options) { + const runner = new ChatCompletionStream(params); + runner._run(() => runner._runChatCompletion(client, { ...params, stream: true }, { ...options, headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' } })); + return runner; + } + async _createChatCompletion(client, params, options) { + super._createChatCompletion; + const signal = options?.signal; + if (signal) { + if (signal.aborted) + this.controller.abort(); + signal.addEventListener('abort', () => this.controller.abort()); } - return this._client.get(`/fine_tuning/checkpoints/${fineTunedModelCheckpoint}/permissions`, { - query, - ...options, + __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_beginRequest).call(this); + const stream = await client.chat.completions.create({ ...params, stream: true }, { ...options, signal: this.controller.signal }); + this._connected(); + for await (const chunk of stream) { + __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_addChunk).call(this, chunk); + } + if (stream.controller.signal?.aborted) { + throw new APIUserAbortError(); + } + return this._addChatCompletion(__classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this)); + } + async _fromReadableStream(readableStream, options) { + const signal = options?.signal; + if (signal) { + if (signal.aborted) + this.controller.abort(); + signal.addEventListener('abort', () => this.controller.abort()); + } + __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_beginRequest).call(this); + this._connected(); + const stream = Stream.fromReadableStream(readableStream, this.controller); + let chatId; + for await (const chunk of stream) { + if (chatId && chatId !== chunk.id) { + // A new request has been made. + this._addChatCompletion(__classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this)); + } + __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_addChunk).call(this, chunk); + chatId = chunk.id; + } + if (stream.controller.signal?.aborted) { + throw new APIUserAbortError(); + } + return this._addChatCompletion(__classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this)); + } + [(_ChatCompletionStream_params = new WeakMap(), _ChatCompletionStream_choiceEventStates = new WeakMap(), _ChatCompletionStream_currentChatCompletionSnapshot = new WeakMap(), _ChatCompletionStream_instances = new WeakSet(), _ChatCompletionStream_beginRequest = function _ChatCompletionStream_beginRequest() { + if (this.ended) + return; + __classPrivateFieldSet(this, _ChatCompletionStream_currentChatCompletionSnapshot, undefined, "f"); + }, _ChatCompletionStream_getChoiceEventState = function _ChatCompletionStream_getChoiceEventState(choice) { + let state = __classPrivateFieldGet(this, _ChatCompletionStream_choiceEventStates, "f")[choice.index]; + if (state) { + return state; + } + state = { + content_done: false, + refusal_done: false, + logprobs_content_done: false, + logprobs_refusal_done: false, + done_tool_calls: new Set(), + current_tool_call_index: null, + }; + __classPrivateFieldGet(this, _ChatCompletionStream_choiceEventStates, "f")[choice.index] = state; + return state; + }, _ChatCompletionStream_addChunk = function _ChatCompletionStream_addChunk(chunk) { + if (this.ended) + return; + const completion = __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_accumulateChatCompletion).call(this, chunk); + this._emit('chunk', chunk, completion); + for (const choice of chunk.choices) { + const choiceSnapshot = completion.choices[choice.index]; + if (choice.delta.content != null && + choiceSnapshot.message?.role === 'assistant' && + choiceSnapshot.message?.content) { + this._emit('content', choice.delta.content, choiceSnapshot.message.content); + this._emit('content.delta', { + delta: choice.delta.content, + snapshot: choiceSnapshot.message.content, + parsed: choiceSnapshot.message.parsed, + }); + } + if (choice.delta.refusal != null && + choiceSnapshot.message?.role === 'assistant' && + choiceSnapshot.message?.refusal) { + this._emit('refusal.delta', { + delta: choice.delta.refusal, + snapshot: choiceSnapshot.message.refusal, + }); + } + if (choice.logprobs?.content != null && choiceSnapshot.message?.role === 'assistant') { + this._emit('logprobs.content.delta', { + content: choice.logprobs?.content, + snapshot: choiceSnapshot.logprobs?.content ?? [], + }); + } + if (choice.logprobs?.refusal != null && choiceSnapshot.message?.role === 'assistant') { + this._emit('logprobs.refusal.delta', { + refusal: choice.logprobs?.refusal, + snapshot: choiceSnapshot.logprobs?.refusal ?? [], + }); + } + const state = __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot); + if (choiceSnapshot.finish_reason) { + __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitContentDoneEvents).call(this, choiceSnapshot); + if (state.current_tool_call_index != null) { + __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitToolCallDoneEvent).call(this, choiceSnapshot, state.current_tool_call_index); + } + } + for (const toolCall of choice.delta.tool_calls ?? []) { + if (state.current_tool_call_index !== toolCall.index) { + __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitContentDoneEvents).call(this, choiceSnapshot); + // new tool call started, the previous one is done + if (state.current_tool_call_index != null) { + __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitToolCallDoneEvent).call(this, choiceSnapshot, state.current_tool_call_index); + } + } + state.current_tool_call_index = toolCall.index; + } + for (const toolCallDelta of choice.delta.tool_calls ?? []) { + const toolCallSnapshot = choiceSnapshot.message.tool_calls?.[toolCallDelta.index]; + if (!toolCallSnapshot?.type) { + continue; + } + if (toolCallSnapshot?.type === 'function') { + this._emit('tool_calls.function.arguments.delta', { + name: toolCallSnapshot.function?.name, + index: toolCallDelta.index, + arguments: toolCallSnapshot.function.arguments, + parsed_arguments: toolCallSnapshot.function.parsed_arguments, + arguments_delta: toolCallDelta.function?.arguments ?? '', + }); + } + else { + assertNever(toolCallSnapshot?.type); + } + } + } + }, _ChatCompletionStream_emitToolCallDoneEvent = function _ChatCompletionStream_emitToolCallDoneEvent(choiceSnapshot, toolCallIndex) { + const state = __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot); + if (state.done_tool_calls.has(toolCallIndex)) { + // we've already fired the done event + return; + } + const toolCallSnapshot = choiceSnapshot.message.tool_calls?.[toolCallIndex]; + if (!toolCallSnapshot) { + throw new Error('no tool call snapshot'); + } + if (!toolCallSnapshot.type) { + throw new Error('tool call snapshot missing `type`'); + } + if (toolCallSnapshot.type === 'function') { + const inputTool = __classPrivateFieldGet(this, _ChatCompletionStream_params, "f")?.tools?.find((tool) => isChatCompletionFunctionTool(tool) && tool.function.name === toolCallSnapshot.function.name); // TS doesn't narrow based on isChatCompletionTool + this._emit('tool_calls.function.arguments.done', { + name: toolCallSnapshot.function.name, + index: toolCallIndex, + arguments: toolCallSnapshot.function.arguments, + parsed_arguments: isAutoParsableTool(inputTool) ? inputTool.$parseRaw(toolCallSnapshot.function.arguments) + : inputTool?.function.strict ? JSON.parse(toolCallSnapshot.function.arguments) + : null, + }); + } + else { + assertNever(toolCallSnapshot.type); + } + }, _ChatCompletionStream_emitContentDoneEvents = function _ChatCompletionStream_emitContentDoneEvents(choiceSnapshot) { + const state = __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot); + if (choiceSnapshot.message.content && !state.content_done) { + state.content_done = true; + const responseFormat = __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getAutoParseableResponseFormat).call(this); + this._emit('content.done', { + content: choiceSnapshot.message.content, + parsed: responseFormat ? responseFormat.$parseRaw(choiceSnapshot.message.content) : null, + }); + } + if (choiceSnapshot.message.refusal && !state.refusal_done) { + state.refusal_done = true; + this._emit('refusal.done', { refusal: choiceSnapshot.message.refusal }); + } + if (choiceSnapshot.logprobs?.content && !state.logprobs_content_done) { + state.logprobs_content_done = true; + this._emit('logprobs.content.done', { content: choiceSnapshot.logprobs.content }); + } + if (choiceSnapshot.logprobs?.refusal && !state.logprobs_refusal_done) { + state.logprobs_refusal_done = true; + this._emit('logprobs.refusal.done', { refusal: choiceSnapshot.logprobs.refusal }); + } + }, _ChatCompletionStream_endRequest = function _ChatCompletionStream_endRequest() { + if (this.ended) { + throw new error_OpenAIError(`stream has ended, this shouldn't happen`); + } + const snapshot = __classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f"); + if (!snapshot) { + throw new error_OpenAIError(`request ended without sending any chunks`); + } + __classPrivateFieldSet(this, _ChatCompletionStream_currentChatCompletionSnapshot, undefined, "f"); + __classPrivateFieldSet(this, _ChatCompletionStream_choiceEventStates, [], "f"); + return finalizeChatCompletion(snapshot, __classPrivateFieldGet(this, _ChatCompletionStream_params, "f")); + }, _ChatCompletionStream_getAutoParseableResponseFormat = function _ChatCompletionStream_getAutoParseableResponseFormat() { + const responseFormat = __classPrivateFieldGet(this, _ChatCompletionStream_params, "f")?.response_format; + if (isAutoParsableResponseFormat(responseFormat)) { + return responseFormat; + } + return null; + }, _ChatCompletionStream_accumulateChatCompletion = function _ChatCompletionStream_accumulateChatCompletion(chunk) { + var _a, _b, _c, _d; + let snapshot = __classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f"); + const { choices, ...rest } = chunk; + if (!snapshot) { + snapshot = __classPrivateFieldSet(this, _ChatCompletionStream_currentChatCompletionSnapshot, { + ...rest, + choices: [], + }, "f"); + } + else { + Object.assign(snapshot, rest); + } + for (const { delta, finish_reason, index, logprobs = null, ...other } of chunk.choices) { + let choice = snapshot.choices[index]; + if (!choice) { + choice = snapshot.choices[index] = { finish_reason, index, message: {}, logprobs, ...other }; + } + if (logprobs) { + if (!choice.logprobs) { + choice.logprobs = Object.assign({}, logprobs); + } + else { + const { content, refusal, ...rest } = logprobs; + assertIsEmpty(rest); + Object.assign(choice.logprobs, rest); + if (content) { + (_a = choice.logprobs).content ?? (_a.content = []); + choice.logprobs.content.push(...content); + } + if (refusal) { + (_b = choice.logprobs).refusal ?? (_b.refusal = []); + choice.logprobs.refusal.push(...refusal); + } + } + } + if (finish_reason) { + choice.finish_reason = finish_reason; + if (__classPrivateFieldGet(this, _ChatCompletionStream_params, "f") && hasAutoParseableInput(__classPrivateFieldGet(this, _ChatCompletionStream_params, "f"))) { + if (finish_reason === 'length') { + throw new LengthFinishReasonError(); + } + if (finish_reason === 'content_filter') { + throw new ContentFilterFinishReasonError(); + } + } + } + Object.assign(choice, other); + if (!delta) + continue; // Shouldn't happen; just in case. + const { content, refusal, function_call, role, tool_calls, ...rest } = delta; + assertIsEmpty(rest); + Object.assign(choice.message, rest); + if (refusal) { + choice.message.refusal = (choice.message.refusal || '') + refusal; + } + if (role) + choice.message.role = role; + if (function_call) { + if (!choice.message.function_call) { + choice.message.function_call = function_call; + } + else { + if (function_call.name) + choice.message.function_call.name = function_call.name; + if (function_call.arguments) { + (_c = choice.message.function_call).arguments ?? (_c.arguments = ''); + choice.message.function_call.arguments += function_call.arguments; + } + } + } + if (content) { + choice.message.content = (choice.message.content || '') + content; + if (!choice.message.refusal && __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getAutoParseableResponseFormat).call(this)) { + choice.message.parsed = partialParse(choice.message.content); + } + } + if (tool_calls) { + if (!choice.message.tool_calls) + choice.message.tool_calls = []; + for (const { index, id, type, function: fn, ...rest } of tool_calls) { + const tool_call = ((_d = choice.message.tool_calls)[index] ?? (_d[index] = {})); + Object.assign(tool_call, rest); + if (id) + tool_call.id = id; + if (type) + tool_call.type = type; + if (fn) + tool_call.function ?? (tool_call.function = { name: fn.name ?? '', arguments: '' }); + if (fn?.name) + tool_call.function.name = fn.name; + if (fn?.arguments) { + tool_call.function.arguments += fn.arguments; + if (shouldParseToolCall(__classPrivateFieldGet(this, _ChatCompletionStream_params, "f"), tool_call)) { + tool_call.function.parsed_arguments = partialParse(tool_call.function.arguments); + } + } + } + } + } + return snapshot; + }, Symbol.asyncIterator)]() { + const pushQueue = []; + const readQueue = []; + let done = false; + this.on('chunk', (chunk) => { + const reader = readQueue.shift(); + if (reader) { + reader.resolve(chunk); + } + else { + pushQueue.push(chunk); + } + }); + this.on('end', () => { + done = true; + for (const reader of readQueue) { + reader.resolve(undefined); + } + readQueue.length = 0; + }); + this.on('abort', (err) => { + done = true; + for (const reader of readQueue) { + reader.reject(err); + } + readQueue.length = 0; + }); + this.on('error', (err) => { + done = true; + for (const reader of readQueue) { + reader.reject(err); + } + readQueue.length = 0; }); + return { + next: async () => { + if (!pushQueue.length) { + if (done) { + return { value: undefined, done: true }; + } + return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((chunk) => (chunk ? { value: chunk, done: false } : { value: undefined, done: true })); + } + const chunk = pushQueue.shift(); + return { value: chunk, done: false }; + }, + return: async () => { + this.abort(); + return { value: undefined, done: true }; + }, + }; } - /** - * **NOTE:** This endpoint requires an [admin API key](../admin-api-keys). - * - * Organization owners can use this endpoint to delete a permission for a - * fine-tuned model checkpoint. - * - * @example - * ```ts - * const permission = - * await client.fineTuning.checkpoints.permissions.del( - * 'ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd', - * 'cp_zc4Q7MP6XxulcVzj4MZdwsAB', - * ); - * ``` - */ - del(fineTunedModelCheckpoint, permissionId, options) { - return this._client.delete(`/fine_tuning/checkpoints/${fineTunedModelCheckpoint}/permissions/${permissionId}`, options); + toReadableStream() { + const stream = new Stream(this[Symbol.asyncIterator].bind(this), this.controller); + return stream.toReadableStream(); } } +function finalizeChatCompletion(snapshot, params) { + const { id, choices, created, model, system_fingerprint, ...rest } = snapshot; + const completion = { + ...rest, + id, + choices: choices.map(({ message, finish_reason, index, logprobs, ...choiceRest }) => { + if (!finish_reason) { + throw new error_OpenAIError(`missing finish_reason for choice ${index}`); + } + const { content = null, function_call, tool_calls, ...messageRest } = message; + const role = message.role; // this is what we expect; in theory it could be different which would make our types a slight lie but would be fine. + if (!role) { + throw new error_OpenAIError(`missing role for choice ${index}`); + } + if (function_call) { + const { arguments: args, name } = function_call; + if (args == null) { + throw new error_OpenAIError(`missing function_call.arguments for choice ${index}`); + } + if (!name) { + throw new error_OpenAIError(`missing function_call.name for choice ${index}`); + } + return { + ...choiceRest, + message: { + content, + function_call: { arguments: args, name }, + role, + refusal: message.refusal ?? null, + }, + finish_reason, + index, + logprobs, + }; + } + if (tool_calls) { + return { + ...choiceRest, + index, + finish_reason, + logprobs, + message: { + ...messageRest, + role, + content, + refusal: message.refusal ?? null, + tool_calls: tool_calls.map((tool_call, i) => { + const { function: fn, type, id, ...toolRest } = tool_call; + const { arguments: args, name, ...fnRest } = fn || {}; + if (id == null) { + throw new error_OpenAIError(`missing choices[${index}].tool_calls[${i}].id\n${str(snapshot)}`); + } + if (type == null) { + throw new error_OpenAIError(`missing choices[${index}].tool_calls[${i}].type\n${str(snapshot)}`); + } + if (name == null) { + throw new error_OpenAIError(`missing choices[${index}].tool_calls[${i}].function.name\n${str(snapshot)}`); + } + if (args == null) { + throw new error_OpenAIError(`missing choices[${index}].tool_calls[${i}].function.arguments\n${str(snapshot)}`); + } + return { ...toolRest, id, type, function: { ...fnRest, name, arguments: args } }; + }), + }, + }; + } + return { + ...choiceRest, + message: { ...messageRest, content, role, refusal: message.refusal ?? null }, + finish_reason, + index, + logprobs, + }; + }), + created, + model, + object: 'chat.completion', + ...(system_fingerprint ? { system_fingerprint } : {}), + }; + return maybeParseChatCompletion(completion, params); +} +function str(x) { + return JSON.stringify(x); +} /** - * Note: no pagination actually occurs yet, this is for forwards-compatibility. + * Ensures the given argument is an empty object, useful for + * asserting that all known properties on an object have been + * destructured. */ -class PermissionCreateResponsesPage extends Page { +function assertIsEmpty(obj) { + return; } -Permissions.PermissionCreateResponsesPage = PermissionCreateResponsesPage; -//# sourceMappingURL=permissions.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/fine-tuning/checkpoints/checkpoints.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - +function assertNever(_x) { } +//# sourceMappingURL=ChatCompletionStream.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/lib/ChatCompletionStreamingRunner.mjs -class Checkpoints extends APIResource { - constructor() { - super(...arguments); - this.permissions = new Permissions(this._client); +class ChatCompletionStreamingRunner extends ChatCompletionStream { + static fromReadableStream(stream) { + const runner = new ChatCompletionStreamingRunner(null); + runner._run(() => runner._fromReadableStream(stream)); + return runner; + } + static runTools(client, params, options) { + const runner = new ChatCompletionStreamingRunner( + // @ts-expect-error TODO these types are incompatible + params); + const opts = { + ...options, + headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'runTools' }, + }; + runner._run(() => runner._runTools(client, params, opts)); + return runner; } } -Checkpoints.Permissions = Permissions; -Checkpoints.PermissionCreateResponsesPage = PermissionCreateResponsesPage; -//# sourceMappingURL=checkpoints.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/fine-tuning/jobs/checkpoints.mjs +//# sourceMappingURL=ChatCompletionStreamingRunner.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/chat/completions/completions.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -class checkpoints_Checkpoints extends APIResource { - list(fineTuningJobId, query = {}, options) { - if (isRequestOptions(query)) { - return this.list(fineTuningJobId, {}, query); - } - return this._client.getAPIList(`/fine_tuning/jobs/${fineTuningJobId}/checkpoints`, FineTuningJobCheckpointsPage, { query, ...options }); - } -} -class FineTuningJobCheckpointsPage extends CursorPage { -} -checkpoints_Checkpoints.FineTuningJobCheckpointsPage = FineTuningJobCheckpointsPage; -//# sourceMappingURL=checkpoints.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/fine-tuning/jobs/jobs.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -class Jobs extends APIResource { + +class Completions extends APIResource { constructor() { super(...arguments); - this.checkpoints = new checkpoints_Checkpoints(this._client); + this.messages = new Messages(this._client); + } + create(body, options) { + return this._client.post('/chat/completions', { body, ...options, stream: body.stream ?? false }); } /** - * Creates a fine-tuning job which begins the process of creating a new model from - * a given dataset. - * - * Response includes details of the enqueued job including job status and the name - * of the fine-tuned models once complete. - * - * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/fine-tuning) + * Get a stored chat completion. Only Chat Completions that have been created with + * the `store` parameter set to `true` will be returned. * * @example * ```ts - * const fineTuningJob = await client.fineTuning.jobs.create({ - * model: 'gpt-4o-mini', - * training_file: 'file-abc123', - * }); + * const chatCompletion = + * await client.chat.completions.retrieve('completion_id'); * ``` */ - create(body, options) { - return this._client.post('/fine_tuning/jobs', { body, ...options }); + retrieve(completionID, options) { + return this._client.get(path `/chat/completions/${completionID}`, options); } /** - * Get info about a fine-tuning job. - * - * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/fine-tuning) + * Modify a stored chat completion. Only Chat Completions that have been created + * with the `store` parameter set to `true` can be modified. Currently, the only + * supported modification is to update the `metadata` field. * * @example * ```ts - * const fineTuningJob = await client.fineTuning.jobs.retrieve( - * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', + * const chatCompletion = await client.chat.completions.update( + * 'completion_id', + * { metadata: { foo: 'string' } }, * ); * ``` */ - retrieve(fineTuningJobId, options) { - return this._client.get(`/fine_tuning/jobs/${fineTuningJobId}`, options); - } - list(query = {}, options) { - if (isRequestOptions(query)) { - return this.list({}, query); - } - return this._client.getAPIList('/fine_tuning/jobs', FineTuningJobsPage, { query, ...options }); + update(completionID, body, options) { + return this._client.post(path `/chat/completions/${completionID}`, { body, ...options }); } /** - * Immediately cancel a fine-tune job. + * List stored Chat Completions. Only Chat Completions that have been stored with + * the `store` parameter set to `true` will be returned. * * @example * ```ts - * const fineTuningJob = await client.fineTuning.jobs.cancel( - * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', - * ); + * // Automatically fetches more pages as needed. + * for await (const chatCompletion of client.chat.completions.list()) { + * // ... + * } * ``` */ - cancel(fineTuningJobId, options) { - return this._client.post(`/fine_tuning/jobs/${fineTuningJobId}/cancel`, options); - } - listEvents(fineTuningJobId, query = {}, options) { - if (isRequestOptions(query)) { - return this.listEvents(fineTuningJobId, {}, query); - } - return this._client.getAPIList(`/fine_tuning/jobs/${fineTuningJobId}/events`, FineTuningJobEventsPage, { - query, - ...options, - }); + list(query = {}, options) { + return this._client.getAPIList('/chat/completions', (CursorPage), { query, ...options }); } /** - * Pause a fine-tune job. + * Delete a stored chat completion. Only Chat Completions that have been created + * with the `store` parameter set to `true` can be deleted. * * @example * ```ts - * const fineTuningJob = await client.fineTuning.jobs.pause( - * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', - * ); + * const chatCompletionDeleted = + * await client.chat.completions.delete('completion_id'); * ``` */ - pause(fineTuningJobId, options) { - return this._client.post(`/fine_tuning/jobs/${fineTuningJobId}/pause`, options); + delete(completionID, options) { + return this._client.delete(path `/chat/completions/${completionID}`, options); + } + parse(body, options) { + validateInputTools(body.tools); + return this._client.chat.completions + .create(body, { + ...options, + headers: { + ...options?.headers, + 'X-Stainless-Helper-Method': 'chat.completions.parse', + }, + }) + ._thenUnwrap((completion) => parseChatCompletion(completion, body)); + } + runTools(body, options) { + if (body.stream) { + return ChatCompletionStreamingRunner.runTools(this._client, body, options); + } + return ChatCompletionRunner.runTools(this._client, body, options); } /** - * Resume a fine-tune job. - * - * @example - * ```ts - * const fineTuningJob = await client.fineTuning.jobs.resume( - * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', - * ); - * ``` + * Creates a chat completion stream */ - resume(fineTuningJobId, options) { - return this._client.post(`/fine_tuning/jobs/${fineTuningJobId}/resume`, options); + stream(body, options) { + return ChatCompletionStream.createChatCompletion(this._client, body, options); } } -class FineTuningJobsPage extends CursorPage { -} -class FineTuningJobEventsPage extends CursorPage { -} -Jobs.FineTuningJobsPage = FineTuningJobsPage; -Jobs.FineTuningJobEventsPage = FineTuningJobEventsPage; -Jobs.Checkpoints = checkpoints_Checkpoints; -Jobs.FineTuningJobCheckpointsPage = FineTuningJobCheckpointsPage; -//# sourceMappingURL=jobs.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/fine-tuning/fine-tuning.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - +Completions.Messages = Messages; +//# sourceMappingURL=completions.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/chat/chat.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -class FineTuning extends APIResource { +class Chat extends APIResource { constructor() { super(...arguments); - this.methods = new Methods(this._client); - this.jobs = new Jobs(this._client); - this.checkpoints = new Checkpoints(this._client); - this.alpha = new Alpha(this._client); + this.completions = new Completions(this._client); } } -FineTuning.Methods = Methods; -FineTuning.Jobs = Jobs; -FineTuning.FineTuningJobsPage = FineTuningJobsPage; -FineTuning.FineTuningJobEventsPage = FineTuningJobEventsPage; -FineTuning.Checkpoints = Checkpoints; -FineTuning.Alpha = Alpha; -//# sourceMappingURL=fine-tuning.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/graders/grader-models.mjs +Chat.Completions = Completions; +//# sourceMappingURL=chat.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/chat/completions/index.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -class GraderModels extends APIResource { -} -//# sourceMappingURL=grader-models.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/graders/graders.mjs + + +//# sourceMappingURL=index.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/chat/index.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +//# sourceMappingURL=index.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/internal/headers.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -class graders_Graders extends APIResource { - constructor() { - super(...arguments); - this.graderModels = new GraderModels(this._client); +const brand_privateNullableHeaders = /* @__PURE__ */ Symbol('brand.privateNullableHeaders'); +function* iterateHeaders(headers) { + if (!headers) + return; + if (brand_privateNullableHeaders in headers) { + const { values, nulls } = headers; + yield* values.entries(); + for (const name of nulls) { + yield [name, null]; + } + return; } -} -graders_Graders.GraderModels = GraderModels; -//# sourceMappingURL=graders.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/lib/Util.mjs -/** - * Like `Promise.allSettled()` but throws an error if any promises are rejected. - */ -const allSettledWithThrow = async (promises) => { - const results = await Promise.allSettled(promises); - const rejected = results.filter((result) => result.status === 'rejected'); - if (rejected.length) { - for (const result of rejected) { - console.error(result.reason); + let shouldClear = false; + let iter; + if (headers instanceof Headers) { + iter = headers.entries(); + } + else if (isReadonlyArray(headers)) { + iter = headers; + } + else { + shouldClear = true; + iter = Object.entries(headers ?? {}); + } + for (let row of iter) { + const name = row[0]; + if (typeof name !== 'string') + throw new TypeError('expected header name to be a string'); + const values = isReadonlyArray(row[1]) ? row[1] : [row[1]]; + let didClear = false; + for (const value of values) { + if (value === undefined) + continue; + // Objects keys always overwrite older headers, they never append. + // Yield a null to clear the header before adding the new values. + if (shouldClear && !didClear) { + didClear = true; + yield [name, null]; + } + yield [name, value]; } - throw new Error(`${rejected.length} promise(s) failed - see the above errors`); } - // Note: TS was complaining about using `.filter().map()` here for some reason - const values = []; - for (const result of results) { - if (result.status === 'fulfilled') { - values.push(result.value); +} +const buildHeaders = (newHeaders) => { + const targetHeaders = new Headers(); + const nullHeaders = new Set(); + for (const headers of newHeaders) { + const seenHeaders = new Set(); + for (const [name, value] of iterateHeaders(headers)) { + const lowerName = name.toLowerCase(); + if (!seenHeaders.has(lowerName)) { + targetHeaders.delete(name); + seenHeaders.add(lowerName); + } + if (value === null) { + targetHeaders.delete(name); + nullHeaders.add(lowerName); + } + else { + targetHeaders.append(name, value); + nullHeaders.delete(lowerName); + } } } - return values; + return { [brand_privateNullableHeaders]: true, values: targetHeaders, nulls: nullHeaders }; }; -//# sourceMappingURL=Util.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/vector-stores/files.mjs +const isEmptyHeaders = (headers) => { + for (const _ of iterateHeaders(headers)) + return false; + return true; +}; +//# sourceMappingURL=headers.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/audio/speech.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -class files_Files extends APIResource { - /** - * Create a vector store file by attaching a - * [File](https://platform.openai.com/docs/api-reference/files) to a - * [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object). - */ - create(vectorStoreId, body, options) { - return this._client.post(`/vector_stores/${vectorStoreId}/files`, { - body, - ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, - }); - } - /** - * Retrieves a vector store file. - */ - retrieve(vectorStoreId, fileId, options) { - return this._client.get(`/vector_stores/${vectorStoreId}/files/${fileId}`, { - ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, - }); - } +class Speech extends APIResource { /** - * Update attributes on a vector store file. + * Generates audio from the input text. + * + * @example + * ```ts + * const speech = await client.audio.speech.create({ + * input: 'input', + * model: 'string', + * voice: 'ash', + * }); + * + * const content = await speech.blob(); + * console.log(content); + * ``` */ - update(vectorStoreId, fileId, body, options) { - return this._client.post(`/vector_stores/${vectorStoreId}/files/${fileId}`, { + create(body, options) { + return this._client.post('/audio/speech', { body, ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, - }); - } - list(vectorStoreId, query = {}, options) { - if (isRequestOptions(query)) { - return this.list(vectorStoreId, {}, query); - } - return this._client.getAPIList(`/vector_stores/${vectorStoreId}/files`, VectorStoreFilesPage, { - query, - ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, - }); - } - /** - * Delete a vector store file. This will remove the file from the vector store but - * the file itself will not be deleted. To delete the file, use the - * [delete file](https://platform.openai.com/docs/api-reference/files/delete) - * endpoint. - */ - del(vectorStoreId, fileId, options) { - return this._client.delete(`/vector_stores/${vectorStoreId}/files/${fileId}`, { - ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, + headers: buildHeaders([{ Accept: 'application/octet-stream' }, options?.headers]), + __binaryResponse: true, }); } - /** - * Attach a file to the given vector store and wait for it to be processed. - */ - async createAndPoll(vectorStoreId, body, options) { - const file = await this.create(vectorStoreId, body, options); - return await this.poll(vectorStoreId, file.id, options); - } - /** - * Wait for the vector store file to finish processing. - * - * Note: this will return even if the file failed to process, you need to check - * file.last_error and file.status to handle these cases - */ - async poll(vectorStoreId, fileId, options) { - const headers = { ...options?.headers, 'X-Stainless-Poll-Helper': 'true' }; - if (options?.pollIntervalMs) { - headers['X-Stainless-Custom-Poll-Interval'] = options.pollIntervalMs.toString(); - } - while (true) { - const fileResponse = await this.retrieve(vectorStoreId, fileId, { - ...options, - headers, - }).withResponse(); - const file = fileResponse.data; - switch (file.status) { - case 'in_progress': - let sleepInterval = 5000; - if (options?.pollIntervalMs) { - sleepInterval = options.pollIntervalMs; - } - else { - const headerInterval = fileResponse.response.headers.get('openai-poll-after-ms'); - if (headerInterval) { - const headerIntervalMs = parseInt(headerInterval); - if (!isNaN(headerIntervalMs)) { - sleepInterval = headerIntervalMs; - } - } - } - await sleep(sleepInterval); - break; - case 'failed': - case 'completed': - return file; - } - } - } - /** - * Upload a file to the `files` API and then attach it to the given vector store. - * - * Note the file will be asynchronously processed (you can use the alternative - * polling helper method to wait for processing to complete). - */ - async upload(vectorStoreId, file, options) { - const fileInfo = await this._client.files.create({ file: file, purpose: 'assistants' }, options); - return this.create(vectorStoreId, { file_id: fileInfo.id }, options); - } - /** - * Add a file to a vector store and poll until processing is complete. - */ - async uploadAndPoll(vectorStoreId, file, options) { - const fileInfo = await this.upload(vectorStoreId, file, options); - return await this.poll(vectorStoreId, fileInfo.id, options); - } - /** - * Retrieve the parsed contents of a vector store file. - */ - content(vectorStoreId, fileId, options) { - return this._client.getAPIList(`/vector_stores/${vectorStoreId}/files/${fileId}/content`, FileContentResponsesPage, { ...options, headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers } }); - } -} -class VectorStoreFilesPage extends CursorPage { -} -/** - * Note: no pagination actually occurs yet, this is for forwards-compatibility. - */ -class FileContentResponsesPage extends Page { } -files_Files.VectorStoreFilesPage = VectorStoreFilesPage; -files_Files.FileContentResponsesPage = FileContentResponsesPage; -//# sourceMappingURL=files.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/vector-stores/file-batches.mjs +//# sourceMappingURL=speech.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/audio/transcriptions.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - -class FileBatches extends APIResource { - /** - * Create a vector store file batch. - */ - create(vectorStoreId, body, options) { - return this._client.post(`/vector_stores/${vectorStoreId}/file_batches`, { +class Transcriptions extends APIResource { + create(body, options) { + return this._client.post('/audio/transcriptions', multipartFormRequestOptions({ body, ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, - }); - } - /** - * Retrieves a vector store file batch. - */ - retrieve(vectorStoreId, batchId, options) { - return this._client.get(`/vector_stores/${vectorStoreId}/file_batches/${batchId}`, { - ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, - }); - } - /** - * Cancel a vector store file batch. This attempts to cancel the processing of - * files in this batch as soon as possible. - */ - cancel(vectorStoreId, batchId, options) { - return this._client.post(`/vector_stores/${vectorStoreId}/file_batches/${batchId}/cancel`, { - ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, - }); - } - /** - * Create a vector store batch and poll until all files have been processed. - */ - async createAndPoll(vectorStoreId, body, options) { - const batch = await this.create(vectorStoreId, body); - return await this.poll(vectorStoreId, batch.id, options); - } - listFiles(vectorStoreId, batchId, query = {}, options) { - if (isRequestOptions(query)) { - return this.listFiles(vectorStoreId, batchId, {}, query); - } - return this._client.getAPIList(`/vector_stores/${vectorStoreId}/file_batches/${batchId}/files`, VectorStoreFilesPage, { query, ...options, headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers } }); - } - /** - * Wait for the given file batch to be processed. - * - * Note: this will return even if one of the files failed to process, you need to - * check batch.file_counts.failed_count to handle this case. - */ - async poll(vectorStoreId, batchId, options) { - const headers = { ...options?.headers, 'X-Stainless-Poll-Helper': 'true' }; - if (options?.pollIntervalMs) { - headers['X-Stainless-Custom-Poll-Interval'] = options.pollIntervalMs.toString(); - } - while (true) { - const { data: batch, response } = await this.retrieve(vectorStoreId, batchId, { - ...options, - headers, - }).withResponse(); - switch (batch.status) { - case 'in_progress': - let sleepInterval = 5000; - if (options?.pollIntervalMs) { - sleepInterval = options.pollIntervalMs; - } - else { - const headerInterval = response.headers.get('openai-poll-after-ms'); - if (headerInterval) { - const headerIntervalMs = parseInt(headerInterval); - if (!isNaN(headerIntervalMs)) { - sleepInterval = headerIntervalMs; - } - } - } - await sleep(sleepInterval); - break; - case 'failed': - case 'cancelled': - case 'completed': - return batch; - } - } - } - /** - * Uploads the given files concurrently and then creates a vector store file batch. - * - * The concurrency limit is configurable using the `maxConcurrency` parameter. - */ - async uploadAndPoll(vectorStoreId, { files, fileIds = [] }, options) { - if (files == null || files.length == 0) { - throw new Error(`No \`files\` provided to process. If you've already uploaded files you should use \`.createAndPoll()\` instead`); - } - const configuredConcurrency = options?.maxConcurrency ?? 5; - // We cap the number of workers at the number of files (so we don't start any unnecessary workers) - const concurrencyLimit = Math.min(configuredConcurrency, files.length); - const client = this._client; - const fileIterator = files.values(); - const allFileIds = [...fileIds]; - // This code is based on this design. The libraries don't accommodate our environment limits. - // https://stackoverflow.com/questions/40639432/what-is-the-best-way-to-limit-concurrency-when-using-es6s-promise-all - async function processFiles(iterator) { - for (let item of iterator) { - const fileObj = await client.files.create({ file: item, purpose: 'assistants' }, options); - allFileIds.push(fileObj.id); - } - } - // Start workers to process results - const workers = Array(concurrencyLimit).fill(fileIterator).map(processFiles); - // Wait for all processing to complete. - await allSettledWithThrow(workers); - return await this.createAndPoll(vectorStoreId, { - file_ids: allFileIds, - }); + stream: body.stream ?? false, + __metadata: { model: body.model }, + }, this._client)); } } +//# sourceMappingURL=transcriptions.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/audio/translations.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -//# sourceMappingURL=file-batches.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/vector-stores/vector-stores.mjs + +class Translations extends APIResource { + create(body, options) { + return this._client.post('/audio/translations', multipartFormRequestOptions({ body, ...options, __metadata: { model: body.model } }, this._client)); + } +} +//# sourceMappingURL=translations.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/audio/audio.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. @@ -72119,87 +66146,52 @@ class FileBatches extends APIResource { -class VectorStores extends APIResource { +class Audio extends APIResource { constructor() { super(...arguments); - this.files = new files_Files(this._client); - this.fileBatches = new FileBatches(this._client); + this.transcriptions = new Transcriptions(this._client); + this.translations = new Translations(this._client); + this.speech = new Speech(this._client); } +} +Audio.Transcriptions = Transcriptions; +Audio.Translations = Translations; +Audio.Speech = Speech; +//# sourceMappingURL=audio.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/batches.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + +class Batches extends APIResource { /** - * Create a vector store. + * Creates and executes a batch from an uploaded file of requests */ create(body, options) { - return this._client.post('/vector_stores', { - body, - ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, - }); + return this._client.post('/batches', { body, ...options }); } /** - * Retrieves a vector store. + * Retrieves a batch. */ - retrieve(vectorStoreId, options) { - return this._client.get(`/vector_stores/${vectorStoreId}`, { - ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, - }); + retrieve(batchID, options) { + return this._client.get(path `/batches/${batchID}`, options); } /** - * Modifies a vector store. + * List your organization's batches. */ - update(vectorStoreId, body, options) { - return this._client.post(`/vector_stores/${vectorStoreId}`, { - body, - ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, - }); - } list(query = {}, options) { - if (isRequestOptions(query)) { - return this.list({}, query); - } - return this._client.getAPIList('/vector_stores', VectorStoresPage, { - query, - ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, - }); - } - /** - * Delete a vector store. - */ - del(vectorStoreId, options) { - return this._client.delete(`/vector_stores/${vectorStoreId}`, { - ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, - }); + return this._client.getAPIList('/batches', (CursorPage), { query, ...options }); } /** - * Search a vector store for relevant chunks based on a query and file attributes - * filter. + * Cancels an in-progress batch. The batch will be in status `cancelling` for up to + * 10 minutes, before changing to `cancelled`, where it will have partial results + * (if any) available in the output file. */ - search(vectorStoreId, body, options) { - return this._client.getAPIList(`/vector_stores/${vectorStoreId}/search`, VectorStoreSearchResponsesPage, { - body, - method: 'post', - ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, - }); + cancel(batchID, options) { + return this._client.post(path `/batches/${batchID}/cancel`, options); } -} -class VectorStoresPage extends CursorPage { -} -/** - * Note: no pagination actually occurs yet, this is for forwards-compatibility. - */ -class VectorStoreSearchResponsesPage extends Page { -} -VectorStores.VectorStoresPage = VectorStoresPage; -VectorStores.VectorStoreSearchResponsesPage = VectorStoreSearchResponsesPage; -VectorStores.Files = files_Files; -VectorStores.VectorStoreFilesPage = VectorStoreFilesPage; -VectorStores.FileContentResponsesPage = FileContentResponsesPage; -VectorStores.FileBatches = FileBatches; -//# sourceMappingURL=vector-stores.mjs.map +} +//# sourceMappingURL=batches.mjs.map ;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/assistants.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. @@ -72221,7 +66213,7 @@ class Assistants extends APIResource { return this._client.post('/assistants', { body, ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), }); } /** @@ -72234,10 +66226,10 @@ class Assistants extends APIResource { * ); * ``` */ - retrieve(assistantId, options) { - return this._client.get(`/assistants/${assistantId}`, { + retrieve(assistantID, options) { + return this._client.get(path `/assistants/${assistantID}`, { ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), }); } /** @@ -72250,21 +66242,29 @@ class Assistants extends APIResource { * ); * ``` */ - update(assistantId, body, options) { - return this._client.post(`/assistants/${assistantId}`, { + update(assistantID, body, options) { + return this._client.post(path `/assistants/${assistantID}`, { body, ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), }); } + /** + * Returns a list of assistants. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const assistant of client.beta.assistants.list()) { + * // ... + * } + * ``` + */ list(query = {}, options) { - if (isRequestOptions(query)) { - return this.list({}, query); - } - return this._client.getAPIList('/assistants', AssistantsPage, { + return this._client.getAPIList('/assistants', (CursorPage), { query, ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), }); } /** @@ -72272,1585 +66272,1886 @@ class Assistants extends APIResource { * * @example * ```ts - * const assistantDeleted = await client.beta.assistants.del( - * 'assistant_id', - * ); + * const assistantDeleted = + * await client.beta.assistants.delete('assistant_id'); * ``` */ - del(assistantId, options) { - return this._client.delete(`/assistants/${assistantId}`, { + delete(assistantID, options) { + return this._client.delete(path `/assistants/${assistantID}`, { ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), }); } } -class AssistantsPage extends CursorPage { -} -Assistants.AssistantsPage = AssistantsPage; //# sourceMappingURL=assistants.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/lib/RunnableFunction.mjs -function isRunnableFunctionWithParse(fn) { - return typeof fn.parse === 'function'; +;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/realtime/sessions.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + +class Sessions extends APIResource { + /** + * Create an ephemeral API token for use in client-side applications with the + * Realtime API. Can be configured with the same session parameters as the + * `session.update` client event. + * + * It responds with a session object, plus a `client_secret` key which contains a + * usable ephemeral API token that can be used to authenticate browser clients for + * the Realtime API. + * + * @example + * ```ts + * const session = + * await client.beta.realtime.sessions.create(); + * ``` + */ + create(body, options) { + return this._client.post('/realtime/sessions', { + body, + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } } -/** - * This is helper class for passing a `function` and `parse` where the `function` - * argument type matches the `parse` return type. - * - * @deprecated - please use ParsingToolFunction instead. - */ -class ParsingFunction { - constructor(input) { - this.function = input.function; - this.parse = input.parse; - this.parameters = input.parameters; - this.description = input.description; - this.name = input.name; +//# sourceMappingURL=sessions.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/realtime/transcription-sessions.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + +class TranscriptionSessions extends APIResource { + /** + * Create an ephemeral API token for use in client-side applications with the + * Realtime API specifically for realtime transcriptions. Can be configured with + * the same session parameters as the `transcription_session.update` client event. + * + * It responds with a session object, plus a `client_secret` key which contains a + * usable ephemeral API token that can be used to authenticate browser clients for + * the Realtime API. + * + * @example + * ```ts + * const transcriptionSession = + * await client.beta.realtime.transcriptionSessions.create(); + * ``` + */ + create(body, options) { + return this._client.post('/realtime/transcription_sessions', { + body, + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); } } +//# sourceMappingURL=transcription-sessions.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/realtime/realtime.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + + /** - * This is helper class for passing a `function` and `parse` where the `function` - * argument type matches the `parse` return type. + * @deprecated Realtime has now launched and is generally available. The old beta API is now deprecated. */ -class ParsingToolFunction { - constructor(input) { - this.type = 'function'; - this.function = input; +class Realtime extends APIResource { + constructor() { + super(...arguments); + this.sessions = new Sessions(this._client); + this.transcriptionSessions = new TranscriptionSessions(this._client); } } -//# sourceMappingURL=RunnableFunction.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/lib/chatCompletionUtils.mjs -const isAssistantMessage = (message) => { - return message?.role === 'assistant'; -}; -const isFunctionMessage = (message) => { - return message?.role === 'function'; -}; -const isToolMessage = (message) => { - return message?.role === 'tool'; -}; -function isPresent(obj) { - return obj != null; -} -//# sourceMappingURL=chatCompletionUtils.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/lib/EventStream.mjs -var EventStream_classPrivateFieldSet = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { - if (kind === "m") throw new TypeError("Private method is not writable"); - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); - return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; -}; -var EventStream_classPrivateFieldGet = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) { - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); -}; -var _EventStream_instances, _EventStream_connectedPromise, _EventStream_resolveConnectedPromise, _EventStream_rejectConnectedPromise, _EventStream_endPromise, _EventStream_resolveEndPromise, _EventStream_rejectEndPromise, _EventStream_listeners, _EventStream_ended, _EventStream_errored, _EventStream_aborted, _EventStream_catchingPromiseCreated, _EventStream_handleError; +Realtime.Sessions = Sessions; +Realtime.TranscriptionSessions = TranscriptionSessions; +//# sourceMappingURL=realtime.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/threads/messages.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -class EventStream { - constructor() { - _EventStream_instances.add(this); - this.controller = new AbortController(); - _EventStream_connectedPromise.set(this, void 0); - _EventStream_resolveConnectedPromise.set(this, () => { }); - _EventStream_rejectConnectedPromise.set(this, () => { }); - _EventStream_endPromise.set(this, void 0); - _EventStream_resolveEndPromise.set(this, () => { }); - _EventStream_rejectEndPromise.set(this, () => { }); - _EventStream_listeners.set(this, {}); - _EventStream_ended.set(this, false); - _EventStream_errored.set(this, false); - _EventStream_aborted.set(this, false); - _EventStream_catchingPromiseCreated.set(this, false); - EventStream_classPrivateFieldSet(this, _EventStream_connectedPromise, new Promise((resolve, reject) => { - EventStream_classPrivateFieldSet(this, _EventStream_resolveConnectedPromise, resolve, "f"); - EventStream_classPrivateFieldSet(this, _EventStream_rejectConnectedPromise, reject, "f"); - }), "f"); - EventStream_classPrivateFieldSet(this, _EventStream_endPromise, new Promise((resolve, reject) => { - EventStream_classPrivateFieldSet(this, _EventStream_resolveEndPromise, resolve, "f"); - EventStream_classPrivateFieldSet(this, _EventStream_rejectEndPromise, reject, "f"); - }), "f"); - // Don't let these promises cause unhandled rejection errors. - // we will manually cause an unhandled rejection error later - // if the user hasn't registered any error listener or called - // any promise-returning method. - EventStream_classPrivateFieldGet(this, _EventStream_connectedPromise, "f").catch(() => { }); - EventStream_classPrivateFieldGet(this, _EventStream_endPromise, "f").catch(() => { }); - } - _run(executor) { - // Unfortunately if we call `executor()` immediately we get runtime errors about - // references to `this` before the `super()` constructor call returns. - setTimeout(() => { - executor().then(() => { - this._emitFinal(); - this._emit('end'); - }, EventStream_classPrivateFieldGet(this, _EventStream_instances, "m", _EventStream_handleError).bind(this)); - }, 0); - } - _connected() { - if (this.ended) - return; - EventStream_classPrivateFieldGet(this, _EventStream_resolveConnectedPromise, "f").call(this); - this._emit('connect'); - } - get ended() { - return EventStream_classPrivateFieldGet(this, _EventStream_ended, "f"); - } - get errored() { - return EventStream_classPrivateFieldGet(this, _EventStream_errored, "f"); - } - get aborted() { - return EventStream_classPrivateFieldGet(this, _EventStream_aborted, "f"); - } - abort() { - this.controller.abort(); - } + + + +/** + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ +class messages_Messages extends APIResource { /** - * Adds the listener function to the end of the listeners array for the event. - * No checks are made to see if the listener has already been added. Multiple calls passing - * the same combination of event and listener will result in the listener being added, and - * called, multiple times. - * @returns this ChatCompletionStream, so that calls can be chained + * Create a message. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API */ - on(event, listener) { - const listeners = EventStream_classPrivateFieldGet(this, _EventStream_listeners, "f")[event] || (EventStream_classPrivateFieldGet(this, _EventStream_listeners, "f")[event] = []); - listeners.push({ listener }); - return this; + create(threadID, body, options) { + return this._client.post(path `/threads/${threadID}/messages`, { + body, + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); } /** - * Removes the specified listener from the listener array for the event. - * off() will remove, at most, one instance of a listener from the listener array. If any single - * listener has been added multiple times to the listener array for the specified event, then - * off() must be called multiple times to remove each instance. - * @returns this ChatCompletionStream, so that calls can be chained + * Retrieve a message. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API */ - off(event, listener) { - const listeners = EventStream_classPrivateFieldGet(this, _EventStream_listeners, "f")[event]; - if (!listeners) - return this; - const index = listeners.findIndex((l) => l.listener === listener); - if (index >= 0) - listeners.splice(index, 1); - return this; + retrieve(messageID, params, options) { + const { thread_id } = params; + return this._client.get(path `/threads/${thread_id}/messages/${messageID}`, { + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); } /** - * Adds a one-time listener function for the event. The next time the event is triggered, - * this listener is removed and then invoked. - * @returns this ChatCompletionStream, so that calls can be chained + * Modifies a message. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API */ - once(event, listener) { - const listeners = EventStream_classPrivateFieldGet(this, _EventStream_listeners, "f")[event] || (EventStream_classPrivateFieldGet(this, _EventStream_listeners, "f")[event] = []); - listeners.push({ listener, once: true }); - return this; + update(messageID, params, options) { + const { thread_id, ...body } = params; + return this._client.post(path `/threads/${thread_id}/messages/${messageID}`, { + body, + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); } /** - * This is similar to `.once()`, but returns a Promise that resolves the next time - * the event is triggered, instead of calling a listener callback. - * @returns a Promise that resolves the next time given event is triggered, - * or rejects if an error is emitted. (If you request the 'error' event, - * returns a promise that resolves with the error). + * Returns a list of messages for a given thread. * - * Example: + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + list(threadID, query = {}, options) { + return this._client.getAPIList(path `/threads/${threadID}/messages`, (CursorPage), { + query, + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + /** + * Deletes a message. * - * const message = await stream.emitted('message') // rejects if the stream errors + * @deprecated The Assistants API is deprecated in favor of the Responses API */ - emitted(event) { - return new Promise((resolve, reject) => { - EventStream_classPrivateFieldSet(this, _EventStream_catchingPromiseCreated, true, "f"); - if (event !== 'error') - this.once('error', reject); - this.once(event, resolve); + delete(messageID, params, options) { + const { thread_id } = params; + return this._client.delete(path `/threads/${thread_id}/messages/${messageID}`, { + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), }); } - async done() { - EventStream_classPrivateFieldSet(this, _EventStream_catchingPromiseCreated, true, "f"); - await EventStream_classPrivateFieldGet(this, _EventStream_endPromise, "f"); +} +//# sourceMappingURL=messages.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/threads/runs/steps.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + +/** + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ +class Steps extends APIResource { + /** + * Retrieves a run step. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + retrieve(stepID, params, options) { + const { thread_id, run_id, ...query } = params; + return this._client.get(path `/threads/${thread_id}/runs/${run_id}/steps/${stepID}`, { + query, + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); } - _emit(event, ...args) { - // make sure we don't emit any events after end - if (EventStream_classPrivateFieldGet(this, _EventStream_ended, "f")) { - return; - } - if (event === 'end') { - EventStream_classPrivateFieldSet(this, _EventStream_ended, true, "f"); - EventStream_classPrivateFieldGet(this, _EventStream_resolveEndPromise, "f").call(this); - } - const listeners = EventStream_classPrivateFieldGet(this, _EventStream_listeners, "f")[event]; - if (listeners) { - EventStream_classPrivateFieldGet(this, _EventStream_listeners, "f")[event] = listeners.filter((l) => !l.once); - listeners.forEach(({ listener }) => listener(...args)); - } - if (event === 'abort') { - const error = args[0]; - if (!EventStream_classPrivateFieldGet(this, _EventStream_catchingPromiseCreated, "f") && !listeners?.length) { - Promise.reject(error); - } - EventStream_classPrivateFieldGet(this, _EventStream_rejectConnectedPromise, "f").call(this, error); - EventStream_classPrivateFieldGet(this, _EventStream_rejectEndPromise, "f").call(this, error); - this._emit('end'); - return; - } - if (event === 'error') { - // NOTE: _emit('error', error) should only be called from #handleError(). - const error = args[0]; - if (!EventStream_classPrivateFieldGet(this, _EventStream_catchingPromiseCreated, "f") && !listeners?.length) { - // Trigger an unhandled rejection if the user hasn't registered any error handlers. - // If you are seeing stack traces here, make sure to handle errors via either: - // - runner.on('error', () => ...) - // - await runner.done() - // - await runner.finalChatCompletion() - // - etc. - Promise.reject(error); - } - EventStream_classPrivateFieldGet(this, _EventStream_rejectConnectedPromise, "f").call(this, error); - EventStream_classPrivateFieldGet(this, _EventStream_rejectEndPromise, "f").call(this, error); - this._emit('end'); - } + /** + * Returns a list of run steps belonging to a run. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + list(runID, params, options) { + const { thread_id, ...query } = params; + return this._client.getAPIList(path `/threads/${thread_id}/runs/${runID}/steps`, (CursorPage), { + query, + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); } - _emitFinal() { } } -_EventStream_connectedPromise = new WeakMap(), _EventStream_resolveConnectedPromise = new WeakMap(), _EventStream_rejectConnectedPromise = new WeakMap(), _EventStream_endPromise = new WeakMap(), _EventStream_resolveEndPromise = new WeakMap(), _EventStream_rejectEndPromise = new WeakMap(), _EventStream_listeners = new WeakMap(), _EventStream_ended = new WeakMap(), _EventStream_errored = new WeakMap(), _EventStream_aborted = new WeakMap(), _EventStream_catchingPromiseCreated = new WeakMap(), _EventStream_instances = new WeakSet(), _EventStream_handleError = function _EventStream_handleError(error) { - EventStream_classPrivateFieldSet(this, _EventStream_errored, true, "f"); - if (error instanceof Error && error.name === 'AbortError') { - error = new APIUserAbortError(); - } - if (error instanceof APIUserAbortError) { - EventStream_classPrivateFieldSet(this, _EventStream_aborted, true, "f"); - return this._emit('abort', error); +//# sourceMappingURL=steps.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/internal/utils/base64.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + +const toBase64 = (data) => { + if (!data) + return ''; + if (typeof globalThis.Buffer !== 'undefined') { + return globalThis.Buffer.from(data).toString('base64'); } - if (error instanceof error_OpenAIError) { - return this._emit('error', error); + if (typeof data === 'string') { + data = encodeUTF8(data); } - if (error instanceof Error) { - const openAIError = new error_OpenAIError(error.message); - // @ts-ignore - openAIError.cause = error; - return this._emit('error', openAIError); + if (typeof btoa !== 'undefined') { + return btoa(String.fromCharCode.apply(null, data)); } - return this._emit('error', new error_OpenAIError(String(error))); + throw new OpenAIError('Cannot generate base64 string; Expected `Buffer` or `btoa` to be defined'); }; -//# sourceMappingURL=EventStream.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/lib/parser.mjs - -function makeParseableResponseFormat(response_format, parser) { - const obj = { ...response_format }; - Object.defineProperties(obj, { - $brand: { - value: 'auto-parseable-response-format', - enumerable: false, - }, - $parseRaw: { - value: parser, - enumerable: false, - }, - }); - return obj; -} -function parser_makeParseableTextFormat(response_format, parser) { - const obj = { ...response_format }; - Object.defineProperties(obj, { - $brand: { - value: 'auto-parseable-response-format', - enumerable: false, - }, - $parseRaw: { - value: parser, - enumerable: false, - }, - }); - return obj; -} -function isAutoParsableResponseFormat(response_format) { - return response_format?.['$brand'] === 'auto-parseable-response-format'; -} -function parser_makeParseableTool(tool, { parser, callback, }) { - const obj = { ...tool }; - Object.defineProperties(obj, { - $brand: { - value: 'auto-parseable-tool', - enumerable: false, - }, - $parseRaw: { - value: parser, - enumerable: false, - }, - $callback: { - value: callback, - enumerable: false, - }, - }); - return obj; -} -function isAutoParsableTool(tool) { - return tool?.['$brand'] === 'auto-parseable-tool'; -} -function maybeParseChatCompletion(completion, params) { - if (!params || !hasAutoParseableInput(params)) { - return { - ...completion, - choices: completion.choices.map((choice) => ({ - ...choice, - message: { - ...choice.message, - parsed: null, - ...(choice.message.tool_calls ? - { - tool_calls: choice.message.tool_calls, - } - : undefined), - }, - })), - }; +const fromBase64 = (str) => { + if (typeof globalThis.Buffer !== 'undefined') { + const buf = globalThis.Buffer.from(str, 'base64'); + return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength); } - return parseChatCompletion(completion, params); -} -function parseChatCompletion(completion, params) { - const choices = completion.choices.map((choice) => { - if (choice.finish_reason === 'length') { - throw new LengthFinishReasonError(); + if (typeof atob !== 'undefined') { + const bstr = atob(str); + const buf = new Uint8Array(bstr.length); + for (let i = 0; i < bstr.length; i++) { + buf[i] = bstr.charCodeAt(i); } - if (choice.finish_reason === 'content_filter') { - throw new ContentFilterFinishReasonError(); - } - return { - ...choice, - message: { - ...choice.message, - ...(choice.message.tool_calls ? - { - tool_calls: choice.message.tool_calls?.map((toolCall) => parseToolCall(params, toolCall)) ?? undefined, - } - : undefined), - parsed: choice.message.content && !choice.message.refusal ? - parseResponseFormat(params, choice.message.content) - : null, - }, - }; - }); - return { ...completion, choices }; -} -function parseResponseFormat(params, content) { - if (params.response_format?.type !== 'json_schema') { - return null; + return buf; } - if (params.response_format?.type === 'json_schema') { - if ('$parseRaw' in params.response_format) { - const response_format = params.response_format; - return response_format.$parseRaw(content); - } - return JSON.parse(content); + throw new OpenAIError('Cannot decode base64 string; Expected `Buffer` or `atob` to be defined'); +}; +/** + * Converts a Base64 encoded string to a Float32Array. + * @param base64Str - The Base64 encoded string. + * @returns An Array of numbers interpreted as Float32 values. + */ +const toFloat32Array = (base64Str) => { + if (typeof Buffer !== 'undefined') { + // for Node.js environment + const buf = Buffer.from(base64Str, 'base64'); + return Array.from(new Float32Array(buf.buffer, buf.byteOffset, buf.length / Float32Array.BYTES_PER_ELEMENT)); } - return null; -} -function parseToolCall(params, toolCall) { - const inputTool = params.tools?.find((inputTool) => inputTool.function?.name === toolCall.function.name); - return { - ...toolCall, - function: { - ...toolCall.function, - parsed_arguments: isAutoParsableTool(inputTool) ? inputTool.$parseRaw(toolCall.function.arguments) - : inputTool?.function.strict ? JSON.parse(toolCall.function.arguments) - : null, - }, - }; -} -function shouldParseToolCall(params, toolCall) { - if (!params) { - return false; + else { + // for legacy web platform APIs + const binaryStr = atob(base64Str); + const len = binaryStr.length; + const bytes = new Uint8Array(len); + for (let i = 0; i < len; i++) { + bytes[i] = binaryStr.charCodeAt(i); + } + return Array.from(new Float32Array(bytes.buffer)); } - const inputTool = params.tools?.find((inputTool) => inputTool.function?.name === toolCall.function.name); - return isAutoParsableTool(inputTool) || inputTool?.function.strict || false; -} -function hasAutoParseableInput(params) { - if (isAutoParsableResponseFormat(params.response_format)) { - return true; +}; +//# sourceMappingURL=base64.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/internal/utils/env.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +/** + * Read an environment variable. + * + * Trims beginning and trailing whitespace. + * + * Will return undefined if the environment variable doesn't exist or cannot be accessed. + */ +const readEnv = (env) => { + if (typeof globalThis.process !== 'undefined') { + return globalThis.process.env?.[env]?.trim() ?? undefined; } - return (params.tools?.some((t) => isAutoParsableTool(t) || (t.type === 'function' && t.function.strict === true)) ?? false); -} -function validateInputTools(tools) { - for (const tool of tools ?? []) { - if (tool.type !== 'function') { - throw new error_OpenAIError(`Currently only \`function\` tool types support auto-parsing; Received \`${tool.type}\``); - } - if (tool.function.strict !== true) { - throw new error_OpenAIError(`The \`${tool.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`); - } + if (typeof globalThis.Deno !== 'undefined') { + return globalThis.Deno.env?.get?.(env)?.trim(); } -} -//# sourceMappingURL=parser.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/lib/AbstractChatCompletionRunner.mjs -var AbstractChatCompletionRunner_classPrivateFieldGet = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) { - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); + return undefined; }; -var _AbstractChatCompletionRunner_instances, _AbstractChatCompletionRunner_getFinalContent, _AbstractChatCompletionRunner_getFinalMessage, _AbstractChatCompletionRunner_getFinalFunctionCall, _AbstractChatCompletionRunner_getFinalFunctionCallResult, _AbstractChatCompletionRunner_calculateTotalUsage, _AbstractChatCompletionRunner_validateParams, _AbstractChatCompletionRunner_stringifyFunctionCallResult; +//# sourceMappingURL=env.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/internal/utils.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -const DEFAULT_MAX_CHAT_COMPLETIONS = 10; -class AbstractChatCompletionRunner extends EventStream { + +//# sourceMappingURL=utils.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/lib/AssistantStream.mjs +var _AssistantStream_instances, _a, _AssistantStream_events, _AssistantStream_runStepSnapshots, _AssistantStream_messageSnapshots, _AssistantStream_messageSnapshot, _AssistantStream_finalRun, _AssistantStream_currentContentIndex, _AssistantStream_currentContent, _AssistantStream_currentToolCallIndex, _AssistantStream_currentToolCall, _AssistantStream_currentEvent, _AssistantStream_currentRunSnapshot, _AssistantStream_currentRunStepSnapshot, _AssistantStream_addEvent, _AssistantStream_endRequest, _AssistantStream_handleMessage, _AssistantStream_handleRunStep, _AssistantStream_handleEvent, _AssistantStream_accumulateRunStep, _AssistantStream_accumulateMessage, _AssistantStream_accumulateContent, _AssistantStream_handleRun; + + + + + +class AssistantStream extends EventStream { constructor() { super(...arguments); - _AbstractChatCompletionRunner_instances.add(this); - this._chatCompletions = []; - this.messages = []; - } - _addChatCompletion(chatCompletion) { - this._chatCompletions.push(chatCompletion); - this._emit('chatCompletion', chatCompletion); - const message = chatCompletion.choices[0]?.message; - if (message) - this._addMessage(message); - return chatCompletion; + _AssistantStream_instances.add(this); + //Track all events in a single list for reference + _AssistantStream_events.set(this, []); + //Used to accumulate deltas + //We are accumulating many types so the value here is not strict + _AssistantStream_runStepSnapshots.set(this, {}); + _AssistantStream_messageSnapshots.set(this, {}); + _AssistantStream_messageSnapshot.set(this, void 0); + _AssistantStream_finalRun.set(this, void 0); + _AssistantStream_currentContentIndex.set(this, void 0); + _AssistantStream_currentContent.set(this, void 0); + _AssistantStream_currentToolCallIndex.set(this, void 0); + _AssistantStream_currentToolCall.set(this, void 0); + //For current snapshot methods + _AssistantStream_currentEvent.set(this, void 0); + _AssistantStream_currentRunSnapshot.set(this, void 0); + _AssistantStream_currentRunStepSnapshot.set(this, void 0); } - _addMessage(message, emit = true) { - if (!('content' in message)) - message.content = null; - this.messages.push(message); - if (emit) { - this._emit('message', message); - if ((isFunctionMessage(message) || isToolMessage(message)) && message.content) { - // Note, this assumes that {role: 'tool', content: …} is always the result of a call of tool of type=function. - this._emit('functionCallResult', message.content); + [(_AssistantStream_events = new WeakMap(), _AssistantStream_runStepSnapshots = new WeakMap(), _AssistantStream_messageSnapshots = new WeakMap(), _AssistantStream_messageSnapshot = new WeakMap(), _AssistantStream_finalRun = new WeakMap(), _AssistantStream_currentContentIndex = new WeakMap(), _AssistantStream_currentContent = new WeakMap(), _AssistantStream_currentToolCallIndex = new WeakMap(), _AssistantStream_currentToolCall = new WeakMap(), _AssistantStream_currentEvent = new WeakMap(), _AssistantStream_currentRunSnapshot = new WeakMap(), _AssistantStream_currentRunStepSnapshot = new WeakMap(), _AssistantStream_instances = new WeakSet(), Symbol.asyncIterator)]() { + const pushQueue = []; + const readQueue = []; + let done = false; + //Catch all for passing along all events + this.on('event', (event) => { + const reader = readQueue.shift(); + if (reader) { + reader.resolve(event); } - else if (isAssistantMessage(message) && message.function_call) { - this._emit('functionCall', message.function_call); + else { + pushQueue.push(event); } - else if (isAssistantMessage(message) && message.tool_calls) { - for (const tool_call of message.tool_calls) { - if (tool_call.type === 'function') { - this._emit('functionCall', tool_call.function); + }); + this.on('end', () => { + done = true; + for (const reader of readQueue) { + reader.resolve(undefined); + } + readQueue.length = 0; + }); + this.on('abort', (err) => { + done = true; + for (const reader of readQueue) { + reader.reject(err); + } + readQueue.length = 0; + }); + this.on('error', (err) => { + done = true; + for (const reader of readQueue) { + reader.reject(err); + } + readQueue.length = 0; + }); + return { + next: async () => { + if (!pushQueue.length) { + if (done) { + return { value: undefined, done: true }; } + return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((chunk) => (chunk ? { value: chunk, done: false } : { value: undefined, done: true })); } - } - } - } - /** - * @returns a promise that resolves with the final ChatCompletion, or rejects - * if an error occurred or the stream ended prematurely without producing a ChatCompletion. - */ - async finalChatCompletion() { - await this.done(); - const completion = this._chatCompletions[this._chatCompletions.length - 1]; - if (!completion) - throw new error_OpenAIError('stream ended without producing a ChatCompletion'); - return completion; - } - /** - * @returns a promise that resolves with the content of the final ChatCompletionMessage, or rejects - * if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage. - */ - async finalContent() { - await this.done(); - return AbstractChatCompletionRunner_classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalContent).call(this); - } - /** - * @returns a promise that resolves with the the final assistant ChatCompletionMessage response, - * or rejects if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage. - */ - async finalMessage() { - await this.done(); - return AbstractChatCompletionRunner_classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this); - } - /** - * @returns a promise that resolves with the content of the final FunctionCall, or rejects - * if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage. - */ - async finalFunctionCall() { - await this.done(); - return AbstractChatCompletionRunner_classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionCall).call(this); - } - async finalFunctionCallResult() { - await this.done(); - return AbstractChatCompletionRunner_classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionCallResult).call(this); - } - async totalUsage() { - await this.done(); - return AbstractChatCompletionRunner_classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_calculateTotalUsage).call(this); - } - allChatCompletions() { - return [...this._chatCompletions]; + const chunk = pushQueue.shift(); + return { value: chunk, done: false }; + }, + return: async () => { + this.abort(); + return { value: undefined, done: true }; + }, + }; } - _emitFinal() { - const completion = this._chatCompletions[this._chatCompletions.length - 1]; - if (completion) - this._emit('finalChatCompletion', completion); - const finalMessage = AbstractChatCompletionRunner_classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this); - if (finalMessage) - this._emit('finalMessage', finalMessage); - const finalContent = AbstractChatCompletionRunner_classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalContent).call(this); - if (finalContent) - this._emit('finalContent', finalContent); - const finalFunctionCall = AbstractChatCompletionRunner_classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionCall).call(this); - if (finalFunctionCall) - this._emit('finalFunctionCall', finalFunctionCall); - const finalFunctionCallResult = AbstractChatCompletionRunner_classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionCallResult).call(this); - if (finalFunctionCallResult != null) - this._emit('finalFunctionCallResult', finalFunctionCallResult); - if (this._chatCompletions.some((c) => c.usage)) { - this._emit('totalUsage', AbstractChatCompletionRunner_classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_calculateTotalUsage).call(this)); - } + static fromReadableStream(stream) { + const runner = new _a(); + runner._run(() => runner._fromReadableStream(stream)); + return runner; } - async _createChatCompletion(client, params, options) { + async _fromReadableStream(readableStream, options) { const signal = options?.signal; if (signal) { if (signal.aborted) this.controller.abort(); signal.addEventListener('abort', () => this.controller.abort()); } - AbstractChatCompletionRunner_classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_validateParams).call(this, params); - const chatCompletion = await client.chat.completions.create({ ...params, stream: false }, { ...options, signal: this.controller.signal }); this._connected(); - return this._addChatCompletion(parseChatCompletion(chatCompletion, params)); - } - async _runChatCompletion(client, params, options) { - for (const message of params.messages) { - this._addMessage(message, false); - } - return await this._createChatCompletion(client, params, options); - } - async _runFunctions(client, params, options) { - const role = 'function'; - const { function_call = 'auto', stream, ...restParams } = params; - const singleFunctionToCall = typeof function_call !== 'string' && function_call?.name; - const { maxChatCompletions = DEFAULT_MAX_CHAT_COMPLETIONS } = options || {}; - const functionsByName = {}; - for (const f of params.functions) { - functionsByName[f.name || f.function.name] = f; - } - const functions = params.functions.map((f) => ({ - name: f.name || f.function.name, - parameters: f.parameters, - description: f.description, - })); - for (const message of params.messages) { - this._addMessage(message, false); - } - for (let i = 0; i < maxChatCompletions; ++i) { - const chatCompletion = await this._createChatCompletion(client, { - ...restParams, - function_call, - functions, - messages: [...this.messages], - }, options); - const message = chatCompletion.choices[0]?.message; - if (!message) { - throw new error_OpenAIError(`missing message in ChatCompletion response`); - } - if (!message.function_call) - return; - const { name, arguments: args } = message.function_call; - const fn = functionsByName[name]; - if (!fn) { - const content = `Invalid function_call: ${JSON.stringify(name)}. Available options are: ${functions - .map((f) => JSON.stringify(f.name)) - .join(', ')}. Please try again`; - this._addMessage({ role, name, content }); - continue; - } - else if (singleFunctionToCall && singleFunctionToCall !== name) { - const content = `Invalid function_call: ${JSON.stringify(name)}. ${JSON.stringify(singleFunctionToCall)} requested. Please try again`; - this._addMessage({ role, name, content }); - continue; - } - let parsed; - try { - parsed = isRunnableFunctionWithParse(fn) ? await fn.parse(args) : args; - } - catch (error) { - this._addMessage({ - role, - name, - content: error instanceof Error ? error.message : String(error), - }); - continue; - } - // @ts-expect-error it can't rule out `never` type. - const rawContent = await fn.function(parsed, this); - const content = AbstractChatCompletionRunner_classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_stringifyFunctionCallResult).call(this, rawContent); - this._addMessage({ role, name, content }); - if (singleFunctionToCall) - return; - } - } - async _runTools(client, params, options) { - const role = 'tool'; - const { tool_choice = 'auto', stream, ...restParams } = params; - const singleFunctionToCall = typeof tool_choice !== 'string' && tool_choice?.function?.name; - const { maxChatCompletions = DEFAULT_MAX_CHAT_COMPLETIONS } = options || {}; - // TODO(someday): clean this logic up - const inputTools = params.tools.map((tool) => { - if (isAutoParsableTool(tool)) { - if (!tool.$callback) { - throw new error_OpenAIError('Tool given to `.runTools()` that does not have an associated function'); - } - return { - type: 'function', - function: { - function: tool.$callback, - name: tool.function.name, - description: tool.function.description || '', - parameters: tool.function.parameters, - parse: tool.$parseRaw, - strict: true, - }, - }; - } - return tool; - }); - const functionsByName = {}; - for (const f of inputTools) { - if (f.type === 'function') { - functionsByName[f.function.name || f.function.function.name] = f.function; - } - } - const tools = 'tools' in params ? - inputTools.map((t) => t.type === 'function' ? - { - type: 'function', - function: { - name: t.function.name || t.function.function.name, - parameters: t.function.parameters, - description: t.function.description, - strict: t.function.strict, - }, - } - : t) - : undefined; - for (const message of params.messages) { - this._addMessage(message, false); + const stream = Stream.fromReadableStream(readableStream, this.controller); + for await (const event of stream) { + __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event); } - for (let i = 0; i < maxChatCompletions; ++i) { - const chatCompletion = await this._createChatCompletion(client, { - ...restParams, - tool_choice, - tools, - messages: [...this.messages], - }, options); - const message = chatCompletion.choices[0]?.message; - if (!message) { - throw new error_OpenAIError(`missing message in ChatCompletion response`); - } - if (!message.tool_calls?.length) { - return; - } - for (const tool_call of message.tool_calls) { - if (tool_call.type !== 'function') - continue; - const tool_call_id = tool_call.id; - const { name, arguments: args } = tool_call.function; - const fn = functionsByName[name]; - if (!fn) { - const content = `Invalid tool_call: ${JSON.stringify(name)}. Available options are: ${Object.keys(functionsByName) - .map((name) => JSON.stringify(name)) - .join(', ')}. Please try again`; - this._addMessage({ role, tool_call_id, content }); - continue; - } - else if (singleFunctionToCall && singleFunctionToCall !== name) { - const content = `Invalid tool_call: ${JSON.stringify(name)}. ${JSON.stringify(singleFunctionToCall)} requested. Please try again`; - this._addMessage({ role, tool_call_id, content }); - continue; - } - let parsed; - try { - parsed = isRunnableFunctionWithParse(fn) ? await fn.parse(args) : args; - } - catch (error) { - const content = error instanceof Error ? error.message : String(error); - this._addMessage({ role, tool_call_id, content }); - continue; - } - // @ts-expect-error it can't rule out `never` type. - const rawContent = await fn.function(parsed, this); - const content = AbstractChatCompletionRunner_classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_stringifyFunctionCallResult).call(this, rawContent); - this._addMessage({ role, tool_call_id, content }); - if (singleFunctionToCall) { - return; - } - } + if (stream.controller.signal?.aborted) { + throw new APIUserAbortError(); } - return; + return this._addRun(__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this)); } -} -_AbstractChatCompletionRunner_instances = new WeakSet(), _AbstractChatCompletionRunner_getFinalContent = function _AbstractChatCompletionRunner_getFinalContent() { - return AbstractChatCompletionRunner_classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this).content ?? null; -}, _AbstractChatCompletionRunner_getFinalMessage = function _AbstractChatCompletionRunner_getFinalMessage() { - let i = this.messages.length; - while (i-- > 0) { - const message = this.messages[i]; - if (isAssistantMessage(message)) { - const { function_call, ...rest } = message; - // TODO: support audio here - const ret = { - ...rest, - content: message.content ?? null, - refusal: message.refusal ?? null, - }; - if (function_call) { - ret.function_call = function_call; - } - return ret; - } + toReadableStream() { + const stream = new Stream(this[Symbol.asyncIterator].bind(this), this.controller); + return stream.toReadableStream(); } - throw new error_OpenAIError('stream ended without producing a ChatCompletionMessage with role=assistant'); -}, _AbstractChatCompletionRunner_getFinalFunctionCall = function _AbstractChatCompletionRunner_getFinalFunctionCall() { - for (let i = this.messages.length - 1; i >= 0; i--) { - const message = this.messages[i]; - if (isAssistantMessage(message) && message?.function_call) { - return message.function_call; - } - if (isAssistantMessage(message) && message?.tool_calls?.length) { - return message.tool_calls.at(-1)?.function; - } + static createToolAssistantStream(runId, runs, params, options) { + const runner = new _a(); + runner._run(() => runner._runToolAssistantStream(runId, runs, params, { + ...options, + headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' }, + })); + return runner; } - return; -}, _AbstractChatCompletionRunner_getFinalFunctionCallResult = function _AbstractChatCompletionRunner_getFinalFunctionCallResult() { - for (let i = this.messages.length - 1; i >= 0; i--) { - const message = this.messages[i]; - if (isFunctionMessage(message) && message.content != null) { - return message.content; + async _createToolAssistantStream(run, runId, params, options) { + const signal = options?.signal; + if (signal) { + if (signal.aborted) + this.controller.abort(); + signal.addEventListener('abort', () => this.controller.abort()); } - if (isToolMessage(message) && - message.content != null && - typeof message.content === 'string' && - this.messages.some((x) => x.role === 'assistant' && - x.tool_calls?.some((y) => y.type === 'function' && y.id === message.tool_call_id))) { - return message.content; + const body = { ...params, stream: true }; + const stream = await run.submitToolOutputs(runId, body, { + ...options, + signal: this.controller.signal, + }); + this._connected(); + for await (const event of stream) { + __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event); } - } - return; -}, _AbstractChatCompletionRunner_calculateTotalUsage = function _AbstractChatCompletionRunner_calculateTotalUsage() { - const total = { - completion_tokens: 0, - prompt_tokens: 0, - total_tokens: 0, - }; - for (const { usage } of this._chatCompletions) { - if (usage) { - total.completion_tokens += usage.completion_tokens; - total.prompt_tokens += usage.prompt_tokens; - total.total_tokens += usage.total_tokens; + if (stream.controller.signal?.aborted) { + throw new APIUserAbortError(); } + return this._addRun(__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this)); } - return total; -}, _AbstractChatCompletionRunner_validateParams = function _AbstractChatCompletionRunner_validateParams(params) { - if (params.n != null && params.n > 1) { - throw new error_OpenAIError('ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.'); - } -}, _AbstractChatCompletionRunner_stringifyFunctionCallResult = function _AbstractChatCompletionRunner_stringifyFunctionCallResult(rawContent) { - return (typeof rawContent === 'string' ? rawContent - : rawContent === undefined ? 'undefined' - : JSON.stringify(rawContent)); -}; -//# sourceMappingURL=AbstractChatCompletionRunner.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/lib/ChatCompletionRunner.mjs - - -class ChatCompletionRunner extends AbstractChatCompletionRunner { - /** @deprecated - please use `runTools` instead. */ - static runFunctions(client, params, options) { - const runner = new ChatCompletionRunner(); - const opts = { + static createThreadAssistantStream(params, thread, options) { + const runner = new _a(); + runner._run(() => runner._threadAssistantStream(params, thread, { ...options, - headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'runFunctions' }, - }; - runner._run(() => runner._runFunctions(client, params, opts)); + headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' }, + })); return runner; } - static runTools(client, params, options) { - const runner = new ChatCompletionRunner(); - const opts = { + static createAssistantStream(threadId, runs, params, options) { + const runner = new _a(); + runner._run(() => runner._runAssistantStream(threadId, runs, params, { ...options, - headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'runTools' }, - }; - runner._run(() => runner._runTools(client, params, opts)); + headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' }, + })); return runner; } - _addMessage(message, emit = true) { - super._addMessage(message, emit); - if (isAssistantMessage(message) && message.content) { - this._emit('content', message.content); - } + currentEvent() { + return __classPrivateFieldGet(this, _AssistantStream_currentEvent, "f"); } -} -//# sourceMappingURL=ChatCompletionRunner.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/partial-json-parser/parser.mjs -const STR = 0b000000001; -const NUM = 0b000000010; -const ARR = 0b000000100; -const OBJ = 0b000001000; -const NULL = 0b000010000; -const BOOL = 0b000100000; -const NAN = 0b001000000; -const INFINITY = 0b010000000; -const MINUS_INFINITY = 0b100000000; -const INF = INFINITY | MINUS_INFINITY; -const SPECIAL = NULL | BOOL | INF | NAN; -const ATOM = STR | NUM | SPECIAL; -const COLLECTION = ARR | OBJ; -const ALL = ATOM | COLLECTION; -const Allow = { - STR, - NUM, - ARR, - OBJ, - NULL, - BOOL, - NAN, - INFINITY, - MINUS_INFINITY, - INF, - SPECIAL, - ATOM, - COLLECTION, - ALL, -}; -// The JSON string segment was unable to be parsed completely -class PartialJSON extends Error { -} -class MalformedJSON extends Error { -} -/** - * Parse incomplete JSON - * @param {string} jsonString Partial JSON to be parsed - * @param {number} allowPartial Specify what types are allowed to be partial, see {@link Allow} for details - * @returns The parsed JSON - * @throws {PartialJSON} If the JSON is incomplete (related to the `allow` parameter) - * @throws {MalformedJSON} If the JSON is malformed - */ -function parseJSON(jsonString, allowPartial = Allow.ALL) { - if (typeof jsonString !== 'string') { - throw new TypeError(`expecting str, got ${typeof jsonString}`); + currentRun() { + return __classPrivateFieldGet(this, _AssistantStream_currentRunSnapshot, "f"); } - if (!jsonString.trim()) { - throw new Error(`${jsonString} is empty`); + currentMessageSnapshot() { + return __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f"); } - return _parseJSON(jsonString.trim(), allowPartial); -} -const _parseJSON = (jsonString, allow) => { - const length = jsonString.length; - let index = 0; - const markPartialJSON = (msg) => { - throw new PartialJSON(`${msg} at position ${index}`); - }; - const throwMalformedError = (msg) => { - throw new MalformedJSON(`${msg} at position ${index}`); - }; - const parseAny = () => { - skipBlank(); - if (index >= length) - markPartialJSON('Unexpected end of input'); - if (jsonString[index] === '"') - return parseStr(); - if (jsonString[index] === '{') - return parseObj(); - if (jsonString[index] === '[') - return parseArr(); - if (jsonString.substring(index, index + 4) === 'null' || - (Allow.NULL & allow && length - index < 4 && 'null'.startsWith(jsonString.substring(index)))) { - index += 4; - return null; - } - if (jsonString.substring(index, index + 4) === 'true' || - (Allow.BOOL & allow && length - index < 4 && 'true'.startsWith(jsonString.substring(index)))) { - index += 4; - return true; + currentRunStepSnapshot() { + return __classPrivateFieldGet(this, _AssistantStream_currentRunStepSnapshot, "f"); + } + async finalRunSteps() { + await this.done(); + return Object.values(__classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")); + } + async finalMessages() { + await this.done(); + return Object.values(__classPrivateFieldGet(this, _AssistantStream_messageSnapshots, "f")); + } + async finalRun() { + await this.done(); + if (!__classPrivateFieldGet(this, _AssistantStream_finalRun, "f")) + throw Error('Final run was not received.'); + return __classPrivateFieldGet(this, _AssistantStream_finalRun, "f"); + } + async _createThreadAssistantStream(thread, params, options) { + const signal = options?.signal; + if (signal) { + if (signal.aborted) + this.controller.abort(); + signal.addEventListener('abort', () => this.controller.abort()); } - if (jsonString.substring(index, index + 5) === 'false' || - (Allow.BOOL & allow && length - index < 5 && 'false'.startsWith(jsonString.substring(index)))) { - index += 5; - return false; + const body = { ...params, stream: true }; + const stream = await thread.createAndRun(body, { ...options, signal: this.controller.signal }); + this._connected(); + for await (const event of stream) { + __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event); } - if (jsonString.substring(index, index + 8) === 'Infinity' || - (Allow.INFINITY & allow && length - index < 8 && 'Infinity'.startsWith(jsonString.substring(index)))) { - index += 8; - return Infinity; + if (stream.controller.signal?.aborted) { + throw new APIUserAbortError(); } - if (jsonString.substring(index, index + 9) === '-Infinity' || - (Allow.MINUS_INFINITY & allow && - 1 < length - index && - length - index < 9 && - '-Infinity'.startsWith(jsonString.substring(index)))) { - index += 9; - return -Infinity; + return this._addRun(__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this)); + } + async _createAssistantStream(run, threadId, params, options) { + const signal = options?.signal; + if (signal) { + if (signal.aborted) + this.controller.abort(); + signal.addEventListener('abort', () => this.controller.abort()); } - if (jsonString.substring(index, index + 3) === 'NaN' || - (Allow.NAN & allow && length - index < 3 && 'NaN'.startsWith(jsonString.substring(index)))) { - index += 3; - return NaN; + const body = { ...params, stream: true }; + const stream = await run.create(threadId, body, { ...options, signal: this.controller.signal }); + this._connected(); + for await (const event of stream) { + __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event); } - return parseNum(); - }; - const parseStr = () => { - const start = index; - let escape = false; - index++; // skip initial quote - while (index < length && (jsonString[index] !== '"' || (escape && jsonString[index - 1] === '\\'))) { - escape = jsonString[index] === '\\' ? !escape : false; - index++; + if (stream.controller.signal?.aborted) { + throw new APIUserAbortError(); } - if (jsonString.charAt(index) == '"') { - try { - return JSON.parse(jsonString.substring(start, ++index - Number(escape))); + return this._addRun(__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this)); + } + static accumulateDelta(acc, delta) { + for (const [key, deltaValue] of Object.entries(delta)) { + if (!acc.hasOwnProperty(key)) { + acc[key] = deltaValue; + continue; } - catch (e) { - throwMalformedError(String(e)); + let accValue = acc[key]; + if (accValue === null || accValue === undefined) { + acc[key] = deltaValue; + continue; } - } - else if (Allow.STR & allow) { - try { - return JSON.parse(jsonString.substring(start, index - Number(escape)) + '"'); + // We don't accumulate these special properties + if (key === 'index' || key === 'type') { + acc[key] = deltaValue; + continue; } - catch (e) { - // SyntaxError: Invalid escape sequence - return JSON.parse(jsonString.substring(start, jsonString.lastIndexOf('\\')) + '"'); + // Type-specific accumulation logic + if (typeof accValue === 'string' && typeof deltaValue === 'string') { + accValue += deltaValue; } - } - markPartialJSON('Unterminated string literal'); - }; - const parseObj = () => { - index++; // skip initial brace - skipBlank(); - const obj = {}; - try { - while (jsonString[index] !== '}') { - skipBlank(); - if (index >= length && Allow.OBJ & allow) - return obj; - const key = parseStr(); - skipBlank(); - index++; // skip colon - try { - const value = parseAny(); - Object.defineProperty(obj, key, { value, writable: true, enumerable: true, configurable: true }); + else if (typeof accValue === 'number' && typeof deltaValue === 'number') { + accValue += deltaValue; + } + else if (isObj(accValue) && isObj(deltaValue)) { + accValue = this.accumulateDelta(accValue, deltaValue); + } + else if (Array.isArray(accValue) && Array.isArray(deltaValue)) { + if (accValue.every((x) => typeof x === 'string' || typeof x === 'number')) { + accValue.push(...deltaValue); // Use spread syntax for efficient addition + continue; } - catch (e) { - if (Allow.OBJ & allow) - return obj; - else - throw e; + for (const deltaEntry of deltaValue) { + if (!isObj(deltaEntry)) { + throw new Error(`Expected array delta entry to be an object but got: ${deltaEntry}`); + } + const index = deltaEntry['index']; + if (index == null) { + console.error(deltaEntry); + throw new Error('Expected array delta entry to have an `index` property'); + } + if (typeof index !== 'number') { + throw new Error(`Expected array delta entry \`index\` property to be a number but got ${index}`); + } + const accEntry = accValue[index]; + if (accEntry == null) { + accValue.push(deltaEntry); + } + else { + accValue[index] = this.accumulateDelta(accEntry, deltaEntry); + } } - skipBlank(); - if (jsonString[index] === ',') - index++; // skip comma + continue; + } + else { + throw Error(`Unhandled record type: ${key}, deltaValue: ${deltaValue}, accValue: ${accValue}`); } + acc[key] = accValue; } - catch (e) { - if (Allow.OBJ & allow) - return obj; - else - markPartialJSON("Expected '}' at end of object"); + return acc; + } + _addRun(run) { + return run; + } + async _threadAssistantStream(params, thread, options) { + return await this._createThreadAssistantStream(thread, params, options); + } + async _runAssistantStream(threadId, runs, params, options) { + return await this._createAssistantStream(runs, threadId, params, options); + } + async _runToolAssistantStream(runId, runs, params, options) { + return await this._createToolAssistantStream(runs, runId, params, options); + } +} +_a = AssistantStream, _AssistantStream_addEvent = function _AssistantStream_addEvent(event) { + if (this.ended) + return; + __classPrivateFieldSet(this, _AssistantStream_currentEvent, event, "f"); + __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_handleEvent).call(this, event); + switch (event.event) { + case 'thread.created': + //No action on this event. + break; + case 'thread.run.created': + case 'thread.run.queued': + case 'thread.run.in_progress': + case 'thread.run.requires_action': + case 'thread.run.completed': + case 'thread.run.incomplete': + case 'thread.run.failed': + case 'thread.run.cancelling': + case 'thread.run.cancelled': + case 'thread.run.expired': + __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_handleRun).call(this, event); + break; + case 'thread.run.step.created': + case 'thread.run.step.in_progress': + case 'thread.run.step.delta': + case 'thread.run.step.completed': + case 'thread.run.step.failed': + case 'thread.run.step.cancelled': + case 'thread.run.step.expired': + __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_handleRunStep).call(this, event); + break; + case 'thread.message.created': + case 'thread.message.in_progress': + case 'thread.message.delta': + case 'thread.message.completed': + case 'thread.message.incomplete': + __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_handleMessage).call(this, event); + break; + case 'error': + //This is included for completeness, but errors are processed in the SSE event processing so this should not occur + throw new Error('Encountered an error event in event processing - errors should be processed earlier'); + default: + AssistantStream_assertNever(event); + } +}, _AssistantStream_endRequest = function _AssistantStream_endRequest() { + if (this.ended) { + throw new error_OpenAIError(`stream has ended, this shouldn't happen`); + } + if (!__classPrivateFieldGet(this, _AssistantStream_finalRun, "f")) + throw Error('Final run has not been received'); + return __classPrivateFieldGet(this, _AssistantStream_finalRun, "f"); +}, _AssistantStream_handleMessage = function _AssistantStream_handleMessage(event) { + const [accumulatedMessage, newContent] = __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_accumulateMessage).call(this, event, __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f")); + __classPrivateFieldSet(this, _AssistantStream_messageSnapshot, accumulatedMessage, "f"); + __classPrivateFieldGet(this, _AssistantStream_messageSnapshots, "f")[accumulatedMessage.id] = accumulatedMessage; + for (const content of newContent) { + const snapshotContent = accumulatedMessage.content[content.index]; + if (snapshotContent?.type == 'text') { + this._emit('textCreated', snapshotContent.text); } - index++; // skip final brace - return obj; - }; - const parseArr = () => { - index++; // skip initial bracket - const arr = []; - try { - while (jsonString[index] !== ']') { - arr.push(parseAny()); - skipBlank(); - if (jsonString[index] === ',') { - index++; // skip comma + } + switch (event.event) { + case 'thread.message.created': + this._emit('messageCreated', event.data); + break; + case 'thread.message.in_progress': + break; + case 'thread.message.delta': + this._emit('messageDelta', event.data.delta, accumulatedMessage); + if (event.data.delta.content) { + for (const content of event.data.delta.content) { + //If it is text delta, emit a text delta event + if (content.type == 'text' && content.text) { + let textDelta = content.text; + let snapshot = accumulatedMessage.content[content.index]; + if (snapshot && snapshot.type == 'text') { + this._emit('textDelta', textDelta, snapshot.text); + } + else { + throw Error('The snapshot associated with this text delta is not text or missing'); + } + } + if (content.index != __classPrivateFieldGet(this, _AssistantStream_currentContentIndex, "f")) { + //See if we have in progress content + if (__classPrivateFieldGet(this, _AssistantStream_currentContent, "f")) { + switch (__classPrivateFieldGet(this, _AssistantStream_currentContent, "f").type) { + case 'text': + this._emit('textDone', __classPrivateFieldGet(this, _AssistantStream_currentContent, "f").text, __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f")); + break; + case 'image_file': + this._emit('imageFileDone', __classPrivateFieldGet(this, _AssistantStream_currentContent, "f").image_file, __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f")); + break; + } + } + __classPrivateFieldSet(this, _AssistantStream_currentContentIndex, content.index, "f"); + } + __classPrivateFieldSet(this, _AssistantStream_currentContent, accumulatedMessage.content[content.index], "f"); } } - } - catch (e) { - if (Allow.ARR & allow) { - return arr; + break; + case 'thread.message.completed': + case 'thread.message.incomplete': + //We emit the latest content we were working on on completion (including incomplete) + if (__classPrivateFieldGet(this, _AssistantStream_currentContentIndex, "f") !== undefined) { + const currentContent = event.data.content[__classPrivateFieldGet(this, _AssistantStream_currentContentIndex, "f")]; + if (currentContent) { + switch (currentContent.type) { + case 'image_file': + this._emit('imageFileDone', currentContent.image_file, __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f")); + break; + case 'text': + this._emit('textDone', currentContent.text, __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f")); + break; + } + } } - markPartialJSON("Expected ']' at end of array"); - } - index++; // skip final bracket - return arr; - }; - const parseNum = () => { - if (index === 0) { - if (jsonString === '-' && Allow.NUM & allow) - markPartialJSON("Not sure what '-' is"); - try { - return JSON.parse(jsonString); + if (__classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f")) { + this._emit('messageDone', event.data); } - catch (e) { - if (Allow.NUM & allow) { - try { - if ('.' === jsonString[jsonString.length - 1]) - return JSON.parse(jsonString.substring(0, jsonString.lastIndexOf('.'))); - return JSON.parse(jsonString.substring(0, jsonString.lastIndexOf('e'))); + __classPrivateFieldSet(this, _AssistantStream_messageSnapshot, undefined, "f"); + } +}, _AssistantStream_handleRunStep = function _AssistantStream_handleRunStep(event) { + const accumulatedRunStep = __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_accumulateRunStep).call(this, event); + __classPrivateFieldSet(this, _AssistantStream_currentRunStepSnapshot, accumulatedRunStep, "f"); + switch (event.event) { + case 'thread.run.step.created': + this._emit('runStepCreated', event.data); + break; + case 'thread.run.step.delta': + const delta = event.data.delta; + if (delta.step_details && + delta.step_details.type == 'tool_calls' && + delta.step_details.tool_calls && + accumulatedRunStep.step_details.type == 'tool_calls') { + for (const toolCall of delta.step_details.tool_calls) { + if (toolCall.index == __classPrivateFieldGet(this, _AssistantStream_currentToolCallIndex, "f")) { + this._emit('toolCallDelta', toolCall, accumulatedRunStep.step_details.tool_calls[toolCall.index]); + } + else { + if (__classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")) { + this._emit('toolCallDone', __classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")); + } + __classPrivateFieldSet(this, _AssistantStream_currentToolCallIndex, toolCall.index, "f"); + __classPrivateFieldSet(this, _AssistantStream_currentToolCall, accumulatedRunStep.step_details.tool_calls[toolCall.index], "f"); + if (__classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")) + this._emit('toolCallCreated', __classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")); } - catch (e) { } } - throwMalformedError(String(e)); } - } - const start = index; - if (jsonString[index] === '-') - index++; - while (jsonString[index] && !',]}'.includes(jsonString[index])) - index++; - if (index == length && !(Allow.NUM & allow)) - markPartialJSON('Unterminated number literal'); - try { - return JSON.parse(jsonString.substring(start, index)); - } - catch (e) { - if (jsonString.substring(start, index) === '-' && Allow.NUM & allow) - markPartialJSON("Not sure what '-' is"); - try { - return JSON.parse(jsonString.substring(start, jsonString.lastIndexOf('e'))); + this._emit('runStepDelta', event.data.delta, accumulatedRunStep); + break; + case 'thread.run.step.completed': + case 'thread.run.step.failed': + case 'thread.run.step.cancelled': + case 'thread.run.step.expired': + __classPrivateFieldSet(this, _AssistantStream_currentRunStepSnapshot, undefined, "f"); + const details = event.data.step_details; + if (details.type == 'tool_calls') { + if (__classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")) { + this._emit('toolCallDone', __classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")); + __classPrivateFieldSet(this, _AssistantStream_currentToolCall, undefined, "f"); + } } - catch (e) { - throwMalformedError(String(e)); + this._emit('runStepDone', event.data, accumulatedRunStep); + break; + case 'thread.run.step.in_progress': + break; + } +}, _AssistantStream_handleEvent = function _AssistantStream_handleEvent(event) { + __classPrivateFieldGet(this, _AssistantStream_events, "f").push(event); + this._emit('event', event); +}, _AssistantStream_accumulateRunStep = function _AssistantStream_accumulateRunStep(event) { + switch (event.event) { + case 'thread.run.step.created': + __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id] = event.data; + return event.data; + case 'thread.run.step.delta': + let snapshot = __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id]; + if (!snapshot) { + throw Error('Received a RunStepDelta before creation of a snapshot'); } - } - }; - const skipBlank = () => { - while (index < length && ' \n\r\t'.includes(jsonString[index])) { - index++; - } - }; - return parseAny(); + let data = event.data; + if (data.delta) { + const accumulated = _a.accumulateDelta(snapshot, data.delta); + __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id] = accumulated; + } + return __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id]; + case 'thread.run.step.completed': + case 'thread.run.step.failed': + case 'thread.run.step.cancelled': + case 'thread.run.step.expired': + case 'thread.run.step.in_progress': + __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id] = event.data; + break; + } + if (__classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id]) + return __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id]; + throw new Error('No snapshot available'); +}, _AssistantStream_accumulateMessage = function _AssistantStream_accumulateMessage(event, snapshot) { + let newContent = []; + switch (event.event) { + case 'thread.message.created': + //On creation the snapshot is just the initial message + return [event.data, newContent]; + case 'thread.message.delta': + if (!snapshot) { + throw Error('Received a delta with no existing snapshot (there should be one from message creation)'); + } + let data = event.data; + //If this delta does not have content, nothing to process + if (data.delta.content) { + for (const contentElement of data.delta.content) { + if (contentElement.index in snapshot.content) { + let currentContent = snapshot.content[contentElement.index]; + snapshot.content[contentElement.index] = __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_accumulateContent).call(this, contentElement, currentContent); + } + else { + snapshot.content[contentElement.index] = contentElement; + // This is a new element + newContent.push(contentElement); + } + } + } + return [snapshot, newContent]; + case 'thread.message.in_progress': + case 'thread.message.completed': + case 'thread.message.incomplete': + //No changes on other thread events + if (snapshot) { + return [snapshot, newContent]; + } + else { + throw Error('Received thread message event with no existing snapshot'); + } + } + throw Error('Tried to accumulate a non-message event'); +}, _AssistantStream_accumulateContent = function _AssistantStream_accumulateContent(contentElement, currentContent) { + return _a.accumulateDelta(currentContent, contentElement); +}, _AssistantStream_handleRun = function _AssistantStream_handleRun(event) { + __classPrivateFieldSet(this, _AssistantStream_currentRunSnapshot, event.data, "f"); + switch (event.event) { + case 'thread.run.created': + break; + case 'thread.run.queued': + break; + case 'thread.run.in_progress': + break; + case 'thread.run.requires_action': + case 'thread.run.cancelled': + case 'thread.run.failed': + case 'thread.run.completed': + case 'thread.run.expired': + case 'thread.run.incomplete': + __classPrivateFieldSet(this, _AssistantStream_finalRun, event.data, "f"); + if (__classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")) { + this._emit('toolCallDone', __classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")); + __classPrivateFieldSet(this, _AssistantStream_currentToolCall, undefined, "f"); + } + break; + case 'thread.run.cancelling': + break; + } }; -// using this function with malformed JSON is undefined behavior -const partialParse = (input) => parseJSON(input, Allow.ALL ^ Allow.NUM); +function AssistantStream_assertNever(_x) { } +//# sourceMappingURL=AssistantStream.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/threads/runs/runs.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + + + + + +/** + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ +class Runs extends APIResource { + constructor() { + super(...arguments); + this.steps = new Steps(this._client); + } + create(threadID, params, options) { + const { include, ...body } = params; + return this._client.post(path `/threads/${threadID}/runs`, { + query: { include }, + body, + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + stream: params.stream ?? false, + }); + } + /** + * Retrieves a run. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + retrieve(runID, params, options) { + const { thread_id } = params; + return this._client.get(path `/threads/${thread_id}/runs/${runID}`, { + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + /** + * Modifies a run. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + update(runID, params, options) { + const { thread_id, ...body } = params; + return this._client.post(path `/threads/${thread_id}/runs/${runID}`, { + body, + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + /** + * Returns a list of runs belonging to a thread. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + list(threadID, query = {}, options) { + return this._client.getAPIList(path `/threads/${threadID}/runs`, (CursorPage), { + query, + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + /** + * Cancels a run that is `in_progress`. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + cancel(runID, params, options) { + const { thread_id } = params; + return this._client.post(path `/threads/${thread_id}/runs/${runID}/cancel`, { + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + /** + * A helper to create a run an poll for a terminal state. More information on Run + * lifecycles can be found here: + * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps + */ + async createAndPoll(threadId, body, options) { + const run = await this.create(threadId, body, options); + return await this.poll(run.id, { thread_id: threadId }, options); + } + /** + * Create a Run stream + * + * @deprecated use `stream` instead + */ + createAndStream(threadId, body, options) { + return AssistantStream.createAssistantStream(threadId, this._client.beta.threads.runs, body, options); + } + /** + * A helper to poll a run status until it reaches a terminal state. More + * information on Run lifecycles can be found here: + * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps + */ + async poll(runId, params, options) { + const headers = buildHeaders([ + options?.headers, + { + 'X-Stainless-Poll-Helper': 'true', + 'X-Stainless-Custom-Poll-Interval': options?.pollIntervalMs?.toString() ?? undefined, + }, + ]); + while (true) { + const { data: run, response } = await this.retrieve(runId, params, { + ...options, + headers: { ...options?.headers, ...headers }, + }).withResponse(); + switch (run.status) { + //If we are in any sort of intermediate state we poll + case 'queued': + case 'in_progress': + case 'cancelling': + let sleepInterval = 5000; + if (options?.pollIntervalMs) { + sleepInterval = options.pollIntervalMs; + } + else { + const headerInterval = response.headers.get('openai-poll-after-ms'); + if (headerInterval) { + const headerIntervalMs = parseInt(headerInterval); + if (!isNaN(headerIntervalMs)) { + sleepInterval = headerIntervalMs; + } + } + } + await sleep(sleepInterval); + break; + //We return the run in any terminal state. + case 'requires_action': + case 'incomplete': + case 'cancelled': + case 'completed': + case 'failed': + case 'expired': + return run; + } + } + } + /** + * Create a Run stream + */ + stream(threadId, body, options) { + return AssistantStream.createAssistantStream(threadId, this._client.beta.threads.runs, body, options); + } + submitToolOutputs(runID, params, options) { + const { thread_id, ...body } = params; + return this._client.post(path `/threads/${thread_id}/runs/${runID}/submit_tool_outputs`, { + body, + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + stream: params.stream ?? false, + }); + } + /** + * A helper to submit a tool output to a run and poll for a terminal run state. + * More information on Run lifecycles can be found here: + * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps + */ + async submitToolOutputsAndPoll(runId, params, options) { + const run = await this.submitToolOutputs(runId, params, options); + return await this.poll(run.id, params, options); + } + /** + * Submit the tool outputs from a previous run and stream the run to a terminal + * state. More information on Run lifecycles can be found here: + * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps + */ + submitToolOutputsStream(runId, params, options) { + return AssistantStream.createToolAssistantStream(runId, this._client.beta.threads.runs, params, options); + } +} +Runs.Steps = Steps; +//# sourceMappingURL=runs.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/threads/threads.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -//# sourceMappingURL=parser.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/lib/ChatCompletionStream.mjs -var ChatCompletionStream_classPrivateFieldSet = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { - if (kind === "m") throw new TypeError("Private method is not writable"); - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); - return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; -}; -var ChatCompletionStream_classPrivateFieldGet = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) { - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); -}; -var _ChatCompletionStream_instances, _ChatCompletionStream_params, _ChatCompletionStream_choiceEventStates, _ChatCompletionStream_currentChatCompletionSnapshot, _ChatCompletionStream_beginRequest, _ChatCompletionStream_getChoiceEventState, _ChatCompletionStream_addChunk, _ChatCompletionStream_emitToolCallDoneEvent, _ChatCompletionStream_emitContentDoneEvents, _ChatCompletionStream_endRequest, _ChatCompletionStream_getAutoParseableResponseFormat, _ChatCompletionStream_accumulateChatCompletion; -class ChatCompletionStream extends AbstractChatCompletionRunner { - constructor(params) { - super(); - _ChatCompletionStream_instances.add(this); - _ChatCompletionStream_params.set(this, void 0); - _ChatCompletionStream_choiceEventStates.set(this, void 0); - _ChatCompletionStream_currentChatCompletionSnapshot.set(this, void 0); - ChatCompletionStream_classPrivateFieldSet(this, _ChatCompletionStream_params, params, "f"); - ChatCompletionStream_classPrivateFieldSet(this, _ChatCompletionStream_choiceEventStates, [], "f"); + + +/** + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ +class Threads extends APIResource { + constructor() { + super(...arguments); + this.runs = new Runs(this._client); + this.messages = new messages_Messages(this._client); } - get currentChatCompletionSnapshot() { - return ChatCompletionStream_classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f"); + /** + * Create a thread. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + create(body = {}, options) { + return this._client.post('/threads', { + body, + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); } /** - * Intended for use on the frontend, consuming a stream produced with - * `.toReadableStream()` on the backend. + * Retrieves a thread. * - * Note that messages sent to the model do not appear in `.on('message')` - * in this context. + * @deprecated The Assistants API is deprecated in favor of the Responses API */ - static fromReadableStream(stream) { - const runner = new ChatCompletionStream(null); - runner._run(() => runner._fromReadableStream(stream)); - return runner; + retrieve(threadID, options) { + return this._client.get(path `/threads/${threadID}`, { + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); } - static createChatCompletion(client, params, options) { - const runner = new ChatCompletionStream(params); - runner._run(() => runner._runChatCompletion(client, { ...params, stream: true }, { ...options, headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' } })); - return runner; + /** + * Modifies a thread. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + update(threadID, body, options) { + return this._client.post(path `/threads/${threadID}`, { + body, + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); } - async _createChatCompletion(client, params, options) { - super._createChatCompletion; - const signal = options?.signal; - if (signal) { - if (signal.aborted) - this.controller.abort(); - signal.addEventListener('abort', () => this.controller.abort()); - } - ChatCompletionStream_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_beginRequest).call(this); - const stream = await client.chat.completions.create({ ...params, stream: true }, { ...options, signal: this.controller.signal }); - this._connected(); - for await (const chunk of stream) { - ChatCompletionStream_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_addChunk).call(this, chunk); - } - if (stream.controller.signal?.aborted) { - throw new APIUserAbortError(); - } - return this._addChatCompletion(ChatCompletionStream_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this)); + /** + * Delete a thread. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + delete(threadID, options) { + return this._client.delete(path `/threads/${threadID}`, { + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); } - async _fromReadableStream(readableStream, options) { - const signal = options?.signal; - if (signal) { - if (signal.aborted) - this.controller.abort(); - signal.addEventListener('abort', () => this.controller.abort()); - } - ChatCompletionStream_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_beginRequest).call(this); - this._connected(); - const stream = Stream.fromReadableStream(readableStream, this.controller); - let chatId; - for await (const chunk of stream) { - if (chatId && chatId !== chunk.id) { - // A new request has been made. - this._addChatCompletion(ChatCompletionStream_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this)); - } - ChatCompletionStream_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_addChunk).call(this, chunk); - chatId = chunk.id; - } - if (stream.controller.signal?.aborted) { - throw new APIUserAbortError(); - } - return this._addChatCompletion(ChatCompletionStream_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this)); + createAndRun(body, options) { + return this._client.post('/threads/runs', { + body, + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + stream: body.stream ?? false, + }); } - [(_ChatCompletionStream_params = new WeakMap(), _ChatCompletionStream_choiceEventStates = new WeakMap(), _ChatCompletionStream_currentChatCompletionSnapshot = new WeakMap(), _ChatCompletionStream_instances = new WeakSet(), _ChatCompletionStream_beginRequest = function _ChatCompletionStream_beginRequest() { - if (this.ended) - return; - ChatCompletionStream_classPrivateFieldSet(this, _ChatCompletionStream_currentChatCompletionSnapshot, undefined, "f"); - }, _ChatCompletionStream_getChoiceEventState = function _ChatCompletionStream_getChoiceEventState(choice) { - let state = ChatCompletionStream_classPrivateFieldGet(this, _ChatCompletionStream_choiceEventStates, "f")[choice.index]; - if (state) { - return state; - } - state = { - content_done: false, - refusal_done: false, - logprobs_content_done: false, - logprobs_refusal_done: false, - done_tool_calls: new Set(), - current_tool_call_index: null, - }; - ChatCompletionStream_classPrivateFieldGet(this, _ChatCompletionStream_choiceEventStates, "f")[choice.index] = state; - return state; - }, _ChatCompletionStream_addChunk = function _ChatCompletionStream_addChunk(chunk) { - if (this.ended) - return; - const completion = ChatCompletionStream_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_accumulateChatCompletion).call(this, chunk); - this._emit('chunk', chunk, completion); - for (const choice of chunk.choices) { - const choiceSnapshot = completion.choices[choice.index]; - if (choice.delta.content != null && - choiceSnapshot.message?.role === 'assistant' && - choiceSnapshot.message?.content) { - this._emit('content', choice.delta.content, choiceSnapshot.message.content); - this._emit('content.delta', { - delta: choice.delta.content, - snapshot: choiceSnapshot.message.content, - parsed: choiceSnapshot.message.parsed, - }); - } - if (choice.delta.refusal != null && - choiceSnapshot.message?.role === 'assistant' && - choiceSnapshot.message?.refusal) { - this._emit('refusal.delta', { - delta: choice.delta.refusal, - snapshot: choiceSnapshot.message.refusal, - }); - } - if (choice.logprobs?.content != null && choiceSnapshot.message?.role === 'assistant') { - this._emit('logprobs.content.delta', { - content: choice.logprobs?.content, - snapshot: choiceSnapshot.logprobs?.content ?? [], - }); - } - if (choice.logprobs?.refusal != null && choiceSnapshot.message?.role === 'assistant') { - this._emit('logprobs.refusal.delta', { - refusal: choice.logprobs?.refusal, - snapshot: choiceSnapshot.logprobs?.refusal ?? [], - }); - } - const state = ChatCompletionStream_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot); - if (choiceSnapshot.finish_reason) { - ChatCompletionStream_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitContentDoneEvents).call(this, choiceSnapshot); - if (state.current_tool_call_index != null) { - ChatCompletionStream_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitToolCallDoneEvent).call(this, choiceSnapshot, state.current_tool_call_index); - } - } - for (const toolCall of choice.delta.tool_calls ?? []) { - if (state.current_tool_call_index !== toolCall.index) { - ChatCompletionStream_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitContentDoneEvents).call(this, choiceSnapshot); - // new tool call started, the previous one is done - if (state.current_tool_call_index != null) { - ChatCompletionStream_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitToolCallDoneEvent).call(this, choiceSnapshot, state.current_tool_call_index); - } - } - state.current_tool_call_index = toolCall.index; - } - for (const toolCallDelta of choice.delta.tool_calls ?? []) { - const toolCallSnapshot = choiceSnapshot.message.tool_calls?.[toolCallDelta.index]; - if (!toolCallSnapshot?.type) { - continue; - } - if (toolCallSnapshot?.type === 'function') { - this._emit('tool_calls.function.arguments.delta', { - name: toolCallSnapshot.function?.name, - index: toolCallDelta.index, - arguments: toolCallSnapshot.function.arguments, - parsed_arguments: toolCallSnapshot.function.parsed_arguments, - arguments_delta: toolCallDelta.function?.arguments ?? '', - }); - } - else { - assertNever(toolCallSnapshot?.type); - } - } - } - }, _ChatCompletionStream_emitToolCallDoneEvent = function _ChatCompletionStream_emitToolCallDoneEvent(choiceSnapshot, toolCallIndex) { - const state = ChatCompletionStream_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot); - if (state.done_tool_calls.has(toolCallIndex)) { - // we've already fired the done event - return; - } - const toolCallSnapshot = choiceSnapshot.message.tool_calls?.[toolCallIndex]; - if (!toolCallSnapshot) { - throw new Error('no tool call snapshot'); - } - if (!toolCallSnapshot.type) { - throw new Error('tool call snapshot missing `type`'); - } - if (toolCallSnapshot.type === 'function') { - const inputTool = ChatCompletionStream_classPrivateFieldGet(this, _ChatCompletionStream_params, "f")?.tools?.find((tool) => tool.type === 'function' && tool.function.name === toolCallSnapshot.function.name); - this._emit('tool_calls.function.arguments.done', { - name: toolCallSnapshot.function.name, - index: toolCallIndex, - arguments: toolCallSnapshot.function.arguments, - parsed_arguments: isAutoParsableTool(inputTool) ? inputTool.$parseRaw(toolCallSnapshot.function.arguments) - : inputTool?.function.strict ? JSON.parse(toolCallSnapshot.function.arguments) - : null, - }); - } - else { - assertNever(toolCallSnapshot.type); - } - }, _ChatCompletionStream_emitContentDoneEvents = function _ChatCompletionStream_emitContentDoneEvents(choiceSnapshot) { - const state = ChatCompletionStream_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot); - if (choiceSnapshot.message.content && !state.content_done) { - state.content_done = true; - const responseFormat = ChatCompletionStream_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getAutoParseableResponseFormat).call(this); - this._emit('content.done', { - content: choiceSnapshot.message.content, - parsed: responseFormat ? responseFormat.$parseRaw(choiceSnapshot.message.content) : null, - }); - } - if (choiceSnapshot.message.refusal && !state.refusal_done) { - state.refusal_done = true; - this._emit('refusal.done', { refusal: choiceSnapshot.message.refusal }); - } - if (choiceSnapshot.logprobs?.content && !state.logprobs_content_done) { - state.logprobs_content_done = true; - this._emit('logprobs.content.done', { content: choiceSnapshot.logprobs.content }); - } - if (choiceSnapshot.logprobs?.refusal && !state.logprobs_refusal_done) { - state.logprobs_refusal_done = true; - this._emit('logprobs.refusal.done', { refusal: choiceSnapshot.logprobs.refusal }); - } - }, _ChatCompletionStream_endRequest = function _ChatCompletionStream_endRequest() { - if (this.ended) { - throw new error_OpenAIError(`stream has ended, this shouldn't happen`); - } - const snapshot = ChatCompletionStream_classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f"); - if (!snapshot) { - throw new error_OpenAIError(`request ended without sending any chunks`); - } - ChatCompletionStream_classPrivateFieldSet(this, _ChatCompletionStream_currentChatCompletionSnapshot, undefined, "f"); - ChatCompletionStream_classPrivateFieldSet(this, _ChatCompletionStream_choiceEventStates, [], "f"); - return finalizeChatCompletion(snapshot, ChatCompletionStream_classPrivateFieldGet(this, _ChatCompletionStream_params, "f")); - }, _ChatCompletionStream_getAutoParseableResponseFormat = function _ChatCompletionStream_getAutoParseableResponseFormat() { - const responseFormat = ChatCompletionStream_classPrivateFieldGet(this, _ChatCompletionStream_params, "f")?.response_format; - if (isAutoParsableResponseFormat(responseFormat)) { - return responseFormat; - } - return null; - }, _ChatCompletionStream_accumulateChatCompletion = function _ChatCompletionStream_accumulateChatCompletion(chunk) { - var _a, _b, _c, _d; - let snapshot = ChatCompletionStream_classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f"); - const { choices, ...rest } = chunk; - if (!snapshot) { - snapshot = ChatCompletionStream_classPrivateFieldSet(this, _ChatCompletionStream_currentChatCompletionSnapshot, { - ...rest, - choices: [], - }, "f"); - } - else { - Object.assign(snapshot, rest); - } - for (const { delta, finish_reason, index, logprobs = null, ...other } of chunk.choices) { - let choice = snapshot.choices[index]; - if (!choice) { - choice = snapshot.choices[index] = { finish_reason, index, message: {}, logprobs, ...other }; - } - if (logprobs) { - if (!choice.logprobs) { - choice.logprobs = Object.assign({}, logprobs); - } - else { - const { content, refusal, ...rest } = logprobs; - assertIsEmpty(rest); - Object.assign(choice.logprobs, rest); - if (content) { - (_a = choice.logprobs).content ?? (_a.content = []); - choice.logprobs.content.push(...content); - } - if (refusal) { - (_b = choice.logprobs).refusal ?? (_b.refusal = []); - choice.logprobs.refusal.push(...refusal); - } - } - } - if (finish_reason) { - choice.finish_reason = finish_reason; - if (ChatCompletionStream_classPrivateFieldGet(this, _ChatCompletionStream_params, "f") && hasAutoParseableInput(ChatCompletionStream_classPrivateFieldGet(this, _ChatCompletionStream_params, "f"))) { - if (finish_reason === 'length') { - throw new LengthFinishReasonError(); - } - if (finish_reason === 'content_filter') { - throw new ContentFilterFinishReasonError(); - } - } - } - Object.assign(choice, other); - if (!delta) - continue; // Shouldn't happen; just in case. - const { content, refusal, function_call, role, tool_calls, ...rest } = delta; - assertIsEmpty(rest); - Object.assign(choice.message, rest); - if (refusal) { - choice.message.refusal = (choice.message.refusal || '') + refusal; - } - if (role) - choice.message.role = role; - if (function_call) { - if (!choice.message.function_call) { - choice.message.function_call = function_call; - } - else { - if (function_call.name) - choice.message.function_call.name = function_call.name; - if (function_call.arguments) { - (_c = choice.message.function_call).arguments ?? (_c.arguments = ''); - choice.message.function_call.arguments += function_call.arguments; - } - } - } - if (content) { - choice.message.content = (choice.message.content || '') + content; - if (!choice.message.refusal && ChatCompletionStream_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getAutoParseableResponseFormat).call(this)) { - choice.message.parsed = partialParse(choice.message.content); - } - } - if (tool_calls) { - if (!choice.message.tool_calls) - choice.message.tool_calls = []; - for (const { index, id, type, function: fn, ...rest } of tool_calls) { - const tool_call = ((_d = choice.message.tool_calls)[index] ?? (_d[index] = {})); - Object.assign(tool_call, rest); - if (id) - tool_call.id = id; - if (type) - tool_call.type = type; - if (fn) - tool_call.function ?? (tool_call.function = { name: fn.name ?? '', arguments: '' }); - if (fn?.name) - tool_call.function.name = fn.name; - if (fn?.arguments) { - tool_call.function.arguments += fn.arguments; - if (shouldParseToolCall(ChatCompletionStream_classPrivateFieldGet(this, _ChatCompletionStream_params, "f"), tool_call)) { - tool_call.function.parsed_arguments = partialParse(tool_call.function.arguments); - } - } - } - } + /** + * A helper to create a thread, start a run and then poll for a terminal state. + * More information on Run lifecycles can be found here: + * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps + */ + async createAndRunPoll(body, options) { + const run = await this.createAndRun(body, options); + return await this.runs.poll(run.id, { thread_id: run.thread_id }, options); + } + /** + * Create a thread and stream the run back + */ + createAndRunStream(body, options) { + return AssistantStream.createThreadAssistantStream(body, this._client.beta.threads, options); + } +} +Threads.Runs = Runs; +Threads.Messages = messages_Messages; +//# sourceMappingURL=threads.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/beta.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + + + + +class Beta extends APIResource { + constructor() { + super(...arguments); + this.realtime = new Realtime(this._client); + this.assistants = new Assistants(this._client); + this.threads = new Threads(this._client); + } +} +Beta.Realtime = Realtime; +Beta.Assistants = Assistants; +Beta.Threads = Threads; +//# sourceMappingURL=beta.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/completions.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +class completions_Completions extends APIResource { + create(body, options) { + return this._client.post('/completions', { body, ...options, stream: body.stream ?? false }); + } +} +//# sourceMappingURL=completions.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/containers/files/content.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + +class Content extends APIResource { + /** + * Retrieve Container File Content + */ + retrieve(fileID, params, options) { + const { container_id } = params; + return this._client.get(path `/containers/${container_id}/files/${fileID}/content`, { + ...options, + headers: buildHeaders([{ Accept: 'application/binary' }, options?.headers]), + __binaryResponse: true, + }); + } +} +//# sourceMappingURL=content.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/containers/files/files.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + + + + +class Files extends APIResource { + constructor() { + super(...arguments); + this.content = new Content(this._client); + } + /** + * Create a Container File + * + * You can send either a multipart/form-data request with the raw file content, or + * a JSON request with a file ID. + */ + create(containerID, body, options) { + return this._client.post(path `/containers/${containerID}/files`, multipartFormRequestOptions({ body, ...options }, this._client)); + } + /** + * Retrieve Container File + */ + retrieve(fileID, params, options) { + const { container_id } = params; + return this._client.get(path `/containers/${container_id}/files/${fileID}`, options); + } + /** + * List Container files + */ + list(containerID, query = {}, options) { + return this._client.getAPIList(path `/containers/${containerID}/files`, (CursorPage), { + query, + ...options, + }); + } + /** + * Delete Container File + */ + delete(fileID, params, options) { + const { container_id } = params; + return this._client.delete(path `/containers/${container_id}/files/${fileID}`, { + ...options, + headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), + }); + } +} +Files.Content = Content; +//# sourceMappingURL=files.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/containers/containers.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + + + +class Containers extends APIResource { + constructor() { + super(...arguments); + this.files = new Files(this._client); + } + /** + * Create Container + */ + create(body, options) { + return this._client.post('/containers', { body, ...options }); + } + /** + * Retrieve Container + */ + retrieve(containerID, options) { + return this._client.get(path `/containers/${containerID}`, options); + } + /** + * List Containers + */ + list(query = {}, options) { + return this._client.getAPIList('/containers', (CursorPage), { query, ...options }); + } + /** + * Delete Container + */ + delete(containerID, options) { + return this._client.delete(path `/containers/${containerID}`, { + ...options, + headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), + }); + } +} +Containers.Files = Files; +//# sourceMappingURL=containers.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/conversations/items.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + +class Items extends APIResource { + /** + * Create items in a conversation with the given ID. + */ + create(conversationID, params, options) { + const { include, ...body } = params; + return this._client.post(path `/conversations/${conversationID}/items`, { + query: { include }, + body, + ...options, + }); + } + /** + * Get a single item from a conversation with the given IDs. + */ + retrieve(itemID, params, options) { + const { conversation_id, ...query } = params; + return this._client.get(path `/conversations/${conversation_id}/items/${itemID}`, { query, ...options }); + } + /** + * List all items for a conversation with the given ID. + */ + list(conversationID, query = {}, options) { + return this._client.getAPIList(path `/conversations/${conversationID}/items`, (ConversationCursorPage), { query, ...options }); + } + /** + * Delete an item from a conversation with the given IDs. + */ + delete(itemID, params, options) { + const { conversation_id } = params; + return this._client.delete(path `/conversations/${conversation_id}/items/${itemID}`, options); + } +} +//# sourceMappingURL=items.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/conversations/conversations.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + +class Conversations extends APIResource { + constructor() { + super(...arguments); + this.items = new Items(this._client); + } + /** + * Create a conversation. + */ + create(body, options) { + return this._client.post('/conversations', { body, ...options }); + } + /** + * Get a conversation with the given ID. + */ + retrieve(conversationID, options) { + return this._client.get(path `/conversations/${conversationID}`, options); + } + /** + * Update a conversation's metadata with the given ID. + */ + update(conversationID, body, options) { + return this._client.post(path `/conversations/${conversationID}`, { body, ...options }); + } + /** + * Delete a conversation with the given ID. + */ + delete(conversationID, options) { + return this._client.delete(path `/conversations/${conversationID}`, options); + } +} +Conversations.Items = Items; +//# sourceMappingURL=conversations.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/embeddings.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + +class Embeddings extends APIResource { + /** + * Creates an embedding vector representing the input text. + * + * @example + * ```ts + * const createEmbeddingResponse = + * await client.embeddings.create({ + * input: 'The quick brown fox jumped over the lazy dog', + * model: 'text-embedding-3-small', + * }); + * ``` + */ + create(body, options) { + const hasUserProvidedEncodingFormat = !!body.encoding_format; + // No encoding_format specified, defaulting to base64 for performance reasons + // See https://github.com/openai/openai-node/pull/1312 + let encoding_format = hasUserProvidedEncodingFormat ? body.encoding_format : 'base64'; + if (hasUserProvidedEncodingFormat) { + loggerFor(this._client).debug('embeddings/user defined encoding_format:', body.encoding_format); } - return snapshot; - }, Symbol.asyncIterator)]() { - const pushQueue = []; - const readQueue = []; - let done = false; - this.on('chunk', (chunk) => { - const reader = readQueue.shift(); - if (reader) { - reader.resolve(chunk); - } - else { - pushQueue.push(chunk); - } - }); - this.on('end', () => { - done = true; - for (const reader of readQueue) { - reader.resolve(undefined); - } - readQueue.length = 0; + const response = this._client.post('/embeddings', { + body: { + ...body, + encoding_format: encoding_format, + }, + ...options, }); - this.on('abort', (err) => { - done = true; - for (const reader of readQueue) { - reader.reject(err); + // if the user specified an encoding_format, return the response as-is + if (hasUserProvidedEncodingFormat) { + return response; + } + // in this stage, we are sure the user did not specify an encoding_format + // and we defaulted to base64 for performance reasons + // we are sure then that the response is base64 encoded, let's decode it + // the returned result will be a float32 array since this is OpenAI API's default encoding + loggerFor(this._client).debug('embeddings/decoding base64 embeddings from base64'); + return response._thenUnwrap((response) => { + if (response && response.data) { + response.data.forEach((embeddingBase64Obj) => { + const embeddingBase64Str = embeddingBase64Obj.embedding; + embeddingBase64Obj.embedding = toFloat32Array(embeddingBase64Str); + }); } - readQueue.length = 0; + return response; }); - this.on('error', (err) => { - done = true; - for (const reader of readQueue) { - reader.reject(err); - } - readQueue.length = 0; + } +} +//# sourceMappingURL=embeddings.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/evals/runs/output-items.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + +class OutputItems extends APIResource { + /** + * Get an evaluation run output item by ID. + */ + retrieve(outputItemID, params, options) { + const { eval_id, run_id } = params; + return this._client.get(path `/evals/${eval_id}/runs/${run_id}/output_items/${outputItemID}`, options); + } + /** + * Get a list of output items for an evaluation run. + */ + list(runID, params, options) { + const { eval_id, ...query } = params; + return this._client.getAPIList(path `/evals/${eval_id}/runs/${runID}/output_items`, (CursorPage), { query, ...options }); + } +} +//# sourceMappingURL=output-items.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/evals/runs/runs.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + + +class runs_Runs extends APIResource { + constructor() { + super(...arguments); + this.outputItems = new OutputItems(this._client); + } + /** + * Kicks off a new run for a given evaluation, specifying the data source, and what + * model configuration to use to test. The datasource will be validated against the + * schema specified in the config of the evaluation. + */ + create(evalID, body, options) { + return this._client.post(path `/evals/${evalID}/runs`, { body, ...options }); + } + /** + * Get an evaluation run by ID. + */ + retrieve(runID, params, options) { + const { eval_id } = params; + return this._client.get(path `/evals/${eval_id}/runs/${runID}`, options); + } + /** + * Get a list of runs for an evaluation. + */ + list(evalID, query = {}, options) { + return this._client.getAPIList(path `/evals/${evalID}/runs`, (CursorPage), { + query, + ...options, }); - return { - next: async () => { - if (!pushQueue.length) { - if (done) { - return { value: undefined, done: true }; - } - return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((chunk) => (chunk ? { value: chunk, done: false } : { value: undefined, done: true })); - } - const chunk = pushQueue.shift(); - return { value: chunk, done: false }; - }, - return: async () => { - this.abort(); - return { value: undefined, done: true }; - }, - }; } - toReadableStream() { - const stream = new Stream(this[Symbol.asyncIterator].bind(this), this.controller); - return stream.toReadableStream(); + /** + * Delete an eval run. + */ + delete(runID, params, options) { + const { eval_id } = params; + return this._client.delete(path `/evals/${eval_id}/runs/${runID}`, options); + } + /** + * Cancel an ongoing evaluation run. + */ + cancel(runID, params, options) { + const { eval_id } = params; + return this._client.post(path `/evals/${eval_id}/runs/${runID}`, options); } } -function finalizeChatCompletion(snapshot, params) { - const { id, choices, created, model, system_fingerprint, ...rest } = snapshot; - const completion = { - ...rest, - id, - choices: choices.map(({ message, finish_reason, index, logprobs, ...choiceRest }) => { - if (!finish_reason) { - throw new error_OpenAIError(`missing finish_reason for choice ${index}`); - } - const { content = null, function_call, tool_calls, ...messageRest } = message; - const role = message.role; // this is what we expect; in theory it could be different which would make our types a slight lie but would be fine. - if (!role) { - throw new error_OpenAIError(`missing role for choice ${index}`); - } - if (function_call) { - const { arguments: args, name } = function_call; - if (args == null) { - throw new error_OpenAIError(`missing function_call.arguments for choice ${index}`); - } - if (!name) { - throw new error_OpenAIError(`missing function_call.name for choice ${index}`); - } - return { - ...choiceRest, - message: { - content, - function_call: { arguments: args, name }, - role, - refusal: message.refusal ?? null, - }, - finish_reason, - index, - logprobs, - }; - } - if (tool_calls) { - return { - ...choiceRest, - index, - finish_reason, - logprobs, - message: { - ...messageRest, - role, - content, - refusal: message.refusal ?? null, - tool_calls: tool_calls.map((tool_call, i) => { - const { function: fn, type, id, ...toolRest } = tool_call; - const { arguments: args, name, ...fnRest } = fn || {}; - if (id == null) { - throw new error_OpenAIError(`missing choices[${index}].tool_calls[${i}].id\n${str(snapshot)}`); - } - if (type == null) { - throw new error_OpenAIError(`missing choices[${index}].tool_calls[${i}].type\n${str(snapshot)}`); - } - if (name == null) { - throw new error_OpenAIError(`missing choices[${index}].tool_calls[${i}].function.name\n${str(snapshot)}`); - } - if (args == null) { - throw new error_OpenAIError(`missing choices[${index}].tool_calls[${i}].function.arguments\n${str(snapshot)}`); - } - return { ...toolRest, id, type, function: { ...fnRest, name, arguments: args } }; - }), - }, - }; +runs_Runs.OutputItems = OutputItems; +//# sourceMappingURL=runs.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/evals/evals.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + + +class Evals extends APIResource { + constructor() { + super(...arguments); + this.runs = new runs_Runs(this._client); + } + /** + * Create the structure of an evaluation that can be used to test a model's + * performance. An evaluation is a set of testing criteria and the config for a + * data source, which dictates the schema of the data used in the evaluation. After + * creating an evaluation, you can run it on different models and model parameters. + * We support several types of graders and datasources. For more information, see + * the [Evals guide](https://platform.openai.com/docs/guides/evals). + */ + create(body, options) { + return this._client.post('/evals', { body, ...options }); + } + /** + * Get an evaluation by ID. + */ + retrieve(evalID, options) { + return this._client.get(path `/evals/${evalID}`, options); + } + /** + * Update certain properties of an evaluation. + */ + update(evalID, body, options) { + return this._client.post(path `/evals/${evalID}`, { body, ...options }); + } + /** + * List evaluations for a project. + */ + list(query = {}, options) { + return this._client.getAPIList('/evals', (CursorPage), { query, ...options }); + } + /** + * Delete an evaluation. + */ + delete(evalID, options) { + return this._client.delete(path `/evals/${evalID}`, options); + } +} +Evals.Runs = runs_Runs; +//# sourceMappingURL=evals.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/files.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + + + + +class files_Files extends APIResource { + /** + * Upload a file that can be used across various endpoints. Individual files can be + * up to 512 MB, and the size of all files uploaded by one organization can be up + * to 1 TB. + * + * The Assistants API supports files up to 2 million tokens and of specific file + * types. See the + * [Assistants Tools guide](https://platform.openai.com/docs/assistants/tools) for + * details. + * + * The Fine-tuning API only supports `.jsonl` files. The input also has certain + * required formats for fine-tuning + * [chat](https://platform.openai.com/docs/api-reference/fine-tuning/chat-input) or + * [completions](https://platform.openai.com/docs/api-reference/fine-tuning/completions-input) + * models. + * + * The Batch API only supports `.jsonl` files up to 200 MB in size. The input also + * has a specific required + * [format](https://platform.openai.com/docs/api-reference/batch/request-input). + * + * Please [contact us](https://help.openai.com/) if you need to increase these + * storage limits. + */ + create(body, options) { + return this._client.post('/files', multipartFormRequestOptions({ body, ...options }, this._client)); + } + /** + * Returns information about a specific file. + */ + retrieve(fileID, options) { + return this._client.get(path `/files/${fileID}`, options); + } + /** + * Returns a list of files. + */ + list(query = {}, options) { + return this._client.getAPIList('/files', (CursorPage), { query, ...options }); + } + /** + * Delete a file. + */ + delete(fileID, options) { + return this._client.delete(path `/files/${fileID}`, options); + } + /** + * Returns the contents of the specified file. + */ + content(fileID, options) { + return this._client.get(path `/files/${fileID}/content`, { + ...options, + headers: buildHeaders([{ Accept: 'application/binary' }, options?.headers]), + __binaryResponse: true, + }); + } + /** + * Waits for the given file to be processed, default timeout is 30 mins. + */ + async waitForProcessing(id, { pollInterval = 5000, maxWait = 30 * 60 * 1000 } = {}) { + const TERMINAL_STATES = new Set(['processed', 'error', 'deleted']); + const start = Date.now(); + let file = await this.retrieve(id); + while (!file.status || !TERMINAL_STATES.has(file.status)) { + await sleep(pollInterval); + file = await this.retrieve(id); + if (Date.now() - start > maxWait) { + throw new APIConnectionTimeoutError({ + message: `Giving up on waiting for file ${id} to finish processing after ${maxWait} milliseconds.`, + }); } - return { - ...choiceRest, - message: { ...messageRest, content, role, refusal: message.refusal ?? null }, - finish_reason, - index, - logprobs, - }; - }), - created, - model, - object: 'chat.completion', - ...(system_fingerprint ? { system_fingerprint } : {}), - }; - return maybeParseChatCompletion(completion, params); + } + return file; + } } -function str(x) { - return JSON.stringify(x); +//# sourceMappingURL=files.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/fine-tuning/methods.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +class Methods extends APIResource { } -/** - * Ensures the given argument is an empty object, useful for - * asserting that all known properties on an object have been - * destructured. - */ -function assertIsEmpty(obj) { - return; +//# sourceMappingURL=methods.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/fine-tuning/alpha/graders.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +class Graders extends APIResource { + /** + * Run a grader. + * + * @example + * ```ts + * const response = await client.fineTuning.alpha.graders.run({ + * grader: { + * input: 'input', + * name: 'name', + * operation: 'eq', + * reference: 'reference', + * type: 'string_check', + * }, + * model_sample: 'model_sample', + * }); + * ``` + */ + run(body, options) { + return this._client.post('/fine_tuning/alpha/graders/run', { body, ...options }); + } + /** + * Validate a grader. + * + * @example + * ```ts + * const response = + * await client.fineTuning.alpha.graders.validate({ + * grader: { + * input: 'input', + * name: 'name', + * operation: 'eq', + * reference: 'reference', + * type: 'string_check', + * }, + * }); + * ``` + */ + validate(body, options) { + return this._client.post('/fine_tuning/alpha/graders/validate', { body, ...options }); + } } -function assertNever(_x) { } -//# sourceMappingURL=ChatCompletionStream.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/lib/ChatCompletionStreamingRunner.mjs +//# sourceMappingURL=graders.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/fine-tuning/alpha/alpha.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -class ChatCompletionStreamingRunner extends ChatCompletionStream { - static fromReadableStream(stream) { - const runner = new ChatCompletionStreamingRunner(null); - runner._run(() => runner._fromReadableStream(stream)); - return runner; + + +class Alpha extends APIResource { + constructor() { + super(...arguments); + this.graders = new Graders(this._client); + } +} +Alpha.Graders = Graders; +//# sourceMappingURL=alpha.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/fine-tuning/checkpoints/permissions.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + +class Permissions extends APIResource { + /** + * **NOTE:** Calling this endpoint requires an [admin API key](../admin-api-keys). + * + * This enables organization owners to share fine-tuned models with other projects + * in their organization. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const permissionCreateResponse of client.fineTuning.checkpoints.permissions.create( + * 'ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd', + * { project_ids: ['string'] }, + * )) { + * // ... + * } + * ``` + */ + create(fineTunedModelCheckpoint, body, options) { + return this._client.getAPIList(path `/fine_tuning/checkpoints/${fineTunedModelCheckpoint}/permissions`, (Page), { body, method: 'post', ...options }); + } + /** + * **NOTE:** This endpoint requires an [admin API key](../admin-api-keys). + * + * Organization owners can use this endpoint to view all permissions for a + * fine-tuned model checkpoint. + * + * @example + * ```ts + * const permission = + * await client.fineTuning.checkpoints.permissions.retrieve( + * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', + * ); + * ``` + */ + retrieve(fineTunedModelCheckpoint, query = {}, options) { + return this._client.get(path `/fine_tuning/checkpoints/${fineTunedModelCheckpoint}/permissions`, { + query, + ...options, + }); + } + /** + * **NOTE:** This endpoint requires an [admin API key](../admin-api-keys). + * + * Organization owners can use this endpoint to delete a permission for a + * fine-tuned model checkpoint. + * + * @example + * ```ts + * const permission = + * await client.fineTuning.checkpoints.permissions.delete( + * 'cp_zc4Q7MP6XxulcVzj4MZdwsAB', + * { + * fine_tuned_model_checkpoint: + * 'ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd', + * }, + * ); + * ``` + */ + delete(permissionID, params, options) { + const { fine_tuned_model_checkpoint } = params; + return this._client.delete(path `/fine_tuning/checkpoints/${fine_tuned_model_checkpoint}/permissions/${permissionID}`, options); + } +} +//# sourceMappingURL=permissions.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/fine-tuning/checkpoints/checkpoints.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + +class Checkpoints extends APIResource { + constructor() { + super(...arguments); + this.permissions = new Permissions(this._client); + } +} +Checkpoints.Permissions = Permissions; +//# sourceMappingURL=checkpoints.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/fine-tuning/jobs/checkpoints.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + +class checkpoints_Checkpoints extends APIResource { + /** + * List checkpoints for a fine-tuning job. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const fineTuningJobCheckpoint of client.fineTuning.jobs.checkpoints.list( + * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', + * )) { + * // ... + * } + * ``` + */ + list(fineTuningJobID, query = {}, options) { + return this._client.getAPIList(path `/fine_tuning/jobs/${fineTuningJobID}/checkpoints`, (CursorPage), { query, ...options }); + } +} +//# sourceMappingURL=checkpoints.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/fine-tuning/jobs/jobs.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + + +class Jobs extends APIResource { + constructor() { + super(...arguments); + this.checkpoints = new checkpoints_Checkpoints(this._client); + } + /** + * Creates a fine-tuning job which begins the process of creating a new model from + * a given dataset. + * + * Response includes details of the enqueued job including job status and the name + * of the fine-tuned models once complete. + * + * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/model-optimization) + * + * @example + * ```ts + * const fineTuningJob = await client.fineTuning.jobs.create({ + * model: 'gpt-4o-mini', + * training_file: 'file-abc123', + * }); + * ``` + */ + create(body, options) { + return this._client.post('/fine_tuning/jobs', { body, ...options }); } - /** @deprecated - please use `runTools` instead. */ - static runFunctions(client, params, options) { - const runner = new ChatCompletionStreamingRunner(null); - const opts = { - ...options, - headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'runFunctions' }, - }; - runner._run(() => runner._runFunctions(client, params, opts)); - return runner; + /** + * Get info about a fine-tuning job. + * + * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/model-optimization) + * + * @example + * ```ts + * const fineTuningJob = await client.fineTuning.jobs.retrieve( + * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', + * ); + * ``` + */ + retrieve(fineTuningJobID, options) { + return this._client.get(path `/fine_tuning/jobs/${fineTuningJobID}`, options); } - static runTools(client, params, options) { - const runner = new ChatCompletionStreamingRunner( - // @ts-expect-error TODO these types are incompatible - params); - const opts = { - ...options, - headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'runTools' }, - }; - runner._run(() => runner._runTools(client, params, opts)); - return runner; + /** + * List your organization's fine-tuning jobs + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const fineTuningJob of client.fineTuning.jobs.list()) { + * // ... + * } + * ``` + */ + list(query = {}, options) { + return this._client.getAPIList('/fine_tuning/jobs', (CursorPage), { query, ...options }); + } + /** + * Immediately cancel a fine-tune job. + * + * @example + * ```ts + * const fineTuningJob = await client.fineTuning.jobs.cancel( + * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', + * ); + * ``` + */ + cancel(fineTuningJobID, options) { + return this._client.post(path `/fine_tuning/jobs/${fineTuningJobID}/cancel`, options); + } + /** + * Get status updates for a fine-tuning job. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const fineTuningJobEvent of client.fineTuning.jobs.listEvents( + * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', + * )) { + * // ... + * } + * ``` + */ + listEvents(fineTuningJobID, query = {}, options) { + return this._client.getAPIList(path `/fine_tuning/jobs/${fineTuningJobID}/events`, (CursorPage), { query, ...options }); + } + /** + * Pause a fine-tune job. + * + * @example + * ```ts + * const fineTuningJob = await client.fineTuning.jobs.pause( + * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', + * ); + * ``` + */ + pause(fineTuningJobID, options) { + return this._client.post(path `/fine_tuning/jobs/${fineTuningJobID}/pause`, options); + } + /** + * Resume a fine-tune job. + * + * @example + * ```ts + * const fineTuningJob = await client.fineTuning.jobs.resume( + * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', + * ); + * ``` + */ + resume(fineTuningJobID, options) { + return this._client.post(path `/fine_tuning/jobs/${fineTuningJobID}/resume`, options); } } -//# sourceMappingURL=ChatCompletionStreamingRunner.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/chat/completions.mjs +Jobs.Checkpoints = checkpoints_Checkpoints; +//# sourceMappingURL=jobs.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/fine-tuning/fine-tuning.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. @@ -73861,169 +68162,492 @@ class ChatCompletionStreamingRunner extends ChatCompletionStream { -class chat_completions_Completions extends APIResource { - parse(body, options) { - validateInputTools(body.tools); - return this._client.chat.completions - .create(body, { - ...options, - headers: { - ...options?.headers, - 'X-Stainless-Helper-Method': 'beta.chat.completions.parse', - }, - }) - ._thenUnwrap((completion) => parseChatCompletion(completion, body)); - } - runFunctions(body, options) { - if (body.stream) { - return ChatCompletionStreamingRunner.runFunctions(this._client, body, options); - } - return ChatCompletionRunner.runFunctions(this._client, body, options); - } - runTools(body, options) { - if (body.stream) { - return ChatCompletionStreamingRunner.runTools(this._client, body, options); - } - return ChatCompletionRunner.runTools(this._client, body, options); - } - /** - * Creates a chat completion stream - */ - stream(body, options) { - return ChatCompletionStream.createChatCompletion(this._client, body, options); +class FineTuning extends APIResource { + constructor() { + super(...arguments); + this.methods = new Methods(this._client); + this.jobs = new Jobs(this._client); + this.checkpoints = new Checkpoints(this._client); + this.alpha = new Alpha(this._client); } } -//# sourceMappingURL=completions.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/chat/chat.mjs +FineTuning.Methods = Methods; +FineTuning.Jobs = Jobs; +FineTuning.Checkpoints = Checkpoints; +FineTuning.Alpha = Alpha; +//# sourceMappingURL=fine-tuning.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/graders/grader-models.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +class GraderModels extends APIResource { +} +//# sourceMappingURL=grader-models.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/graders/graders.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -class chat_Chat extends APIResource { + +class graders_Graders extends APIResource { constructor() { super(...arguments); - this.completions = new chat_completions_Completions(this._client); + this.graderModels = new GraderModels(this._client); } } -(function (Chat) { - Chat.Completions = chat_completions_Completions; -})(chat_Chat || (chat_Chat = {})); -//# sourceMappingURL=chat.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/realtime/sessions.mjs +graders_Graders.GraderModels = GraderModels; +//# sourceMappingURL=graders.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/images.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -class Sessions extends APIResource { + +class Images extends APIResource { /** - * Create an ephemeral API token for use in client-side applications with the - * Realtime API. Can be configured with the same session parameters as the - * `session.update` client event. - * - * It responds with a session object, plus a `client_secret` key which contains a - * usable ephemeral API token that can be used to authenticate browser clients for - * the Realtime API. + * Creates a variation of a given image. This endpoint only supports `dall-e-2`. * * @example * ```ts - * const session = - * await client.beta.realtime.sessions.create(); + * const imagesResponse = await client.images.createVariation({ + * image: fs.createReadStream('otter.png'), + * }); * ``` */ - create(body, options) { - return this._client.post('/realtime/sessions', { - body, - ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, - }); + createVariation(body, options) { + return this._client.post('/images/variations', multipartFormRequestOptions({ body, ...options }, this._client)); + } + edit(body, options) { + return this._client.post('/images/edits', multipartFormRequestOptions({ body, ...options, stream: body.stream ?? false }, this._client)); + } + generate(body, options) { + return this._client.post('/images/generations', { body, ...options, stream: body.stream ?? false }); } } -//# sourceMappingURL=sessions.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/realtime/transcription-sessions.mjs +//# sourceMappingURL=images.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/models.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -class TranscriptionSessions extends APIResource { + + +class Models extends APIResource { /** - * Create an ephemeral API token for use in client-side applications with the - * Realtime API specifically for realtime transcriptions. Can be configured with - * the same session parameters as the `transcription_session.update` client event. - * - * It responds with a session object, plus a `client_secret` key which contains a - * usable ephemeral API token that can be used to authenticate browser clients for - * the Realtime API. - * - * @example - * ```ts - * const transcriptionSession = - * await client.beta.realtime.transcriptionSessions.create(); - * ``` + * Retrieves a model instance, providing basic information about the model such as + * the owner and permissioning. */ - create(body, options) { - return this._client.post('/realtime/transcription_sessions', { - body, - ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, - }); + retrieve(model, options) { + return this._client.get(path `/models/${model}`, options); + } + /** + * Lists the currently available models, and provides basic information about each + * one such as the owner and availability. + */ + list(options) { + return this._client.getAPIList('/models', (Page), options); + } + /** + * Delete a fine-tuned model. You must have the Owner role in your organization to + * delete a model. + */ + delete(model, options) { + return this._client.delete(path `/models/${model}`, options); } } -//# sourceMappingURL=transcription-sessions.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/realtime/realtime.mjs +//# sourceMappingURL=models.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/moderations.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +class Moderations extends APIResource { + /** + * Classifies if text and/or image inputs are potentially harmful. Learn more in + * the [moderation guide](https://platform.openai.com/docs/guides/moderation). + */ + create(body, options) { + return this._client.post('/moderations', { body, ...options }); + } +} +//# sourceMappingURL=moderations.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/realtime/client-secrets.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +class ClientSecrets extends APIResource { + /** + * Create a Realtime client secret with an associated session configuration. + */ + create(body, options) { + return this._client.post('/realtime/client_secrets', { body, ...options }); + } +} +//# sourceMappingURL=client-secrets.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/realtime/realtime.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -class Realtime extends APIResource { +class realtime_Realtime extends APIResource { constructor() { super(...arguments); - this.sessions = new Sessions(this._client); - this.transcriptionSessions = new TranscriptionSessions(this._client); + this.clientSecrets = new ClientSecrets(this._client); } } -Realtime.Sessions = Sessions; -Realtime.TranscriptionSessions = TranscriptionSessions; +realtime_Realtime.ClientSecrets = ClientSecrets; //# sourceMappingURL=realtime.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/lib/AssistantStream.mjs -var AssistantStream_classPrivateFieldGet = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) { - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); -}; -var AssistantStream_classPrivateFieldSet = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { - if (kind === "m") throw new TypeError("Private method is not writable"); - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); - return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; -}; -var _AssistantStream_instances, _AssistantStream_events, _AssistantStream_runStepSnapshots, _AssistantStream_messageSnapshots, _AssistantStream_messageSnapshot, _AssistantStream_finalRun, _AssistantStream_currentContentIndex, _AssistantStream_currentContent, _AssistantStream_currentToolCallIndex, _AssistantStream_currentToolCall, _AssistantStream_currentEvent, _AssistantStream_currentRunSnapshot, _AssistantStream_currentRunStepSnapshot, _AssistantStream_addEvent, _AssistantStream_endRequest, _AssistantStream_handleMessage, _AssistantStream_handleRunStep, _AssistantStream_handleEvent, _AssistantStream_accumulateRunStep, _AssistantStream_accumulateMessage, _AssistantStream_accumulateContent, _AssistantStream_handleRun; +;// CONCATENATED MODULE: ./node_modules/openai/lib/ResponsesParser.mjs + +function maybeParseResponse(response, params) { + if (!params || !ResponsesParser_hasAutoParseableInput(params)) { + return { + ...response, + output_parsed: null, + output: response.output.map((item) => { + if (item.type === 'function_call') { + return { + ...item, + parsed_arguments: null, + }; + } + if (item.type === 'message') { + return { + ...item, + content: item.content.map((content) => ({ + ...content, + parsed: null, + })), + }; + } + else { + return item; + } + }), + }; + } + return parseResponse(response, params); +} +function parseResponse(response, params) { + const output = response.output.map((item) => { + if (item.type === 'function_call') { + return { + ...item, + parsed_arguments: ResponsesParser_parseToolCall(params, item), + }; + } + if (item.type === 'message') { + const content = item.content.map((content) => { + if (content.type === 'output_text') { + return { + ...content, + parsed: parseTextFormat(params, content.text), + }; + } + return content; + }); + return { + ...item, + content, + }; + } + return item; + }); + const parsed = Object.assign({}, response, { output }); + if (!Object.getOwnPropertyDescriptor(response, 'output_text')) { + addOutputText(parsed); + } + Object.defineProperty(parsed, 'output_parsed', { + enumerable: true, + get() { + for (const output of parsed.output) { + if (output.type !== 'message') { + continue; + } + for (const content of output.content) { + if (content.type === 'output_text' && content.parsed !== null) { + return content.parsed; + } + } + } + return null; + }, + }); + return parsed; +} +function parseTextFormat(params, content) { + if (params.text?.format?.type !== 'json_schema') { + return null; + } + if ('$parseRaw' in params.text?.format) { + const text_format = params.text?.format; + return text_format.$parseRaw(content); + } + return JSON.parse(content); +} +function ResponsesParser_hasAutoParseableInput(params) { + if (isAutoParsableResponseFormat(params.text?.format)) { + return true; + } + return false; +} +function ResponsesParser_makeParseableResponseTool(tool, { parser, callback, }) { + const obj = { ...tool }; + Object.defineProperties(obj, { + $brand: { + value: 'auto-parseable-tool', + enumerable: false, + }, + $parseRaw: { + value: parser, + enumerable: false, + }, + $callback: { + value: callback, + enumerable: false, + }, + }); + return obj; +} +function ResponsesParser_isAutoParsableTool(tool) { + return tool?.['$brand'] === 'auto-parseable-tool'; +} +function getInputToolByName(input_tools, name) { + return input_tools.find((tool) => tool.type === 'function' && tool.name === name); +} +function ResponsesParser_parseToolCall(params, toolCall) { + const inputTool = getInputToolByName(params.tools ?? [], toolCall.name); + return { + ...toolCall, + ...toolCall, + parsed_arguments: ResponsesParser_isAutoParsableTool(inputTool) ? inputTool.$parseRaw(toolCall.arguments) + : inputTool?.strict ? JSON.parse(toolCall.arguments) + : null, + }; +} +function ResponsesParser_shouldParseToolCall(params, toolCall) { + if (!params) { + return false; + } + const inputTool = getInputToolByName(params.tools ?? [], toolCall.name); + return ResponsesParser_isAutoParsableTool(inputTool) || inputTool?.strict || false; +} +function ResponsesParser_validateInputTools(tools) { + for (const tool of tools ?? []) { + if (tool.type !== 'function') { + throw new OpenAIError(`Currently only \`function\` tool types support auto-parsing; Received \`${tool.type}\``); + } + if (tool.function.strict !== true) { + throw new OpenAIError(`The \`${tool.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`); + } + } +} +function addOutputText(rsp) { + const texts = []; + for (const output of rsp.output) { + if (output.type !== 'message') { + continue; + } + for (const content of output.content) { + if (content.type === 'output_text') { + texts.push(content.text); + } + } + } + rsp.output_text = texts.join(''); +} +//# sourceMappingURL=ResponsesParser.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/lib/responses/ResponseStream.mjs +var _ResponseStream_instances, _ResponseStream_params, _ResponseStream_currentResponseSnapshot, _ResponseStream_finalResponse, _ResponseStream_beginRequest, _ResponseStream_addEvent, _ResponseStream_endRequest, _ResponseStream_accumulateResponse; -class AssistantStream extends EventStream { - constructor() { - super(...arguments); - _AssistantStream_instances.add(this); - //Track all events in a single list for reference - _AssistantStream_events.set(this, []); - //Used to accumulate deltas - //We are accumulating many types so the value here is not strict - _AssistantStream_runStepSnapshots.set(this, {}); - _AssistantStream_messageSnapshots.set(this, {}); - _AssistantStream_messageSnapshot.set(this, void 0); - _AssistantStream_finalRun.set(this, void 0); - _AssistantStream_currentContentIndex.set(this, void 0); - _AssistantStream_currentContent.set(this, void 0); - _AssistantStream_currentToolCallIndex.set(this, void 0); - _AssistantStream_currentToolCall.set(this, void 0); - //For current snapshot methods - _AssistantStream_currentEvent.set(this, void 0); - _AssistantStream_currentRunSnapshot.set(this, void 0); - _AssistantStream_currentRunStepSnapshot.set(this, void 0); + +class ResponseStream extends EventStream { + constructor(params) { + super(); + _ResponseStream_instances.add(this); + _ResponseStream_params.set(this, void 0); + _ResponseStream_currentResponseSnapshot.set(this, void 0); + _ResponseStream_finalResponse.set(this, void 0); + __classPrivateFieldSet(this, _ResponseStream_params, params, "f"); } - [(_AssistantStream_events = new WeakMap(), _AssistantStream_runStepSnapshots = new WeakMap(), _AssistantStream_messageSnapshots = new WeakMap(), _AssistantStream_messageSnapshot = new WeakMap(), _AssistantStream_finalRun = new WeakMap(), _AssistantStream_currentContentIndex = new WeakMap(), _AssistantStream_currentContent = new WeakMap(), _AssistantStream_currentToolCallIndex = new WeakMap(), _AssistantStream_currentToolCall = new WeakMap(), _AssistantStream_currentEvent = new WeakMap(), _AssistantStream_currentRunSnapshot = new WeakMap(), _AssistantStream_currentRunStepSnapshot = new WeakMap(), _AssistantStream_instances = new WeakSet(), Symbol.asyncIterator)]() { + static createResponse(client, params, options) { + const runner = new ResponseStream(params); + runner._run(() => runner._createOrRetrieveResponse(client, params, { + ...options, + headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' }, + })); + return runner; + } + async _createOrRetrieveResponse(client, params, options) { + const signal = options?.signal; + if (signal) { + if (signal.aborted) + this.controller.abort(); + signal.addEventListener('abort', () => this.controller.abort()); + } + __classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_beginRequest).call(this); + let stream; + let starting_after = null; + if ('response_id' in params) { + stream = await client.responses.retrieve(params.response_id, { stream: true }, { ...options, signal: this.controller.signal, stream: true }); + starting_after = params.starting_after ?? null; + } + else { + stream = await client.responses.create({ ...params, stream: true }, { ...options, signal: this.controller.signal }); + } + this._connected(); + for await (const event of stream) { + __classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_addEvent).call(this, event, starting_after); + } + if (stream.controller.signal?.aborted) { + throw new APIUserAbortError(); + } + return __classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_endRequest).call(this); + } + [(_ResponseStream_params = new WeakMap(), _ResponseStream_currentResponseSnapshot = new WeakMap(), _ResponseStream_finalResponse = new WeakMap(), _ResponseStream_instances = new WeakSet(), _ResponseStream_beginRequest = function _ResponseStream_beginRequest() { + if (this.ended) + return; + __classPrivateFieldSet(this, _ResponseStream_currentResponseSnapshot, undefined, "f"); + }, _ResponseStream_addEvent = function _ResponseStream_addEvent(event, starting_after) { + if (this.ended) + return; + const maybeEmit = (name, event) => { + if (starting_after == null || event.sequence_number > starting_after) { + this._emit(name, event); + } + }; + const response = __classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_accumulateResponse).call(this, event); + maybeEmit('event', event); + switch (event.type) { + case 'response.output_text.delta': { + const output = response.output[event.output_index]; + if (!output) { + throw new error_OpenAIError(`missing output at index ${event.output_index}`); + } + if (output.type === 'message') { + const content = output.content[event.content_index]; + if (!content) { + throw new error_OpenAIError(`missing content at index ${event.content_index}`); + } + if (content.type !== 'output_text') { + throw new error_OpenAIError(`expected content to be 'output_text', got ${content.type}`); + } + maybeEmit('response.output_text.delta', { + ...event, + snapshot: content.text, + }); + } + break; + } + case 'response.function_call_arguments.delta': { + const output = response.output[event.output_index]; + if (!output) { + throw new error_OpenAIError(`missing output at index ${event.output_index}`); + } + if (output.type === 'function_call') { + maybeEmit('response.function_call_arguments.delta', { + ...event, + snapshot: output.arguments, + }); + } + break; + } + default: + maybeEmit(event.type, event); + break; + } + }, _ResponseStream_endRequest = function _ResponseStream_endRequest() { + if (this.ended) { + throw new error_OpenAIError(`stream has ended, this shouldn't happen`); + } + const snapshot = __classPrivateFieldGet(this, _ResponseStream_currentResponseSnapshot, "f"); + if (!snapshot) { + throw new error_OpenAIError(`request ended without sending any events`); + } + __classPrivateFieldSet(this, _ResponseStream_currentResponseSnapshot, undefined, "f"); + const parsedResponse = finalizeResponse(snapshot, __classPrivateFieldGet(this, _ResponseStream_params, "f")); + __classPrivateFieldSet(this, _ResponseStream_finalResponse, parsedResponse, "f"); + return parsedResponse; + }, _ResponseStream_accumulateResponse = function _ResponseStream_accumulateResponse(event) { + let snapshot = __classPrivateFieldGet(this, _ResponseStream_currentResponseSnapshot, "f"); + if (!snapshot) { + if (event.type !== 'response.created') { + throw new error_OpenAIError(`When snapshot hasn't been set yet, expected 'response.created' event, got ${event.type}`); + } + snapshot = __classPrivateFieldSet(this, _ResponseStream_currentResponseSnapshot, event.response, "f"); + return snapshot; + } + switch (event.type) { + case 'response.output_item.added': { + snapshot.output.push(event.item); + break; + } + case 'response.content_part.added': { + const output = snapshot.output[event.output_index]; + if (!output) { + throw new error_OpenAIError(`missing output at index ${event.output_index}`); + } + const type = output.type; + const part = event.part; + if (type === 'message' && part.type !== 'reasoning_text') { + output.content.push(part); + } + else if (type === 'reasoning' && part.type === 'reasoning_text') { + if (!output.content) { + output.content = []; + } + output.content.push(part); + } + break; + } + case 'response.output_text.delta': { + const output = snapshot.output[event.output_index]; + if (!output) { + throw new error_OpenAIError(`missing output at index ${event.output_index}`); + } + if (output.type === 'message') { + const content = output.content[event.content_index]; + if (!content) { + throw new error_OpenAIError(`missing content at index ${event.content_index}`); + } + if (content.type !== 'output_text') { + throw new error_OpenAIError(`expected content to be 'output_text', got ${content.type}`); + } + content.text += event.delta; + } + break; + } + case 'response.function_call_arguments.delta': { + const output = snapshot.output[event.output_index]; + if (!output) { + throw new error_OpenAIError(`missing output at index ${event.output_index}`); + } + if (output.type === 'function_call') { + output.arguments += event.delta; + } + break; + } + case 'response.reasoning_text.delta': { + const output = snapshot.output[event.output_index]; + if (!output) { + throw new error_OpenAIError(`missing output at index ${event.output_index}`); + } + if (output.type === 'reasoning') { + const content = output.content?.[event.content_index]; + if (!content) { + throw new error_OpenAIError(`missing content at index ${event.content_index}`); + } + if (content.type !== 'reasoning_text') { + throw new error_OpenAIError(`expected content to be 'reasoning_text', got ${content.type}`); + } + content.text += event.delta; + } + break; + } + case 'response.completed': { + __classPrivateFieldSet(this, _ResponseStream_currentResponseSnapshot, event.response, "f"); + break; + } + } + return snapshot; + }, Symbol.asyncIterator)]() { const pushQueue = []; const readQueue = []; let done = false; - //Catch all for passing along all events this.on('event', (event) => { const reader = readQueue.shift(); if (reader) { @@ -74060,10 +68684,10 @@ class AssistantStream extends EventStream { if (done) { return { value: undefined, done: true }; } - return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((chunk) => (chunk ? { value: chunk, done: false } : { value: undefined, done: true })); + return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((event) => (event ? { value: event, done: false } : { value: undefined, done: true })); } - const chunk = pushQueue.shift(); - return { value: chunk, done: false }; + const event = pushQueue.shift(); + return { value: event, done: false }; }, return: async () => { this.abort(); @@ -74071,599 +68695,682 @@ class AssistantStream extends EventStream { }, }; } - static fromReadableStream(stream) { - const runner = new AssistantStream(); - runner._run(() => runner._fromReadableStream(stream)); - return runner; - } - async _fromReadableStream(readableStream, options) { - const signal = options?.signal; - if (signal) { - if (signal.aborted) - this.controller.abort(); - signal.addEventListener('abort', () => this.controller.abort()); - } - this._connected(); - const stream = Stream.fromReadableStream(readableStream, this.controller); - for await (const event of stream) { - AssistantStream_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event); - } - if (stream.controller.signal?.aborted) { - throw new APIUserAbortError(); - } - return this._addRun(AssistantStream_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this)); + /** + * @returns a promise that resolves with the final Response, or rejects + * if an error occurred or the stream ended prematurely without producing a REsponse. + */ + async finalResponse() { + await this.done(); + const response = __classPrivateFieldGet(this, _ResponseStream_finalResponse, "f"); + if (!response) + throw new error_OpenAIError('stream ended without producing a ChatCompletion'); + return response; } - toReadableStream() { - const stream = new Stream(this[Symbol.asyncIterator].bind(this), this.controller); - return stream.toReadableStream(); +} +function finalizeResponse(snapshot, params) { + return maybeParseResponse(snapshot, params); +} +//# sourceMappingURL=ResponseStream.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/responses/input-items.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + +class InputItems extends APIResource { + /** + * Returns a list of input items for a given response. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const responseItem of client.responses.inputItems.list( + * 'response_id', + * )) { + * // ... + * } + * ``` + */ + list(responseID, query = {}, options) { + return this._client.getAPIList(path `/responses/${responseID}/input_items`, (CursorPage), { query, ...options }); } - static createToolAssistantStream(threadId, runId, runs, params, options) { - const runner = new AssistantStream(); - runner._run(() => runner._runToolAssistantStream(threadId, runId, runs, params, { - ...options, - headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' }, - })); - return runner; +} +//# sourceMappingURL=input-items.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/responses/responses.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + + + + +class Responses extends APIResource { + constructor() { + super(...arguments); + this.inputItems = new InputItems(this._client); } - async _createToolAssistantStream(run, threadId, runId, params, options) { - const signal = options?.signal; - if (signal) { - if (signal.aborted) - this.controller.abort(); - signal.addEventListener('abort', () => this.controller.abort()); - } - const body = { ...params, stream: true }; - const stream = await run.submitToolOutputs(threadId, runId, body, { - ...options, - signal: this.controller.signal, + create(body, options) { + return this._client.post('/responses', { body, ...options, stream: body.stream ?? false })._thenUnwrap((rsp) => { + if ('object' in rsp && rsp.object === 'response') { + addOutputText(rsp); + } + return rsp; }); - this._connected(); - for await (const event of stream) { - AssistantStream_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event); - } - if (stream.controller.signal?.aborted) { - throw new APIUserAbortError(); - } - return this._addRun(AssistantStream_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this)); } - static createThreadAssistantStream(params, thread, options) { - const runner = new AssistantStream(); - runner._run(() => runner._threadAssistantStream(params, thread, { + retrieve(responseID, query = {}, options) { + return this._client.get(path `/responses/${responseID}`, { + query, ...options, - headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' }, - })); - return runner; + stream: query?.stream ?? false, + })._thenUnwrap((rsp) => { + if ('object' in rsp && rsp.object === 'response') { + addOutputText(rsp); + } + return rsp; + }); } - static createAssistantStream(threadId, runs, params, options) { - const runner = new AssistantStream(); - runner._run(() => runner._runAssistantStream(threadId, runs, params, { + /** + * Deletes a model response with the given ID. + * + * @example + * ```ts + * await client.responses.delete( + * 'resp_677efb5139a88190b512bc3fef8e535d', + * ); + * ``` + */ + delete(responseID, options) { + return this._client.delete(path `/responses/${responseID}`, { ...options, - headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' }, - })); - return runner; + headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), + }); } - currentEvent() { - return AssistantStream_classPrivateFieldGet(this, _AssistantStream_currentEvent, "f"); + parse(body, options) { + return this._client.responses + .create(body, options) + ._thenUnwrap((response) => parseResponse(response, body)); } - currentRun() { - return AssistantStream_classPrivateFieldGet(this, _AssistantStream_currentRunSnapshot, "f"); + /** + * Creates a model response stream + */ + stream(body, options) { + return ResponseStream.createResponse(this._client, body, options); } - currentMessageSnapshot() { - return AssistantStream_classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f"); + /** + * Cancels a model response with the given ID. Only responses created with the + * `background` parameter set to `true` can be cancelled. + * [Learn more](https://platform.openai.com/docs/guides/background). + * + * @example + * ```ts + * const response = await client.responses.cancel( + * 'resp_677efb5139a88190b512bc3fef8e535d', + * ); + * ``` + */ + cancel(responseID, options) { + return this._client.post(path `/responses/${responseID}/cancel`, options); } - currentRunStepSnapshot() { - return AssistantStream_classPrivateFieldGet(this, _AssistantStream_currentRunStepSnapshot, "f"); +} +Responses.InputItems = InputItems; +//# sourceMappingURL=responses.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/uploads/parts.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + +class Parts extends APIResource { + /** + * Adds a + * [Part](https://platform.openai.com/docs/api-reference/uploads/part-object) to an + * [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object. + * A Part represents a chunk of bytes from the file you are trying to upload. + * + * Each Part can be at most 64 MB, and you can add Parts until you hit the Upload + * maximum of 8 GB. + * + * It is possible to add multiple Parts in parallel. You can decide the intended + * order of the Parts when you + * [complete the Upload](https://platform.openai.com/docs/api-reference/uploads/complete). + */ + create(uploadID, body, options) { + return this._client.post(path `/uploads/${uploadID}/parts`, multipartFormRequestOptions({ body, ...options }, this._client)); } - async finalRunSteps() { - await this.done(); - return Object.values(AssistantStream_classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")); +} +//# sourceMappingURL=parts.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/uploads/uploads.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + +class Uploads extends APIResource { + constructor() { + super(...arguments); + this.parts = new Parts(this._client); } - async finalMessages() { - await this.done(); - return Object.values(AssistantStream_classPrivateFieldGet(this, _AssistantStream_messageSnapshots, "f")); + /** + * Creates an intermediate + * [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object + * that you can add + * [Parts](https://platform.openai.com/docs/api-reference/uploads/part-object) to. + * Currently, an Upload can accept at most 8 GB in total and expires after an hour + * after you create it. + * + * Once you complete the Upload, we will create a + * [File](https://platform.openai.com/docs/api-reference/files/object) object that + * contains all the parts you uploaded. This File is usable in the rest of our + * platform as a regular File object. + * + * For certain `purpose` values, the correct `mime_type` must be specified. Please + * refer to documentation for the + * [supported MIME types for your use case](https://platform.openai.com/docs/assistants/tools/file-search#supported-files). + * + * For guidance on the proper filename extensions for each purpose, please follow + * the documentation on + * [creating a File](https://platform.openai.com/docs/api-reference/files/create). + */ + create(body, options) { + return this._client.post('/uploads', { body, ...options }); } - async finalRun() { - await this.done(); - if (!AssistantStream_classPrivateFieldGet(this, _AssistantStream_finalRun, "f")) - throw Error('Final run was not received.'); - return AssistantStream_classPrivateFieldGet(this, _AssistantStream_finalRun, "f"); + /** + * Cancels the Upload. No Parts may be added after an Upload is cancelled. + */ + cancel(uploadID, options) { + return this._client.post(path `/uploads/${uploadID}/cancel`, options); } - async _createThreadAssistantStream(thread, params, options) { - const signal = options?.signal; - if (signal) { - if (signal.aborted) - this.controller.abort(); - signal.addEventListener('abort', () => this.controller.abort()); - } - const body = { ...params, stream: true }; - const stream = await thread.createAndRun(body, { ...options, signal: this.controller.signal }); - this._connected(); - for await (const event of stream) { - AssistantStream_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event); - } - if (stream.controller.signal?.aborted) { - throw new APIUserAbortError(); - } - return this._addRun(AssistantStream_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this)); + /** + * Completes the + * [Upload](https://platform.openai.com/docs/api-reference/uploads/object). + * + * Within the returned Upload object, there is a nested + * [File](https://platform.openai.com/docs/api-reference/files/object) object that + * is ready to use in the rest of the platform. + * + * You can specify the order of the Parts by passing in an ordered list of the Part + * IDs. + * + * The number of bytes uploaded upon completion must match the number of bytes + * initially specified when creating the Upload object. No Parts may be added after + * an Upload is completed. + */ + complete(uploadID, body, options) { + return this._client.post(path `/uploads/${uploadID}/complete`, { body, ...options }); } - async _createAssistantStream(run, threadId, params, options) { - const signal = options?.signal; - if (signal) { - if (signal.aborted) - this.controller.abort(); - signal.addEventListener('abort', () => this.controller.abort()); - } - const body = { ...params, stream: true }; - const stream = await run.create(threadId, body, { ...options, signal: this.controller.signal }); - this._connected(); - for await (const event of stream) { - AssistantStream_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event); - } - if (stream.controller.signal?.aborted) { - throw new APIUserAbortError(); +} +Uploads.Parts = Parts; +//# sourceMappingURL=uploads.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/lib/Util.mjs +/** + * Like `Promise.allSettled()` but throws an error if any promises are rejected. + */ +const allSettledWithThrow = async (promises) => { + const results = await Promise.allSettled(promises); + const rejected = results.filter((result) => result.status === 'rejected'); + if (rejected.length) { + for (const result of rejected) { + console.error(result.reason); } - return this._addRun(AssistantStream_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this)); + throw new Error(`${rejected.length} promise(s) failed - see the above errors`); } - static accumulateDelta(acc, delta) { - for (const [key, deltaValue] of Object.entries(delta)) { - if (!acc.hasOwnProperty(key)) { - acc[key] = deltaValue; - continue; - } - let accValue = acc[key]; - if (accValue === null || accValue === undefined) { - acc[key] = deltaValue; - continue; - } - // We don't accumulate these special properties - if (key === 'index' || key === 'type') { - acc[key] = deltaValue; - continue; - } - // Type-specific accumulation logic - if (typeof accValue === 'string' && typeof deltaValue === 'string') { - accValue += deltaValue; - } - else if (typeof accValue === 'number' && typeof deltaValue === 'number') { - accValue += deltaValue; - } - else if (isObj(accValue) && isObj(deltaValue)) { - accValue = this.accumulateDelta(accValue, deltaValue); - } - else if (Array.isArray(accValue) && Array.isArray(deltaValue)) { - if (accValue.every((x) => typeof x === 'string' || typeof x === 'number')) { - accValue.push(...deltaValue); // Use spread syntax for efficient addition - continue; - } - for (const deltaEntry of deltaValue) { - if (!isObj(deltaEntry)) { - throw new Error(`Expected array delta entry to be an object but got: ${deltaEntry}`); - } - const index = deltaEntry['index']; - if (index == null) { - console.error(deltaEntry); - throw new Error('Expected array delta entry to have an `index` property'); - } - if (typeof index !== 'number') { - throw new Error(`Expected array delta entry \`index\` property to be a number but got ${index}`); - } - const accEntry = accValue[index]; - if (accEntry == null) { - accValue.push(deltaEntry); - } - else { - accValue[index] = this.accumulateDelta(accEntry, deltaEntry); - } - } - continue; - } - else { - throw Error(`Unhandled record type: ${key}, deltaValue: ${deltaValue}, accValue: ${accValue}`); - } - acc[key] = accValue; + // Note: TS was complaining about using `.filter().map()` here for some reason + const values = []; + for (const result of results) { + if (result.status === 'fulfilled') { + values.push(result.value); } - return acc; - } - _addRun(run) { - return run; - } - async _threadAssistantStream(params, thread, options) { - return await this._createThreadAssistantStream(thread, params, options); - } - async _runAssistantStream(threadId, runs, params, options) { - return await this._createAssistantStream(runs, threadId, params, options); - } - async _runToolAssistantStream(threadId, runId, runs, params, options) { - return await this._createToolAssistantStream(runs, threadId, runId, params, options); - } -} -_AssistantStream_addEvent = function _AssistantStream_addEvent(event) { - if (this.ended) - return; - AssistantStream_classPrivateFieldSet(this, _AssistantStream_currentEvent, event, "f"); - AssistantStream_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_handleEvent).call(this, event); - switch (event.event) { - case 'thread.created': - //No action on this event. - break; - case 'thread.run.created': - case 'thread.run.queued': - case 'thread.run.in_progress': - case 'thread.run.requires_action': - case 'thread.run.completed': - case 'thread.run.incomplete': - case 'thread.run.failed': - case 'thread.run.cancelling': - case 'thread.run.cancelled': - case 'thread.run.expired': - AssistantStream_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_handleRun).call(this, event); - break; - case 'thread.run.step.created': - case 'thread.run.step.in_progress': - case 'thread.run.step.delta': - case 'thread.run.step.completed': - case 'thread.run.step.failed': - case 'thread.run.step.cancelled': - case 'thread.run.step.expired': - AssistantStream_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_handleRunStep).call(this, event); - break; - case 'thread.message.created': - case 'thread.message.in_progress': - case 'thread.message.delta': - case 'thread.message.completed': - case 'thread.message.incomplete': - AssistantStream_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_handleMessage).call(this, event); - break; - case 'error': - //This is included for completeness, but errors are processed in the SSE event processing so this should not occur - throw new Error('Encountered an error event in event processing - errors should be processed earlier'); - default: - AssistantStream_assertNever(event); } -}, _AssistantStream_endRequest = function _AssistantStream_endRequest() { - if (this.ended) { - throw new error_OpenAIError(`stream has ended, this shouldn't happen`); + return values; +}; +//# sourceMappingURL=Util.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/vector-stores/file-batches.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + + + +class FileBatches extends APIResource { + /** + * Create a vector store file batch. + */ + create(vectorStoreID, body, options) { + return this._client.post(path `/vector_stores/${vectorStoreID}/file_batches`, { + body, + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); } - if (!AssistantStream_classPrivateFieldGet(this, _AssistantStream_finalRun, "f")) - throw Error('Final run has not been received'); - return AssistantStream_classPrivateFieldGet(this, _AssistantStream_finalRun, "f"); -}, _AssistantStream_handleMessage = function _AssistantStream_handleMessage(event) { - const [accumulatedMessage, newContent] = AssistantStream_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_accumulateMessage).call(this, event, AssistantStream_classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f")); - AssistantStream_classPrivateFieldSet(this, _AssistantStream_messageSnapshot, accumulatedMessage, "f"); - AssistantStream_classPrivateFieldGet(this, _AssistantStream_messageSnapshots, "f")[accumulatedMessage.id] = accumulatedMessage; - for (const content of newContent) { - const snapshotContent = accumulatedMessage.content[content.index]; - if (snapshotContent?.type == 'text') { - this._emit('textCreated', snapshotContent.text); - } + /** + * Retrieves a vector store file batch. + */ + retrieve(batchID, params, options) { + const { vector_store_id } = params; + return this._client.get(path `/vector_stores/${vector_store_id}/file_batches/${batchID}`, { + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); } - switch (event.event) { - case 'thread.message.created': - this._emit('messageCreated', event.data); - break; - case 'thread.message.in_progress': - break; - case 'thread.message.delta': - this._emit('messageDelta', event.data.delta, accumulatedMessage); - if (event.data.delta.content) { - for (const content of event.data.delta.content) { - //If it is text delta, emit a text delta event - if (content.type == 'text' && content.text) { - let textDelta = content.text; - let snapshot = accumulatedMessage.content[content.index]; - if (snapshot && snapshot.type == 'text') { - this._emit('textDelta', textDelta, snapshot.text); - } - else { - throw Error('The snapshot associated with this text delta is not text or missing'); - } + /** + * Cancel a vector store file batch. This attempts to cancel the processing of + * files in this batch as soon as possible. + */ + cancel(batchID, params, options) { + const { vector_store_id } = params; + return this._client.post(path `/vector_stores/${vector_store_id}/file_batches/${batchID}/cancel`, { + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + /** + * Create a vector store batch and poll until all files have been processed. + */ + async createAndPoll(vectorStoreId, body, options) { + const batch = await this.create(vectorStoreId, body); + return await this.poll(vectorStoreId, batch.id, options); + } + /** + * Returns a list of vector store files in a batch. + */ + listFiles(batchID, params, options) { + const { vector_store_id, ...query } = params; + return this._client.getAPIList(path `/vector_stores/${vector_store_id}/file_batches/${batchID}/files`, (CursorPage), { query, ...options, headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]) }); + } + /** + * Wait for the given file batch to be processed. + * + * Note: this will return even if one of the files failed to process, you need to + * check batch.file_counts.failed_count to handle this case. + */ + async poll(vectorStoreID, batchID, options) { + const headers = buildHeaders([ + options?.headers, + { + 'X-Stainless-Poll-Helper': 'true', + 'X-Stainless-Custom-Poll-Interval': options?.pollIntervalMs?.toString() ?? undefined, + }, + ]); + while (true) { + const { data: batch, response } = await this.retrieve(batchID, { vector_store_id: vectorStoreID }, { + ...options, + headers, + }).withResponse(); + switch (batch.status) { + case 'in_progress': + let sleepInterval = 5000; + if (options?.pollIntervalMs) { + sleepInterval = options.pollIntervalMs; } - if (content.index != AssistantStream_classPrivateFieldGet(this, _AssistantStream_currentContentIndex, "f")) { - //See if we have in progress content - if (AssistantStream_classPrivateFieldGet(this, _AssistantStream_currentContent, "f")) { - switch (AssistantStream_classPrivateFieldGet(this, _AssistantStream_currentContent, "f").type) { - case 'text': - this._emit('textDone', AssistantStream_classPrivateFieldGet(this, _AssistantStream_currentContent, "f").text, AssistantStream_classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f")); - break; - case 'image_file': - this._emit('imageFileDone', AssistantStream_classPrivateFieldGet(this, _AssistantStream_currentContent, "f").image_file, AssistantStream_classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f")); - break; + else { + const headerInterval = response.headers.get('openai-poll-after-ms'); + if (headerInterval) { + const headerIntervalMs = parseInt(headerInterval); + if (!isNaN(headerIntervalMs)) { + sleepInterval = headerIntervalMs; } } - AssistantStream_classPrivateFieldSet(this, _AssistantStream_currentContentIndex, content.index, "f"); - } - AssistantStream_classPrivateFieldSet(this, _AssistantStream_currentContent, accumulatedMessage.content[content.index], "f"); - } - } - break; - case 'thread.message.completed': - case 'thread.message.incomplete': - //We emit the latest content we were working on on completion (including incomplete) - if (AssistantStream_classPrivateFieldGet(this, _AssistantStream_currentContentIndex, "f") !== undefined) { - const currentContent = event.data.content[AssistantStream_classPrivateFieldGet(this, _AssistantStream_currentContentIndex, "f")]; - if (currentContent) { - switch (currentContent.type) { - case 'image_file': - this._emit('imageFileDone', currentContent.image_file, AssistantStream_classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f")); - break; - case 'text': - this._emit('textDone', currentContent.text, AssistantStream_classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f")); - break; } - } + await sleep(sleepInterval); + break; + case 'failed': + case 'cancelled': + case 'completed': + return batch; } - if (AssistantStream_classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f")) { - this._emit('messageDone', event.data); + } + } + /** + * Uploads the given files concurrently and then creates a vector store file batch. + * + * The concurrency limit is configurable using the `maxConcurrency` parameter. + */ + async uploadAndPoll(vectorStoreId, { files, fileIds = [] }, options) { + if (files == null || files.length == 0) { + throw new Error(`No \`files\` provided to process. If you've already uploaded files you should use \`.createAndPoll()\` instead`); + } + const configuredConcurrency = options?.maxConcurrency ?? 5; + // We cap the number of workers at the number of files (so we don't start any unnecessary workers) + const concurrencyLimit = Math.min(configuredConcurrency, files.length); + const client = this._client; + const fileIterator = files.values(); + const allFileIds = [...fileIds]; + // This code is based on this design. The libraries don't accommodate our environment limits. + // https://stackoverflow.com/questions/40639432/what-is-the-best-way-to-limit-concurrency-when-using-es6s-promise-all + async function processFiles(iterator) { + for (let item of iterator) { + const fileObj = await client.files.create({ file: item, purpose: 'assistants' }, options); + allFileIds.push(fileObj.id); } - AssistantStream_classPrivateFieldSet(this, _AssistantStream_messageSnapshot, undefined, "f"); + } + // Start workers to process results + const workers = Array(concurrencyLimit).fill(fileIterator).map(processFiles); + // Wait for all processing to complete. + await allSettledWithThrow(workers); + return await this.createAndPoll(vectorStoreId, { + file_ids: allFileIds, + }); } -}, _AssistantStream_handleRunStep = function _AssistantStream_handleRunStep(event) { - const accumulatedRunStep = AssistantStream_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_accumulateRunStep).call(this, event); - AssistantStream_classPrivateFieldSet(this, _AssistantStream_currentRunStepSnapshot, accumulatedRunStep, "f"); - switch (event.event) { - case 'thread.run.step.created': - this._emit('runStepCreated', event.data); - break; - case 'thread.run.step.delta': - const delta = event.data.delta; - if (delta.step_details && - delta.step_details.type == 'tool_calls' && - delta.step_details.tool_calls && - accumulatedRunStep.step_details.type == 'tool_calls') { - for (const toolCall of delta.step_details.tool_calls) { - if (toolCall.index == AssistantStream_classPrivateFieldGet(this, _AssistantStream_currentToolCallIndex, "f")) { - this._emit('toolCallDelta', toolCall, accumulatedRunStep.step_details.tool_calls[toolCall.index]); +} +//# sourceMappingURL=file-batches.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/vector-stores/files.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + + +class vector_stores_files_Files extends APIResource { + /** + * Create a vector store file by attaching a + * [File](https://platform.openai.com/docs/api-reference/files) to a + * [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object). + */ + create(vectorStoreID, body, options) { + return this._client.post(path `/vector_stores/${vectorStoreID}/files`, { + body, + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + /** + * Retrieves a vector store file. + */ + retrieve(fileID, params, options) { + const { vector_store_id } = params; + return this._client.get(path `/vector_stores/${vector_store_id}/files/${fileID}`, { + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + /** + * Update attributes on a vector store file. + */ + update(fileID, params, options) { + const { vector_store_id, ...body } = params; + return this._client.post(path `/vector_stores/${vector_store_id}/files/${fileID}`, { + body, + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + /** + * Returns a list of vector store files. + */ + list(vectorStoreID, query = {}, options) { + return this._client.getAPIList(path `/vector_stores/${vectorStoreID}/files`, (CursorPage), { + query, + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + /** + * Delete a vector store file. This will remove the file from the vector store but + * the file itself will not be deleted. To delete the file, use the + * [delete file](https://platform.openai.com/docs/api-reference/files/delete) + * endpoint. + */ + delete(fileID, params, options) { + const { vector_store_id } = params; + return this._client.delete(path `/vector_stores/${vector_store_id}/files/${fileID}`, { + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + /** + * Attach a file to the given vector store and wait for it to be processed. + */ + async createAndPoll(vectorStoreId, body, options) { + const file = await this.create(vectorStoreId, body, options); + return await this.poll(vectorStoreId, file.id, options); + } + /** + * Wait for the vector store file to finish processing. + * + * Note: this will return even if the file failed to process, you need to check + * file.last_error and file.status to handle these cases + */ + async poll(vectorStoreID, fileID, options) { + const headers = buildHeaders([ + options?.headers, + { + 'X-Stainless-Poll-Helper': 'true', + 'X-Stainless-Custom-Poll-Interval': options?.pollIntervalMs?.toString() ?? undefined, + }, + ]); + while (true) { + const fileResponse = await this.retrieve(fileID, { + vector_store_id: vectorStoreID, + }, { ...options, headers }).withResponse(); + const file = fileResponse.data; + switch (file.status) { + case 'in_progress': + let sleepInterval = 5000; + if (options?.pollIntervalMs) { + sleepInterval = options.pollIntervalMs; } else { - if (AssistantStream_classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")) { - this._emit('toolCallDone', AssistantStream_classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")); + const headerInterval = fileResponse.response.headers.get('openai-poll-after-ms'); + if (headerInterval) { + const headerIntervalMs = parseInt(headerInterval); + if (!isNaN(headerIntervalMs)) { + sleepInterval = headerIntervalMs; + } } - AssistantStream_classPrivateFieldSet(this, _AssistantStream_currentToolCallIndex, toolCall.index, "f"); - AssistantStream_classPrivateFieldSet(this, _AssistantStream_currentToolCall, accumulatedRunStep.step_details.tool_calls[toolCall.index], "f"); - if (AssistantStream_classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")) - this._emit('toolCallCreated', AssistantStream_classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")); } - } - } - this._emit('runStepDelta', event.data.delta, accumulatedRunStep); - break; - case 'thread.run.step.completed': - case 'thread.run.step.failed': - case 'thread.run.step.cancelled': - case 'thread.run.step.expired': - AssistantStream_classPrivateFieldSet(this, _AssistantStream_currentRunStepSnapshot, undefined, "f"); - const details = event.data.step_details; - if (details.type == 'tool_calls') { - if (AssistantStream_classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")) { - this._emit('toolCallDone', AssistantStream_classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")); - AssistantStream_classPrivateFieldSet(this, _AssistantStream_currentToolCall, undefined, "f"); - } + await sleep(sleepInterval); + break; + case 'failed': + case 'completed': + return file; } - this._emit('runStepDone', event.data, accumulatedRunStep); - break; - case 'thread.run.step.in_progress': - break; + } } -}, _AssistantStream_handleEvent = function _AssistantStream_handleEvent(event) { - AssistantStream_classPrivateFieldGet(this, _AssistantStream_events, "f").push(event); - this._emit('event', event); -}, _AssistantStream_accumulateRunStep = function _AssistantStream_accumulateRunStep(event) { - switch (event.event) { - case 'thread.run.step.created': - AssistantStream_classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id] = event.data; - return event.data; - case 'thread.run.step.delta': - let snapshot = AssistantStream_classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id]; - if (!snapshot) { - throw Error('Received a RunStepDelta before creation of a snapshot'); - } - let data = event.data; - if (data.delta) { - const accumulated = AssistantStream.accumulateDelta(snapshot, data.delta); - AssistantStream_classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id] = accumulated; - } - return AssistantStream_classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id]; - case 'thread.run.step.completed': - case 'thread.run.step.failed': - case 'thread.run.step.cancelled': - case 'thread.run.step.expired': - case 'thread.run.step.in_progress': - AssistantStream_classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id] = event.data; - break; + /** + * Upload a file to the `files` API and then attach it to the given vector store. + * + * Note the file will be asynchronously processed (you can use the alternative + * polling helper method to wait for processing to complete). + */ + async upload(vectorStoreId, file, options) { + const fileInfo = await this._client.files.create({ file: file, purpose: 'assistants' }, options); + return this.create(vectorStoreId, { file_id: fileInfo.id }, options); } - if (AssistantStream_classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id]) - return AssistantStream_classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id]; - throw new Error('No snapshot available'); -}, _AssistantStream_accumulateMessage = function _AssistantStream_accumulateMessage(event, snapshot) { - let newContent = []; - switch (event.event) { - case 'thread.message.created': - //On creation the snapshot is just the initial message - return [event.data, newContent]; - case 'thread.message.delta': - if (!snapshot) { - throw Error('Received a delta with no existing snapshot (there should be one from message creation)'); - } - let data = event.data; - //If this delta does not have content, nothing to process - if (data.delta.content) { - for (const contentElement of data.delta.content) { - if (contentElement.index in snapshot.content) { - let currentContent = snapshot.content[contentElement.index]; - snapshot.content[contentElement.index] = AssistantStream_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_accumulateContent).call(this, contentElement, currentContent); - } - else { - snapshot.content[contentElement.index] = contentElement; - // This is a new element - newContent.push(contentElement); - } - } - } - return [snapshot, newContent]; - case 'thread.message.in_progress': - case 'thread.message.completed': - case 'thread.message.incomplete': - //No changes on other thread events - if (snapshot) { - return [snapshot, newContent]; - } - else { - throw Error('Received thread message event with no existing snapshot'); - } + /** + * Add a file to a vector store and poll until processing is complete. + */ + async uploadAndPoll(vectorStoreId, file, options) { + const fileInfo = await this.upload(vectorStoreId, file, options); + return await this.poll(vectorStoreId, fileInfo.id, options); } - throw Error('Tried to accumulate a non-message event'); -}, _AssistantStream_accumulateContent = function _AssistantStream_accumulateContent(contentElement, currentContent) { - return AssistantStream.accumulateDelta(currentContent, contentElement); -}, _AssistantStream_handleRun = function _AssistantStream_handleRun(event) { - AssistantStream_classPrivateFieldSet(this, _AssistantStream_currentRunSnapshot, event.data, "f"); - switch (event.event) { - case 'thread.run.created': - break; - case 'thread.run.queued': - break; - case 'thread.run.in_progress': - break; - case 'thread.run.requires_action': - case 'thread.run.cancelled': - case 'thread.run.failed': - case 'thread.run.completed': - case 'thread.run.expired': - AssistantStream_classPrivateFieldSet(this, _AssistantStream_finalRun, event.data, "f"); - if (AssistantStream_classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")) { - this._emit('toolCallDone', AssistantStream_classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")); - AssistantStream_classPrivateFieldSet(this, _AssistantStream_currentToolCall, undefined, "f"); - } - break; - case 'thread.run.cancelling': - break; + /** + * Retrieve the parsed contents of a vector store file. + */ + content(fileID, params, options) { + const { vector_store_id } = params; + return this._client.getAPIList(path `/vector_stores/${vector_store_id}/files/${fileID}/content`, (Page), { ...options, headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]) }); } -}; -function AssistantStream_assertNever(_x) { } -//# sourceMappingURL=AssistantStream.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/threads/messages.mjs +} +//# sourceMappingURL=files.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/vector-stores/vector-stores.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -class messages_Messages extends APIResource { + + + + + +class VectorStores extends APIResource { + constructor() { + super(...arguments); + this.files = new vector_stores_files_Files(this._client); + this.fileBatches = new FileBatches(this._client); + } /** - * Create a message. - * - * @example - * ```ts - * const message = await client.beta.threads.messages.create( - * 'thread_id', - * { content: 'string', role: 'user' }, - * ); - * ``` + * Create a vector store. */ - create(threadId, body, options) { - return this._client.post(`/threads/${threadId}/messages`, { + create(body, options) { + return this._client.post('/vector_stores', { body, ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), }); } /** - * Retrieve a message. - * - * @example - * ```ts - * const message = await client.beta.threads.messages.retrieve( - * 'thread_id', - * 'message_id', - * ); - * ``` + * Retrieves a vector store. */ - retrieve(threadId, messageId, options) { - return this._client.get(`/threads/${threadId}/messages/${messageId}`, { + retrieve(vectorStoreID, options) { + return this._client.get(path `/vector_stores/${vectorStoreID}`, { ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), }); } /** - * Modifies a message. - * - * @example - * ```ts - * const message = await client.beta.threads.messages.update( - * 'thread_id', - * 'message_id', - * ); - * ``` + * Modifies a vector store. */ - update(threadId, messageId, body, options) { - return this._client.post(`/threads/${threadId}/messages/${messageId}`, { + update(vectorStoreID, body, options) { + return this._client.post(path `/vector_stores/${vectorStoreID}`, { body, ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), }); } - list(threadId, query = {}, options) { - if (isRequestOptions(query)) { - return this.list(threadId, {}, query); - } - return this._client.getAPIList(`/threads/${threadId}/messages`, MessagesPage, { + /** + * Returns a list of vector stores. + */ + list(query = {}, options) { + return this._client.getAPIList('/vector_stores', (CursorPage), { query, ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), }); } /** - * Deletes a message. - * - * @example - * ```ts - * const messageDeleted = - * await client.beta.threads.messages.del( - * 'thread_id', - * 'message_id', - * ); - * ``` + * Delete a vector store. */ - del(threadId, messageId, options) { - return this._client.delete(`/threads/${threadId}/messages/${messageId}`, { + delete(vectorStoreID, options) { + return this._client.delete(path `/vector_stores/${vectorStoreID}`, { ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + /** + * Search a vector store for relevant chunks based on a query and file attributes + * filter. + */ + search(vectorStoreID, body, options) { + return this._client.getAPIList(path `/vector_stores/${vectorStoreID}/search`, (Page), { + body, + method: 'post', + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), }); } } -class MessagesPage extends CursorPage { -} -messages_Messages.MessagesPage = MessagesPage; -//# sourceMappingURL=messages.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/threads/runs/steps.mjs +VectorStores.Files = vector_stores_files_Files; +VectorStores.FileBatches = FileBatches; +//# sourceMappingURL=vector-stores.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/webhooks.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +var _Webhooks_instances, _Webhooks_validateSecret, _Webhooks_getRequiredHeader; -class Steps extends APIResource { - retrieve(threadId, runId, stepId, query = {}, options) { - if (isRequestOptions(query)) { - return this.retrieve(threadId, runId, stepId, {}, query); - } - return this._client.get(`/threads/${threadId}/runs/${runId}/steps/${stepId}`, { - query, - ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, - }); + +class Webhooks extends APIResource { + constructor() { + super(...arguments); + _Webhooks_instances.add(this); + } + /** + * Validates that the given payload was sent by OpenAI and parses the payload. + */ + async unwrap(payload, headers, secret = this._client.webhookSecret, tolerance = 300) { + await this.verifySignature(payload, headers, secret, tolerance); + return JSON.parse(payload); } - list(threadId, runId, query = {}, options) { - if (isRequestOptions(query)) { - return this.list(threadId, runId, {}, query); + /** + * Validates whether or not the webhook payload was sent by OpenAI. + * + * An error will be raised if the webhook payload was not sent by OpenAI. + * + * @param payload - The webhook payload + * @param headers - The webhook headers + * @param secret - The webhook secret (optional, will use client secret if not provided) + * @param tolerance - Maximum age of the webhook in seconds (default: 300 = 5 minutes) + */ + async verifySignature(payload, headers, secret = this._client.webhookSecret, tolerance = 300) { + if (typeof crypto === 'undefined' || + typeof crypto.subtle.importKey !== 'function' || + typeof crypto.subtle.verify !== 'function') { + throw new Error('Webhook signature verification is only supported when the `crypto` global is defined'); + } + __classPrivateFieldGet(this, _Webhooks_instances, "m", _Webhooks_validateSecret).call(this, secret); + const headersObj = buildHeaders([headers]).values; + const signatureHeader = __classPrivateFieldGet(this, _Webhooks_instances, "m", _Webhooks_getRequiredHeader).call(this, headersObj, 'webhook-signature'); + const timestamp = __classPrivateFieldGet(this, _Webhooks_instances, "m", _Webhooks_getRequiredHeader).call(this, headersObj, 'webhook-timestamp'); + const webhookId = __classPrivateFieldGet(this, _Webhooks_instances, "m", _Webhooks_getRequiredHeader).call(this, headersObj, 'webhook-id'); + // Validate timestamp to prevent replay attacks + const timestampSeconds = parseInt(timestamp, 10); + if (isNaN(timestampSeconds)) { + throw new InvalidWebhookSignatureError('Invalid webhook timestamp format'); + } + const nowSeconds = Math.floor(Date.now() / 1000); + if (nowSeconds - timestampSeconds > tolerance) { + throw new InvalidWebhookSignatureError('Webhook timestamp is too old'); + } + if (timestampSeconds > nowSeconds + tolerance) { + throw new InvalidWebhookSignatureError('Webhook timestamp is too new'); + } + // Extract signatures from v1, format + // The signature header can have multiple values, separated by spaces. + // Each value is in the format v1,. We should accept if any match. + const signatures = signatureHeader + .split(' ') + .map((part) => (part.startsWith('v1,') ? part.substring(3) : part)); + // Decode the secret if it starts with whsec_ + const decodedSecret = secret.startsWith('whsec_') ? + Buffer.from(secret.replace('whsec_', ''), 'base64') + : Buffer.from(secret, 'utf-8'); + // Create the signed payload: {webhook_id}.{timestamp}.{payload} + const signedPayload = webhookId ? `${webhookId}.${timestamp}.${payload}` : `${timestamp}.${payload}`; + // Import the secret as a cryptographic key for HMAC + const key = await crypto.subtle.importKey('raw', decodedSecret, { name: 'HMAC', hash: 'SHA-256' }, false, ['verify']); + // Check if any signature matches using timing-safe WebCrypto verify + for (const signature of signatures) { + try { + const signatureBytes = Buffer.from(signature, 'base64'); + const isValid = await crypto.subtle.verify('HMAC', key, signatureBytes, new TextEncoder().encode(signedPayload)); + if (isValid) { + return; // Valid signature found + } + } + catch { + // Invalid base64 or signature format, continue to next signature + continue; + } } - return this._client.getAPIList(`/threads/${threadId}/runs/${runId}/steps`, RunStepsPage, { - query, - ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, - }); + throw new InvalidWebhookSignatureError('The given webhook signature does not match the expected signature'); } } -class RunStepsPage extends CursorPage { -} -Steps.RunStepsPage = RunStepsPage; -//# sourceMappingURL=steps.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/threads/runs/runs.mjs +_Webhooks_instances = new WeakSet(), _Webhooks_validateSecret = function _Webhooks_validateSecret(secret) { + if (typeof secret !== 'string' || secret.length === 0) { + throw new Error(`The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function`); + } +}, _Webhooks_getRequiredHeader = function _Webhooks_getRequiredHeader(headers, name) { + if (!headers) { + throw new Error(`Headers are required`); + } + const value = headers.get(name); + if (value === null || value === undefined) { + throw new Error(`Missing required header: ${name}`); + } + return value; +}; +//# sourceMappingURL=webhooks.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/index.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. @@ -74672,288 +69379,672 @@ Steps.RunStepsPage = RunStepsPage; -class Runs extends APIResource { - constructor() { - super(...arguments); - this.steps = new Steps(this._client); - } - create(threadId, params, options) { - const { include, ...body } = params; - return this._client.post(`/threads/${threadId}/runs`, { - query: { include }, - body, - ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, - stream: params.stream ?? false, - }); + + + + + + + + + + + + + + +//# sourceMappingURL=index.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/client.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +var _OpenAI_instances, client_a, _OpenAI_encoder, _OpenAI_baseURLOverridden; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +/** + * API Client for interfacing with the OpenAI API. + */ +class OpenAI { + /** + * API Client for interfacing with the OpenAI API. + * + * @param {string | undefined} [opts.apiKey=process.env['OPENAI_API_KEY'] ?? undefined] + * @param {string | null | undefined} [opts.organization=process.env['OPENAI_ORG_ID'] ?? null] + * @param {string | null | undefined} [opts.project=process.env['OPENAI_PROJECT_ID'] ?? null] + * @param {string | null | undefined} [opts.webhookSecret=process.env['OPENAI_WEBHOOK_SECRET'] ?? null] + * @param {string} [opts.baseURL=process.env['OPENAI_BASE_URL'] ?? https://api.openai.com/v1] - Override the default base URL for the API. + * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out. + * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls. + * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation. + * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request. + * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API. + * @param {Record} opts.defaultQuery - Default query parameters to include with every request to the API. + * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers. + */ + constructor({ baseURL = readEnv('OPENAI_BASE_URL'), apiKey = readEnv('OPENAI_API_KEY'), organization = readEnv('OPENAI_ORG_ID') ?? null, project = readEnv('OPENAI_PROJECT_ID') ?? null, webhookSecret = readEnv('OPENAI_WEBHOOK_SECRET') ?? null, ...opts } = {}) { + _OpenAI_instances.add(this); + _OpenAI_encoder.set(this, void 0); + this.completions = new completions_Completions(this); + this.chat = new Chat(this); + this.embeddings = new Embeddings(this); + this.files = new files_Files(this); + this.images = new Images(this); + this.audio = new Audio(this); + this.moderations = new Moderations(this); + this.models = new Models(this); + this.fineTuning = new FineTuning(this); + this.graders = new graders_Graders(this); + this.vectorStores = new VectorStores(this); + this.webhooks = new Webhooks(this); + this.beta = new Beta(this); + this.batches = new Batches(this); + this.uploads = new Uploads(this); + this.responses = new Responses(this); + this.realtime = new realtime_Realtime(this); + this.conversations = new Conversations(this); + this.evals = new Evals(this); + this.containers = new Containers(this); + if (apiKey === undefined) { + throw new error_OpenAIError('Missing credentials. Please pass an `apiKey`, or set the `OPENAI_API_KEY` environment variable.'); + } + const options = { + apiKey, + organization, + project, + webhookSecret, + ...opts, + baseURL: baseURL || `https://api.openai.com/v1`, + }; + if (!options.dangerouslyAllowBrowser && isRunningInBrowser()) { + throw new error_OpenAIError("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew OpenAI({ apiKey, dangerouslyAllowBrowser: true });\n\nhttps://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety\n"); + } + this.baseURL = options.baseURL; + this.timeout = options.timeout ?? client_a.DEFAULT_TIMEOUT /* 10 minutes */; + this.logger = options.logger ?? console; + const defaultLogLevel = 'warn'; + // Set default logLevel early so that we can log a warning in parseLogLevel. + this.logLevel = defaultLogLevel; + this.logLevel = + parseLogLevel(options.logLevel, 'ClientOptions.logLevel', this) ?? + parseLogLevel(readEnv('OPENAI_LOG'), "process.env['OPENAI_LOG']", this) ?? + defaultLogLevel; + this.fetchOptions = options.fetchOptions; + this.maxRetries = options.maxRetries ?? 2; + this.fetch = options.fetch ?? getDefaultFetch(); + __classPrivateFieldSet(this, _OpenAI_encoder, FallbackEncoder, "f"); + this._options = options; + this.apiKey = typeof apiKey === 'string' ? apiKey : 'Missing Key'; + this.organization = organization; + this.project = project; + this.webhookSecret = webhookSecret; } /** - * Retrieves a run. - * - * @example - * ```ts - * const run = await client.beta.threads.runs.retrieve( - * 'thread_id', - * 'run_id', - * ); - * ``` + * Create a new client instance re-using the same options given to the current client with optional overriding. */ - retrieve(threadId, runId, options) { - return this._client.get(`/threads/${threadId}/runs/${runId}`, { + withOptions(options) { + const client = new this.constructor({ + ...this._options, + baseURL: this.baseURL, + maxRetries: this.maxRetries, + timeout: this.timeout, + logger: this.logger, + logLevel: this.logLevel, + fetch: this.fetch, + fetchOptions: this.fetchOptions, + apiKey: this.apiKey, + organization: this.organization, + project: this.project, + webhookSecret: this.webhookSecret, ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, }); + return client; } - /** - * Modifies a run. - * - * @example - * ```ts - * const run = await client.beta.threads.runs.update( - * 'thread_id', - * 'run_id', - * ); - * ``` - */ - update(threadId, runId, body, options) { - return this._client.post(`/threads/${threadId}/runs/${runId}`, { - body, - ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, - }); + defaultQuery() { + return this._options.defaultQuery; + } + validateHeaders({ values, nulls }) { + return; + } + async authHeaders(opts) { + return buildHeaders([{ Authorization: `Bearer ${this.apiKey}` }]); + } + stringifyQuery(query) { + return stringify(query, { arrayFormat: 'brackets' }); + } + getUserAgent() { + return `${this.constructor.name}/JS ${VERSION}`; + } + defaultIdempotencyKey() { + return `stainless-node-retry-${uuid4()}`; + } + makeStatusError(status, error, message, headers) { + return APIError.generate(status, error, message, headers); } - list(threadId, query = {}, options) { - if (isRequestOptions(query)) { - return this.list(threadId, {}, query); + async _callApiKey() { + const apiKey = this._options.apiKey; + if (typeof apiKey !== 'function') + return false; + let token; + try { + token = await apiKey(); } - return this._client.getAPIList(`/threads/${threadId}/runs`, RunsPage, { - query, - ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, - }); + catch (err) { + if (err instanceof error_OpenAIError) + throw err; + throw new error_OpenAIError(`Failed to get token from 'apiKey' function: ${err.message}`, + // @ts-ignore + { cause: err }); + } + if (typeof token !== 'string' || !token) { + throw new error_OpenAIError(`Expected 'apiKey' function argument to return a string but it returned ${token}`); + } + this.apiKey = token; + return true; } - /** - * Cancels a run that is `in_progress`. - * - * @example - * ```ts - * const run = await client.beta.threads.runs.cancel( - * 'thread_id', - * 'run_id', - * ); - * ``` - */ - cancel(threadId, runId, options) { - return this._client.post(`/threads/${threadId}/runs/${runId}/cancel`, { - ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, - }); + buildURL(path, query, defaultBaseURL) { + const baseURL = (!__classPrivateFieldGet(this, _OpenAI_instances, "m", _OpenAI_baseURLOverridden).call(this) && defaultBaseURL) || this.baseURL; + const url = isAbsoluteURL(path) ? + new URL(path) + : new URL(baseURL + (baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path)); + const defaultQuery = this.defaultQuery(); + if (!isEmptyObj(defaultQuery)) { + query = { ...defaultQuery, ...query }; + } + if (typeof query === 'object' && query && !Array.isArray(query)) { + url.search = this.stringifyQuery(query); + } + return url.toString(); } /** - * A helper to create a run an poll for a terminal state. More information on Run - * lifecycles can be found here: - * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps + * Used as a callback for mutating the given `FinalRequestOptions` object. */ - async createAndPoll(threadId, body, options) { - const run = await this.create(threadId, body, options); - return await this.poll(threadId, run.id, options); + async prepareOptions(options) { + await this._callApiKey(); } /** - * Create a Run stream + * Used as a callback for mutating the given `RequestInit` object. * - * @deprecated use `stream` instead + * This is useful for cases where you want to add certain headers based off of + * the request properties, e.g. `method` or `url`. */ - createAndStream(threadId, body, options) { - return AssistantStream.createAssistantStream(threadId, this._client.beta.threads.runs, body, options); + async prepareRequest(request, { url, options }) { } + get(path, opts) { + return this.methodRequest('get', path, opts); } - /** - * A helper to poll a run status until it reaches a terminal state. More - * information on Run lifecycles can be found here: - * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps - */ - async poll(threadId, runId, options) { - const headers = { ...options?.headers, 'X-Stainless-Poll-Helper': 'true' }; - if (options?.pollIntervalMs) { - headers['X-Stainless-Custom-Poll-Interval'] = options.pollIntervalMs.toString(); + post(path, opts) { + return this.methodRequest('post', path, opts); + } + patch(path, opts) { + return this.methodRequest('patch', path, opts); + } + put(path, opts) { + return this.methodRequest('put', path, opts); + } + delete(path, opts) { + return this.methodRequest('delete', path, opts); + } + methodRequest(method, path, opts) { + return this.request(Promise.resolve(opts).then((opts) => { + return { method, path, ...opts }; + })); + } + request(options, remainingRetries = null) { + return new APIPromise(this, this.makeRequest(options, remainingRetries, undefined)); + } + async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) { + const options = await optionsInput; + const maxRetries = options.maxRetries ?? this.maxRetries; + if (retriesRemaining == null) { + retriesRemaining = maxRetries; } - while (true) { - const { data: run, response } = await this.retrieve(threadId, runId, { - ...options, - headers: { ...options?.headers, ...headers }, - }).withResponse(); - switch (run.status) { - //If we are in any sort of intermediate state we poll - case 'queued': - case 'in_progress': - case 'cancelling': - let sleepInterval = 5000; - if (options?.pollIntervalMs) { - sleepInterval = options.pollIntervalMs; - } - else { - const headerInterval = response.headers.get('openai-poll-after-ms'); - if (headerInterval) { - const headerIntervalMs = parseInt(headerInterval); - if (!isNaN(headerIntervalMs)) { - sleepInterval = headerIntervalMs; - } - } - } - await sleep(sleepInterval); - break; - //We return the run in any terminal state. - case 'requires_action': - case 'incomplete': - case 'cancelled': - case 'completed': - case 'failed': - case 'expired': - return run; + await this.prepareOptions(options); + const { req, url, timeout } = await this.buildRequest(options, { + retryCount: maxRetries - retriesRemaining, + }); + await this.prepareRequest(req, { url, options }); + /** Not an API request ID, just for correlating local log entries. */ + const requestLogID = 'log_' + ((Math.random() * (1 << 24)) | 0).toString(16).padStart(6, '0'); + const retryLogStr = retryOfRequestLogID === undefined ? '' : `, retryOf: ${retryOfRequestLogID}`; + const startTime = Date.now(); + loggerFor(this).debug(`[${requestLogID}] sending request`, formatRequestDetails({ + retryOfRequestLogID, + method: options.method, + url, + options, + headers: req.headers, + })); + if (options.signal?.aborted) { + throw new APIUserAbortError(); + } + const controller = new AbortController(); + const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError); + const headersTime = Date.now(); + if (response instanceof globalThis.Error) { + const retryMessage = `retrying, ${retriesRemaining} attempts remaining`; + if (options.signal?.aborted) { + throw new APIUserAbortError(); + } + // detect native connection timeout errors + // deno throws "TypeError: error sending request for url (https://example/): client error (Connect): tcp connect error: Operation timed out (os error 60): Operation timed out (os error 60)" + // undici throws "TypeError: fetch failed" with cause "ConnectTimeoutError: Connect Timeout Error (attempted address: example:443, timeout: 1ms)" + // others do not provide enough information to distinguish timeouts from other connection errors + const isTimeout = isAbortError(response) || + /timed? ?out/i.test(String(response) + ('cause' in response ? String(response.cause) : '')); + if (retriesRemaining) { + loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - ${retryMessage}`); + loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (${retryMessage})`, formatRequestDetails({ + retryOfRequestLogID, + url, + durationMs: headersTime - startTime, + message: response.message, + })); + return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID); + } + loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - error; no more retries left`); + loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (error; no more retries left)`, formatRequestDetails({ + retryOfRequestLogID, + url, + durationMs: headersTime - startTime, + message: response.message, + })); + if (isTimeout) { + throw new APIConnectionTimeoutError(); + } + throw new APIConnectionError({ cause: response }); + } + const specialHeaders = [...response.headers.entries()] + .filter(([name]) => name === 'x-request-id') + .map(([name, value]) => ', ' + name + ': ' + JSON.stringify(value)) + .join(''); + const responseInfo = `[${requestLogID}${retryLogStr}${specialHeaders}] ${req.method} ${url} ${response.ok ? 'succeeded' : 'failed'} with status ${response.status} in ${headersTime - startTime}ms`; + if (!response.ok) { + const shouldRetry = await this.shouldRetry(response); + if (retriesRemaining && shouldRetry) { + const retryMessage = `retrying, ${retriesRemaining} attempts remaining`; + // We don't need the body of this response. + await CancelReadableStream(response.body); + loggerFor(this).info(`${responseInfo} - ${retryMessage}`); + loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({ + retryOfRequestLogID, + url: response.url, + status: response.status, + headers: response.headers, + durationMs: headersTime - startTime, + })); + return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers); } + const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`; + loggerFor(this).info(`${responseInfo} - ${retryMessage}`); + const errText = await response.text().catch((err) => castToError(err).message); + const errJSON = safeJSON(errText); + const errMessage = errJSON ? undefined : errText; + loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({ + retryOfRequestLogID, + url: response.url, + status: response.status, + headers: response.headers, + message: errMessage, + durationMs: Date.now() - startTime, + })); + const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers); + throw err; } + loggerFor(this).info(responseInfo); + loggerFor(this).debug(`[${requestLogID}] response start`, formatRequestDetails({ + retryOfRequestLogID, + url: response.url, + status: response.status, + headers: response.headers, + durationMs: headersTime - startTime, + })); + return { response, options, controller, requestLogID, retryOfRequestLogID, startTime }; } - /** - * Create a Run stream - */ - stream(threadId, body, options) { - return AssistantStream.createAssistantStream(threadId, this._client.beta.threads.runs, body, options); + getAPIList(path, Page, opts) { + return this.requestAPIList(Page, { method: 'get', path, ...opts }); } - submitToolOutputs(threadId, runId, body, options) { - return this._client.post(`/threads/${threadId}/runs/${runId}/submit_tool_outputs`, { - body, + requestAPIList(Page, options) { + const request = this.makeRequest(options, null, undefined); + return new PagePromise(this, request, Page); + } + async fetchWithTimeout(url, init, ms, controller) { + const { signal, method, ...options } = init || {}; + if (signal) + signal.addEventListener('abort', () => controller.abort()); + const timeout = setTimeout(() => controller.abort(), ms); + const isReadableBody = (globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream) || + (typeof options.body === 'object' && options.body !== null && Symbol.asyncIterator in options.body); + const fetchOptions = { + signal: controller.signal, + ...(isReadableBody ? { duplex: 'half' } : {}), + method: 'GET', ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, - stream: body.stream ?? false, - }); + }; + if (method) { + // Custom methods like 'patch' need to be uppercased + // See https://github.com/nodejs/undici/issues/2294 + fetchOptions.method = method.toUpperCase(); + } + try { + // use undefined this binding; fetch errors if bound to something else in browser/cloudflare + return await this.fetch.call(undefined, url, fetchOptions); + } + finally { + clearTimeout(timeout); + } } - /** - * A helper to submit a tool output to a run and poll for a terminal run state. - * More information on Run lifecycles can be found here: - * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps - */ - async submitToolOutputsAndPoll(threadId, runId, body, options) { - const run = await this.submitToolOutputs(threadId, runId, body, options); - return await this.poll(threadId, run.id, options); + async shouldRetry(response) { + // Note this is not a standard header. + const shouldRetryHeader = response.headers.get('x-should-retry'); + // If the server explicitly says whether or not to retry, obey. + if (shouldRetryHeader === 'true') + return true; + if (shouldRetryHeader === 'false') + return false; + // Retry on request timeouts. + if (response.status === 408) + return true; + // Retry on lock timeouts. + if (response.status === 409) + return true; + // Retry on rate limits. + if (response.status === 429) + return true; + // Retry internal errors. + if (response.status >= 500) + return true; + return false; } - /** - * Submit the tool outputs from a previous run and stream the run to a terminal - * state. More information on Run lifecycles can be found here: - * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps - */ - submitToolOutputsStream(threadId, runId, body, options) { - return AssistantStream.createToolAssistantStream(threadId, runId, this._client.beta.threads.runs, body, options); + async retryRequest(options, retriesRemaining, requestLogID, responseHeaders) { + let timeoutMillis; + // Note the `retry-after-ms` header may not be standard, but is a good idea and we'd like proactive support for it. + const retryAfterMillisHeader = responseHeaders?.get('retry-after-ms'); + if (retryAfterMillisHeader) { + const timeoutMs = parseFloat(retryAfterMillisHeader); + if (!Number.isNaN(timeoutMs)) { + timeoutMillis = timeoutMs; + } + } + // About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After + const retryAfterHeader = responseHeaders?.get('retry-after'); + if (retryAfterHeader && !timeoutMillis) { + const timeoutSeconds = parseFloat(retryAfterHeader); + if (!Number.isNaN(timeoutSeconds)) { + timeoutMillis = timeoutSeconds * 1000; + } + else { + timeoutMillis = Date.parse(retryAfterHeader) - Date.now(); + } + } + // If the API asks us to wait a certain amount of time (and it's a reasonable amount), + // just do what it says, but otherwise calculate a default + if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1000)) { + const maxRetries = options.maxRetries ?? this.maxRetries; + timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries); + } + await sleep(timeoutMillis); + return this.makeRequest(options, retriesRemaining - 1, requestLogID); + } + calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) { + const initialRetryDelay = 0.5; + const maxRetryDelay = 8.0; + const numRetries = maxRetries - retriesRemaining; + // Apply exponential backoff, but not more than the max. + const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay); + // Apply some jitter, take up to at most 25 percent of the retry time. + const jitter = 1 - Math.random() * 0.25; + return sleepSeconds * jitter * 1000; + } + async buildRequest(inputOptions, { retryCount = 0 } = {}) { + const options = { ...inputOptions }; + const { method, path, query, defaultBaseURL } = options; + const url = this.buildURL(path, query, defaultBaseURL); + if ('timeout' in options) + validatePositiveInteger('timeout', options.timeout); + options.timeout = options.timeout ?? this.timeout; + const { bodyHeaders, body } = this.buildBody({ options }); + const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount }); + const req = { + method, + headers: reqHeaders, + ...(options.signal && { signal: options.signal }), + ...(globalThis.ReadableStream && + body instanceof globalThis.ReadableStream && { duplex: 'half' }), + ...(body && { body }), + ...(this.fetchOptions ?? {}), + ...(options.fetchOptions ?? {}), + }; + return { req, url, timeout: options.timeout }; + } + async buildHeaders({ options, method, bodyHeaders, retryCount, }) { + let idempotencyHeaders = {}; + if (this.idempotencyHeader && method !== 'get') { + if (!options.idempotencyKey) + options.idempotencyKey = this.defaultIdempotencyKey(); + idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey; + } + const headers = buildHeaders([ + idempotencyHeaders, + { + Accept: 'application/json', + 'User-Agent': this.getUserAgent(), + 'X-Stainless-Retry-Count': String(retryCount), + ...(options.timeout ? { 'X-Stainless-Timeout': String(Math.trunc(options.timeout / 1000)) } : {}), + ...getPlatformHeaders(), + 'OpenAI-Organization': this.organization, + 'OpenAI-Project': this.project, + }, + await this.authHeaders(options), + this._options.defaultHeaders, + bodyHeaders, + options.headers, + ]); + this.validateHeaders(headers); + return headers.values; + } + buildBody({ options: { body, headers: rawHeaders } }) { + if (!body) { + return { bodyHeaders: undefined, body: undefined }; + } + const headers = buildHeaders([rawHeaders]); + if ( + // Pass raw type verbatim + ArrayBuffer.isView(body) || + body instanceof ArrayBuffer || + body instanceof DataView || + (typeof body === 'string' && + // Preserve legacy string encoding behavior for now + headers.values.has('content-type')) || + // `Blob` is superset of `File` + (globalThis.Blob && body instanceof globalThis.Blob) || + // `FormData` -> `multipart/form-data` + body instanceof FormData || + // `URLSearchParams` -> `application/x-www-form-urlencoded` + body instanceof URLSearchParams || + // Send chunked stream (each chunk has own `length`) + (globalThis.ReadableStream && body instanceof globalThis.ReadableStream)) { + return { bodyHeaders: undefined, body: body }; + } + else if (typeof body === 'object' && + (Symbol.asyncIterator in body || + (Symbol.iterator in body && 'next' in body && typeof body.next === 'function'))) { + return { bodyHeaders: undefined, body: ReadableStreamFrom(body) }; + } + else { + return __classPrivateFieldGet(this, _OpenAI_encoder, "f").call(this, { body, headers }); + } } } -class RunsPage extends CursorPage { -} -Runs.RunsPage = RunsPage; -Runs.Steps = Steps; -Runs.RunStepsPage = RunStepsPage; -//# sourceMappingURL=runs.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/threads/threads.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - +client_a = OpenAI, _OpenAI_encoder = new WeakMap(), _OpenAI_instances = new WeakSet(), _OpenAI_baseURLOverridden = function _OpenAI_baseURLOverridden() { + return this.baseURL !== 'https://api.openai.com/v1'; +}; +OpenAI.OpenAI = client_a; +OpenAI.DEFAULT_TIMEOUT = 600000; // 10 minutes +OpenAI.OpenAIError = error_OpenAIError; +OpenAI.APIError = APIError; +OpenAI.APIConnectionError = APIConnectionError; +OpenAI.APIConnectionTimeoutError = APIConnectionTimeoutError; +OpenAI.APIUserAbortError = APIUserAbortError; +OpenAI.NotFoundError = NotFoundError; +OpenAI.ConflictError = ConflictError; +OpenAI.RateLimitError = RateLimitError; +OpenAI.BadRequestError = BadRequestError; +OpenAI.AuthenticationError = AuthenticationError; +OpenAI.InternalServerError = InternalServerError; +OpenAI.PermissionDeniedError = PermissionDeniedError; +OpenAI.UnprocessableEntityError = UnprocessableEntityError; +OpenAI.InvalidWebhookSignatureError = InvalidWebhookSignatureError; +OpenAI.toFile = toFile; +OpenAI.Completions = completions_Completions; +OpenAI.Chat = Chat; +OpenAI.Embeddings = Embeddings; +OpenAI.Files = files_Files; +OpenAI.Images = Images; +OpenAI.Audio = Audio; +OpenAI.Moderations = Moderations; +OpenAI.Models = Models; +OpenAI.FineTuning = FineTuning; +OpenAI.Graders = graders_Graders; +OpenAI.VectorStores = VectorStores; +OpenAI.Webhooks = Webhooks; +OpenAI.Beta = Beta; +OpenAI.Batches = Batches; +OpenAI.Uploads = Uploads; +OpenAI.Responses = Responses; +OpenAI.Realtime = realtime_Realtime; +OpenAI.Conversations = Conversations; +OpenAI.Evals = Evals; +OpenAI.Containers = Containers; +//# sourceMappingURL=client.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/azure.mjs -class Threads extends APIResource { - constructor() { - super(...arguments); - this.runs = new Runs(this._client); - this.messages = new messages_Messages(this._client); - } - create(body = {}, options) { - if (isRequestOptions(body)) { - return this.create({}, body); - } - return this._client.post('/threads', { - body, - ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, - }); - } - /** - * Retrieves a thread. - * - * @example - * ```ts - * const thread = await client.beta.threads.retrieve( - * 'thread_id', - * ); - * ``` - */ - retrieve(threadId, options) { - return this._client.get(`/threads/${threadId}`, { - ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, - }); - } - /** - * Modifies a thread. - * - * @example - * ```ts - * const thread = await client.beta.threads.update( - * 'thread_id', - * ); - * ``` - */ - update(threadId, body, options) { - return this._client.post(`/threads/${threadId}`, { - body, - ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, - }); - } +/** API Client for interfacing with the Azure OpenAI API. */ +class AzureOpenAI extends OpenAI { /** - * Delete a thread. + * API Client for interfacing with the Azure OpenAI API. * - * @example - * ```ts - * const threadDeleted = await client.beta.threads.del( - * 'thread_id', - * ); - * ``` + * @param {string | undefined} [opts.apiVersion=process.env['OPENAI_API_VERSION'] ?? undefined] + * @param {string | undefined} [opts.endpoint=process.env['AZURE_OPENAI_ENDPOINT'] ?? undefined] - Your Azure endpoint, including the resource, e.g. `https://example-resource.azure.openai.com/` + * @param {string | undefined} [opts.apiKey=process.env['AZURE_OPENAI_API_KEY'] ?? undefined] + * @param {string | undefined} opts.deployment - A model deployment, if given, sets the base client URL to include `/deployments/{deployment}`. + * @param {string | null | undefined} [opts.organization=process.env['OPENAI_ORG_ID'] ?? null] + * @param {string} [opts.baseURL=process.env['OPENAI_BASE_URL']] - Sets the base URL for the API, e.g. `https://example-resource.azure.openai.com/openai/`. + * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out. + * @param {number} [opts.httpAgent] - An HTTP agent used to manage HTTP(s) connections. + * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation. + * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request. + * @param {Headers} opts.defaultHeaders - Default headers to include with every request to the API. + * @param {DefaultQuery} opts.defaultQuery - Default query parameters to include with every request to the API. + * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers. */ - del(threadId, options) { - return this._client.delete(`/threads/${threadId}`, { - ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, - }); - } - createAndRun(body, options) { - return this._client.post('/threads/runs', { - body, - ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, - stream: body.stream ?? false, + constructor({ baseURL = readEnv('OPENAI_BASE_URL'), apiKey = readEnv('AZURE_OPENAI_API_KEY'), apiVersion = readEnv('OPENAI_API_VERSION'), endpoint, deployment, azureADTokenProvider, dangerouslyAllowBrowser, ...opts } = {}) { + if (!apiVersion) { + throw new error_OpenAIError("The OPENAI_API_VERSION environment variable is missing or empty; either provide it, or instantiate the AzureOpenAI client with an apiVersion option, like new AzureOpenAI({ apiVersion: 'My API Version' })."); + } + if (typeof azureADTokenProvider === 'function') { + dangerouslyAllowBrowser = true; + } + if (!azureADTokenProvider && !apiKey) { + throw new error_OpenAIError('Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.'); + } + if (azureADTokenProvider && apiKey) { + throw new error_OpenAIError('The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.'); + } + opts.defaultQuery = { ...opts.defaultQuery, 'api-version': apiVersion }; + if (!baseURL) { + if (!endpoint) { + endpoint = process.env['AZURE_OPENAI_ENDPOINT']; + } + if (!endpoint) { + throw new error_OpenAIError('Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable'); + } + baseURL = `${endpoint}/openai`; + } + else { + if (endpoint) { + throw new error_OpenAIError('baseURL and endpoint are mutually exclusive'); + } + } + super({ + apiKey: azureADTokenProvider ?? apiKey, + baseURL, + ...opts, + ...(dangerouslyAllowBrowser !== undefined ? { dangerouslyAllowBrowser } : {}), }); + this.apiVersion = ''; + this.apiVersion = apiVersion; + this.deploymentName = deployment; } - /** - * A helper to create a thread, start a run and then poll for a terminal state. - * More information on Run lifecycles can be found here: - * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps - */ - async createAndRunPoll(body, options) { - const run = await this.createAndRun(body, options); - return await this.runs.poll(run.thread_id, run.id, options); + async buildRequest(options, props = {}) { + if (_deployments_endpoints.has(options.path) && options.method === 'post' && options.body !== undefined) { + if (!isObj(options.body)) { + throw new Error('Expected request body to be an object'); + } + const model = this.deploymentName || options.body['model'] || options.__metadata?.['model']; + if (model !== undefined && !this.baseURL.includes('/deployments')) { + options.path = `/deployments/${model}${options.path}`; + } + } + return super.buildRequest(options, props); } - /** - * Create a thread and stream the run back - */ - createAndRunStream(body, options) { - return AssistantStream.createThreadAssistantStream(body, this._client.beta.threads, options); + async authHeaders(opts) { + if (typeof this._options.apiKey === 'string') { + return buildHeaders([{ 'api-key': this.apiKey }]); + } + return super.authHeaders(opts); } } -Threads.Runs = Runs; -Threads.RunsPage = RunsPage; -Threads.Messages = messages_Messages; -Threads.MessagesPage = MessagesPage; -//# sourceMappingURL=threads.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/beta.mjs +const _deployments_endpoints = new Set([ + '/completions', + '/chat/completions', + '/embeddings', + '/audio/transcriptions', + '/audio/translations', + '/audio/speech', + '/images/generations', + '/batches', + '/images/edits', +]); +//# sourceMappingURL=azure.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/index.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. @@ -74962,758 +70053,754 @@ Threads.MessagesPage = MessagesPage; +//# sourceMappingURL=index.mjs.map +;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/internal/tslib.mjs +function tslib_classPrivateFieldSet(receiver, state, value, kind, f) { + if (kind === "m") + throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) + throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) + throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return kind === "a" ? f.call(receiver, value) : f ? (f.value = value) : state.set(receiver, value), value; +} +function tslib_classPrivateFieldGet(receiver, state, kind, f) { + if (kind === "a" && !f) + throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) + throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +} -class Beta extends APIResource { - constructor() { - super(...arguments); - this.realtime = new Realtime(this._client); - this.chat = new chat_Chat(this._client); - this.assistants = new Assistants(this._client); - this.threads = new Threads(this._client); +;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/internal/utils/uuid.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +/** + * https://stackoverflow.com/a/2117523 + */ +let uuid_uuid4 = function () { + const { crypto } = globalThis; + if (crypto?.randomUUID) { + uuid_uuid4 = crypto.randomUUID.bind(crypto); + return crypto.randomUUID(); } + const u8 = new Uint8Array(1); + const randomByte = crypto ? () => crypto.getRandomValues(u8)[0] : () => (Math.random() * 0xff) & 0xff; + return '10000000-1000-4000-8000-100000000000'.replace(/[018]/g, (c) => (+c ^ (randomByte() & (15 >> (+c / 4)))).toString(16)); +}; +//# sourceMappingURL=uuid.mjs.map +;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/internal/errors.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +function errors_isAbortError(err) { + return (typeof err === 'object' && + err !== null && + // Spec-compliant fetch implementations + (('name' in err && err.name === 'AbortError') || + // Expo fetch + ('message' in err && String(err.message).includes('FetchRequestCanceledException')))); } -Beta.Realtime = Realtime; -Beta.Assistants = Assistants; -Beta.AssistantsPage = AssistantsPage; -Beta.Threads = Threads; -//# sourceMappingURL=beta.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/batches.mjs +const errors_castToError = (err) => { + if (err instanceof Error) + return err; + if (typeof err === 'object' && err !== null) { + try { + if (Object.prototype.toString.call(err) === '[object Error]') { + // @ts-ignore - not all envs have native support for cause yet + const error = new Error(err.message, err.cause ? { cause: err.cause } : {}); + if (err.stack) + error.stack = err.stack; + // @ts-ignore - not all envs have native support for cause yet + if (err.cause && !error.cause) + error.cause = err.cause; + if (err.name) + error.name = err.name; + return error; + } + } + catch { } + try { + return new Error(JSON.stringify(err)); + } + catch { } + } + return new Error(err); +}; +//# sourceMappingURL=errors.mjs.map +;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/core/error.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - -class Batches extends APIResource { - /** - * Creates and executes a batch from an uploaded file of requests - */ - create(body, options) { - return this._client.post('/batches', { body, ...options }); +class error_AnthropicError extends Error { +} +class error_APIError extends error_AnthropicError { + constructor(status, error, message, headers) { + super(`${error_APIError.makeMessage(status, error, message)}`); + this.status = status; + this.headers = headers; + this.requestID = headers?.get('request-id'); + this.error = error; } - /** - * Retrieves a batch. - */ - retrieve(batchId, options) { - return this._client.get(`/batches/${batchId}`, options); + static makeMessage(status, error, message) { + const msg = error?.message ? + typeof error.message === 'string' ? + error.message + : JSON.stringify(error.message) + : error ? JSON.stringify(error) + : message; + if (status && msg) { + return `${status} ${msg}`; + } + if (status) { + return `${status} status code (no body)`; + } + if (msg) { + return msg; + } + return '(no status code or body)'; } - list(query = {}, options) { - if (isRequestOptions(query)) { - return this.list({}, query); + static generate(status, errorResponse, message, headers) { + if (!status || !headers) { + return new error_APIConnectionError({ message, cause: errors_castToError(errorResponse) }); + } + const error = errorResponse; + if (status === 400) { + return new error_BadRequestError(status, error, message, headers); + } + if (status === 401) { + return new error_AuthenticationError(status, error, message, headers); + } + if (status === 403) { + return new error_PermissionDeniedError(status, error, message, headers); + } + if (status === 404) { + return new error_NotFoundError(status, error, message, headers); } - return this._client.getAPIList('/batches', BatchesPage, { query, ...options }); + if (status === 409) { + return new error_ConflictError(status, error, message, headers); + } + if (status === 422) { + return new error_UnprocessableEntityError(status, error, message, headers); + } + if (status === 429) { + return new error_RateLimitError(status, error, message, headers); + } + if (status >= 500) { + return new error_InternalServerError(status, error, message, headers); + } + return new error_APIError(status, error, message, headers); } - /** - * Cancels an in-progress batch. The batch will be in status `cancelling` for up to - * 10 minutes, before changing to `cancelled`, where it will have partial results - * (if any) available in the output file. - */ - cancel(batchId, options) { - return this._client.post(`/batches/${batchId}/cancel`, options); +} +class error_APIUserAbortError extends error_APIError { + constructor({ message } = {}) { + super(undefined, undefined, message || 'Request was aborted.', undefined); } } -class BatchesPage extends CursorPage { +class error_APIConnectionError extends error_APIError { + constructor({ message, cause }) { + super(undefined, undefined, message || 'Connection error.', undefined); + // in some environments the 'cause' property is already declared + // @ts-ignore + if (cause) + this.cause = cause; + } } -Batches.BatchesPage = BatchesPage; -//# sourceMappingURL=batches.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/uploads/parts.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - -class Parts extends APIResource { - /** - * Adds a - * [Part](https://platform.openai.com/docs/api-reference/uploads/part-object) to an - * [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object. - * A Part represents a chunk of bytes from the file you are trying to upload. - * - * Each Part can be at most 64 MB, and you can add Parts until you hit the Upload - * maximum of 8 GB. - * - * It is possible to add multiple Parts in parallel. You can decide the intended - * order of the Parts when you - * [complete the Upload](https://platform.openai.com/docs/api-reference/uploads/complete). - */ - create(uploadId, body, options) { - return this._client.post(`/uploads/${uploadId}/parts`, multipartFormRequestOptions({ body, ...options })); +class error_APIConnectionTimeoutError extends error_APIConnectionError { + constructor({ message } = {}) { + super({ message: message ?? 'Request timed out.' }); } } -//# sourceMappingURL=parts.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/uploads/uploads.mjs +class error_BadRequestError extends error_APIError { +} +class error_AuthenticationError extends error_APIError { +} +class error_PermissionDeniedError extends error_APIError { +} +class error_NotFoundError extends error_APIError { +} +class error_ConflictError extends error_APIError { +} +class error_UnprocessableEntityError extends error_APIError { +} +class error_RateLimitError extends error_APIError { +} +class error_InternalServerError extends error_APIError { +} +//# sourceMappingURL=error.mjs.map +;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/internal/utils/values.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - -class Uploads extends APIResource { - constructor() { - super(...arguments); - this.parts = new Parts(this._client); +// https://url.spec.whatwg.org/#url-scheme-string +const values_startsWithSchemeRegexp = /^[a-z][a-z0-9+.-]*:/i; +const values_isAbsoluteURL = (url) => { + return values_startsWithSchemeRegexp.test(url); +}; +let utils_values_isArray = (val) => ((utils_values_isArray = Array.isArray), utils_values_isArray(val)); +let values_isReadonlyArray = utils_values_isArray; +/** Returns an object if the given value isn't an object, otherwise returns as-is */ +function values_maybeObj(x) { + if (typeof x !== 'object') { + return {}; } - /** - * Creates an intermediate - * [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object - * that you can add - * [Parts](https://platform.openai.com/docs/api-reference/uploads/part-object) to. - * Currently, an Upload can accept at most 8 GB in total and expires after an hour - * after you create it. - * - * Once you complete the Upload, we will create a - * [File](https://platform.openai.com/docs/api-reference/files/object) object that - * contains all the parts you uploaded. This File is usable in the rest of our - * platform as a regular File object. - * - * For certain `purpose` values, the correct `mime_type` must be specified. Please - * refer to documentation for the - * [supported MIME types for your use case](https://platform.openai.com/docs/assistants/tools/file-search#supported-files). - * - * For guidance on the proper filename extensions for each purpose, please follow - * the documentation on - * [creating a File](https://platform.openai.com/docs/api-reference/files/create). - */ - create(body, options) { - return this._client.post('/uploads', { body, ...options }); + return x ?? {}; +} +// https://stackoverflow.com/a/34491287 +function values_isEmptyObj(obj) { + if (!obj) + return true; + for (const _k in obj) + return false; + return true; +} +// https://eslint.org/docs/latest/rules/no-prototype-builtins +function values_hasOwn(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} +function values_isObj(obj) { + return obj != null && typeof obj === 'object' && !Array.isArray(obj); +} +const values_ensurePresent = (value) => { + if (value == null) { + throw new AnthropicError(`Expected a value to be given but received ${value} instead.`); } - /** - * Cancels the Upload. No Parts may be added after an Upload is cancelled. - */ - cancel(uploadId, options) { - return this._client.post(`/uploads/${uploadId}/cancel`, options); + return value; +}; +const values_validatePositiveInteger = (name, n) => { + if (typeof n !== 'number' || !Number.isInteger(n)) { + throw new error_AnthropicError(`${name} must be an integer`); } - /** - * Completes the - * [Upload](https://platform.openai.com/docs/api-reference/uploads/object). - * - * Within the returned Upload object, there is a nested - * [File](https://platform.openai.com/docs/api-reference/files/object) object that - * is ready to use in the rest of the platform. - * - * You can specify the order of the Parts by passing in an ordered list of the Part - * IDs. - * - * The number of bytes uploaded upon completion must match the number of bytes - * initially specified when creating the Upload object. No Parts may be added after - * an Upload is completed. - */ - complete(uploadId, body, options) { - return this._client.post(`/uploads/${uploadId}/complete`, { body, ...options }); + if (n < 0) { + throw new error_AnthropicError(`${name} must be a positive integer`); } -} -Uploads.Parts = Parts; -//# sourceMappingURL=uploads.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/lib/ResponsesParser.mjs - - -function maybeParseResponse(response, params) { - if (!params || !ResponsesParser_hasAutoParseableInput(params)) { - return { - ...response, - output_parsed: null, - output: response.output.map((item) => { - if (item.type === 'function_call') { - return { - ...item, - parsed_arguments: null, - }; - } - if (item.type === 'message') { - return { - ...item, - content: item.content.map((content) => ({ - ...content, - parsed: null, - })), - }; - } - else { - return item; - } - }), - }; + return n; +}; +const values_coerceInteger = (value) => { + if (typeof value === 'number') + return Math.round(value); + if (typeof value === 'string') + return parseInt(value, 10); + throw new AnthropicError(`Could not coerce ${value} (type: ${typeof value}) into a number`); +}; +const values_coerceFloat = (value) => { + if (typeof value === 'number') + return value; + if (typeof value === 'string') + return parseFloat(value); + throw new AnthropicError(`Could not coerce ${value} (type: ${typeof value}) into a number`); +}; +const values_coerceBoolean = (value) => { + if (typeof value === 'boolean') + return value; + if (typeof value === 'string') + return value === 'true'; + return Boolean(value); +}; +const values_maybeCoerceInteger = (value) => { + if (value === undefined) { + return undefined; } - return parseResponse(response, params); -} -function parseResponse(response, params) { - const output = response.output.map((item) => { - if (item.type === 'function_call') { - return { - ...item, - parsed_arguments: ResponsesParser_parseToolCall(params, item), - }; - } - if (item.type === 'message') { - const content = item.content.map((content) => { - if (content.type === 'output_text') { - return { - ...content, - parsed: parseTextFormat(params, content.text), - }; - } - return content; - }); - return { - ...item, - content, - }; - } - return item; - }); - const parsed = Object.assign({}, response, { output }); - if (!Object.getOwnPropertyDescriptor(response, 'output_text')) { - addOutputText(parsed); + return values_coerceInteger(value); +}; +const values_maybeCoerceFloat = (value) => { + if (value === undefined) { + return undefined; + } + return values_coerceFloat(value); +}; +const values_maybeCoerceBoolean = (value) => { + if (value === undefined) { + return undefined; + } + return values_coerceBoolean(value); +}; +const values_safeJSON = (text) => { + try { + return JSON.parse(text); + } + catch (err) { + return undefined; + } +}; +//# sourceMappingURL=values.mjs.map +;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/internal/utils/sleep.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +const sleep_sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); +//# sourceMappingURL=sleep.mjs.map +;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/version.mjs +const version_VERSION = '0.59.0'; // x-release-please-version +//# sourceMappingURL=version.mjs.map +;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/internal/detect-platform.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +const detect_platform_isRunningInBrowser = () => { + return ( + // @ts-ignore + typeof window !== 'undefined' && + // @ts-ignore + typeof window.document !== 'undefined' && + // @ts-ignore + typeof navigator !== 'undefined'); +}; +/** + * Note this does not detect 'browser'; for that, use getBrowserInfo(). + */ +function detect_platform_getDetectedPlatform() { + if (typeof Deno !== 'undefined' && Deno.build != null) { + return 'deno'; } - Object.defineProperty(parsed, 'output_parsed', { - enumerable: true, - get() { - for (const output of parsed.output) { - if (output.type !== 'message') { - continue; - } - for (const content of output.content) { - if (content.type === 'output_text' && content.parsed !== null) { - return content.parsed; - } - } - } - return null; - }, - }); - return parsed; -} -function parseTextFormat(params, content) { - if (params.text?.format?.type !== 'json_schema') { - return null; + if (typeof EdgeRuntime !== 'undefined') { + return 'edge'; } - if ('$parseRaw' in params.text?.format) { - const text_format = params.text?.format; - return text_format.$parseRaw(content); + if (Object.prototype.toString.call(typeof globalThis.process !== 'undefined' ? globalThis.process : 0) === '[object process]') { + return 'node'; } - return JSON.parse(content); + return 'unknown'; } -function ResponsesParser_hasAutoParseableInput(params) { - if (isAutoParsableResponseFormat(params.text?.format)) { - return true; +const detect_platform_getPlatformProperties = () => { + const detectedPlatform = detect_platform_getDetectedPlatform(); + if (detectedPlatform === 'deno') { + return { + 'X-Stainless-Lang': 'js', + 'X-Stainless-Package-Version': version_VERSION, + 'X-Stainless-OS': detect_platform_normalizePlatform(Deno.build.os), + 'X-Stainless-Arch': detect_platform_normalizeArch(Deno.build.arch), + 'X-Stainless-Runtime': 'deno', + 'X-Stainless-Runtime-Version': typeof Deno.version === 'string' ? Deno.version : Deno.version?.deno ?? 'unknown', + }; } - return false; -} -function ResponsesParser_makeParseableResponseTool(tool, { parser, callback, }) { - const obj = { ...tool }; - Object.defineProperties(obj, { - $brand: { - value: 'auto-parseable-tool', - enumerable: false, - }, - $parseRaw: { - value: parser, - enumerable: false, - }, - $callback: { - value: callback, - enumerable: false, - }, - }); - return obj; -} -function ResponsesParser_isAutoParsableTool(tool) { - return tool?.['$brand'] === 'auto-parseable-tool'; -} -function getInputToolByName(input_tools, name) { - return input_tools.find((tool) => tool.type === 'function' && tool.name === name); -} -function ResponsesParser_parseToolCall(params, toolCall) { - const inputTool = getInputToolByName(params.tools ?? [], toolCall.name); - return { - ...toolCall, - ...toolCall, - parsed_arguments: ResponsesParser_isAutoParsableTool(inputTool) ? inputTool.$parseRaw(toolCall.arguments) - : inputTool?.strict ? JSON.parse(toolCall.arguments) - : null, - }; -} -function ResponsesParser_shouldParseToolCall(params, toolCall) { - if (!params) { - return false; + if (typeof EdgeRuntime !== 'undefined') { + return { + 'X-Stainless-Lang': 'js', + 'X-Stainless-Package-Version': version_VERSION, + 'X-Stainless-OS': 'Unknown', + 'X-Stainless-Arch': `other:${EdgeRuntime}`, + 'X-Stainless-Runtime': 'edge', + 'X-Stainless-Runtime-Version': globalThis.process.version, + }; } - const inputTool = getInputToolByName(params.tools ?? [], toolCall.name); - return ResponsesParser_isAutoParsableTool(inputTool) || inputTool?.strict || false; -} -function ResponsesParser_validateInputTools(tools) { - for (const tool of tools ?? []) { - if (tool.type !== 'function') { - throw new OpenAIError(`Currently only \`function\` tool types support auto-parsing; Received \`${tool.type}\``); - } - if (tool.function.strict !== true) { - throw new OpenAIError(`The \`${tool.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`); - } + // Check if Node.js + if (detectedPlatform === 'node') { + return { + 'X-Stainless-Lang': 'js', + 'X-Stainless-Package-Version': version_VERSION, + 'X-Stainless-OS': detect_platform_normalizePlatform(globalThis.process.platform ?? 'unknown'), + 'X-Stainless-Arch': detect_platform_normalizeArch(globalThis.process.arch ?? 'unknown'), + 'X-Stainless-Runtime': 'node', + 'X-Stainless-Runtime-Version': globalThis.process.version ?? 'unknown', + }; } -} -function addOutputText(rsp) { - const texts = []; - for (const output of rsp.output) { - if (output.type !== 'message') { - continue; - } - for (const content of output.content) { - if (content.type === 'output_text') { - texts.push(content.text); - } - } + const browserInfo = detect_platform_getBrowserInfo(); + if (browserInfo) { + return { + 'X-Stainless-Lang': 'js', + 'X-Stainless-Package-Version': version_VERSION, + 'X-Stainless-OS': 'Unknown', + 'X-Stainless-Arch': 'unknown', + 'X-Stainless-Runtime': `browser:${browserInfo.browser}`, + 'X-Stainless-Runtime-Version': browserInfo.version, + }; } - rsp.output_text = texts.join(''); -} -//# sourceMappingURL=ResponsesParser.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/responses/input-items.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - -class InputItems extends APIResource { - list(responseId, query = {}, options) { - if (isRequestOptions(query)) { - return this.list(responseId, {}, query); + // TODO add support for Cloudflare workers, etc. + return { + 'X-Stainless-Lang': 'js', + 'X-Stainless-Package-Version': version_VERSION, + 'X-Stainless-OS': 'Unknown', + 'X-Stainless-Arch': 'unknown', + 'X-Stainless-Runtime': 'unknown', + 'X-Stainless-Runtime-Version': 'unknown', + }; +}; +// Note: modified from https://github.com/JS-DevTools/host-environment/blob/b1ab79ecde37db5d6e163c050e54fe7d287d7c92/src/isomorphic.browser.ts +function detect_platform_getBrowserInfo() { + if (typeof navigator === 'undefined' || !navigator) { + return null; + } + // NOTE: The order matters here! + const browserPatterns = [ + { key: 'edge', pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: 'ie', pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: 'ie', pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: 'chrome', pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: 'firefox', pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: 'safari', pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ }, + ]; + // Find the FIRST matching browser + for (const { key, pattern } of browserPatterns) { + const match = pattern.exec(navigator.userAgent); + if (match) { + const major = match[1] || 0; + const minor = match[2] || 0; + const patch = match[3] || 0; + return { browser: key, version: `${major}.${minor}.${patch}` }; } - return this._client.getAPIList(`/responses/${responseId}/input_items`, ResponseItemsPage, { - query, - ...options, - }); } + return null; } - -//# sourceMappingURL=input-items.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/lib/responses/ResponseStream.mjs -var ResponseStream_classPrivateFieldSet = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { - if (kind === "m") throw new TypeError("Private method is not writable"); - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); - return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +const detect_platform_normalizeArch = (arch) => { + // Node docs: + // - https://nodejs.org/api/process.html#processarch + // Deno docs: + // - https://doc.deno.land/deno/stable/~/Deno.build + if (arch === 'x32') + return 'x32'; + if (arch === 'x86_64' || arch === 'x64') + return 'x64'; + if (arch === 'arm') + return 'arm'; + if (arch === 'aarch64' || arch === 'arm64') + return 'arm64'; + if (arch) + return `other:${arch}`; + return 'unknown'; }; -var ResponseStream_classPrivateFieldGet = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) { - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +const detect_platform_normalizePlatform = (platform) => { + // Node platforms: + // - https://nodejs.org/api/process.html#processplatform + // Deno platforms: + // - https://doc.deno.land/deno/stable/~/Deno.build + // - https://github.com/denoland/deno/issues/14799 + platform = platform.toLowerCase(); + // NOTE: this iOS check is untested and may not work + // Node does not work natively on IOS, there is a fork at + // https://github.com/nodejs-mobile/nodejs-mobile + // however it is unknown at the time of writing how to detect if it is running + if (platform.includes('ios')) + return 'iOS'; + if (platform === 'android') + return 'Android'; + if (platform === 'darwin') + return 'MacOS'; + if (platform === 'win32') + return 'Windows'; + if (platform === 'freebsd') + return 'FreeBSD'; + if (platform === 'openbsd') + return 'OpenBSD'; + if (platform === 'linux') + return 'Linux'; + if (platform) + return `Other:${platform}`; + return 'Unknown'; }; -var _ResponseStream_instances, _ResponseStream_params, _ResponseStream_currentResponseSnapshot, _ResponseStream_finalResponse, _ResponseStream_beginRequest, _ResponseStream_addEvent, _ResponseStream_endRequest, _ResponseStream_accumulateResponse; - - - -class ResponseStream extends EventStream { - constructor(params) { - super(); - _ResponseStream_instances.add(this); - _ResponseStream_params.set(this, void 0); - _ResponseStream_currentResponseSnapshot.set(this, void 0); - _ResponseStream_finalResponse.set(this, void 0); - ResponseStream_classPrivateFieldSet(this, _ResponseStream_params, params, "f"); - } - static createResponse(client, params, options) { - const runner = new ResponseStream(params); - runner._run(() => runner._createResponse(client, params, { - ...options, - headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' }, - })); - return runner; +let detect_platform_platformHeaders; +const detect_platform_getPlatformHeaders = () => { + return (detect_platform_platformHeaders ?? (detect_platform_platformHeaders = detect_platform_getPlatformProperties())); +}; +//# sourceMappingURL=detect-platform.mjs.map +;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/internal/shims.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +function shims_getDefaultFetch() { + if (typeof fetch !== 'undefined') { + return fetch; } - async _createResponse(client, params, options) { - const signal = options?.signal; - if (signal) { - if (signal.aborted) - this.controller.abort(); - signal.addEventListener('abort', () => this.controller.abort()); - } - ResponseStream_classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_beginRequest).call(this); - const stream = await client.responses.create({ ...params, stream: true }, { ...options, signal: this.controller.signal }); - this._connected(); - for await (const event of stream) { - ResponseStream_classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_addEvent).call(this, event); - } - if (stream.controller.signal?.aborted) { - throw new APIUserAbortError(); - } - return ResponseStream_classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_endRequest).call(this); + throw new Error('`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`'); +} +function shims_makeReadableStream(...args) { + const ReadableStream = globalThis.ReadableStream; + if (typeof ReadableStream === 'undefined') { + // Note: All of the platforms / runtimes we officially support already define + // `ReadableStream` as a global, so this should only ever be hit on unsupported runtimes. + throw new Error('`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`'); } - [(_ResponseStream_params = new WeakMap(), _ResponseStream_currentResponseSnapshot = new WeakMap(), _ResponseStream_finalResponse = new WeakMap(), _ResponseStream_instances = new WeakSet(), _ResponseStream_beginRequest = function _ResponseStream_beginRequest() { - if (this.ended) - return; - ResponseStream_classPrivateFieldSet(this, _ResponseStream_currentResponseSnapshot, undefined, "f"); - }, _ResponseStream_addEvent = function _ResponseStream_addEvent(event) { - if (this.ended) - return; - const response = ResponseStream_classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_accumulateResponse).call(this, event); - this._emit('event', event); - switch (event.type) { - case 'response.output_text.delta': { - const output = response.output[event.output_index]; - if (!output) { - throw new error_OpenAIError(`missing output at index ${event.output_index}`); - } - if (output.type === 'message') { - const content = output.content[event.content_index]; - if (!content) { - throw new error_OpenAIError(`missing content at index ${event.content_index}`); - } - if (content.type !== 'output_text') { - throw new error_OpenAIError(`expected content to be 'output_text', got ${content.type}`); - } - this._emit('response.output_text.delta', { - ...event, - snapshot: content.text, - }); - } - break; - } - case 'response.function_call_arguments.delta': { - const output = response.output[event.output_index]; - if (!output) { - throw new error_OpenAIError(`missing output at index ${event.output_index}`); - } - if (output.type === 'function_call') { - this._emit('response.function_call_arguments.delta', { - ...event, - snapshot: output.arguments, - }); - } - break; - } - default: - // @ts-ignore - this._emit(event.type, event); - break; - } - }, _ResponseStream_endRequest = function _ResponseStream_endRequest() { - if (this.ended) { - throw new error_OpenAIError(`stream has ended, this shouldn't happen`); - } - const snapshot = ResponseStream_classPrivateFieldGet(this, _ResponseStream_currentResponseSnapshot, "f"); - if (!snapshot) { - throw new error_OpenAIError(`request ended without sending any events`); - } - ResponseStream_classPrivateFieldSet(this, _ResponseStream_currentResponseSnapshot, undefined, "f"); - const parsedResponse = finalizeResponse(snapshot, ResponseStream_classPrivateFieldGet(this, _ResponseStream_params, "f")); - ResponseStream_classPrivateFieldSet(this, _ResponseStream_finalResponse, parsedResponse, "f"); - return parsedResponse; - }, _ResponseStream_accumulateResponse = function _ResponseStream_accumulateResponse(event) { - let snapshot = ResponseStream_classPrivateFieldGet(this, _ResponseStream_currentResponseSnapshot, "f"); - if (!snapshot) { - if (event.type !== 'response.created') { - throw new error_OpenAIError(`When snapshot hasn't been set yet, expected 'response.created' event, got ${event.type}`); - } - snapshot = ResponseStream_classPrivateFieldSet(this, _ResponseStream_currentResponseSnapshot, event.response, "f"); - return snapshot; - } - switch (event.type) { - case 'response.output_item.added': { - snapshot.output.push(event.item); - break; - } - case 'response.content_part.added': { - const output = snapshot.output[event.output_index]; - if (!output) { - throw new error_OpenAIError(`missing output at index ${event.output_index}`); - } - if (output.type === 'message') { - output.content.push(event.part); - } - break; - } - case 'response.output_text.delta': { - const output = snapshot.output[event.output_index]; - if (!output) { - throw new error_OpenAIError(`missing output at index ${event.output_index}`); - } - if (output.type === 'message') { - const content = output.content[event.content_index]; - if (!content) { - throw new error_OpenAIError(`missing content at index ${event.content_index}`); - } - if (content.type !== 'output_text') { - throw new error_OpenAIError(`expected content to be 'output_text', got ${content.type}`); - } - content.text += event.delta; - } - break; - } - case 'response.function_call_arguments.delta': { - const output = snapshot.output[event.output_index]; - if (!output) { - throw new error_OpenAIError(`missing output at index ${event.output_index}`); - } - if (output.type === 'function_call') { - output.arguments += event.delta; - } - break; - } - case 'response.completed': { - ResponseStream_classPrivateFieldSet(this, _ResponseStream_currentResponseSnapshot, event.response, "f"); - break; - } - } - return snapshot; - }, Symbol.asyncIterator)]() { - const pushQueue = []; - const readQueue = []; - let done = false; - this.on('event', (event) => { - const reader = readQueue.shift(); - if (reader) { - reader.resolve(event); + return new ReadableStream(...args); +} +function shims_ReadableStreamFrom(iterable) { + let iter = Symbol.asyncIterator in iterable ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator](); + return shims_makeReadableStream({ + start() { }, + async pull(controller) { + const { done, value } = await iter.next(); + if (done) { + controller.close(); } else { - pushQueue.push(event); - } - }); - this.on('end', () => { - done = true; - for (const reader of readQueue) { - reader.resolve(undefined); + controller.enqueue(value); } - readQueue.length = 0; - }); - this.on('abort', (err) => { - done = true; - for (const reader of readQueue) { - reader.reject(err); + }, + async cancel() { + await iter.return?.(); + }, + }); +} +/** + * Most browsers don't yet have async iterable support for ReadableStream, + * and Node has a very different way of reading bytes from its "ReadableStream". + * + * This polyfill was pulled from https://github.com/MattiasBuelens/web-streams-polyfill/pull/122#issuecomment-1627354490 + */ +function shims_ReadableStreamToAsyncIterable(stream) { + if (stream[Symbol.asyncIterator]) + return stream; + const reader = stream.getReader(); + return { + async next() { + try { + const result = await reader.read(); + if (result?.done) + reader.releaseLock(); // release lock when stream becomes closed + return result; } - readQueue.length = 0; - }); - this.on('error', (err) => { - done = true; - for (const reader of readQueue) { - reader.reject(err); + catch (e) { + reader.releaseLock(); // release lock when stream becomes errored + throw e; } - readQueue.length = 0; - }); - return { - next: async () => { - if (!pushQueue.length) { - if (done) { - return { value: undefined, done: true }; - } - return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((event) => (event ? { value: event, done: false } : { value: undefined, done: true })); - } - const event = pushQueue.shift(); - return { value: event, done: false }; - }, - return: async () => { - this.abort(); - return { value: undefined, done: true }; - }, - }; + }, + async return() { + const cancelPromise = reader.cancel(); + reader.releaseLock(); + await cancelPromise; + return { done: true, value: undefined }; + }, + [Symbol.asyncIterator]() { + return this; + }, + }; +} +/** + * Cancels a ReadableStream we don't need to consume. + * See https://undici.nodejs.org/#/?id=garbage-collection + */ +async function shims_CancelReadableStream(stream) { + if (stream === null || typeof stream !== 'object') + return; + if (stream[Symbol.asyncIterator]) { + await stream[Symbol.asyncIterator]().return?.(); + return; } - /** - * @returns a promise that resolves with the final Response, or rejects - * if an error occurred or the stream ended prematurely without producing a REsponse. - */ - async finalResponse() { - await this.done(); - const response = ResponseStream_classPrivateFieldGet(this, _ResponseStream_finalResponse, "f"); - if (!response) - throw new error_OpenAIError('stream ended without producing a ChatCompletion'); - return response; + const reader = stream.getReader(); + const cancelPromise = reader.cancel(); + reader.releaseLock(); + await cancelPromise; +} +//# sourceMappingURL=shims.mjs.map +;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/internal/request-options.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +const request_options_FallbackEncoder = ({ headers, body }) => { + return { + bodyHeaders: { + 'content-type': 'application/json', + }, + body: JSON.stringify(body), + }; +}; +//# sourceMappingURL=request-options.mjs.map +;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/internal/utils/bytes.mjs +function bytes_concatBytes(buffers) { + let length = 0; + for (const buffer of buffers) { + length += buffer.length; + } + const output = new Uint8Array(length); + let index = 0; + for (const buffer of buffers) { + output.set(buffer, index); + index += buffer.length; } + return output; } -function finalizeResponse(snapshot, params) { - return maybeParseResponse(snapshot, params); +let bytes_encodeUTF8_; +function utils_bytes_encodeUTF8(str) { + let encoder; + return (bytes_encodeUTF8_ ?? + ((encoder = new globalThis.TextEncoder()), (bytes_encodeUTF8_ = encoder.encode.bind(encoder))))(str); } -//# sourceMappingURL=ResponseStream.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/responses/responses.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - +let bytes_decodeUTF8_; +function bytes_decodeUTF8(bytes) { + let decoder; + return (bytes_decodeUTF8_ ?? + ((decoder = new globalThis.TextDecoder()), (bytes_decodeUTF8_ = decoder.decode.bind(decoder))))(bytes); +} +//# sourceMappingURL=bytes.mjs.map +;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/internal/decoders/line.mjs +var line_LineDecoder_buffer, line_LineDecoder_carriageReturnIndex; -class Responses extends APIResource { +/** + * A re-implementation of httpx's `LineDecoder` in Python that handles incrementally + * reading lines from text. + * + * https://github.com/encode/httpx/blob/920333ea98118e9cf617f246905d7b202510941c/httpx/_decoders.py#L258 + */ +class line_LineDecoder { constructor() { - super(...arguments); - this.inputItems = new InputItems(this._client); + line_LineDecoder_buffer.set(this, void 0); + line_LineDecoder_carriageReturnIndex.set(this, void 0); + tslib_classPrivateFieldSet(this, line_LineDecoder_buffer, new Uint8Array(), "f"); + tslib_classPrivateFieldSet(this, line_LineDecoder_carriageReturnIndex, null, "f"); } - create(body, options) { - return this._client.post('/responses', { body, ...options, stream: body.stream ?? false })._thenUnwrap((rsp) => { - if ('object' in rsp && rsp.object === 'response') { - addOutputText(rsp); + decode(chunk) { + if (chunk == null) { + return []; + } + const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) + : typeof chunk === 'string' ? utils_bytes_encodeUTF8(chunk) + : chunk; + tslib_classPrivateFieldSet(this, line_LineDecoder_buffer, bytes_concatBytes([tslib_classPrivateFieldGet(this, line_LineDecoder_buffer, "f"), binaryChunk]), "f"); + const lines = []; + let patternIndex; + while ((patternIndex = line_findNewlineIndex(tslib_classPrivateFieldGet(this, line_LineDecoder_buffer, "f"), tslib_classPrivateFieldGet(this, line_LineDecoder_carriageReturnIndex, "f"))) != null) { + if (patternIndex.carriage && tslib_classPrivateFieldGet(this, line_LineDecoder_carriageReturnIndex, "f") == null) { + // skip until we either get a corresponding `\n`, a new `\r` or nothing + tslib_classPrivateFieldSet(this, line_LineDecoder_carriageReturnIndex, patternIndex.index, "f"); + continue; } - return rsp; - }); - } - retrieve(responseId, query = {}, options) { - if (isRequestOptions(query)) { - return this.retrieve(responseId, {}, query); + // we got double \r or \rtext\n + if (tslib_classPrivateFieldGet(this, line_LineDecoder_carriageReturnIndex, "f") != null && + (patternIndex.index !== tslib_classPrivateFieldGet(this, line_LineDecoder_carriageReturnIndex, "f") + 1 || patternIndex.carriage)) { + lines.push(bytes_decodeUTF8(tslib_classPrivateFieldGet(this, line_LineDecoder_buffer, "f").subarray(0, tslib_classPrivateFieldGet(this, line_LineDecoder_carriageReturnIndex, "f") - 1))); + tslib_classPrivateFieldSet(this, line_LineDecoder_buffer, tslib_classPrivateFieldGet(this, line_LineDecoder_buffer, "f").subarray(tslib_classPrivateFieldGet(this, line_LineDecoder_carriageReturnIndex, "f")), "f"); + tslib_classPrivateFieldSet(this, line_LineDecoder_carriageReturnIndex, null, "f"); + continue; + } + const endIndex = tslib_classPrivateFieldGet(this, line_LineDecoder_carriageReturnIndex, "f") !== null ? patternIndex.preceding - 1 : patternIndex.preceding; + const line = bytes_decodeUTF8(tslib_classPrivateFieldGet(this, line_LineDecoder_buffer, "f").subarray(0, endIndex)); + lines.push(line); + tslib_classPrivateFieldSet(this, line_LineDecoder_buffer, tslib_classPrivateFieldGet(this, line_LineDecoder_buffer, "f").subarray(patternIndex.index), "f"); + tslib_classPrivateFieldSet(this, line_LineDecoder_carriageReturnIndex, null, "f"); } - return this._client.get(`/responses/${responseId}`, { query, ...options }); - } - /** - * Deletes a model response with the given ID. - * - * @example - * ```ts - * await client.responses.del( - * 'resp_677efb5139a88190b512bc3fef8e535d', - * ); - * ``` - */ - del(responseId, options) { - return this._client.delete(`/responses/${responseId}`, { - ...options, - headers: { Accept: '*/*', ...options?.headers }, - }); - } - parse(body, options) { - return this._client.responses - .create(body, options) - ._thenUnwrap((response) => parseResponse(response, body)); + return lines; } - /** - * Creates a model response stream - */ - stream(body, options) { - return ResponseStream.createResponse(this._client, body, options); + flush() { + if (!tslib_classPrivateFieldGet(this, line_LineDecoder_buffer, "f").length) { + return []; + } + return this.decode('\n'); } } -class ResponseItemsPage extends CursorPage { -} -Responses.InputItems = InputItems; -//# sourceMappingURL=responses.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/evals/runs/output-items.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - -class OutputItems extends APIResource { - /** - * Get an evaluation run output item by ID. - */ - retrieve(evalId, runId, outputItemId, options) { - return this._client.get(`/evals/${evalId}/runs/${runId}/output_items/${outputItemId}`, options); - } - list(evalId, runId, query = {}, options) { - if (isRequestOptions(query)) { - return this.list(evalId, runId, {}, query); +line_LineDecoder_buffer = new WeakMap(), line_LineDecoder_carriageReturnIndex = new WeakMap(); +// prettier-ignore +line_LineDecoder.NEWLINE_CHARS = new Set(['\n', '\r']); +line_LineDecoder.NEWLINE_REGEXP = /\r\n|[\n\r]/g; +/** + * This function searches the buffer for the end patterns, (\r or \n) + * and returns an object with the index preceding the matched newline and the + * index after the newline char. `null` is returned if no new line is found. + * + * ```ts + * findNewLineIndex('abc\ndef') -> { preceding: 2, index: 3 } + * ``` + */ +function line_findNewlineIndex(buffer, startIndex) { + const newline = 0x0a; // \n + const carriage = 0x0d; // \r + for (let i = startIndex ?? 0; i < buffer.length; i++) { + if (buffer[i] === newline) { + return { preceding: i, index: i + 1, carriage: false }; + } + if (buffer[i] === carriage) { + return { preceding: i, index: i + 1, carriage: true }; } - return this._client.getAPIList(`/evals/${evalId}/runs/${runId}/output_items`, OutputItemListResponsesPage, { query, ...options }); } + return null; } -class OutputItemListResponsesPage extends CursorPage { +function line_findDoubleNewlineIndex(buffer) { + // This function searches the buffer for the end patterns (\r\r, \n\n, \r\n\r\n) + // and returns the index right after the first occurrence of any pattern, + // or -1 if none of the patterns are found. + const newline = 0x0a; // \n + const carriage = 0x0d; // \r + for (let i = 0; i < buffer.length - 1; i++) { + if (buffer[i] === newline && buffer[i + 1] === newline) { + // \n\n + return i + 2; + } + if (buffer[i] === carriage && buffer[i + 1] === carriage) { + // \r\r + return i + 2; + } + if (buffer[i] === carriage && + buffer[i + 1] === newline && + i + 3 < buffer.length && + buffer[i + 2] === carriage && + buffer[i + 3] === newline) { + // \r\n\r\n + return i + 4; + } + } + return -1; } -OutputItems.OutputItemListResponsesPage = OutputItemListResponsesPage; -//# sourceMappingURL=output-items.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/evals/runs/runs.mjs +//# sourceMappingURL=line.mjs.map +;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/internal/utils/log.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - -class runs_Runs extends APIResource { - constructor() { - super(...arguments); - this.outputItems = new OutputItems(this._client); - } - /** - * Create a new evaluation run. This is the endpoint that will kick off grading. - */ - create(evalId, body, options) { - return this._client.post(`/evals/${evalId}/runs`, { body, ...options }); - } - /** - * Get an evaluation run by ID. - */ - retrieve(evalId, runId, options) { - return this._client.get(`/evals/${evalId}/runs/${runId}`, options); +const log_levelNumbers = { + off: 0, + error: 200, + warn: 300, + info: 400, + debug: 500, +}; +const log_parseLogLevel = (maybeLevel, sourceName, client) => { + if (!maybeLevel) { + return undefined; } - list(evalId, query = {}, options) { - if (isRequestOptions(query)) { - return this.list(evalId, {}, query); - } - return this._client.getAPIList(`/evals/${evalId}/runs`, RunListResponsesPage, { query, ...options }); + if (values_hasOwn(log_levelNumbers, maybeLevel)) { + return maybeLevel; } - /** - * Delete an eval run. - */ - del(evalId, runId, options) { - return this._client.delete(`/evals/${evalId}/runs/${runId}`, options); + log_loggerFor(client).warn(`${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(Object.keys(log_levelNumbers))}`); + return undefined; +}; +function log_noop() { } +function log_makeLogFn(fnLevel, logger, logLevel) { + if (!logger || log_levelNumbers[fnLevel] > log_levelNumbers[logLevel]) { + return log_noop; } - /** - * Cancel an ongoing evaluation run. - */ - cancel(evalId, runId, options) { - return this._client.post(`/evals/${evalId}/runs/${runId}`, options); + else { + // Don't wrap logger functions, we want the stacktrace intact! + return logger[fnLevel].bind(logger); } } -class RunListResponsesPage extends CursorPage { -} -runs_Runs.RunListResponsesPage = RunListResponsesPage; -runs_Runs.OutputItems = OutputItems; -runs_Runs.OutputItemListResponsesPage = OutputItemListResponsesPage; -//# sourceMappingURL=runs.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/evals/evals.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - -class Evals extends APIResource { - constructor() { - super(...arguments); - this.runs = new runs_Runs(this._client); +const log_noopLogger = { + error: log_noop, + warn: log_noop, + info: log_noop, + debug: log_noop, +}; +let log_cachedLoggers = /* @__PURE__ */ new WeakMap(); +function log_loggerFor(client) { + const logger = client.logger; + const logLevel = client.logLevel ?? 'off'; + if (!logger) { + return log_noopLogger; } - /** - * Create the structure of an evaluation that can be used to test a model's - * performance. An evaluation is a set of testing criteria and a datasource. After - * creating an evaluation, you can run it on different models and model parameters. - * We support several types of graders and datasources. For more information, see - * the [Evals guide](https://platform.openai.com/docs/guides/evals). - */ - create(body, options) { - return this._client.post('/evals', { body, ...options }); + const cachedLogger = log_cachedLoggers.get(logger); + if (cachedLogger && cachedLogger[0] === logLevel) { + return cachedLogger[1]; } - /** - * Get an evaluation by ID. - */ - retrieve(evalId, options) { - return this._client.get(`/evals/${evalId}`, options); + const levelLogger = { + error: log_makeLogFn('error', logger, logLevel), + warn: log_makeLogFn('warn', logger, logLevel), + info: log_makeLogFn('info', logger, logLevel), + debug: log_makeLogFn('debug', logger, logLevel), + }; + log_cachedLoggers.set(logger, [logLevel, levelLogger]); + return levelLogger; +} +const log_formatRequestDetails = (details) => { + if (details.options) { + details.options = { ...details.options }; + delete details.options['headers']; // redundant + leaks internals } - /** - * Update certain properties of an evaluation. - */ - update(evalId, body, options) { - return this._client.post(`/evals/${evalId}`, { body, ...options }); + if (details.headers) { + details.headers = Object.fromEntries((details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map(([name, value]) => [ + name, + (name.toLowerCase() === 'x-api-key' || + name.toLowerCase() === 'authorization' || + name.toLowerCase() === 'cookie' || + name.toLowerCase() === 'set-cookie') ? + '***' + : value, + ])); } - list(query = {}, options) { - if (isRequestOptions(query)) { - return this.list({}, query); + if ('retryOfRequestLogID' in details) { + if (details.retryOfRequestLogID) { + details.retryOf = details.retryOfRequestLogID; } - return this._client.getAPIList('/evals', EvalListResponsesPage, { query, ...options }); - } - /** - * Delete an evaluation. - */ - del(evalId, options) { - return this._client.delete(`/evals/${evalId}`, options); + delete details.retryOfRequestLogID; } -} -class EvalListResponsesPage extends CursorPage { -} -Evals.EvalListResponsesPage = EvalListResponsesPage; -Evals.Runs = runs_Runs; -Evals.RunListResponsesPage = RunListResponsesPage; -//# sourceMappingURL=evals.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/index.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -var _a; - - - - - - - - - - - - - + return details; +}; +//# sourceMappingURL=log.mjs.map +;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/core/streaming.mjs +var streaming_Stream_client; @@ -75724,2433 +70811,2324 @@ var _a; -/** - * API Client for interfacing with the OpenAI API. - */ -class OpenAI extends APIClient { - /** - * API Client for interfacing with the OpenAI API. - * - * @param {string | undefined} [opts.apiKey=process.env['OPENAI_API_KEY'] ?? undefined] - * @param {string | null | undefined} [opts.organization=process.env['OPENAI_ORG_ID'] ?? null] - * @param {string | null | undefined} [opts.project=process.env['OPENAI_PROJECT_ID'] ?? null] - * @param {string} [opts.baseURL=process.env['OPENAI_BASE_URL'] ?? https://api.openai.com/v1] - Override the default base URL for the API. - * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out. - * @param {number} [opts.httpAgent] - An HTTP agent used to manage HTTP(s) connections. - * @param {Core.Fetch} [opts.fetch] - Specify a custom `fetch` function implementation. - * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request. - * @param {Core.Headers} opts.defaultHeaders - Default headers to include with every request to the API. - * @param {Core.DefaultQuery} opts.defaultQuery - Default query parameters to include with every request to the API. - * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers. - */ - constructor({ baseURL = readEnv('OPENAI_BASE_URL'), apiKey = readEnv('OPENAI_API_KEY'), organization = readEnv('OPENAI_ORG_ID') ?? null, project = readEnv('OPENAI_PROJECT_ID') ?? null, ...opts } = {}) { - if (apiKey === undefined) { - throw new error_OpenAIError("The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' })."); - } - const options = { - apiKey, - organization, - project, - ...opts, - baseURL: baseURL || `https://api.openai.com/v1`, - }; - if (!options.dangerouslyAllowBrowser && isRunningInBrowser()) { - throw new error_OpenAIError("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew OpenAI({ apiKey, dangerouslyAllowBrowser: true });\n\nhttps://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety\n"); - } - super({ - baseURL: options.baseURL, - timeout: options.timeout ?? 600000 /* 10 minutes */, - httpAgent: options.httpAgent, - maxRetries: options.maxRetries, - fetch: options.fetch, - }); - this.completions = new Completions(this); - this.chat = new Chat(this); - this.embeddings = new Embeddings(this); - this.files = new Files(this); - this.images = new Images(this); - this.audio = new Audio(this); - this.moderations = new Moderations(this); - this.models = new Models(this); - this.fineTuning = new FineTuning(this); - this.graders = new graders_Graders(this); - this.vectorStores = new VectorStores(this); - this.beta = new Beta(this); - this.batches = new Batches(this); - this.uploads = new Uploads(this); - this.responses = new Responses(this); - this.evals = new Evals(this); - this._options = options; - this.apiKey = apiKey; - this.organization = organization; - this.project = project; - } - defaultQuery() { - return this._options.defaultQuery; - } - defaultHeaders(opts) { - return { - ...super.defaultHeaders(opts), - 'OpenAI-Organization': this.organization, - 'OpenAI-Project': this.project, - ...this._options.defaultHeaders, - }; - } - authHeaders(opts) { - return { Authorization: `Bearer ${this.apiKey}` }; +class streaming_Stream { + constructor(iterator, controller, client) { + this.iterator = iterator; + streaming_Stream_client.set(this, void 0); + this.controller = controller; + tslib_classPrivateFieldSet(this, streaming_Stream_client, client, "f"); } - stringifyQuery(query) { - return stringify(query, { arrayFormat: 'brackets' }); + static fromSSEResponse(response, controller, client) { + let consumed = false; + const logger = client ? log_loggerFor(client) : console; + async function* iterator() { + if (consumed) { + throw new error_AnthropicError('Cannot iterate over a consumed stream, use `.tee()` to split the stream.'); + } + consumed = true; + let done = false; + try { + for await (const sse of streaming_iterSSEMessages(response, controller)) { + if (sse.event === 'completion') { + try { + yield JSON.parse(sse.data); + } + catch (e) { + logger.error(`Could not parse message into JSON:`, sse.data); + logger.error(`From chunk:`, sse.raw); + throw e; + } + } + if (sse.event === 'message_start' || + sse.event === 'message_delta' || + sse.event === 'message_stop' || + sse.event === 'content_block_start' || + sse.event === 'content_block_delta' || + sse.event === 'content_block_stop') { + try { + yield JSON.parse(sse.data); + } + catch (e) { + logger.error(`Could not parse message into JSON:`, sse.data); + logger.error(`From chunk:`, sse.raw); + throw e; + } + } + if (sse.event === 'ping') { + continue; + } + if (sse.event === 'error') { + throw new error_APIError(undefined, values_safeJSON(sse.data) ?? sse.data, undefined, response.headers); + } + } + done = true; + } + catch (e) { + // If the user calls `stream.controller.abort()`, we should exit without throwing. + if (errors_isAbortError(e)) + return; + throw e; + } + finally { + // If the user `break`s, abort the ongoing request. + if (!done) + controller.abort(); + } + } + return new streaming_Stream(iterator, controller, client); } -} -_a = OpenAI; -OpenAI.OpenAI = _a; -OpenAI.DEFAULT_TIMEOUT = 600000; // 10 minutes -OpenAI.OpenAIError = error_OpenAIError; -OpenAI.APIError = APIError; -OpenAI.APIConnectionError = APIConnectionError; -OpenAI.APIConnectionTimeoutError = APIConnectionTimeoutError; -OpenAI.APIUserAbortError = APIUserAbortError; -OpenAI.NotFoundError = NotFoundError; -OpenAI.ConflictError = ConflictError; -OpenAI.RateLimitError = RateLimitError; -OpenAI.BadRequestError = BadRequestError; -OpenAI.AuthenticationError = AuthenticationError; -OpenAI.InternalServerError = InternalServerError; -OpenAI.PermissionDeniedError = PermissionDeniedError; -OpenAI.UnprocessableEntityError = UnprocessableEntityError; -OpenAI.toFile = toFile; -OpenAI.fileFromPath = fileFromPath; -OpenAI.Completions = Completions; -OpenAI.Chat = Chat; -OpenAI.ChatCompletionsPage = ChatCompletionsPage; -OpenAI.Embeddings = Embeddings; -OpenAI.Files = Files; -OpenAI.FileObjectsPage = FileObjectsPage; -OpenAI.Images = Images; -OpenAI.Audio = Audio; -OpenAI.Moderations = Moderations; -OpenAI.Models = Models; -OpenAI.ModelsPage = ModelsPage; -OpenAI.FineTuning = FineTuning; -OpenAI.Graders = graders_Graders; -OpenAI.VectorStores = VectorStores; -OpenAI.VectorStoresPage = VectorStoresPage; -OpenAI.VectorStoreSearchResponsesPage = VectorStoreSearchResponsesPage; -OpenAI.Beta = Beta; -OpenAI.Batches = Batches; -OpenAI.BatchesPage = BatchesPage; -OpenAI.Uploads = Uploads; -OpenAI.Responses = Responses; -OpenAI.Evals = Evals; -OpenAI.EvalListResponsesPage = EvalListResponsesPage; -/** API Client for interfacing with the Azure OpenAI API. */ -class AzureOpenAI extends OpenAI { /** - * API Client for interfacing with the Azure OpenAI API. - * - * @param {string | undefined} [opts.apiVersion=process.env['OPENAI_API_VERSION'] ?? undefined] - * @param {string | undefined} [opts.endpoint=process.env['AZURE_OPENAI_ENDPOINT'] ?? undefined] - Your Azure endpoint, including the resource, e.g. `https://example-resource.azure.openai.com/` - * @param {string | undefined} [opts.apiKey=process.env['AZURE_OPENAI_API_KEY'] ?? undefined] - * @param {string | undefined} opts.deployment - A model deployment, if given, sets the base client URL to include `/deployments/{deployment}`. - * @param {string | null | undefined} [opts.organization=process.env['OPENAI_ORG_ID'] ?? null] - * @param {string} [opts.baseURL=process.env['OPENAI_BASE_URL']] - Sets the base URL for the API, e.g. `https://example-resource.azure.openai.com/openai/`. - * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out. - * @param {number} [opts.httpAgent] - An HTTP agent used to manage HTTP(s) connections. - * @param {Core.Fetch} [opts.fetch] - Specify a custom `fetch` function implementation. - * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request. - * @param {Core.Headers} opts.defaultHeaders - Default headers to include with every request to the API. - * @param {Core.DefaultQuery} opts.defaultQuery - Default query parameters to include with every request to the API. - * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers. + * Generates a Stream from a newline-separated ReadableStream + * where each item is a JSON value. */ - constructor({ baseURL = readEnv('OPENAI_BASE_URL'), apiKey = readEnv('AZURE_OPENAI_API_KEY'), apiVersion = readEnv('OPENAI_API_VERSION'), endpoint, deployment, azureADTokenProvider, dangerouslyAllowBrowser, ...opts } = {}) { - if (!apiVersion) { - throw new error_OpenAIError("The OPENAI_API_VERSION environment variable is missing or empty; either provide it, or instantiate the AzureOpenAI client with an apiVersion option, like new AzureOpenAI({ apiVersion: 'My API Version' })."); - } - if (typeof azureADTokenProvider === 'function') { - dangerouslyAllowBrowser = true; - } - if (!azureADTokenProvider && !apiKey) { - throw new error_OpenAIError('Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.'); - } - if (azureADTokenProvider && apiKey) { - throw new error_OpenAIError('The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.'); - } - // define a sentinel value to avoid any typing issues - apiKey ?? (apiKey = API_KEY_SENTINEL); - opts.defaultQuery = { ...opts.defaultQuery, 'api-version': apiVersion }; - if (!baseURL) { - if (!endpoint) { - endpoint = process.env['AZURE_OPENAI_ENDPOINT']; + static fromReadableStream(readableStream, controller, client) { + let consumed = false; + async function* iterLines() { + const lineDecoder = new line_LineDecoder(); + const iter = shims_ReadableStreamToAsyncIterable(readableStream); + for await (const chunk of iter) { + for (const line of lineDecoder.decode(chunk)) { + yield line; + } } - if (!endpoint) { - throw new error_OpenAIError('Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable'); + for (const line of lineDecoder.flush()) { + yield line; } - baseURL = `${endpoint}/openai`; } - else { - if (endpoint) { - throw new error_OpenAIError('baseURL and endpoint are mutually exclusive'); + async function* iterator() { + if (consumed) { + throw new error_AnthropicError('Cannot iterate over a consumed stream, use `.tee()` to split the stream.'); + } + consumed = true; + let done = false; + try { + for await (const line of iterLines()) { + if (done) + continue; + if (line) + yield JSON.parse(line); + } + done = true; + } + catch (e) { + // If the user calls `stream.controller.abort()`, we should exit without throwing. + if (errors_isAbortError(e)) + return; + throw e; + } + finally { + // If the user `break`s, abort the ongoing request. + if (!done) + controller.abort(); } } - super({ - apiKey, - baseURL, - ...opts, - ...(dangerouslyAllowBrowser !== undefined ? { dangerouslyAllowBrowser } : {}), + return new streaming_Stream(iterator, controller, client); + } + [(streaming_Stream_client = new WeakMap(), Symbol.asyncIterator)]() { + return this.iterator(); + } + /** + * Splits the stream into two streams which can be + * independently read from at different speeds. + */ + tee() { + const left = []; + const right = []; + const iterator = this.iterator(); + const teeIterator = (queue) => { + return { + next: () => { + if (queue.length === 0) { + const result = iterator.next(); + left.push(result); + right.push(result); + } + return queue.shift(); + }, + }; + }; + return [ + new streaming_Stream(() => teeIterator(left), this.controller, tslib_classPrivateFieldGet(this, streaming_Stream_client, "f")), + new streaming_Stream(() => teeIterator(right), this.controller, tslib_classPrivateFieldGet(this, streaming_Stream_client, "f")), + ]; + } + /** + * Converts this stream to a newline-separated ReadableStream of + * JSON stringified values in the stream + * which can be turned back into a Stream with `Stream.fromReadableStream()`. + */ + toReadableStream() { + const self = this; + let iter; + return shims_makeReadableStream({ + async start() { + iter = self[Symbol.asyncIterator](); + }, + async pull(ctrl) { + try { + const { value, done } = await iter.next(); + if (done) + return ctrl.close(); + const bytes = utils_bytes_encodeUTF8(JSON.stringify(value) + '\n'); + ctrl.enqueue(bytes); + } + catch (err) { + ctrl.error(err); + } + }, + async cancel() { + await iter.return?.(); + }, }); - this.apiVersion = ''; - this._azureADTokenProvider = azureADTokenProvider; - this.apiVersion = apiVersion; - this.deploymentName = deployment; } - buildRequest(options, props = {}) { - if (_deployments_endpoints.has(options.path) && options.method === 'post' && options.body !== undefined) { - if (!isObj(options.body)) { - throw new Error('Expected request body to be an object'); - } - const model = this.deploymentName || options.body['model'] || options.__metadata?.['model']; - if (model !== undefined && !this.baseURL.includes('/deployments')) { - options.path = `/deployments/${model}${options.path}`; - } +} +async function* streaming_iterSSEMessages(response, controller) { + if (!response.body) { + controller.abort(); + if (typeof globalThis.navigator !== 'undefined' && + globalThis.navigator.product === 'ReactNative') { + throw new error_AnthropicError(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`); } - return super.buildRequest(options, props); + throw new error_AnthropicError(`Attempted to iterate over a response with no body`); } - async _getAzureADToken() { - if (typeof this._azureADTokenProvider === 'function') { - const token = await this._azureADTokenProvider(); - if (!token || typeof token !== 'string') { - throw new error_OpenAIError(`Expected 'azureADTokenProvider' argument to return a string but it returned ${token}`); - } - return token; + const sseDecoder = new streaming_SSEDecoder(); + const lineDecoder = new line_LineDecoder(); + const iter = shims_ReadableStreamToAsyncIterable(response.body); + for await (const sseChunk of streaming_iterSSEChunks(iter)) { + for (const line of lineDecoder.decode(sseChunk)) { + const sse = sseDecoder.decode(line); + if (sse) + yield sse; } - return undefined; } - authHeaders(opts) { - return {}; - } - async prepareOptions(opts) { - /** - * The user should provide a bearer token provider if they want - * to use Azure AD authentication. The user shouldn't set the - * Authorization header manually because the header is overwritten - * with the Azure AD token if a bearer token provider is provided. - */ - if (opts.headers?.['api-key']) { - return super.prepareOptions(opts); - } - const token = await this._getAzureADToken(); - opts.headers ?? (opts.headers = {}); - if (token) { - opts.headers['Authorization'] = `Bearer ${token}`; - } - else if (this.apiKey !== API_KEY_SENTINEL) { - opts.headers['api-key'] = this.apiKey; - } - else { - throw new error_OpenAIError('Unable to handle auth'); - } - return super.prepareOptions(opts); + for (const line of lineDecoder.flush()) { + const sse = sseDecoder.decode(line); + if (sse) + yield sse; } } -const _deployments_endpoints = new Set([ - '/completions', - '/chat/completions', - '/embeddings', - '/audio/transcriptions', - '/audio/translations', - '/audio/speech', - '/images/generations', -]); -const API_KEY_SENTINEL = ''; - - -/* harmony default export */ const openai = (OpenAI); -//# sourceMappingURL=index.mjs.map -;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/internal/tslib.mjs -function tslib_classPrivateFieldSet(receiver, state, value, kind, f) { - if (kind === "m") - throw new TypeError("Private method is not writable"); - if (kind === "a" && !f) - throw new TypeError("Private accessor was defined without a setter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) - throw new TypeError("Cannot write private member to an object whose class did not declare it"); - return kind === "a" ? f.call(receiver, value) : f ? (f.value = value) : state.set(receiver, value), value; -} -function tslib_classPrivateFieldGet(receiver, state, kind, f) { - if (kind === "a" && !f) - throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) - throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); -} - - -;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/internal/utils/uuid.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. /** - * https://stackoverflow.com/a/2117523 + * Given an async iterable iterator, iterates over it and yields full + * SSE chunks, i.e. yields when a double new-line is encountered. */ -let uuid_uuid4 = function () { - const { crypto } = globalThis; - if (crypto?.randomUUID) { - uuid_uuid4 = crypto.randomUUID.bind(crypto); - return crypto.randomUUID(); - } - const u8 = new Uint8Array(1); - const randomByte = crypto ? () => crypto.getRandomValues(u8)[0] : () => (Math.random() * 0xff) & 0xff; - return '10000000-1000-4000-8000-100000000000'.replace(/[018]/g, (c) => (+c ^ (randomByte() & (15 >> (+c / 4)))).toString(16)); -}; -//# sourceMappingURL=uuid.mjs.map -;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/internal/errors.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -function isAbortError(err) { - return (typeof err === 'object' && - err !== null && - // Spec-compliant fetch implementations - (('name' in err && err.name === 'AbortError') || - // Expo fetch - ('message' in err && String(err.message).includes('FetchRequestCanceledException')))); -} -const errors_castToError = (err) => { - if (err instanceof Error) - return err; - if (typeof err === 'object' && err !== null) { - try { - if (Object.prototype.toString.call(err) === '[object Error]') { - // @ts-ignore - not all envs have native support for cause yet - const error = new Error(err.message, err.cause ? { cause: err.cause } : {}); - if (err.stack) - error.stack = err.stack; - // @ts-ignore - not all envs have native support for cause yet - if (err.cause && !error.cause) - error.cause = err.cause; - if (err.name) - error.name = err.name; - return error; - } +async function* streaming_iterSSEChunks(iterator) { + let data = new Uint8Array(); + for await (const chunk of iterator) { + if (chunk == null) { + continue; } - catch { } - try { - return new Error(JSON.stringify(err)); + const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) + : typeof chunk === 'string' ? utils_bytes_encodeUTF8(chunk) + : chunk; + let newData = new Uint8Array(data.length + binaryChunk.length); + newData.set(data); + newData.set(binaryChunk, data.length); + data = newData; + let patternIndex; + while ((patternIndex = line_findDoubleNewlineIndex(data)) !== -1) { + yield data.slice(0, patternIndex); + data = data.slice(patternIndex); } - catch { } } - return new Error(err); -}; -//# sourceMappingURL=errors.mjs.map -;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/core/error.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -class error_AnthropicError extends Error { -} -class error_APIError extends error_AnthropicError { - constructor(status, error, message, headers) { - super(`${error_APIError.makeMessage(status, error, message)}`); - this.status = status; - this.headers = headers; - this.requestID = headers?.get('request-id'); - this.error = error; + if (data.length > 0) { + yield data; } - static makeMessage(status, error, message) { - const msg = error?.message ? - typeof error.message === 'string' ? - error.message - : JSON.stringify(error.message) - : error ? JSON.stringify(error) - : message; - if (status && msg) { - return `${status} ${msg}`; - } - if (status) { - return `${status} status code (no body)`; - } - if (msg) { - return msg; - } - return '(no status code or body)'; +} +class streaming_SSEDecoder { + constructor() { + this.event = null; + this.data = []; + this.chunks = []; } - static generate(status, errorResponse, message, headers) { - if (!status || !headers) { - return new error_APIConnectionError({ message, cause: errors_castToError(errorResponse) }); - } - const error = errorResponse; - if (status === 400) { - return new error_BadRequestError(status, error, message, headers); - } - if (status === 401) { - return new error_AuthenticationError(status, error, message, headers); - } - if (status === 403) { - return new error_PermissionDeniedError(status, error, message, headers); + decode(line) { + if (line.endsWith('\r')) { + line = line.substring(0, line.length - 1); } - if (status === 404) { - return new error_NotFoundError(status, error, message, headers); + if (!line) { + // empty line and we didn't previously encounter any messages + if (!this.event && !this.data.length) + return null; + const sse = { + event: this.event, + data: this.data.join('\n'), + raw: this.chunks, + }; + this.event = null; + this.data = []; + this.chunks = []; + return sse; } - if (status === 409) { - return new error_ConflictError(status, error, message, headers); + this.chunks.push(line); + if (line.startsWith(':')) { + return null; } - if (status === 422) { - return new error_UnprocessableEntityError(status, error, message, headers); + let [fieldname, _, value] = streaming_partition(line, ':'); + if (value.startsWith(' ')) { + value = value.substring(1); } - if (status === 429) { - return new error_RateLimitError(status, error, message, headers); + if (fieldname === 'event') { + this.event = value; } - if (status >= 500) { - return new error_InternalServerError(status, error, message, headers); + else if (fieldname === 'data') { + this.data.push(value); } - return new error_APIError(status, error, message, headers); + return null; } } -class error_APIUserAbortError extends error_APIError { - constructor({ message } = {}) { - super(undefined, undefined, message || 'Request was aborted.', undefined); +function streaming_partition(str, delimiter) { + const index = str.indexOf(delimiter); + if (index !== -1) { + return [str.substring(0, index), delimiter, str.substring(index + delimiter.length)]; } + return [str, '', '']; } -class error_APIConnectionError extends error_APIError { - constructor({ message, cause }) { - super(undefined, undefined, message || 'Connection error.', undefined); - // in some environments the 'cause' property is already declared - // @ts-ignore - if (cause) - this.cause = cause; - } +//# sourceMappingURL=streaming.mjs.map +;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/internal/parse.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + +async function parse_defaultParseResponse(client, props) { + const { response, requestLogID, retryOfRequestLogID, startTime } = props; + const body = await (async () => { + if (props.options.stream) { + log_loggerFor(client).debug('response', response.status, response.url, response.headers, response.body); + // Note: there is an invariant here that isn't represented in the type system + // that if you set `stream: true` the response type must also be `Stream` + if (props.options.__streamClass) { + return props.options.__streamClass.fromSSEResponse(response, props.controller); + } + return streaming_Stream.fromSSEResponse(response, props.controller); + } + // fetch refuses to read the body when the status code is 204. + if (response.status === 204) { + return null; + } + if (props.options.__binaryResponse) { + return response; + } + const contentType = response.headers.get('content-type'); + const mediaType = contentType?.split(';')[0]?.trim(); + const isJSON = mediaType?.includes('application/json') || mediaType?.endsWith('+json'); + if (isJSON) { + const json = await response.json(); + return parse_addRequestID(json, response); + } + const text = await response.text(); + return text; + })(); + log_loggerFor(client).debug(`[${requestLogID}] response parsed`, log_formatRequestDetails({ + retryOfRequestLogID, + url: response.url, + status: response.status, + body, + durationMs: Date.now() - startTime, + })); + return body; } -class error_APIConnectionTimeoutError extends error_APIConnectionError { - constructor({ message } = {}) { - super({ message: message ?? 'Request timed out.' }); +function parse_addRequestID(value, response) { + if (!value || typeof value !== 'object' || Array.isArray(value)) { + return value; } + return Object.defineProperty(value, '_request_id', { + value: response.headers.get('request-id'), + enumerable: false, + }); } -class error_BadRequestError extends error_APIError { -} -class error_AuthenticationError extends error_APIError { -} -class error_PermissionDeniedError extends error_APIError { -} -class error_NotFoundError extends error_APIError { -} -class error_ConflictError extends error_APIError { -} -class error_UnprocessableEntityError extends error_APIError { -} -class error_RateLimitError extends error_APIError { -} -class error_InternalServerError extends error_APIError { -} -//# sourceMappingURL=error.mjs.map -;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/internal/utils/values.mjs +//# sourceMappingURL=parse.mjs.map +;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/core/api-promise.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +var api_promise_APIPromise_client; -// https://url.spec.whatwg.org/#url-scheme-string -const values_startsWithSchemeRegexp = /^[a-z][a-z0-9+.-]*:/i; -const values_isAbsoluteURL = (url) => { - return values_startsWithSchemeRegexp.test(url); -}; -/** Returns an object if the given value isn't an object, otherwise returns as-is */ -function maybeObj(x) { - if (typeof x !== 'object') { - return {}; - } - return x ?? {}; -} -// https://stackoverflow.com/a/34491287 -function values_isEmptyObj(obj) { - if (!obj) - return true; - for (const _k in obj) - return false; - return true; -} -// https://eslint.org/docs/latest/rules/no-prototype-builtins -function values_hasOwn(obj, key) { - return Object.prototype.hasOwnProperty.call(obj, key); -} -function values_isObj(obj) { - return obj != null && typeof obj === 'object' && !Array.isArray(obj); -} -const values_ensurePresent = (value) => { - if (value == null) { - throw new AnthropicError(`Expected a value to be given but received ${value} instead.`); + +/** + * A subclass of `Promise` providing additional helper methods + * for interacting with the SDK. + */ +class api_promise_APIPromise extends Promise { + constructor(client, responsePromise, parseResponse = parse_defaultParseResponse) { + super((resolve) => { + // this is maybe a bit weird but this has to be a no-op to not implicitly + // parse the response body; instead .then, .catch, .finally are overridden + // to parse the response + resolve(null); + }); + this.responsePromise = responsePromise; + this.parseResponse = parseResponse; + api_promise_APIPromise_client.set(this, void 0); + tslib_classPrivateFieldSet(this, api_promise_APIPromise_client, client, "f"); } - return value; -}; -const values_validatePositiveInteger = (name, n) => { - if (typeof n !== 'number' || !Number.isInteger(n)) { - throw new error_AnthropicError(`${name} must be an integer`); + _thenUnwrap(transform) { + return new api_promise_APIPromise(tslib_classPrivateFieldGet(this, api_promise_APIPromise_client, "f"), this.responsePromise, async (client, props) => parse_addRequestID(transform(await this.parseResponse(client, props), props), props.response)); } - if (n < 0) { - throw new error_AnthropicError(`${name} must be a positive integer`); + /** + * Gets the raw `Response` instance instead of parsing the response + * data. + * + * If you want to parse the response body but still get the `Response` + * instance, you can use {@link withResponse()}. + * + * 👋 Getting the wrong TypeScript type for `Response`? + * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]` + * to your `tsconfig.json`. + */ + asResponse() { + return this.responsePromise.then((p) => p.response); } - return n; -}; -const values_coerceInteger = (value) => { - if (typeof value === 'number') - return Math.round(value); - if (typeof value === 'string') - return parseInt(value, 10); - throw new AnthropicError(`Could not coerce ${value} (type: ${typeof value}) into a number`); -}; -const values_coerceFloat = (value) => { - if (typeof value === 'number') - return value; - if (typeof value === 'string') - return parseFloat(value); - throw new AnthropicError(`Could not coerce ${value} (type: ${typeof value}) into a number`); -}; -const values_coerceBoolean = (value) => { - if (typeof value === 'boolean') - return value; - if (typeof value === 'string') - return value === 'true'; - return Boolean(value); -}; -const values_maybeCoerceInteger = (value) => { - if (value === undefined) { - return undefined; + /** + * Gets the parsed response data, the raw `Response` instance and the ID of the request, + * returned via the `request-id` header which is useful for debugging requests and resporting + * issues to Anthropic. + * + * If you just want to get the raw `Response` instance without parsing it, + * you can use {@link asResponse()}. + * + * 👋 Getting the wrong TypeScript type for `Response`? + * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]` + * to your `tsconfig.json`. + */ + async withResponse() { + const [data, response] = await Promise.all([this.parse(), this.asResponse()]); + return { data, response, request_id: response.headers.get('request-id') }; } - return values_coerceInteger(value); -}; -const values_maybeCoerceFloat = (value) => { - if (value === undefined) { - return undefined; + parse() { + if (!this.parsedPromise) { + this.parsedPromise = this.responsePromise.then((data) => this.parseResponse(tslib_classPrivateFieldGet(this, api_promise_APIPromise_client, "f"), data)); + } + return this.parsedPromise; } - return values_coerceFloat(value); -}; -const values_maybeCoerceBoolean = (value) => { - if (value === undefined) { - return undefined; + then(onfulfilled, onrejected) { + return this.parse().then(onfulfilled, onrejected); } - return values_coerceBoolean(value); -}; -const values_safeJSON = (text) => { - try { - return JSON.parse(text); + catch(onrejected) { + return this.parse().catch(onrejected); } - catch (err) { - return undefined; + finally(onfinally) { + return this.parse().finally(onfinally); } -}; -//# sourceMappingURL=values.mjs.map -;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/internal/utils/sleep.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -const sleep_sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); -//# sourceMappingURL=sleep.mjs.map -;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/internal/utils/log.mjs +} +api_promise_APIPromise_client = new WeakMap(); +//# sourceMappingURL=api-promise.mjs.map +;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/core/pagination.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +var pagination_AbstractPage_client; -const levelNumbers = { - off: 0, - error: 200, - warn: 300, - info: 400, - debug: 500, -}; -const parseLogLevel = (maybeLevel, sourceName, client) => { - if (!maybeLevel) { - return undefined; + + + + +class pagination_AbstractPage { + constructor(client, response, body, options) { + pagination_AbstractPage_client.set(this, void 0); + tslib_classPrivateFieldSet(this, pagination_AbstractPage_client, client, "f"); + this.options = options; + this.response = response; + this.body = body; } - if (values_hasOwn(levelNumbers, maybeLevel)) { - return maybeLevel; + hasNextPage() { + const items = this.getPaginatedItems(); + if (!items.length) + return false; + return this.nextPageRequestOptions() != null; + } + async getNextPage() { + const nextOptions = this.nextPageRequestOptions(); + if (!nextOptions) { + throw new error_AnthropicError('No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.'); + } + return await tslib_classPrivateFieldGet(this, pagination_AbstractPage_client, "f").requestAPIList(this.constructor, nextOptions); } - loggerFor(client).warn(`${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(Object.keys(levelNumbers))}`); - return undefined; -}; -function noop() { } -function makeLogFn(fnLevel, logger, logLevel) { - if (!logger || levelNumbers[fnLevel] > levelNumbers[logLevel]) { - return noop; + async *iterPages() { + let page = this; + yield page; + while (page.hasNextPage()) { + page = await page.getNextPage(); + yield page; + } } - else { - // Don't wrap logger functions, we want the stacktrace intact! - return logger[fnLevel].bind(logger); + async *[(pagination_AbstractPage_client = new WeakMap(), Symbol.asyncIterator)]() { + for await (const page of this.iterPages()) { + for (const item of page.getPaginatedItems()) { + yield item; + } + } } } -const noopLogger = { - error: noop, - warn: noop, - info: noop, - debug: noop, -}; -let cachedLoggers = new WeakMap(); -function loggerFor(client) { - const logger = client.logger; - const logLevel = client.logLevel ?? 'off'; - if (!logger) { - return noopLogger; +/** + * This subclass of Promise will resolve to an instantiated Page once the request completes. + * + * It also implements AsyncIterable to allow auto-paginating iteration on an unawaited list call, eg: + * + * for await (const item of client.items.list()) { + * console.log(item) + * } + */ +class pagination_PagePromise extends api_promise_APIPromise { + constructor(client, request, Page) { + super(client, request, async (client, props) => new Page(client, props.response, await parse_defaultParseResponse(client, props), props.options)); } - const cachedLogger = cachedLoggers.get(logger); - if (cachedLogger && cachedLogger[0] === logLevel) { - return cachedLogger[1]; + /** + * Allow auto-paginating iteration on an unawaited list call, eg: + * + * for await (const item of client.items.list()) { + * console.log(item) + * } + */ + async *[Symbol.asyncIterator]() { + const page = await this; + for await (const item of page) { + yield item; + } } - const levelLogger = { - error: makeLogFn('error', logger, logLevel), - warn: makeLogFn('warn', logger, logLevel), - info: makeLogFn('info', logger, logLevel), - debug: makeLogFn('debug', logger, logLevel), - }; - cachedLoggers.set(logger, [logLevel, levelLogger]); - return levelLogger; } -const formatRequestDetails = (details) => { - if (details.options) { - details.options = { ...details.options }; - delete details.options['headers']; // redundant + leaks internals +class pagination_Page extends pagination_AbstractPage { + constructor(client, response, body, options) { + super(client, response, body, options); + this.data = body.data || []; + this.has_more = body.has_more || false; + this.first_id = body.first_id || null; + this.last_id = body.last_id || null; } - if (details.headers) { - details.headers = Object.fromEntries((details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map(([name, value]) => [ - name, - (name.toLowerCase() === 'x-api-key' || - name.toLowerCase() === 'authorization' || - name.toLowerCase() === 'cookie' || - name.toLowerCase() === 'set-cookie') ? - '***' - : value, - ])); + getPaginatedItems() { + return this.data ?? []; } - if ('retryOfRequestLogID' in details) { - if (details.retryOfRequestLogID) { - details.retryOf = details.retryOfRequestLogID; + hasNextPage() { + if (this.has_more === false) { + return false; } - delete details.retryOfRequestLogID; + return super.hasNextPage(); } - return details; -}; -//# sourceMappingURL=log.mjs.map -;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/version.mjs -const version_VERSION = '0.50.4'; // x-release-please-version -//# sourceMappingURL=version.mjs.map -;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/internal/detect-platform.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + nextPageRequestOptions() { + if (this.options.query?.['before_id']) { + // in reverse + const first_id = this.first_id; + if (!first_id) { + return null; + } + return { + ...this.options, + query: { + ...values_maybeObj(this.options.query), + before_id: first_id, + }, + }; + } + const cursor = this.last_id; + if (!cursor) { + return null; + } + return { + ...this.options, + query: { + ...values_maybeObj(this.options.query), + after_id: cursor, + }, + }; + } +} +//# sourceMappingURL=pagination.mjs.map +;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/internal/uploads.mjs -const detect_platform_isRunningInBrowser = () => { - return ( - // @ts-ignore - typeof window !== 'undefined' && - // @ts-ignore - typeof window.document !== 'undefined' && - // @ts-ignore - typeof navigator !== 'undefined'); +const uploads_checkFileSupport = () => { + if (typeof File === 'undefined') { + const { process } = globalThis; + const isOldNode = typeof process?.versions?.node === 'string' && parseInt(process.versions.node.split('.')) < 20; + throw new Error('`File` is not defined as a global, which is required for file uploads.' + + (isOldNode ? + " Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`." + : '')); + } }; /** - * Note this does not detect 'browser'; for that, use getBrowserInfo(). + * Construct a `File` instance. This is used to ensure a helpful error is thrown + * for environments that don't define a global `File` yet. */ -function getDetectedPlatform() { - if (typeof Deno !== 'undefined' && Deno.build != null) { - return 'deno'; - } - if (typeof EdgeRuntime !== 'undefined') { - return 'edge'; +function uploads_makeFile(fileBits, fileName, options) { + uploads_checkFileSupport(); + return new File(fileBits, fileName ?? 'unknown_file', options); +} +function uploads_getName(value) { + return (((typeof value === 'object' && + value !== null && + (('name' in value && value.name && String(value.name)) || + ('url' in value && value.url && String(value.url)) || + ('filename' in value && value.filename && String(value.filename)) || + ('path' in value && value.path && String(value.path)))) || + '') + .split(/[\\/]/) + .pop() || undefined); +} +const uploads_isAsyncIterable = (value) => value != null && typeof value === 'object' && typeof value[Symbol.asyncIterator] === 'function'; +/** + * Returns a multipart/form-data request if any part of the given request body contains a File / Blob value. + * Otherwise returns the request as is. + */ +const uploads_maybeMultipartFormRequestOptions = async (opts, fetch) => { + if (!uploads_hasUploadableValue(opts.body)) + return opts; + return { ...opts, body: await uploads_createForm(opts.body, fetch) }; +}; +const uploads_multipartFormRequestOptions = async (opts, fetch) => { + return { ...opts, body: await uploads_createForm(opts.body, fetch) }; +}; +const uploads_supportsFormDataMap = /* @__PURE__ */ new WeakMap(); +/** + * node-fetch doesn't support the global FormData object in recent node versions. Instead of sending + * properly-encoded form data, it just stringifies the object, resulting in a request body of "[object FormData]". + * This function detects if the fetch function provided supports the global FormData object to avoid + * confusing error messages later on. + */ +function uploads_supportsFormData(fetchObject) { + const fetch = typeof fetchObject === 'function' ? fetchObject : fetchObject.fetch; + const cached = uploads_supportsFormDataMap.get(fetch); + if (cached) + return cached; + const promise = (async () => { + try { + const FetchResponse = ('Response' in fetch ? + fetch.Response + : (await fetch('data:,')).constructor); + const data = new FormData(); + if (data.toString() === (await new FetchResponse(data).text())) { + return false; + } + return true; + } + catch { + // avoid false negatives + return true; + } + })(); + uploads_supportsFormDataMap.set(fetch, promise); + return promise; +} +const uploads_createForm = async (body, fetch) => { + if (!(await uploads_supportsFormData(fetch))) { + throw new TypeError('The provided fetch function does not support file uploads with the current global FormData class.'); } - if (Object.prototype.toString.call(typeof globalThis.process !== 'undefined' ? globalThis.process : 0) === '[object process]') { - return 'node'; + const form = new FormData(); + await Promise.all(Object.entries(body || {}).map(([key, value]) => uploads_addFormValue(form, key, value))); + return form; +}; +// We check for Blob not File because Bun.File doesn't inherit from File, +// but they both inherit from Blob and have a `name` property at runtime. +const uploads_isNamedBlob = (value) => value instanceof Blob && 'name' in value; +const uploads_isUploadable = (value) => typeof value === 'object' && + value !== null && + (value instanceof Response || uploads_isAsyncIterable(value) || uploads_isNamedBlob(value)); +const uploads_hasUploadableValue = (value) => { + if (uploads_isUploadable(value)) + return true; + if (Array.isArray(value)) + return value.some(uploads_hasUploadableValue); + if (value && typeof value === 'object') { + for (const k in value) { + if (uploads_hasUploadableValue(value[k])) + return true; + } } - return 'unknown'; -} -const detect_platform_getPlatformProperties = () => { - const detectedPlatform = getDetectedPlatform(); - if (detectedPlatform === 'deno') { - return { - 'X-Stainless-Lang': 'js', - 'X-Stainless-Package-Version': version_VERSION, - 'X-Stainless-OS': detect_platform_normalizePlatform(Deno.build.os), - 'X-Stainless-Arch': detect_platform_normalizeArch(Deno.build.arch), - 'X-Stainless-Runtime': 'deno', - 'X-Stainless-Runtime-Version': typeof Deno.version === 'string' ? Deno.version : Deno.version?.deno ?? 'unknown', - }; + return false; +}; +const uploads_addFormValue = async (form, key, value) => { + if (value === undefined) + return; + if (value == null) { + throw new TypeError(`Received null for "${key}"; to pass null in FormData, you must use the string 'null'`); } - if (typeof EdgeRuntime !== 'undefined') { - return { - 'X-Stainless-Lang': 'js', - 'X-Stainless-Package-Version': version_VERSION, - 'X-Stainless-OS': 'Unknown', - 'X-Stainless-Arch': `other:${EdgeRuntime}`, - 'X-Stainless-Runtime': 'edge', - 'X-Stainless-Runtime-Version': globalThis.process.version, - }; + // TODO: make nested formats configurable + if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { + form.append(key, String(value)); } - // Check if Node.js - if (detectedPlatform === 'node') { - return { - 'X-Stainless-Lang': 'js', - 'X-Stainless-Package-Version': version_VERSION, - 'X-Stainless-OS': detect_platform_normalizePlatform(globalThis.process.platform), - 'X-Stainless-Arch': detect_platform_normalizeArch(globalThis.process.arch), - 'X-Stainless-Runtime': 'node', - 'X-Stainless-Runtime-Version': globalThis.process.version, - }; + else if (value instanceof Response) { + let options = {}; + const contentType = value.headers.get('Content-Type'); + if (contentType) { + options = { type: contentType }; + } + form.append(key, uploads_makeFile([await value.blob()], uploads_getName(value), options)); } - const browserInfo = detect_platform_getBrowserInfo(); - if (browserInfo) { - return { - 'X-Stainless-Lang': 'js', - 'X-Stainless-Package-Version': version_VERSION, - 'X-Stainless-OS': 'Unknown', - 'X-Stainless-Arch': 'unknown', - 'X-Stainless-Runtime': `browser:${browserInfo.browser}`, - 'X-Stainless-Runtime-Version': browserInfo.version, - }; + else if (uploads_isAsyncIterable(value)) { + form.append(key, uploads_makeFile([await new Response(shims_ReadableStreamFrom(value)).blob()], uploads_getName(value))); } - // TODO add support for Cloudflare workers, etc. - return { - 'X-Stainless-Lang': 'js', - 'X-Stainless-Package-Version': version_VERSION, - 'X-Stainless-OS': 'Unknown', - 'X-Stainless-Arch': 'unknown', - 'X-Stainless-Runtime': 'unknown', - 'X-Stainless-Runtime-Version': 'unknown', - }; -}; -// Note: modified from https://github.com/JS-DevTools/host-environment/blob/b1ab79ecde37db5d6e163c050e54fe7d287d7c92/src/isomorphic.browser.ts -function detect_platform_getBrowserInfo() { - if (typeof navigator === 'undefined' || !navigator) { - return null; + else if (uploads_isNamedBlob(value)) { + form.append(key, uploads_makeFile([value], uploads_getName(value), { type: value.type })); } - // NOTE: The order matters here! - const browserPatterns = [ - { key: 'edge', pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, - { key: 'ie', pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, - { key: 'ie', pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ }, - { key: 'chrome', pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, - { key: 'firefox', pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, - { key: 'safari', pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ }, - ]; - // Find the FIRST matching browser - for (const { key, pattern } of browserPatterns) { - const match = pattern.exec(navigator.userAgent); - if (match) { - const major = match[1] || 0; - const minor = match[2] || 0; - const patch = match[3] || 0; - return { browser: key, version: `${major}.${minor}.${patch}` }; - } + else if (Array.isArray(value)) { + await Promise.all(value.map((entry) => uploads_addFormValue(form, key + '[]', entry))); } - return null; -} -const detect_platform_normalizeArch = (arch) => { - // Node docs: - // - https://nodejs.org/api/process.html#processarch - // Deno docs: - // - https://doc.deno.land/deno/stable/~/Deno.build - if (arch === 'x32') - return 'x32'; - if (arch === 'x86_64' || arch === 'x64') - return 'x64'; - if (arch === 'arm') - return 'arm'; - if (arch === 'aarch64' || arch === 'arm64') - return 'arm64'; - if (arch) - return `other:${arch}`; - return 'unknown'; -}; -const detect_platform_normalizePlatform = (platform) => { - // Node platforms: - // - https://nodejs.org/api/process.html#processplatform - // Deno platforms: - // - https://doc.deno.land/deno/stable/~/Deno.build - // - https://github.com/denoland/deno/issues/14799 - platform = platform.toLowerCase(); - // NOTE: this iOS check is untested and may not work - // Node does not work natively on IOS, there is a fork at - // https://github.com/nodejs-mobile/nodejs-mobile - // however it is unknown at the time of writing how to detect if it is running - if (platform.includes('ios')) - return 'iOS'; - if (platform === 'android') - return 'Android'; - if (platform === 'darwin') - return 'MacOS'; - if (platform === 'win32') - return 'Windows'; - if (platform === 'freebsd') - return 'FreeBSD'; - if (platform === 'openbsd') - return 'OpenBSD'; - if (platform === 'linux') - return 'Linux'; - if (platform) - return `Other:${platform}`; - return 'Unknown'; -}; -let detect_platform_platformHeaders; -const detect_platform_getPlatformHeaders = () => { - return (detect_platform_platformHeaders ?? (detect_platform_platformHeaders = detect_platform_getPlatformProperties())); -}; -//# sourceMappingURL=detect-platform.mjs.map -;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/internal/shims.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -function getDefaultFetch() { - if (typeof fetch !== 'undefined') { - return fetch; + else if (typeof value === 'object') { + await Promise.all(Object.entries(value).map(([name, prop]) => uploads_addFormValue(form, `${key}[${name}]`, prop))); } - throw new Error('`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`'); -} -function makeReadableStream(...args) { - const ReadableStream = globalThis.ReadableStream; - if (typeof ReadableStream === 'undefined') { - // Note: All of the platforms / runtimes we officially support already define - // `ReadableStream` as a global, so this should only ever be hit on unsupported runtimes. - throw new Error('`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`'); + else { + throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`); } - return new ReadableStream(...args); -} -function shims_ReadableStreamFrom(iterable) { - let iter = Symbol.asyncIterator in iterable ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator](); - return makeReadableStream({ - start() { }, - async pull(controller) { - const { done, value } = await iter.next(); - if (done) { - controller.close(); - } - else { - controller.enqueue(value); - } - }, - async cancel() { - await iter.return?.(); - }, - }); -} +}; +//# sourceMappingURL=uploads.mjs.map +;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/internal/to-file.mjs + + /** - * Most browsers don't yet have async iterable support for ReadableStream, - * and Node has a very different way of reading bytes from its "ReadableStream". - * - * This polyfill was pulled from https://github.com/MattiasBuelens/web-streams-polyfill/pull/122#issuecomment-1627354490 + * This check adds the arrayBuffer() method type because it is available and used at runtime */ -function shims_ReadableStreamToAsyncIterable(stream) { - if (stream[Symbol.asyncIterator]) - return stream; - const reader = stream.getReader(); - return { - async next() { - try { - const result = await reader.read(); - if (result?.done) - reader.releaseLock(); // release lock when stream becomes closed - return result; - } - catch (e) { - reader.releaseLock(); // release lock when stream becomes errored - throw e; - } - }, - async return() { - const cancelPromise = reader.cancel(); - reader.releaseLock(); - await cancelPromise; - return { done: true, value: undefined }; - }, - [Symbol.asyncIterator]() { - return this; - }, - }; -} +const to_file_isBlobLike = (value) => value != null && + typeof value === 'object' && + typeof value.size === 'number' && + typeof value.type === 'string' && + typeof value.text === 'function' && + typeof value.slice === 'function' && + typeof value.arrayBuffer === 'function'; /** - * Cancels a ReadableStream we don't need to consume. - * See https://undici.nodejs.org/#/?id=garbage-collection + * This check adds the arrayBuffer() method type because it is available and used at runtime */ -async function CancelReadableStream(stream) { - if (stream === null || typeof stream !== 'object') - return; - if (stream[Symbol.asyncIterator]) { - await stream[Symbol.asyncIterator]().return?.(); - return; - } - const reader = stream.getReader(); - const cancelPromise = reader.cancel(); - reader.releaseLock(); - await cancelPromise; -} -//# sourceMappingURL=shims.mjs.map -;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/internal/request-options.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -const FallbackEncoder = ({ headers, body }) => { - return { - bodyHeaders: { - 'content-type': 'application/json', - }, - body: JSON.stringify(body), - }; -}; -//# sourceMappingURL=request-options.mjs.map -;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/internal/utils/bytes.mjs -function concatBytes(buffers) { - let length = 0; - for (const buffer of buffers) { - length += buffer.length; +const to_file_isFileLike = (value) => value != null && + typeof value === 'object' && + typeof value.name === 'string' && + typeof value.lastModified === 'number' && + to_file_isBlobLike(value); +const to_file_isResponseLike = (value) => value != null && + typeof value === 'object' && + typeof value.url === 'string' && + typeof value.blob === 'function'; +/** + * Helper for creating a {@link File} to pass to an SDK upload method from a variety of different data formats + * @param value the raw content of the file. Can be an {@link Uploadable}, {@link BlobLikePart}, or {@link AsyncIterable} of {@link BlobLikePart}s + * @param {string=} name the name of the file. If omitted, toFile will try to determine a file name from bits if possible + * @param {Object=} options additional properties + * @param {string=} options.type the MIME type of the content + * @param {number=} options.lastModified the last modified timestamp + * @returns a {@link File} with the given properties + */ +async function to_file_toFile(value, name, options) { + uploads_checkFileSupport(); + // If it's a promise, resolve it. + value = await value; + name || (name = uploads_getName(value)); + // If we've been given a `File` we don't need to do anything if the name / options + // have not been customised. + if (to_file_isFileLike(value)) { + if (value instanceof File && name == null && options == null) { + return value; + } + return uploads_makeFile([await value.arrayBuffer()], name ?? value.name, { + type: value.type, + lastModified: value.lastModified, + ...options, + }); } - const output = new Uint8Array(length); - let index = 0; - for (const buffer of buffers) { - output.set(buffer, index); - index += buffer.length; + if (to_file_isResponseLike(value)) { + const blob = await value.blob(); + name || (name = new URL(value.url).pathname.split(/[\\/]/).pop()); + return uploads_makeFile(await to_file_getBytes(blob), name, options); } - return output; + const parts = await to_file_getBytes(value); + if (!options?.type) { + const type = parts.find((part) => typeof part === 'object' && 'type' in part && part.type); + if (typeof type === 'string') { + options = { ...options, type }; + } + } + return uploads_makeFile(parts, name, options); } -let encodeUTF8_; -function encodeUTF8(str) { - let encoder; - return (encodeUTF8_ ?? - ((encoder = new globalThis.TextEncoder()), (encodeUTF8_ = encoder.encode.bind(encoder))))(str); +async function to_file_getBytes(value) { + let parts = []; + if (typeof value === 'string' || + ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc. + value instanceof ArrayBuffer) { + parts.push(value); + } + else if (to_file_isBlobLike(value)) { + parts.push(value instanceof Blob ? value : await value.arrayBuffer()); + } + else if (uploads_isAsyncIterable(value) // includes Readable, ReadableStream, etc. + ) { + for await (const chunk of value) { + parts.push(...(await to_file_getBytes(chunk))); // TODO, consider validating? + } + } + else { + const constructor = value?.constructor?.name; + throw new Error(`Unexpected data type: ${typeof value}${constructor ? `; constructor: ${constructor}` : ''}${to_file_propsForError(value)}`); + } + return parts; } -let decodeUTF8_; -function decodeUTF8(bytes) { - let decoder; - return (decodeUTF8_ ?? - ((decoder = new globalThis.TextDecoder()), (decodeUTF8_ = decoder.decode.bind(decoder))))(bytes); +function to_file_propsForError(value) { + if (typeof value !== 'object' || value === null) + return ''; + const props = Object.getOwnPropertyNames(value); + return `; props: [${props.map((p) => `"${p}"`).join(', ')}]`; } -//# sourceMappingURL=bytes.mjs.map -;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/internal/decoders/line.mjs -var _LineDecoder_buffer, line_LineDecoder_carriageReturnIndex; - +//# sourceMappingURL=to-file.mjs.map +;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/core/uploads.mjs -/** - * A re-implementation of httpx's `LineDecoder` in Python that handles incrementally - * reading lines from text. - * - * https://github.com/encode/httpx/blob/920333ea98118e9cf617f246905d7b202510941c/httpx/_decoders.py#L258 - */ -class line_LineDecoder { - constructor() { - _LineDecoder_buffer.set(this, void 0); - line_LineDecoder_carriageReturnIndex.set(this, void 0); - tslib_classPrivateFieldSet(this, _LineDecoder_buffer, new Uint8Array(), "f"); - tslib_classPrivateFieldSet(this, line_LineDecoder_carriageReturnIndex, null, "f"); +//# sourceMappingURL=uploads.mjs.map +;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/core/resource.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +class resource_APIResource { + constructor(client) { + this._client = client; } - decode(chunk) { - if (chunk == null) { - return []; +} +//# sourceMappingURL=resource.mjs.map +;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/internal/headers.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +const headers_brand_privateNullableHeaders = Symbol.for('brand.privateNullableHeaders'); +function* headers_iterateHeaders(headers) { + if (!headers) + return; + if (headers_brand_privateNullableHeaders in headers) { + const { values, nulls } = headers; + yield* values.entries(); + for (const name of nulls) { + yield [name, null]; } - const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) - : typeof chunk === 'string' ? encodeUTF8(chunk) - : chunk; - tslib_classPrivateFieldSet(this, _LineDecoder_buffer, concatBytes([tslib_classPrivateFieldGet(this, _LineDecoder_buffer, "f"), binaryChunk]), "f"); - const lines = []; - let patternIndex; - while ((patternIndex = line_findNewlineIndex(tslib_classPrivateFieldGet(this, _LineDecoder_buffer, "f"), tslib_classPrivateFieldGet(this, line_LineDecoder_carriageReturnIndex, "f"))) != null) { - if (patternIndex.carriage && tslib_classPrivateFieldGet(this, line_LineDecoder_carriageReturnIndex, "f") == null) { - // skip until we either get a corresponding `\n`, a new `\r` or nothing - tslib_classPrivateFieldSet(this, line_LineDecoder_carriageReturnIndex, patternIndex.index, "f"); - continue; - } - // we got double \r or \rtext\n - if (tslib_classPrivateFieldGet(this, line_LineDecoder_carriageReturnIndex, "f") != null && - (patternIndex.index !== tslib_classPrivateFieldGet(this, line_LineDecoder_carriageReturnIndex, "f") + 1 || patternIndex.carriage)) { - lines.push(decodeUTF8(tslib_classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(0, tslib_classPrivateFieldGet(this, line_LineDecoder_carriageReturnIndex, "f") - 1))); - tslib_classPrivateFieldSet(this, _LineDecoder_buffer, tslib_classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(tslib_classPrivateFieldGet(this, line_LineDecoder_carriageReturnIndex, "f")), "f"); - tslib_classPrivateFieldSet(this, line_LineDecoder_carriageReturnIndex, null, "f"); + return; + } + let shouldClear = false; + let iter; + if (headers instanceof Headers) { + iter = headers.entries(); + } + else if (values_isReadonlyArray(headers)) { + iter = headers; + } + else { + shouldClear = true; + iter = Object.entries(headers ?? {}); + } + for (let row of iter) { + const name = row[0]; + if (typeof name !== 'string') + throw new TypeError('expected header name to be a string'); + const values = values_isReadonlyArray(row[1]) ? row[1] : [row[1]]; + let didClear = false; + for (const value of values) { + if (value === undefined) continue; + // Objects keys always overwrite older headers, they never append. + // Yield a null to clear the header before adding the new values. + if (shouldClear && !didClear) { + didClear = true; + yield [name, null]; } - const endIndex = tslib_classPrivateFieldGet(this, line_LineDecoder_carriageReturnIndex, "f") !== null ? patternIndex.preceding - 1 : patternIndex.preceding; - const line = decodeUTF8(tslib_classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(0, endIndex)); - lines.push(line); - tslib_classPrivateFieldSet(this, _LineDecoder_buffer, tslib_classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(patternIndex.index), "f"); - tslib_classPrivateFieldSet(this, line_LineDecoder_carriageReturnIndex, null, "f"); + yield [name, value]; } - return lines; } - flush() { - if (!tslib_classPrivateFieldGet(this, _LineDecoder_buffer, "f").length) { - return []; +} +const headers_buildHeaders = (newHeaders) => { + const targetHeaders = new Headers(); + const nullHeaders = new Set(); + for (const headers of newHeaders) { + const seenHeaders = new Set(); + for (const [name, value] of headers_iterateHeaders(headers)) { + const lowerName = name.toLowerCase(); + if (!seenHeaders.has(lowerName)) { + targetHeaders.delete(name); + seenHeaders.add(lowerName); + } + if (value === null) { + targetHeaders.delete(name); + nullHeaders.add(lowerName); + } + else { + targetHeaders.append(name, value); + nullHeaders.delete(lowerName); + } } - return this.decode('\n'); } -} -_LineDecoder_buffer = new WeakMap(), line_LineDecoder_carriageReturnIndex = new WeakMap(); -// prettier-ignore -line_LineDecoder.NEWLINE_CHARS = new Set(['\n', '\r']); -line_LineDecoder.NEWLINE_REGEXP = /\r\n|[\n\r]/g; + return { [headers_brand_privateNullableHeaders]: true, values: targetHeaders, nulls: nullHeaders }; +}; +const headers_isEmptyHeaders = (headers) => { + for (const _ of headers_iterateHeaders(headers)) + return false; + return true; +}; +//# sourceMappingURL=headers.mjs.map +;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/internal/utils/path.mjs + /** - * This function searches the buffer for the end patterns, (\r or \n) - * and returns an object with the index preceding the matched newline and the - * index after the newline char. `null` is returned if no new line is found. + * Percent-encode everything that isn't safe to have in a path without encoding safe chars. * - * ```ts - * findNewLineIndex('abc\ndef') -> { preceding: 2, index: 3 } - * ``` + * Taken from https://datatracker.ietf.org/doc/html/rfc3986#section-3.3: + * > unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" + * > sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "=" + * > pchar = unreserved / pct-encoded / sub-delims / ":" / "@" */ -function line_findNewlineIndex(buffer, startIndex) { - const newline = 0x0a; // \n - const carriage = 0x0d; // \r - for (let i = startIndex ?? 0; i < buffer.length; i++) { - if (buffer[i] === newline) { - return { preceding: i, index: i + 1, carriage: false }; - } - if (buffer[i] === carriage) { - return { preceding: i, index: i + 1, carriage: true }; - } - } - return null; +function path_encodeURIPath(str) { + return str.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g, encodeURIComponent); } -function line_findDoubleNewlineIndex(buffer) { - // This function searches the buffer for the end patterns (\r\r, \n\n, \r\n\r\n) - // and returns the index right after the first occurrence of any pattern, - // or -1 if none of the patterns are found. - const newline = 0x0a; // \n - const carriage = 0x0d; // \r - for (let i = 0; i < buffer.length - 1; i++) { - if (buffer[i] === newline && buffer[i + 1] === newline) { - // \n\n - return i + 2; - } - if (buffer[i] === carriage && buffer[i + 1] === carriage) { - // \r\r - return i + 2; +const path_EMPTY = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.create(null)); +const path_createPathTagFunction = (pathEncoder = path_encodeURIPath) => function path(statics, ...params) { + // If there are no params, no processing is needed. + if (statics.length === 1) + return statics[0]; + let postPath = false; + const invalidSegments = []; + const path = statics.reduce((previousValue, currentValue, index) => { + if (/[?#]/.test(currentValue)) { + postPath = true; } - if (buffer[i] === carriage && - buffer[i + 1] === newline && - i + 3 < buffer.length && - buffer[i + 2] === carriage && - buffer[i + 3] === newline) { - // \r\n\r\n - return i + 4; + const value = params[index]; + let encoded = (postPath ? encodeURIComponent : pathEncoder)('' + value); + if (index !== params.length && + (value == null || + (typeof value === 'object' && + // handle values from other realms + value.toString === + Object.getPrototypeOf(Object.getPrototypeOf(value.hasOwnProperty ?? path_EMPTY) ?? path_EMPTY) + ?.toString))) { + encoded = value + ''; + invalidSegments.push({ + start: previousValue.length + currentValue.length, + length: encoded.length, + error: `Value of type ${Object.prototype.toString + .call(value) + .slice(8, -1)} is not a valid path parameter`, + }); } + return previousValue + currentValue + (index === params.length ? '' : encoded); + }, ''); + const pathOnly = path.split(/[?#]/, 1)[0]; + const invalidSegmentPattern = /(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi; + let match; + // Find all invalid segments + while ((match = invalidSegmentPattern.exec(pathOnly)) !== null) { + invalidSegments.push({ + start: match.index, + length: match[0].length, + error: `Value "${match[0]}" can\'t be safely passed as a path parameter`, + }); } - return -1; -} -//# sourceMappingURL=line.mjs.map -;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/core/streaming.mjs - - - + invalidSegments.sort((a, b) => a.start - b.start); + if (invalidSegments.length > 0) { + let lastEnd = 0; + const underline = invalidSegments.reduce((acc, segment) => { + const spaces = ' '.repeat(segment.start - lastEnd); + const arrows = '^'.repeat(segment.length); + lastEnd = segment.start + segment.length; + return acc + spaces + arrows; + }, ''); + throw new error_AnthropicError(`Path parameters result in path with invalid segments:\n${invalidSegments + .map((e) => e.error) + .join('\n')}\n${path}\n${underline}`); + } + return path; +}; +/** + * URI-encodes path params and ensures no unsafe /./ or /../ path segments are introduced. + */ +const path_path = /* @__PURE__ */ path_createPathTagFunction(path_encodeURIPath); +//# sourceMappingURL=path.mjs.map +;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/resources/beta/files.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -class streaming_Stream { - constructor(iterator, controller) { - this.iterator = iterator; - this.controller = controller; - } - static fromSSEResponse(response, controller) { - let consumed = false; - async function* iterator() { - if (consumed) { - throw new error_AnthropicError('Cannot iterate over a consumed stream, use `.tee()` to split the stream.'); - } - consumed = true; - let done = false; - try { - for await (const sse of streaming_iterSSEMessages(response, controller)) { - if (sse.event === 'completion') { - try { - yield JSON.parse(sse.data); - } - catch (e) { - console.error(`Could not parse message into JSON:`, sse.data); - console.error(`From chunk:`, sse.raw); - throw e; - } - } - if (sse.event === 'message_start' || - sse.event === 'message_delta' || - sse.event === 'message_stop' || - sse.event === 'content_block_start' || - sse.event === 'content_block_delta' || - sse.event === 'content_block_stop') { - try { - yield JSON.parse(sse.data); - } - catch (e) { - console.error(`Could not parse message into JSON:`, sse.data); - console.error(`From chunk:`, sse.raw); - throw e; - } - } - if (sse.event === 'ping') { - continue; - } - if (sse.event === 'error') { - throw new error_APIError(undefined, values_safeJSON(sse.data) ?? sse.data, undefined, response.headers); - } - } - done = true; - } - catch (e) { - // If the user calls `stream.controller.abort()`, we should exit without throwing. - if (isAbortError(e)) - return; - throw e; - } - finally { - // If the user `break`s, abort the ongoing request. - if (!done) - controller.abort(); - } - } - return new streaming_Stream(iterator, controller); - } +class beta_files_Files extends resource_APIResource { /** - * Generates a Stream from a newline-separated ReadableStream - * where each item is a JSON value. + * List Files + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const fileMetadata of client.beta.files.list()) { + * // ... + * } + * ``` */ - static fromReadableStream(readableStream, controller) { - let consumed = false; - async function* iterLines() { - const lineDecoder = new line_LineDecoder(); - const iter = shims_ReadableStreamToAsyncIterable(readableStream); - for await (const chunk of iter) { - for (const line of lineDecoder.decode(chunk)) { - yield line; - } - } - for (const line of lineDecoder.flush()) { - yield line; - } - } - async function* iterator() { - if (consumed) { - throw new error_AnthropicError('Cannot iterate over a consumed stream, use `.tee()` to split the stream.'); - } - consumed = true; - let done = false; - try { - for await (const line of iterLines()) { - if (done) - continue; - if (line) - yield JSON.parse(line); - } - done = true; - } - catch (e) { - // If the user calls `stream.controller.abort()`, we should exit without throwing. - if (isAbortError(e)) - return; - throw e; - } - finally { - // If the user `break`s, abort the ongoing request. - if (!done) - controller.abort(); - } - } - return new streaming_Stream(iterator, controller); - } - [Symbol.asyncIterator]() { - return this.iterator(); + list(params = {}, options) { + const { betas, ...query } = params ?? {}; + return this._client.getAPIList('/v1/files', (pagination_Page), { + query, + ...options, + headers: headers_buildHeaders([ + { 'anthropic-beta': [...(betas ?? []), 'files-api-2025-04-14'].toString() }, + options?.headers, + ]), + }); } /** - * Splits the stream into two streams which can be - * independently read from at different speeds. + * Delete File + * + * @example + * ```ts + * const deletedFile = await client.beta.files.delete( + * 'file_id', + * ); + * ``` */ - tee() { - const left = []; - const right = []; - const iterator = this.iterator(); - const teeIterator = (queue) => { - return { - next: () => { - if (queue.length === 0) { - const result = iterator.next(); - left.push(result); - right.push(result); - } - return queue.shift(); - }, - }; - }; - return [ - new streaming_Stream(() => teeIterator(left), this.controller), - new streaming_Stream(() => teeIterator(right), this.controller), - ]; + delete(fileID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.delete(path_path `/v1/files/${fileID}`, { + ...options, + headers: headers_buildHeaders([ + { 'anthropic-beta': [...(betas ?? []), 'files-api-2025-04-14'].toString() }, + options?.headers, + ]), + }); } /** - * Converts this stream to a newline-separated ReadableStream of - * JSON stringified values in the stream - * which can be turned back into a Stream with `Stream.fromReadableStream()`. + * Download File + * + * @example + * ```ts + * const response = await client.beta.files.download( + * 'file_id', + * ); + * + * const content = await response.blob(); + * console.log(content); + * ``` */ - toReadableStream() { - const self = this; - let iter; - return makeReadableStream({ - async start() { - iter = self[Symbol.asyncIterator](); - }, - async pull(ctrl) { - try { - const { value, done } = await iter.next(); - if (done) - return ctrl.close(); - const bytes = encodeUTF8(JSON.stringify(value) + '\n'); - ctrl.enqueue(bytes); - } - catch (err) { - ctrl.error(err); - } - }, - async cancel() { - await iter.return?.(); - }, + download(fileID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.get(path_path `/v1/files/${fileID}/content`, { + ...options, + headers: headers_buildHeaders([ + { + 'anthropic-beta': [...(betas ?? []), 'files-api-2025-04-14'].toString(), + Accept: 'application/binary', + }, + options?.headers, + ]), + __binaryResponse: true, }); } -} -async function* streaming_iterSSEMessages(response, controller) { - if (!response.body) { - controller.abort(); - if (typeof globalThis.navigator !== 'undefined' && - globalThis.navigator.product === 'ReactNative') { - throw new error_AnthropicError(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`); - } - throw new error_AnthropicError(`Attempted to iterate over a response with no body`); - } - const sseDecoder = new streaming_SSEDecoder(); - const lineDecoder = new line_LineDecoder(); - const iter = shims_ReadableStreamToAsyncIterable(response.body); - for await (const sseChunk of streaming_iterSSEChunks(iter)) { - for (const line of lineDecoder.decode(sseChunk)) { - const sse = sseDecoder.decode(line); - if (sse) - yield sse; - } - } - for (const line of lineDecoder.flush()) { - const sse = sseDecoder.decode(line); - if (sse) - yield sse; - } -} -/** - * Given an async iterable iterator, iterates over it and yields full - * SSE chunks, i.e. yields when a double new-line is encountered. - */ -async function* streaming_iterSSEChunks(iterator) { - let data = new Uint8Array(); - for await (const chunk of iterator) { - if (chunk == null) { - continue; - } - const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) - : typeof chunk === 'string' ? encodeUTF8(chunk) - : chunk; - let newData = new Uint8Array(data.length + binaryChunk.length); - newData.set(data); - newData.set(binaryChunk, data.length); - data = newData; - let patternIndex; - while ((patternIndex = line_findDoubleNewlineIndex(data)) !== -1) { - yield data.slice(0, patternIndex); - data = data.slice(patternIndex); - } - } - if (data.length > 0) { - yield data; - } -} -class streaming_SSEDecoder { - constructor() { - this.event = null; - this.data = []; - this.chunks = []; + /** + * Get File Metadata + * + * @example + * ```ts + * const fileMetadata = + * await client.beta.files.retrieveMetadata('file_id'); + * ``` + */ + retrieveMetadata(fileID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.get(path_path `/v1/files/${fileID}`, { + ...options, + headers: headers_buildHeaders([ + { 'anthropic-beta': [...(betas ?? []), 'files-api-2025-04-14'].toString() }, + options?.headers, + ]), + }); } - decode(line) { - if (line.endsWith('\r')) { - line = line.substring(0, line.length - 1); - } - if (!line) { - // empty line and we didn't previously encounter any messages - if (!this.event && !this.data.length) - return null; - const sse = { - event: this.event, - data: this.data.join('\n'), - raw: this.chunks, - }; - this.event = null; - this.data = []; - this.chunks = []; - return sse; - } - this.chunks.push(line); - if (line.startsWith(':')) { - return null; - } - let [fieldname, _, value] = streaming_partition(line, ':'); - if (value.startsWith(' ')) { - value = value.substring(1); - } - if (fieldname === 'event') { - this.event = value; - } - else if (fieldname === 'data') { - this.data.push(value); - } - return null; + /** + * Upload File + * + * @example + * ```ts + * const fileMetadata = await client.beta.files.upload({ + * file: fs.createReadStream('path/to/file'), + * }); + * ``` + */ + upload(params, options) { + const { betas, ...body } = params; + return this._client.post('/v1/files', uploads_multipartFormRequestOptions({ + body, + ...options, + headers: headers_buildHeaders([ + { 'anthropic-beta': [...(betas ?? []), 'files-api-2025-04-14'].toString() }, + options?.headers, + ]), + }, this._client)); } } -function streaming_partition(str, delimiter) { - const index = str.indexOf(delimiter); - if (index !== -1) { - return [str.substring(0, index), delimiter, str.substring(index + delimiter.length)]; +//# sourceMappingURL=files.mjs.map +;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/resources/beta/models.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + +class models_Models extends resource_APIResource { + /** + * Get a specific model. + * + * The Models API response can be used to determine information about a specific + * model or resolve a model alias to a model ID. + * + * @example + * ```ts + * const betaModelInfo = await client.beta.models.retrieve( + * 'model_id', + * ); + * ``` + */ + retrieve(modelID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.get(path_path `/v1/models/${modelID}?beta=true`, { + ...options, + headers: headers_buildHeaders([ + { ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) }, + options?.headers, + ]), + }); + } + /** + * List available models. + * + * The Models API response can be used to determine which models are available for + * use in the API. More recently released models are listed first. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const betaModelInfo of client.beta.models.list()) { + * // ... + * } + * ``` + */ + list(params = {}, options) { + const { betas, ...query } = params ?? {}; + return this._client.getAPIList('/v1/models?beta=true', (pagination_Page), { + query, + ...options, + headers: headers_buildHeaders([ + { ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) }, + options?.headers, + ]), + }); } - return [str, '', '']; } -//# sourceMappingURL=streaming.mjs.map -;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/internal/parse.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +//# sourceMappingURL=models.mjs.map +;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/internal/decoders/jsonl.mjs -async function parse_defaultParseResponse(client, props) { - const { response, requestLogID, retryOfRequestLogID, startTime } = props; - const body = await (async () => { - if (props.options.stream) { - loggerFor(client).debug('response', response.status, response.url, response.headers, response.body); - // Note: there is an invariant here that isn't represented in the type system - // that if you set `stream: true` the response type must also be `Stream` - if (props.options.__streamClass) { - return props.options.__streamClass.fromSSEResponse(response, props.controller); + +class JSONLDecoder { + constructor(iterator, controller) { + this.iterator = iterator; + this.controller = controller; + } + async *decoder() { + const lineDecoder = new line_LineDecoder(); + for await (const chunk of this.iterator) { + for (const line of lineDecoder.decode(chunk)) { + yield JSON.parse(line); } - return streaming_Stream.fromSSEResponse(response, props.controller); - } - // fetch refuses to read the body when the status code is 204. - if (response.status === 204) { - return null; } - if (props.options.__binaryResponse) { - return response; + for (const line of lineDecoder.flush()) { + yield JSON.parse(line); } - const contentType = response.headers.get('content-type'); - const mediaType = contentType?.split(';')[0]?.trim(); - const isJSON = mediaType?.includes('application/json') || mediaType?.endsWith('+json'); - if (isJSON) { - const json = await response.json(); - return addRequestID(json, response); + } + [Symbol.asyncIterator]() { + return this.decoder(); + } + static fromResponse(response, controller) { + if (!response.body) { + controller.abort(); + if (typeof globalThis.navigator !== 'undefined' && + globalThis.navigator.product === 'ReactNative') { + throw new error_AnthropicError(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`); + } + throw new error_AnthropicError(`Attempted to iterate over a response with no body`); } - const text = await response.text(); - return text; - })(); - loggerFor(client).debug(`[${requestLogID}] response parsed`, formatRequestDetails({ - retryOfRequestLogID, - url: response.url, - status: response.status, - body, - durationMs: Date.now() - startTime, - })); - return body; -} -function addRequestID(value, response) { - if (!value || typeof value !== 'object' || Array.isArray(value)) { - return value; + return new JSONLDecoder(shims_ReadableStreamToAsyncIterable(response.body), controller); } - return Object.defineProperty(value, '_request_id', { - value: response.headers.get('request-id'), - enumerable: false, - }); } -//# sourceMappingURL=parse.mjs.map -;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/core/api-promise.mjs +//# sourceMappingURL=jsonl.mjs.map +;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/error.mjs + +//# sourceMappingURL=error.mjs.map +;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/resources/beta/messages/batches.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -var _APIPromise_client; -/** - * A subclass of `Promise` providing additional helper methods - * for interacting with the SDK. - */ -class api_promise_APIPromise extends Promise { - constructor(client, responsePromise, parseResponse = parse_defaultParseResponse) { - super((resolve) => { - // this is maybe a bit weird but this has to be a no-op to not implicitly - // parse the response body; instead .then, .catch, .finally are overridden - // to parse the response - resolve(null); + + + + +class batches_Batches extends resource_APIResource { + /** + * Send a batch of Message creation requests. + * + * The Message Batches API can be used to process multiple Messages API requests at + * once. Once a Message Batch is created, it begins processing immediately. Batches + * can take up to 24 hours to complete. + * + * Learn more about the Message Batches API in our + * [user guide](/en/docs/build-with-claude/batch-processing) + * + * @example + * ```ts + * const betaMessageBatch = + * await client.beta.messages.batches.create({ + * requests: [ + * { + * custom_id: 'my-custom-id-1', + * params: { + * max_tokens: 1024, + * messages: [ + * { content: 'Hello, world', role: 'user' }, + * ], + * model: 'claude-sonnet-4-20250514', + * }, + * }, + * ], + * }); + * ``` + */ + create(params, options) { + const { betas, ...body } = params; + return this._client.post('/v1/messages/batches?beta=true', { + body, + ...options, + headers: headers_buildHeaders([ + { 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString() }, + options?.headers, + ]), }); - this.responsePromise = responsePromise; - this.parseResponse = parseResponse; - _APIPromise_client.set(this, void 0); - tslib_classPrivateFieldSet(this, _APIPromise_client, client, "f"); - } - _thenUnwrap(transform) { - return new api_promise_APIPromise(tslib_classPrivateFieldGet(this, _APIPromise_client, "f"), this.responsePromise, async (client, props) => addRequestID(transform(await this.parseResponse(client, props), props), props.response)); } /** - * Gets the raw `Response` instance instead of parsing the response - * data. + * This endpoint is idempotent and can be used to poll for Message Batch + * completion. To access the results of a Message Batch, make a request to the + * `results_url` field in the response. * - * If you want to parse the response body but still get the `Response` - * instance, you can use {@link withResponse()}. + * Learn more about the Message Batches API in our + * [user guide](/en/docs/build-with-claude/batch-processing) * - * 👋 Getting the wrong TypeScript type for `Response`? - * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]` - * to your `tsconfig.json`. + * @example + * ```ts + * const betaMessageBatch = + * await client.beta.messages.batches.retrieve( + * 'message_batch_id', + * ); + * ``` */ - asResponse() { - return this.responsePromise.then((p) => p.response); + retrieve(messageBatchID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.get(path_path `/v1/messages/batches/${messageBatchID}?beta=true`, { + ...options, + headers: headers_buildHeaders([ + { 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString() }, + options?.headers, + ]), + }); } /** - * Gets the parsed response data, the raw `Response` instance and the ID of the request, - * returned via the `request-id` header which is useful for debugging requests and resporting - * issues to Anthropic. + * List all Message Batches within a Workspace. Most recently created batches are + * returned first. * - * If you just want to get the raw `Response` instance without parsing it, - * you can use {@link asResponse()}. + * Learn more about the Message Batches API in our + * [user guide](/en/docs/build-with-claude/batch-processing) * - * 👋 Getting the wrong TypeScript type for `Response`? - * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]` - * to your `tsconfig.json`. + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const betaMessageBatch of client.beta.messages.batches.list()) { + * // ... + * } + * ``` */ - async withResponse() { - const [data, response] = await Promise.all([this.parse(), this.asResponse()]); - return { data, response, request_id: response.headers.get('request-id') }; - } - parse() { - if (!this.parsedPromise) { - this.parsedPromise = this.responsePromise.then((data) => this.parseResponse(tslib_classPrivateFieldGet(this, _APIPromise_client, "f"), data)); - } - return this.parsedPromise; + list(params = {}, options) { + const { betas, ...query } = params ?? {}; + return this._client.getAPIList('/v1/messages/batches?beta=true', (pagination_Page), { + query, + ...options, + headers: headers_buildHeaders([ + { 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString() }, + options?.headers, + ]), + }); } - then(onfulfilled, onrejected) { - return this.parse().then(onfulfilled, onrejected); + /** + * Delete a Message Batch. + * + * Message Batches can only be deleted once they've finished processing. If you'd + * like to delete an in-progress batch, you must first cancel it. + * + * Learn more about the Message Batches API in our + * [user guide](/en/docs/build-with-claude/batch-processing) + * + * @example + * ```ts + * const betaDeletedMessageBatch = + * await client.beta.messages.batches.delete( + * 'message_batch_id', + * ); + * ``` + */ + delete(messageBatchID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.delete(path_path `/v1/messages/batches/${messageBatchID}?beta=true`, { + ...options, + headers: headers_buildHeaders([ + { 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString() }, + options?.headers, + ]), + }); } - catch(onrejected) { - return this.parse().catch(onrejected); + /** + * Batches may be canceled any time before processing ends. Once cancellation is + * initiated, the batch enters a `canceling` state, at which time the system may + * complete any in-progress, non-interruptible requests before finalizing + * cancellation. + * + * The number of canceled requests is specified in `request_counts`. To determine + * which requests were canceled, check the individual results within the batch. + * Note that cancellation may not result in any canceled requests if they were + * non-interruptible. + * + * Learn more about the Message Batches API in our + * [user guide](/en/docs/build-with-claude/batch-processing) + * + * @example + * ```ts + * const betaMessageBatch = + * await client.beta.messages.batches.cancel( + * 'message_batch_id', + * ); + * ``` + */ + cancel(messageBatchID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.post(path_path `/v1/messages/batches/${messageBatchID}/cancel?beta=true`, { + ...options, + headers: headers_buildHeaders([ + { 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString() }, + options?.headers, + ]), + }); } - finally(onfinally) { - return this.parse().finally(onfinally); + /** + * Streams the results of a Message Batch as a `.jsonl` file. + * + * Each line in the file is a JSON object containing the result of a single request + * in the Message Batch. Results are not guaranteed to be in the same order as + * requests. Use the `custom_id` field to match results to requests. + * + * Learn more about the Message Batches API in our + * [user guide](/en/docs/build-with-claude/batch-processing) + * + * @example + * ```ts + * const betaMessageBatchIndividualResponse = + * await client.beta.messages.batches.results( + * 'message_batch_id', + * ); + * ``` + */ + async results(messageBatchID, params = {}, options) { + const batch = await this.retrieve(messageBatchID); + if (!batch.results_url) { + throw new error_AnthropicError(`No batch \`results_url\`; Has it finished processing? ${batch.processing_status} - ${batch.id}`); + } + const { betas } = params ?? {}; + return this._client + .get(batch.results_url, { + ...options, + headers: headers_buildHeaders([ + { + 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString(), + Accept: 'application/binary', + }, + options?.headers, + ]), + stream: true, + __binaryResponse: true, + }) + ._thenUnwrap((_, props) => JSONLDecoder.fromResponse(props.response, props.controller)); } } -_APIPromise_client = new WeakMap(); -//# sourceMappingURL=api-promise.mjs.map -;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/core/pagination.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -var pagination_AbstractPage_client; - - - - +//# sourceMappingURL=batches.mjs.map +;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/streaming.mjs -class pagination_AbstractPage { - constructor(client, response, body, options) { - pagination_AbstractPage_client.set(this, void 0); - tslib_classPrivateFieldSet(this, pagination_AbstractPage_client, client, "f"); - this.options = options; - this.response = response; - this.body = body; - } - hasNextPage() { - const items = this.getPaginatedItems(); - if (!items.length) - return false; - return this.nextPageRequestOptions() != null; - } - async getNextPage() { - const nextOptions = this.nextPageRequestOptions(); - if (!nextOptions) { - throw new error_AnthropicError('No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.'); +//# sourceMappingURL=streaming.mjs.map +;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/_vendor/partial-json-parser/parser.mjs +const tokenize = (input) => { + let current = 0; + let tokens = []; + while (current < input.length) { + let char = input[current]; + if (char === '\\') { + current++; + continue; + } + if (char === '{') { + tokens.push({ + type: 'brace', + value: '{', + }); + current++; + continue; + } + if (char === '}') { + tokens.push({ + type: 'brace', + value: '}', + }); + current++; + continue; + } + if (char === '[') { + tokens.push({ + type: 'paren', + value: '[', + }); + current++; + continue; + } + if (char === ']') { + tokens.push({ + type: 'paren', + value: ']', + }); + current++; + continue; + } + if (char === ':') { + tokens.push({ + type: 'separator', + value: ':', + }); + current++; + continue; + } + if (char === ',') { + tokens.push({ + type: 'delimiter', + value: ',', + }); + current++; + continue; + } + if (char === '"') { + let value = ''; + let danglingQuote = false; + char = input[++current]; + while (char !== '"') { + if (current === input.length) { + danglingQuote = true; + break; + } + if (char === '\\') { + current++; + if (current === input.length) { + danglingQuote = true; + break; + } + value += char + input[current]; + char = input[++current]; + } + else { + value += char; + char = input[++current]; + } + } + char = input[++current]; + if (!danglingQuote) { + tokens.push({ + type: 'string', + value, + }); + } + continue; } - return await tslib_classPrivateFieldGet(this, pagination_AbstractPage_client, "f").requestAPIList(this.constructor, nextOptions); - } - async *iterPages() { - let page = this; - yield page; - while (page.hasNextPage()) { - page = await page.getNextPage(); - yield page; + let WHITESPACE = /\s/; + if (char && WHITESPACE.test(char)) { + current++; + continue; } - } - async *[(pagination_AbstractPage_client = new WeakMap(), Symbol.asyncIterator)]() { - for await (const page of this.iterPages()) { - for (const item of page.getPaginatedItems()) { - yield item; + let NUMBERS = /[0-9]/; + if ((char && NUMBERS.test(char)) || char === '-' || char === '.') { + let value = ''; + if (char === '-') { + value += char; + char = input[++current]; } + while ((char && NUMBERS.test(char)) || char === '.') { + value += char; + char = input[++current]; + } + tokens.push({ + type: 'number', + value, + }); + continue; } - } -} -/** - * This subclass of Promise will resolve to an instantiated Page once the request completes. - * - * It also implements AsyncIterable to allow auto-paginating iteration on an unawaited list call, eg: - * - * for await (const item of client.items.list()) { - * console.log(item) - * } - */ -class pagination_PagePromise extends api_promise_APIPromise { - constructor(client, request, Page) { - super(client, request, async (client, props) => new Page(client, props.response, await parse_defaultParseResponse(client, props), props.options)); - } - /** - * Allow auto-paginating iteration on an unawaited list call, eg: - * - * for await (const item of client.items.list()) { - * console.log(item) - * } - */ - async *[Symbol.asyncIterator]() { - const page = await this; - for await (const item of page) { - yield item; + let LETTERS = /[a-z]/i; + if (char && LETTERS.test(char)) { + let value = ''; + while (char && LETTERS.test(char)) { + if (current === input.length) { + break; + } + value += char; + char = input[++current]; + } + if (value == 'true' || value == 'false' || value === 'null') { + tokens.push({ + type: 'name', + value, + }); + } + else { + // unknown token, e.g. `nul` which isn't quite `null` + current++; + continue; + } + continue; } + current++; } -} -class pagination_Page extends pagination_AbstractPage { - constructor(client, response, body, options) { - super(client, response, body, options); - this.data = body.data || []; - this.has_more = body.has_more || false; - this.first_id = body.first_id || null; - this.last_id = body.last_id || null; - } - getPaginatedItems() { - return this.data ?? []; - } - hasNextPage() { - if (this.has_more === false) { - return false; - } - return super.hasNextPage(); + return tokens; +}, strip = (tokens) => { + if (tokens.length === 0) { + return tokens; } - nextPageRequestOptions() { - if (this.options.query?.['before_id']) { - // in reverse - const first_id = this.first_id; - if (!first_id) { - return null; + let lastToken = tokens[tokens.length - 1]; + switch (lastToken.type) { + case 'separator': + tokens = tokens.slice(0, tokens.length - 1); + return strip(tokens); + break; + case 'number': + let lastCharacterOfLastToken = lastToken.value[lastToken.value.length - 1]; + if (lastCharacterOfLastToken === '.' || lastCharacterOfLastToken === '-') { + tokens = tokens.slice(0, tokens.length - 1); + return strip(tokens); } - return { - ...this.options, - query: { - ...maybeObj(this.options.query), - before_id: first_id, - }, - }; - } - const cursor = this.last_id; - if (!cursor) { - return null; - } - return { - ...this.options, - query: { - ...maybeObj(this.options.query), - after_id: cursor, - }, - }; - } -} -//# sourceMappingURL=pagination.mjs.map -;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/internal/uploads.mjs - -const checkFileSupport = () => { - if (typeof File === 'undefined') { - const { process } = globalThis; - const isOldNode = typeof process?.versions?.node === 'string' && parseInt(process.versions.node.split('.')) < 20; - throw new Error('`File` is not defined as a global, which is required for file uploads.' + - (isOldNode ? - " Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`." - : '')); + case 'string': + let tokenBeforeTheLastToken = tokens[tokens.length - 2]; + if (tokenBeforeTheLastToken?.type === 'delimiter') { + tokens = tokens.slice(0, tokens.length - 1); + return strip(tokens); + } + else if (tokenBeforeTheLastToken?.type === 'brace' && tokenBeforeTheLastToken.value === '{') { + tokens = tokens.slice(0, tokens.length - 1); + return strip(tokens); + } + break; + case 'delimiter': + tokens = tokens.slice(0, tokens.length - 1); + return strip(tokens); + break; } -}; -/** - * Construct a `File` instance. This is used to ensure a helpful error is thrown - * for environments that don't define a global `File` yet. - */ -function makeFile(fileBits, fileName, options) { - checkFileSupport(); - return new File(fileBits, fileName ?? 'unknown_file', options); -} -function uploads_getName(value) { - return (((typeof value === 'object' && - value !== null && - (('name' in value && value.name && String(value.name)) || - ('url' in value && value.url && String(value.url)) || - ('filename' in value && value.filename && String(value.filename)) || - ('path' in value && value.path && String(value.path)))) || - '') - .split(/[\\/]/) - .pop() || undefined); -} -const isAsyncIterable = (value) => value != null && typeof value === 'object' && typeof value[Symbol.asyncIterator] === 'function'; -/** - * Returns a multipart/form-data request if any part of the given request body contains a File / Blob value. - * Otherwise returns the request as is. - */ -const uploads_maybeMultipartFormRequestOptions = async (opts, fetch) => { - if (!uploads_hasUploadableValue(opts.body)) - return opts; - return { ...opts, body: await uploads_createForm(opts.body, fetch) }; -}; -const uploads_multipartFormRequestOptions = async (opts, fetch) => { - return { ...opts, body: await uploads_createForm(opts.body, fetch) }; -}; -const supportsFormDataMap = new WeakMap(); -/** - * node-fetch doesn't support the global FormData object in recent node versions. Instead of sending - * properly-encoded form data, it just stringifies the object, resulting in a request body of "[object FormData]". - * This function detects if the fetch function provided supports the global FormData object to avoid - * confusing error messages later on. - */ -function supportsFormData(fetchObject) { - const fetch = typeof fetchObject === 'function' ? fetchObject : fetchObject.fetch; - const cached = supportsFormDataMap.get(fetch); - if (cached) - return cached; - const promise = (async () => { - try { - const FetchResponse = ('Response' in fetch ? - fetch.Response - : (await fetch('data:,')).constructor); - const data = new FormData(); - if (data.toString() === (await new FetchResponse(data).text())) { - return false; + return tokens; +}, unstrip = (tokens) => { + let tail = []; + tokens.map((token) => { + if (token.type === 'brace') { + if (token.value === '{') { + tail.push('}'); + } + else { + tail.splice(tail.lastIndexOf('}'), 1); } - return true; } - catch { - // avoid false negatives - return true; + if (token.type === 'paren') { + if (token.value === '[') { + tail.push(']'); + } + else { + tail.splice(tail.lastIndexOf(']'), 1); + } } - })(); - supportsFormDataMap.set(fetch, promise); - return promise; -} -const uploads_createForm = async (body, fetch) => { - if (!(await supportsFormData(fetch))) { - throw new TypeError('The provided fetch function does not support file uploads with the current global FormData class.'); + }); + if (tail.length > 0) { + tail.reverse().map((item) => { + if (item === '}') { + tokens.push({ + type: 'brace', + value: '}', + }); + } + else if (item === ']') { + tokens.push({ + type: 'paren', + value: ']', + }); + } + }); } - const form = new FormData(); - await Promise.all(Object.entries(body || {}).map(([key, value]) => uploads_addFormValue(form, key, value))); - return form; -}; -// We check for Blob not File because Bun.File doesn't inherit from File, -// but they both inherit from Blob and have a `name` property at runtime. -const isNamedBlob = (value) => value instanceof Blob && 'name' in value; -const uploads_isUploadable = (value) => typeof value === 'object' && - value !== null && - (value instanceof Response || isAsyncIterable(value) || isNamedBlob(value)); -const uploads_hasUploadableValue = (value) => { - if (uploads_isUploadable(value)) - return true; - if (Array.isArray(value)) - return value.some(uploads_hasUploadableValue); - if (value && typeof value === 'object') { - for (const k in value) { - if (uploads_hasUploadableValue(value[k])) - return true; + return tokens; +}, generate = (tokens) => { + let output = ''; + tokens.map((token) => { + switch (token.type) { + case 'string': + output += '"' + token.value + '"'; + break; + default: + output += token.value; + break; } - } - return false; -}; -const uploads_addFormValue = async (form, key, value) => { - if (value === undefined) - return; - if (value == null) { - throw new TypeError(`Received null for "${key}"; to pass null in FormData, you must use the string 'null'`); - } - // TODO: make nested formats configurable - if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { - form.append(key, String(value)); - } - else if (value instanceof Response) { - form.append(key, makeFile([await value.blob()], uploads_getName(value))); - } - else if (isAsyncIterable(value)) { - form.append(key, makeFile([await new Response(ReadableStreamFrom(value)).blob()], uploads_getName(value))); - } - else if (isNamedBlob(value)) { - form.append(key, value, uploads_getName(value)); - } - else if (Array.isArray(value)) { - await Promise.all(value.map((entry) => uploads_addFormValue(form, key + '[]', entry))); - } - else if (typeof value === 'object') { - await Promise.all(Object.entries(value).map(([name, prop]) => uploads_addFormValue(form, `${key}[${name}]`, prop))); - } - else { - throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`); - } -}; -//# sourceMappingURL=uploads.mjs.map -;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/internal/to-file.mjs + }); + return output; +}, parser_partialParse = (input) => JSON.parse(generate(unstrip(strip(tokenize(input))))); +//# sourceMappingURL=parser.mjs.map +;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/lib/BetaMessageStream.mjs +var _BetaMessageStream_instances, _BetaMessageStream_currentMessageSnapshot, _BetaMessageStream_connectedPromise, _BetaMessageStream_resolveConnectedPromise, _BetaMessageStream_rejectConnectedPromise, _BetaMessageStream_endPromise, _BetaMessageStream_resolveEndPromise, _BetaMessageStream_rejectEndPromise, _BetaMessageStream_listeners, _BetaMessageStream_ended, _BetaMessageStream_errored, _BetaMessageStream_aborted, _BetaMessageStream_catchingPromiseCreated, _BetaMessageStream_response, _BetaMessageStream_request_id, _BetaMessageStream_getFinalMessage, _BetaMessageStream_getFinalText, _BetaMessageStream_handleError, _BetaMessageStream_beginRequest, _BetaMessageStream_addStreamEvent, _BetaMessageStream_endRequest, _BetaMessageStream_accumulateMessage; -/** - * This check adds the arrayBuffer() method type because it is available and used at runtime - */ -const to_file_isBlobLike = (value) => value != null && - typeof value === 'object' && - typeof value.size === 'number' && - typeof value.type === 'string' && - typeof value.text === 'function' && - typeof value.slice === 'function' && - typeof value.arrayBuffer === 'function'; -/** - * This check adds the arrayBuffer() method type because it is available and used at runtime - */ -const to_file_isFileLike = (value) => value != null && - typeof value === 'object' && - typeof value.name === 'string' && - typeof value.lastModified === 'number' && - to_file_isBlobLike(value); -const to_file_isResponseLike = (value) => value != null && - typeof value === 'object' && - typeof value.url === 'string' && - typeof value.blob === 'function'; -/** - * Helper for creating a {@link File} to pass to an SDK upload method from a variety of different data formats - * @param value the raw content of the file. Can be an {@link Uploadable}, {@link BlobLikePart}, or {@link AsyncIterable} of {@link BlobLikePart}s - * @param {string=} name the name of the file. If omitted, toFile will try to determine a file name from bits if possible - * @param {Object=} options additional properties - * @param {string=} options.type the MIME type of the content - * @param {number=} options.lastModified the last modified timestamp - * @returns a {@link File} with the given properties - */ -async function to_file_toFile(value, name, options) { - checkFileSupport(); - // If it's a promise, resolve it. - value = await value; - // If we've been given a `File` we don't need to do anything - if (to_file_isFileLike(value)) { - if (value instanceof File) { - return value; - } - return makeFile([await value.arrayBuffer()], value.name); - } - if (to_file_isResponseLike(value)) { - const blob = await value.blob(); - name || (name = new URL(value.url).pathname.split(/[\\/]/).pop()); - return makeFile(await to_file_getBytes(blob), name, options); - } - const parts = await to_file_getBytes(value); - name || (name = uploads_getName(value)); - if (!options?.type) { - const type = parts.find((part) => typeof part === 'object' && 'type' in part && part.type); - if (typeof type === 'string') { - options = { ...options, type }; - } - } - return makeFile(parts, name, options); + + + + +const JSON_BUF_PROPERTY = '__json_buf'; +function tracksToolInput(content) { + return content.type === 'tool_use' || content.type === 'server_tool_use' || content.type === 'mcp_tool_use'; } -async function to_file_getBytes(value) { - let parts = []; - if (typeof value === 'string' || - ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc. - value instanceof ArrayBuffer) { - parts.push(value); - } - else if (to_file_isBlobLike(value)) { - parts.push(value instanceof Blob ? value : await value.arrayBuffer()); - } - else if (isAsyncIterable(value) // includes Readable, ReadableStream, etc. - ) { - for await (const chunk of value) { - parts.push(...(await to_file_getBytes(chunk))); // TODO, consider validating? - } +class BetaMessageStream { + constructor() { + _BetaMessageStream_instances.add(this); + this.messages = []; + this.receivedMessages = []; + _BetaMessageStream_currentMessageSnapshot.set(this, void 0); + this.controller = new AbortController(); + _BetaMessageStream_connectedPromise.set(this, void 0); + _BetaMessageStream_resolveConnectedPromise.set(this, () => { }); + _BetaMessageStream_rejectConnectedPromise.set(this, () => { }); + _BetaMessageStream_endPromise.set(this, void 0); + _BetaMessageStream_resolveEndPromise.set(this, () => { }); + _BetaMessageStream_rejectEndPromise.set(this, () => { }); + _BetaMessageStream_listeners.set(this, {}); + _BetaMessageStream_ended.set(this, false); + _BetaMessageStream_errored.set(this, false); + _BetaMessageStream_aborted.set(this, false); + _BetaMessageStream_catchingPromiseCreated.set(this, false); + _BetaMessageStream_response.set(this, void 0); + _BetaMessageStream_request_id.set(this, void 0); + _BetaMessageStream_handleError.set(this, (error) => { + tslib_classPrivateFieldSet(this, _BetaMessageStream_errored, true, "f"); + if (errors_isAbortError(error)) { + error = new error_APIUserAbortError(); + } + if (error instanceof error_APIUserAbortError) { + tslib_classPrivateFieldSet(this, _BetaMessageStream_aborted, true, "f"); + return this._emit('abort', error); + } + if (error instanceof error_AnthropicError) { + return this._emit('error', error); + } + if (error instanceof Error) { + const anthropicError = new error_AnthropicError(error.message); + // @ts-ignore + anthropicError.cause = error; + return this._emit('error', anthropicError); + } + return this._emit('error', new error_AnthropicError(String(error))); + }); + tslib_classPrivateFieldSet(this, _BetaMessageStream_connectedPromise, new Promise((resolve, reject) => { + tslib_classPrivateFieldSet(this, _BetaMessageStream_resolveConnectedPromise, resolve, "f"); + tslib_classPrivateFieldSet(this, _BetaMessageStream_rejectConnectedPromise, reject, "f"); + }), "f"); + tslib_classPrivateFieldSet(this, _BetaMessageStream_endPromise, new Promise((resolve, reject) => { + tslib_classPrivateFieldSet(this, _BetaMessageStream_resolveEndPromise, resolve, "f"); + tslib_classPrivateFieldSet(this, _BetaMessageStream_rejectEndPromise, reject, "f"); + }), "f"); + // Don't let these promises cause unhandled rejection errors. + // we will manually cause an unhandled rejection error later + // if the user hasn't registered any error listener or called + // any promise-returning method. + tslib_classPrivateFieldGet(this, _BetaMessageStream_connectedPromise, "f").catch(() => { }); + tslib_classPrivateFieldGet(this, _BetaMessageStream_endPromise, "f").catch(() => { }); } - else { - const constructor = value?.constructor?.name; - throw new Error(`Unexpected data type: ${typeof value}${constructor ? `; constructor: ${constructor}` : ''}${to_file_propsForError(value)}`); + get response() { + return tslib_classPrivateFieldGet(this, _BetaMessageStream_response, "f"); } - return parts; -} -function to_file_propsForError(value) { - if (typeof value !== 'object' || value === null) - return ''; - const props = Object.getOwnPropertyNames(value); - return `; props: [${props.map((p) => `"${p}"`).join(', ')}]`; -} -//# sourceMappingURL=to-file.mjs.map -;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/core/uploads.mjs - -//# sourceMappingURL=uploads.mjs.map -;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/core/resource.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -class resource_APIResource { - constructor(client) { - this._client = client; + get request_id() { + return tslib_classPrivateFieldGet(this, _BetaMessageStream_request_id, "f"); } -} -//# sourceMappingURL=resource.mjs.map -;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/internal/headers.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -const brand_privateNullableHeaders = Symbol.for('brand.privateNullableHeaders'); -const isArray = Array.isArray; -function* iterateHeaders(headers) { - if (!headers) - return; - if (brand_privateNullableHeaders in headers) { - const { values, nulls } = headers; - yield* values.entries(); - for (const name of nulls) { - yield [name, null]; + /** + * Returns the `MessageStream` data, the raw `Response` instance and the ID of the request, + * returned vie the `request-id` header which is useful for debugging requests and resporting + * issues to Anthropic. + * + * This is the same as the `APIPromise.withResponse()` method. + * + * This method will raise an error if you created the stream using `MessageStream.fromReadableStream` + * as no `Response` is available. + */ + async withResponse() { + const response = await tslib_classPrivateFieldGet(this, _BetaMessageStream_connectedPromise, "f"); + if (!response) { + throw new Error('Could not resolve a `Response` object'); } - return; + return { + data: this, + response, + request_id: response.headers.get('request-id'), + }; } - let shouldClear = false; - let iter; - if (headers instanceof Headers) { - iter = headers.entries(); + /** + * Intended for use on the frontend, consuming a stream produced with + * `.toReadableStream()` on the backend. + * + * Note that messages sent to the model do not appear in `.on('message')` + * in this context. + */ + static fromReadableStream(stream) { + const runner = new BetaMessageStream(); + runner._run(() => runner._fromReadableStream(stream)); + return runner; } - else if (isArray(headers)) { - iter = headers; + static createMessage(messages, params, options) { + const runner = new BetaMessageStream(); + for (const message of params.messages) { + runner._addMessageParam(message); + } + runner._run(() => runner._createMessage(messages, { ...params, stream: true }, { ...options, headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' } })); + return runner; } - else { - shouldClear = true; - iter = Object.entries(headers ?? {}); + _run(executor) { + executor().then(() => { + this._emitFinal(); + this._emit('end'); + }, tslib_classPrivateFieldGet(this, _BetaMessageStream_handleError, "f")); } - for (let row of iter) { - const name = row[0]; - if (typeof name !== 'string') - throw new TypeError('expected header name to be a string'); - const values = isArray(row[1]) ? row[1] : [row[1]]; - let didClear = false; - for (const value of values) { - if (value === undefined) - continue; - // Objects keys always overwrite older headers, they never append. - // Yield a null to clear the header before adding the new values. - if (shouldClear && !didClear) { - didClear = true; - yield [name, null]; - } - yield [name, value]; + _addMessageParam(message) { + this.messages.push(message); + } + _addMessage(message, emit = true) { + this.receivedMessages.push(message); + if (emit) { + this._emit('message', message); } } -} -const buildHeaders = (newHeaders) => { - const targetHeaders = new Headers(); - const nullHeaders = new Set(); - for (const headers of newHeaders) { - const seenHeaders = new Set(); - for (const [name, value] of iterateHeaders(headers)) { - const lowerName = name.toLowerCase(); - if (!seenHeaders.has(lowerName)) { - targetHeaders.delete(name); - seenHeaders.add(lowerName); - } - if (value === null) { - targetHeaders.delete(name); - nullHeaders.add(lowerName); + async _createMessage(messages, params, options) { + const signal = options?.signal; + let abortHandler; + if (signal) { + if (signal.aborted) + this.controller.abort(); + abortHandler = this.controller.abort.bind(this.controller); + signal.addEventListener('abort', abortHandler); + } + try { + tslib_classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_beginRequest).call(this); + const { response, data: stream } = await messages + .create({ ...params, stream: true }, { ...options, signal: this.controller.signal }) + .withResponse(); + this._connected(response); + for await (const event of stream) { + tslib_classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_addStreamEvent).call(this, event); + } + if (stream.controller.signal?.aborted) { + throw new error_APIUserAbortError(); } - else { - targetHeaders.append(name, value); - nullHeaders.delete(lowerName); + tslib_classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_endRequest).call(this); + } + finally { + if (signal && abortHandler) { + signal.removeEventListener('abort', abortHandler); } } } - return { [brand_privateNullableHeaders]: true, values: targetHeaders, nulls: nullHeaders }; -}; -const isEmptyHeaders = (headers) => { - for (const _ of iterateHeaders(headers)) - return false; - return true; -}; -//# sourceMappingURL=headers.mjs.map -;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/internal/utils/path.mjs - -/** - * Percent-encode everything that isn't safe to have in a path without encoding safe chars. - * - * Taken from https://datatracker.ietf.org/doc/html/rfc3986#section-3.3: - * > unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" - * > sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "=" - * > pchar = unreserved / pct-encoded / sub-delims / ":" / "@" - */ -function encodeURIPath(str) { - return str.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g, encodeURIComponent); -} -const createPathTagFunction = (pathEncoder = encodeURIPath) => function path(statics, ...params) { - // If there are no params, no processing is needed. - if (statics.length === 1) - return statics[0]; - let postPath = false; - const path = statics.reduce((previousValue, currentValue, index) => { - if (/[?#]/.test(currentValue)) { - postPath = true; - } - return (previousValue + - currentValue + - (index === params.length ? '' : (postPath ? encodeURIComponent : pathEncoder)(String(params[index])))); - }, ''); - const pathOnly = path.split(/[?#]/, 1)[0]; - const invalidSegments = []; - const invalidSegmentPattern = /(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi; - let match; - // Find all invalid segments - while ((match = invalidSegmentPattern.exec(pathOnly)) !== null) { - invalidSegments.push({ - start: match.index, - length: match[0].length, - }); + _connected(response) { + if (this.ended) + return; + tslib_classPrivateFieldSet(this, _BetaMessageStream_response, response, "f"); + tslib_classPrivateFieldSet(this, _BetaMessageStream_request_id, response?.headers.get('request-id'), "f"); + tslib_classPrivateFieldGet(this, _BetaMessageStream_resolveConnectedPromise, "f").call(this, response); + this._emit('connect'); } - if (invalidSegments.length > 0) { - let lastEnd = 0; - const underline = invalidSegments.reduce((acc, segment) => { - const spaces = ' '.repeat(segment.start - lastEnd); - const arrows = '^'.repeat(segment.length); - lastEnd = segment.start + segment.length; - return acc + spaces + arrows; - }, ''); - throw new error_AnthropicError(`Path parameters result in path with invalid segments:\n${path}\n${underline}`); + get ended() { + return tslib_classPrivateFieldGet(this, _BetaMessageStream_ended, "f"); + } + get errored() { + return tslib_classPrivateFieldGet(this, _BetaMessageStream_errored, "f"); + } + get aborted() { + return tslib_classPrivateFieldGet(this, _BetaMessageStream_aborted, "f"); + } + abort() { + this.controller.abort(); } - return path; -}; -/** - * URI-encodes path params and ensures no unsafe /./ or /../ path segments are introduced. - */ -const path = createPathTagFunction(encodeURIPath); -//# sourceMappingURL=path.mjs.map -;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/resources/beta/models.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - -class models_Models extends resource_APIResource { /** - * Get a specific model. - * - * The Models API response can be used to determine information about a specific - * model or resolve a model alias to a model ID. - * - * @example - * ```ts - * const betaModelInfo = await client.beta.models.retrieve( - * 'model_id', - * ); - * ``` + * Adds the listener function to the end of the listeners array for the event. + * No checks are made to see if the listener has already been added. Multiple calls passing + * the same combination of event and listener will result in the listener being added, and + * called, multiple times. + * @returns this MessageStream, so that calls can be chained */ - retrieve(modelID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.get(path `/v1/models/${modelID}?beta=true`, { - ...options, - headers: buildHeaders([ - { ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) }, - options?.headers, - ]), - }); + on(event, listener) { + const listeners = tslib_classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] || (tslib_classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] = []); + listeners.push({ listener }); + return this; } /** - * List available models. + * Removes the specified listener from the listener array for the event. + * off() will remove, at most, one instance of a listener from the listener array. If any single + * listener has been added multiple times to the listener array for the specified event, then + * off() must be called multiple times to remove each instance. + * @returns this MessageStream, so that calls can be chained + */ + off(event, listener) { + const listeners = tslib_classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event]; + if (!listeners) + return this; + const index = listeners.findIndex((l) => l.listener === listener); + if (index >= 0) + listeners.splice(index, 1); + return this; + } + /** + * Adds a one-time listener function for the event. The next time the event is triggered, + * this listener is removed and then invoked. + * @returns this MessageStream, so that calls can be chained + */ + once(event, listener) { + const listeners = tslib_classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] || (tslib_classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] = []); + listeners.push({ listener, once: true }); + return this; + } + /** + * This is similar to `.once()`, but returns a Promise that resolves the next time + * the event is triggered, instead of calling a listener callback. + * @returns a Promise that resolves the next time given event is triggered, + * or rejects if an error is emitted. (If you request the 'error' event, + * returns a promise that resolves with the error). * - * The Models API response can be used to determine which models are available for - * use in the API. More recently released models are listed first. + * Example: * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const betaModelInfo of client.beta.models.list()) { - * // ... - * } - * ``` + * const message = await stream.emitted('message') // rejects if the stream errors */ - list(params = {}, options) { - const { betas, ...query } = params ?? {}; - return this._client.getAPIList('/v1/models?beta=true', (pagination_Page), { - query, - ...options, - headers: buildHeaders([ - { ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) }, - options?.headers, - ]), + emitted(event) { + return new Promise((resolve, reject) => { + tslib_classPrivateFieldSet(this, _BetaMessageStream_catchingPromiseCreated, true, "f"); + if (event !== 'error') + this.once('error', reject); + this.once(event, resolve); }); } -} -//# sourceMappingURL=models.mjs.map -;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/internal/decoders/jsonl.mjs - - - -class JSONLDecoder { - constructor(iterator, controller) { - this.iterator = iterator; - this.controller = controller; + async done() { + tslib_classPrivateFieldSet(this, _BetaMessageStream_catchingPromiseCreated, true, "f"); + await tslib_classPrivateFieldGet(this, _BetaMessageStream_endPromise, "f"); } - async *decoder() { - const lineDecoder = new line_LineDecoder(); - for await (const chunk of this.iterator) { - for (const line of lineDecoder.decode(chunk)) { - yield JSON.parse(line); + get currentMessage() { + return tslib_classPrivateFieldGet(this, _BetaMessageStream_currentMessageSnapshot, "f"); + } + /** + * @returns a promise that resolves with the the final assistant Message response, + * or rejects if an error occurred or the stream ended prematurely without producing a Message. + */ + async finalMessage() { + await this.done(); + return tslib_classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_getFinalMessage).call(this); + } + /** + * @returns a promise that resolves with the the final assistant Message's text response, concatenated + * together if there are more than one text blocks. + * Rejects if an error occurred or the stream ended prematurely without producing a Message. + */ + async finalText() { + await this.done(); + return tslib_classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_getFinalText).call(this); + } + _emit(event, ...args) { + // make sure we don't emit any MessageStreamEvents after end + if (tslib_classPrivateFieldGet(this, _BetaMessageStream_ended, "f")) + return; + if (event === 'end') { + tslib_classPrivateFieldSet(this, _BetaMessageStream_ended, true, "f"); + tslib_classPrivateFieldGet(this, _BetaMessageStream_resolveEndPromise, "f").call(this); + } + const listeners = tslib_classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event]; + if (listeners) { + tslib_classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] = listeners.filter((l) => !l.once); + listeners.forEach(({ listener }) => listener(...args)); + } + if (event === 'abort') { + const error = args[0]; + if (!tslib_classPrivateFieldGet(this, _BetaMessageStream_catchingPromiseCreated, "f") && !listeners?.length) { + Promise.reject(error); + } + tslib_classPrivateFieldGet(this, _BetaMessageStream_rejectConnectedPromise, "f").call(this, error); + tslib_classPrivateFieldGet(this, _BetaMessageStream_rejectEndPromise, "f").call(this, error); + this._emit('end'); + return; + } + if (event === 'error') { + // NOTE: _emit('error', error) should only be called from #handleError(). + const error = args[0]; + if (!tslib_classPrivateFieldGet(this, _BetaMessageStream_catchingPromiseCreated, "f") && !listeners?.length) { + // Trigger an unhandled rejection if the user hasn't registered any error handlers. + // If you are seeing stack traces here, make sure to handle errors via either: + // - runner.on('error', () => ...) + // - await runner.done() + // - await runner.final...() + // - etc. + Promise.reject(error); + } + tslib_classPrivateFieldGet(this, _BetaMessageStream_rejectConnectedPromise, "f").call(this, error); + tslib_classPrivateFieldGet(this, _BetaMessageStream_rejectEndPromise, "f").call(this, error); + this._emit('end'); + } + } + _emitFinal() { + const finalMessage = this.receivedMessages.at(-1); + if (finalMessage) { + this._emit('finalMessage', tslib_classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_getFinalMessage).call(this)); + } + } + async _fromReadableStream(readableStream, options) { + const signal = options?.signal; + let abortHandler; + if (signal) { + if (signal.aborted) + this.controller.abort(); + abortHandler = this.controller.abort.bind(this.controller); + signal.addEventListener('abort', abortHandler); + } + try { + tslib_classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_beginRequest).call(this); + this._connected(null); + const stream = streaming_Stream.fromReadableStream(readableStream, this.controller); + for await (const event of stream) { + tslib_classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_addStreamEvent).call(this, event); + } + if (stream.controller.signal?.aborted) { + throw new error_APIUserAbortError(); + } + tslib_classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_endRequest).call(this); + } + finally { + if (signal && abortHandler) { + signal.removeEventListener('abort', abortHandler); + } + } + } + [(_BetaMessageStream_currentMessageSnapshot = new WeakMap(), _BetaMessageStream_connectedPromise = new WeakMap(), _BetaMessageStream_resolveConnectedPromise = new WeakMap(), _BetaMessageStream_rejectConnectedPromise = new WeakMap(), _BetaMessageStream_endPromise = new WeakMap(), _BetaMessageStream_resolveEndPromise = new WeakMap(), _BetaMessageStream_rejectEndPromise = new WeakMap(), _BetaMessageStream_listeners = new WeakMap(), _BetaMessageStream_ended = new WeakMap(), _BetaMessageStream_errored = new WeakMap(), _BetaMessageStream_aborted = new WeakMap(), _BetaMessageStream_catchingPromiseCreated = new WeakMap(), _BetaMessageStream_response = new WeakMap(), _BetaMessageStream_request_id = new WeakMap(), _BetaMessageStream_handleError = new WeakMap(), _BetaMessageStream_instances = new WeakSet(), _BetaMessageStream_getFinalMessage = function _BetaMessageStream_getFinalMessage() { + if (this.receivedMessages.length === 0) { + throw new error_AnthropicError('stream ended without producing a Message with role=assistant'); + } + return this.receivedMessages.at(-1); + }, _BetaMessageStream_getFinalText = function _BetaMessageStream_getFinalText() { + if (this.receivedMessages.length === 0) { + throw new error_AnthropicError('stream ended without producing a Message with role=assistant'); + } + const textBlocks = this.receivedMessages + .at(-1) + .content.filter((block) => block.type === 'text') + .map((block) => block.text); + if (textBlocks.length === 0) { + throw new error_AnthropicError('stream ended without producing a content block with type=text'); + } + return textBlocks.join(' '); + }, _BetaMessageStream_beginRequest = function _BetaMessageStream_beginRequest() { + if (this.ended) + return; + tslib_classPrivateFieldSet(this, _BetaMessageStream_currentMessageSnapshot, undefined, "f"); + }, _BetaMessageStream_addStreamEvent = function _BetaMessageStream_addStreamEvent(event) { + if (this.ended) + return; + const messageSnapshot = tslib_classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_accumulateMessage).call(this, event); + this._emit('streamEvent', event, messageSnapshot); + switch (event.type) { + case 'content_block_delta': { + const content = messageSnapshot.content.at(-1); + switch (event.delta.type) { + case 'text_delta': { + if (content.type === 'text') { + this._emit('text', event.delta.text, content.text || ''); + } + break; + } + case 'citations_delta': { + if (content.type === 'text') { + this._emit('citation', event.delta.citation, content.citations ?? []); + } + break; + } + case 'input_json_delta': { + if (tracksToolInput(content) && content.input) { + this._emit('inputJson', event.delta.partial_json, content.input); + } + break; + } + case 'thinking_delta': { + if (content.type === 'thinking') { + this._emit('thinking', event.delta.thinking, content.thinking); + } + break; + } + case 'signature_delta': { + if (content.type === 'thinking') { + this._emit('signature', content.signature); + } + break; + } + default: + checkNever(event.delta); + } + break; + } + case 'message_stop': { + this._addMessageParam(messageSnapshot); + this._addMessage(messageSnapshot, true); + break; + } + case 'content_block_stop': { + this._emit('contentBlock', messageSnapshot.content.at(-1)); + break; + } + case 'message_start': { + tslib_classPrivateFieldSet(this, _BetaMessageStream_currentMessageSnapshot, messageSnapshot, "f"); + break; + } + case 'content_block_start': + case 'message_delta': + break; + } + }, _BetaMessageStream_endRequest = function _BetaMessageStream_endRequest() { + if (this.ended) { + throw new error_AnthropicError(`stream has ended, this shouldn't happen`); + } + const snapshot = tslib_classPrivateFieldGet(this, _BetaMessageStream_currentMessageSnapshot, "f"); + if (!snapshot) { + throw new error_AnthropicError(`request ended without sending any chunks`); + } + tslib_classPrivateFieldSet(this, _BetaMessageStream_currentMessageSnapshot, undefined, "f"); + return snapshot; + }, _BetaMessageStream_accumulateMessage = function _BetaMessageStream_accumulateMessage(event) { + let snapshot = tslib_classPrivateFieldGet(this, _BetaMessageStream_currentMessageSnapshot, "f"); + if (event.type === 'message_start') { + if (snapshot) { + throw new error_AnthropicError(`Unexpected event order, got ${event.type} before receiving "message_stop"`); + } + return event.message; + } + if (!snapshot) { + throw new error_AnthropicError(`Unexpected event order, got ${event.type} before "message_start"`); + } + switch (event.type) { + case 'message_stop': + return snapshot; + case 'message_delta': + snapshot.container = event.delta.container; + snapshot.stop_reason = event.delta.stop_reason; + snapshot.stop_sequence = event.delta.stop_sequence; + snapshot.usage.output_tokens = event.usage.output_tokens; + if (event.usage.input_tokens != null) { + snapshot.usage.input_tokens = event.usage.input_tokens; + } + if (event.usage.cache_creation_input_tokens != null) { + snapshot.usage.cache_creation_input_tokens = event.usage.cache_creation_input_tokens; + } + if (event.usage.cache_read_input_tokens != null) { + snapshot.usage.cache_read_input_tokens = event.usage.cache_read_input_tokens; + } + if (event.usage.server_tool_use != null) { + snapshot.usage.server_tool_use = event.usage.server_tool_use; + } + return snapshot; + case 'content_block_start': + snapshot.content.push(event.content_block); + return snapshot; + case 'content_block_delta': { + const snapshotContent = snapshot.content.at(event.index); + switch (event.delta.type) { + case 'text_delta': { + if (snapshotContent?.type === 'text') { + snapshot.content[event.index] = { + ...snapshotContent, + text: (snapshotContent.text || '') + event.delta.text, + }; + } + break; + } + case 'citations_delta': { + if (snapshotContent?.type === 'text') { + snapshot.content[event.index] = { + ...snapshotContent, + citations: [...(snapshotContent.citations ?? []), event.delta.citation], + }; + } + break; + } + case 'input_json_delta': { + if (snapshotContent && tracksToolInput(snapshotContent)) { + // we need to keep track of the raw JSON string as well so that we can + // re-parse it for each delta, for now we just store it as an untyped + // non-enumerable property on the snapshot + let jsonBuf = snapshotContent[JSON_BUF_PROPERTY] || ''; + jsonBuf += event.delta.partial_json; + const newContent = { ...snapshotContent }; + Object.defineProperty(newContent, JSON_BUF_PROPERTY, { + value: jsonBuf, + enumerable: false, + writable: true, + }); + if (jsonBuf) { + try { + newContent.input = parser_partialParse(jsonBuf); + } + catch (err) { + const error = new error_AnthropicError(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${err}. JSON: ${jsonBuf}`); + tslib_classPrivateFieldGet(this, _BetaMessageStream_handleError, "f").call(this, error); + } + } + snapshot.content[event.index] = newContent; + } + break; + } + case 'thinking_delta': { + if (snapshotContent?.type === 'thinking') { + snapshot.content[event.index] = { + ...snapshotContent, + thinking: snapshotContent.thinking + event.delta.thinking, + }; + } + break; + } + case 'signature_delta': { + if (snapshotContent?.type === 'thinking') { + snapshot.content[event.index] = { + ...snapshotContent, + signature: event.delta.signature, + }; + } + break; + } + default: + checkNever(event.delta); + } + return snapshot; } + case 'content_block_stop': + return snapshot; } - for (const line of lineDecoder.flush()) { - yield JSON.parse(line); - } - } - [Symbol.asyncIterator]() { - return this.decoder(); - } - static fromResponse(response, controller) { - if (!response.body) { - controller.abort(); - if (typeof globalThis.navigator !== 'undefined' && - globalThis.navigator.product === 'ReactNative') { - throw new error_AnthropicError(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`); + }, Symbol.asyncIterator)]() { + const pushQueue = []; + const readQueue = []; + let done = false; + this.on('streamEvent', (event) => { + const reader = readQueue.shift(); + if (reader) { + reader.resolve(event); } - throw new error_AnthropicError(`Attempted to iterate over a response with no body`); - } - return new JSONLDecoder(shims_ReadableStreamToAsyncIterable(response.body), controller); + else { + pushQueue.push(event); + } + }); + this.on('end', () => { + done = true; + for (const reader of readQueue) { + reader.resolve(undefined); + } + readQueue.length = 0; + }); + this.on('abort', (err) => { + done = true; + for (const reader of readQueue) { + reader.reject(err); + } + readQueue.length = 0; + }); + this.on('error', (err) => { + done = true; + for (const reader of readQueue) { + reader.reject(err); + } + readQueue.length = 0; + }); + return { + next: async () => { + if (!pushQueue.length) { + if (done) { + return { value: undefined, done: true }; + } + return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((chunk) => (chunk ? { value: chunk, done: false } : { value: undefined, done: true })); + } + const chunk = pushQueue.shift(); + return { value: chunk, done: false }; + }, + return: async () => { + this.abort(); + return { value: undefined, done: true }; + }, + }; + } + toReadableStream() { + const stream = new streaming_Stream(this[Symbol.asyncIterator].bind(this), this.controller); + return stream.toReadableStream(); } } -//# sourceMappingURL=jsonl.mjs.map -;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/error.mjs - -//# sourceMappingURL=error.mjs.map -;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/resources/beta/messages/batches.mjs +// used to ensure exhaustive case matching without throwing a runtime error +function checkNever(x) { } +//# sourceMappingURL=BetaMessageStream.mjs.map +;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/internal/constants.mjs +// File containing shared constants +/** + * Model-specific timeout constraints for non-streaming requests + */ +const MODEL_NONSTREAMING_TOKENS = { + 'claude-opus-4-20250514': 8192, + 'claude-opus-4-0': 8192, + 'claude-4-opus-20250514': 8192, + 'anthropic.claude-opus-4-20250514-v1:0': 8192, + 'claude-opus-4@20250514': 8192, + 'claude-opus-4-1-20250805': 8192, + 'anthropic.claude-opus-4-1-20250805-v1:0': 8192, + 'claude-opus-4-1@20250805': 8192, +}; +//# sourceMappingURL=constants.mjs.map +;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/resources/beta/messages/messages.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +const DEPRECATED_MODELS = { + 'claude-1.3': 'November 6th, 2024', + 'claude-1.3-100k': 'November 6th, 2024', + 'claude-instant-1.1': 'November 6th, 2024', + 'claude-instant-1.1-100k': 'November 6th, 2024', + 'claude-instant-1.2': 'November 6th, 2024', + 'claude-3-sonnet-20240229': 'July 21st, 2025', + 'claude-3-opus-20240229': 'January 5th, 2026', + 'claude-2.1': 'July 21st, 2025', + 'claude-2.0': 'July 21st, 2025', +}; -class batches_Batches extends resource_APIResource { - /** - * Send a batch of Message creation requests. - * - * The Message Batches API can be used to process multiple Messages API requests at - * once. Once a Message Batch is created, it begins processing immediately. Batches - * can take up to 24 hours to complete. - * - * Learn more about the Message Batches API in our - * [user guide](/en/docs/build-with-claude/batch-processing) - * - * @example - * ```ts - * const betaMessageBatch = - * await client.beta.messages.batches.create({ - * requests: [ - * { - * custom_id: 'my-custom-id-1', - * params: { - * max_tokens: 1024, - * messages: [ - * { content: 'Hello, world', role: 'user' }, - * ], - * model: 'claude-3-7-sonnet-20250219', - * }, - * }, - * ], - * }); - * ``` - */ +class messages_messages_Messages extends resource_APIResource { + constructor() { + super(...arguments); + this.batches = new batches_Batches(this._client); + } create(params, options) { const { betas, ...body } = params; - return this._client.post('/v1/messages/batches?beta=true', { + if (body.model in DEPRECATED_MODELS) { + console.warn(`The model '${body.model}' is deprecated and will reach end-of-life on ${DEPRECATED_MODELS[body.model]}\nPlease migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`); + } + let timeout = this._client._options.timeout; + if (!body.stream && timeout == null) { + const maxNonstreamingTokens = MODEL_NONSTREAMING_TOKENS[body.model] ?? undefined; + timeout = this._client.calculateNonstreamingTimeout(body.max_tokens, maxNonstreamingTokens); + } + return this._client.post('/v1/messages?beta=true', { body, + timeout: timeout ?? 600000, ...options, - headers: buildHeaders([ - { 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString() }, - options?.headers, - ]), - }); - } - /** - * This endpoint is idempotent and can be used to poll for Message Batch - * completion. To access the results of a Message Batch, make a request to the - * `results_url` field in the response. - * - * Learn more about the Message Batches API in our - * [user guide](/en/docs/build-with-claude/batch-processing) - * - * @example - * ```ts - * const betaMessageBatch = - * await client.beta.messages.batches.retrieve( - * 'message_batch_id', - * ); - * ``` - */ - retrieve(messageBatchID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.get(path `/v1/messages/batches/${messageBatchID}?beta=true`, { - ...options, - headers: buildHeaders([ - { 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString() }, - options?.headers, - ]), - }); - } - /** - * List all Message Batches within a Workspace. Most recently created batches are - * returned first. - * - * Learn more about the Message Batches API in our - * [user guide](/en/docs/build-with-claude/batch-processing) - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const betaMessageBatch of client.beta.messages.batches.list()) { - * // ... - * } - * ``` - */ - list(params = {}, options) { - const { betas, ...query } = params ?? {}; - return this._client.getAPIList('/v1/messages/batches?beta=true', (pagination_Page), { - query, - ...options, - headers: buildHeaders([ - { 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString() }, + headers: headers_buildHeaders([ + { ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) }, options?.headers, ]), + stream: params.stream ?? false, }); } /** - * Delete a Message Batch. - * - * Message Batches can only be deleted once they've finished processing. If you'd - * like to delete an in-progress batch, you must first cancel it. - * - * Learn more about the Message Batches API in our - * [user guide](/en/docs/build-with-claude/batch-processing) - * - * @example - * ```ts - * const betaDeletedMessageBatch = - * await client.beta.messages.batches.delete( - * 'message_batch_id', - * ); - * ``` + * Create a Message stream */ - delete(messageBatchID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.delete(path `/v1/messages/batches/${messageBatchID}?beta=true`, { - ...options, - headers: buildHeaders([ - { 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString() }, - options?.headers, - ]), - }); + stream(body, options) { + return BetaMessageStream.createMessage(this, body, options); } /** - * Batches may be canceled any time before processing ends. Once cancellation is - * initiated, the batch enters a `canceling` state, at which time the system may - * complete any in-progress, non-interruptible requests before finalizing - * cancellation. + * Count the number of tokens in a Message. * - * The number of canceled requests is specified in `request_counts`. To determine - * which requests were canceled, check the individual results within the batch. - * Note that cancellation may not result in any canceled requests if they were - * non-interruptible. + * The Token Count API can be used to count the number of tokens in a Message, + * including tools, images, and documents, without creating it. * - * Learn more about the Message Batches API in our - * [user guide](/en/docs/build-with-claude/batch-processing) + * Learn more about token counting in our + * [user guide](/en/docs/build-with-claude/token-counting) * * @example * ```ts - * const betaMessageBatch = - * await client.beta.messages.batches.cancel( - * 'message_batch_id', - * ); + * const betaMessageTokensCount = + * await client.beta.messages.countTokens({ + * messages: [{ content: 'string', role: 'user' }], + * model: 'claude-3-7-sonnet-latest', + * }); * ``` */ - cancel(messageBatchID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.post(path `/v1/messages/batches/${messageBatchID}/cancel?beta=true`, { + countTokens(params, options) { + const { betas, ...body } = params; + return this._client.post('/v1/messages/count_tokens?beta=true', { + body, ...options, - headers: buildHeaders([ - { 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString() }, + headers: headers_buildHeaders([ + { 'anthropic-beta': [...(betas ?? []), 'token-counting-2024-11-01'].toString() }, options?.headers, ]), }); } - /** - * Streams the results of a Message Batch as a `.jsonl` file. - * - * Each line in the file is a JSON object containing the result of a single request - * in the Message Batch. Results are not guaranteed to be in the same order as - * requests. Use the `custom_id` field to match results to requests. - * - * Learn more about the Message Batches API in our - * [user guide](/en/docs/build-with-claude/batch-processing) - * - * @example - * ```ts - * const betaMessageBatchIndividualResponse = - * await client.beta.messages.batches.results( - * 'message_batch_id', - * ); - * ``` - */ - async results(messageBatchID, params = {}, options) { - const batch = await this.retrieve(messageBatchID); - if (!batch.results_url) { - throw new error_AnthropicError(`No batch \`results_url\`; Has it finished processing? ${batch.processing_status} - ${batch.id}`); - } - const { betas } = params ?? {}; - return this._client - .get(batch.results_url, { - ...options, - headers: buildHeaders([ - { - 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString(), - Accept: 'application/binary', - }, - options?.headers, - ]), - stream: true, - __binaryResponse: true, - }) - ._thenUnwrap((_, props) => JSONLDecoder.fromResponse(props.response, props.controller)); - } } -//# sourceMappingURL=batches.mjs.map -;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/streaming.mjs +messages_messages_Messages.Batches = batches_Batches; +//# sourceMappingURL=messages.mjs.map +;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/resources/beta/beta.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -//# sourceMappingURL=streaming.mjs.map -;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/_vendor/partial-json-parser/parser.mjs -const tokenize = (input) => { - let current = 0; - let tokens = []; - while (current < input.length) { - let char = input[current]; - if (char === '\\') { - current++; - continue; - } - if (char === '{') { - tokens.push({ - type: 'brace', - value: '{', - }); - current++; - continue; - } - if (char === '}') { - tokens.push({ - type: 'brace', - value: '}', - }); - current++; - continue; - } - if (char === '[') { - tokens.push({ - type: 'paren', - value: '[', - }); - current++; - continue; - } - if (char === ']') { - tokens.push({ - type: 'paren', - value: ']', - }); - current++; - continue; - } - if (char === ':') { - tokens.push({ - type: 'separator', - value: ':', - }); - current++; - continue; - } - if (char === ',') { - tokens.push({ - type: 'delimiter', - value: ',', - }); - current++; - continue; - } - if (char === '"') { - let value = ''; - let danglingQuote = false; - char = input[++current]; - while (char !== '"') { - if (current === input.length) { - danglingQuote = true; - break; - } - if (char === '\\') { - current++; - if (current === input.length) { - danglingQuote = true; - break; - } - value += char + input[current]; - char = input[++current]; - } - else { - value += char; - char = input[++current]; - } - } - char = input[++current]; - if (!danglingQuote) { - tokens.push({ - type: 'string', - value, - }); - } - continue; - } - let WHITESPACE = /\s/; - if (char && WHITESPACE.test(char)) { - current++; - continue; - } - let NUMBERS = /[0-9]/; - if ((char && NUMBERS.test(char)) || char === '-' || char === '.') { - let value = ''; - if (char === '-') { - value += char; - char = input[++current]; - } - while ((char && NUMBERS.test(char)) || char === '.') { - value += char; - char = input[++current]; - } - tokens.push({ - type: 'number', - value, - }); - continue; - } - let LETTERS = /[a-z]/i; - if (char && LETTERS.test(char)) { - let value = ''; - while (char && LETTERS.test(char)) { - if (current === input.length) { - break; - } - value += char; - char = input[++current]; - } - if (value == 'true' || value == 'false' || value === 'null') { - tokens.push({ - type: 'name', - value, - }); - } - else { - // unknown token, e.g. `nul` which isn't quite `null` - current++; - continue; - } - continue; - } - current++; - } - return tokens; -}, strip = (tokens) => { - if (tokens.length === 0) { - return tokens; - } - let lastToken = tokens[tokens.length - 1]; - switch (lastToken.type) { - case 'separator': - tokens = tokens.slice(0, tokens.length - 1); - return strip(tokens); - break; - case 'number': - let lastCharacterOfLastToken = lastToken.value[lastToken.value.length - 1]; - if (lastCharacterOfLastToken === '.' || lastCharacterOfLastToken === '-') { - tokens = tokens.slice(0, tokens.length - 1); - return strip(tokens); - } - case 'string': - let tokenBeforeTheLastToken = tokens[tokens.length - 2]; - if (tokenBeforeTheLastToken?.type === 'delimiter') { - tokens = tokens.slice(0, tokens.length - 1); - return strip(tokens); - } - else if (tokenBeforeTheLastToken?.type === 'brace' && tokenBeforeTheLastToken.value === '{') { - tokens = tokens.slice(0, tokens.length - 1); - return strip(tokens); - } - break; - case 'delimiter': - tokens = tokens.slice(0, tokens.length - 1); - return strip(tokens); - break; - } - return tokens; -}, unstrip = (tokens) => { - let tail = []; - tokens.map((token) => { - if (token.type === 'brace') { - if (token.value === '{') { - tail.push('}'); - } - else { - tail.splice(tail.lastIndexOf('}'), 1); - } - } - if (token.type === 'paren') { - if (token.value === '[') { - tail.push(']'); - } - else { - tail.splice(tail.lastIndexOf(']'), 1); - } - } - }); - if (tail.length > 0) { - tail.reverse().map((item) => { - if (item === '}') { - tokens.push({ - type: 'brace', - value: '}', - }); - } - else if (item === ']') { - tokens.push({ - type: 'paren', - value: ']', - }); - } - }); + + + + + + +class beta_Beta extends resource_APIResource { + constructor() { + super(...arguments); + this.models = new models_Models(this._client); + this.messages = new messages_messages_Messages(this._client); + this.files = new beta_files_Files(this._client); } - return tokens; -}, generate = (tokens) => { - let output = ''; - tokens.map((token) => { - switch (token.type) { - case 'string': - output += '"' + token.value + '"'; - break; - default: - output += token.value; - break; - } - }); - return output; -}, parser_partialParse = (input) => JSON.parse(generate(unstrip(strip(tokenize(input))))); +} +beta_Beta.Models = models_Models; +beta_Beta.Messages = messages_messages_Messages; +beta_Beta.Files = beta_files_Files; +//# sourceMappingURL=beta.mjs.map +;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/resources/completions.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -//# sourceMappingURL=parser.mjs.map -;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/lib/BetaMessageStream.mjs -var _BetaMessageStream_instances, _BetaMessageStream_currentMessageSnapshot, _BetaMessageStream_connectedPromise, _BetaMessageStream_resolveConnectedPromise, _BetaMessageStream_rejectConnectedPromise, _BetaMessageStream_endPromise, _BetaMessageStream_resolveEndPromise, _BetaMessageStream_rejectEndPromise, _BetaMessageStream_listeners, _BetaMessageStream_ended, _BetaMessageStream_errored, _BetaMessageStream_aborted, _BetaMessageStream_catchingPromiseCreated, _BetaMessageStream_response, _BetaMessageStream_request_id, _BetaMessageStream_getFinalMessage, _BetaMessageStream_getFinalText, _BetaMessageStream_handleError, _BetaMessageStream_beginRequest, _BetaMessageStream_addStreamEvent, _BetaMessageStream_endRequest, _BetaMessageStream_accumulateMessage; + +class resources_completions_Completions extends resource_APIResource { + create(params, options) { + const { betas, ...body } = params; + return this._client.post('/v1/complete', { + body, + timeout: this._client._options.timeout ?? 600000, + ...options, + headers: headers_buildHeaders([ + { ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) }, + options?.headers, + ]), + stream: params.stream ?? false, + }); + } +} +//# sourceMappingURL=completions.mjs.map +;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/lib/MessageStream.mjs +var _MessageStream_instances, _MessageStream_currentMessageSnapshot, _MessageStream_connectedPromise, _MessageStream_resolveConnectedPromise, _MessageStream_rejectConnectedPromise, _MessageStream_endPromise, _MessageStream_resolveEndPromise, _MessageStream_rejectEndPromise, _MessageStream_listeners, _MessageStream_ended, _MessageStream_errored, _MessageStream_aborted, _MessageStream_catchingPromiseCreated, _MessageStream_response, _MessageStream_request_id, _MessageStream_getFinalMessage, _MessageStream_getFinalText, _MessageStream_handleError, _MessageStream_beginRequest, _MessageStream_addStreamEvent, _MessageStream_endRequest, _MessageStream_accumulateMessage; -const JSON_BUF_PROPERTY = '__json_buf'; -class BetaMessageStream { +const MessageStream_JSON_BUF_PROPERTY = '__json_buf'; +function MessageStream_tracksToolInput(content) { + return content.type === 'tool_use' || content.type === 'server_tool_use'; +} +class MessageStream { constructor() { - _BetaMessageStream_instances.add(this); + _MessageStream_instances.add(this); this.messages = []; this.receivedMessages = []; - _BetaMessageStream_currentMessageSnapshot.set(this, void 0); + _MessageStream_currentMessageSnapshot.set(this, void 0); this.controller = new AbortController(); - _BetaMessageStream_connectedPromise.set(this, void 0); - _BetaMessageStream_resolveConnectedPromise.set(this, () => { }); - _BetaMessageStream_rejectConnectedPromise.set(this, () => { }); - _BetaMessageStream_endPromise.set(this, void 0); - _BetaMessageStream_resolveEndPromise.set(this, () => { }); - _BetaMessageStream_rejectEndPromise.set(this, () => { }); - _BetaMessageStream_listeners.set(this, {}); - _BetaMessageStream_ended.set(this, false); - _BetaMessageStream_errored.set(this, false); - _BetaMessageStream_aborted.set(this, false); - _BetaMessageStream_catchingPromiseCreated.set(this, false); - _BetaMessageStream_response.set(this, void 0); - _BetaMessageStream_request_id.set(this, void 0); - _BetaMessageStream_handleError.set(this, (error) => { - tslib_classPrivateFieldSet(this, _BetaMessageStream_errored, true, "f"); - if (isAbortError(error)) { + _MessageStream_connectedPromise.set(this, void 0); + _MessageStream_resolveConnectedPromise.set(this, () => { }); + _MessageStream_rejectConnectedPromise.set(this, () => { }); + _MessageStream_endPromise.set(this, void 0); + _MessageStream_resolveEndPromise.set(this, () => { }); + _MessageStream_rejectEndPromise.set(this, () => { }); + _MessageStream_listeners.set(this, {}); + _MessageStream_ended.set(this, false); + _MessageStream_errored.set(this, false); + _MessageStream_aborted.set(this, false); + _MessageStream_catchingPromiseCreated.set(this, false); + _MessageStream_response.set(this, void 0); + _MessageStream_request_id.set(this, void 0); + _MessageStream_handleError.set(this, (error) => { + tslib_classPrivateFieldSet(this, _MessageStream_errored, true, "f"); + if (errors_isAbortError(error)) { error = new error_APIUserAbortError(); } if (error instanceof error_APIUserAbortError) { - tslib_classPrivateFieldSet(this, _BetaMessageStream_aborted, true, "f"); + tslib_classPrivateFieldSet(this, _MessageStream_aborted, true, "f"); return this._emit('abort', error); } if (error instanceof error_AnthropicError) { @@ -78164,26 +73142,26 @@ class BetaMessageStream { } return this._emit('error', new error_AnthropicError(String(error))); }); - tslib_classPrivateFieldSet(this, _BetaMessageStream_connectedPromise, new Promise((resolve, reject) => { - tslib_classPrivateFieldSet(this, _BetaMessageStream_resolveConnectedPromise, resolve, "f"); - tslib_classPrivateFieldSet(this, _BetaMessageStream_rejectConnectedPromise, reject, "f"); + tslib_classPrivateFieldSet(this, _MessageStream_connectedPromise, new Promise((resolve, reject) => { + tslib_classPrivateFieldSet(this, _MessageStream_resolveConnectedPromise, resolve, "f"); + tslib_classPrivateFieldSet(this, _MessageStream_rejectConnectedPromise, reject, "f"); }), "f"); - tslib_classPrivateFieldSet(this, _BetaMessageStream_endPromise, new Promise((resolve, reject) => { - tslib_classPrivateFieldSet(this, _BetaMessageStream_resolveEndPromise, resolve, "f"); - tslib_classPrivateFieldSet(this, _BetaMessageStream_rejectEndPromise, reject, "f"); + tslib_classPrivateFieldSet(this, _MessageStream_endPromise, new Promise((resolve, reject) => { + tslib_classPrivateFieldSet(this, _MessageStream_resolveEndPromise, resolve, "f"); + tslib_classPrivateFieldSet(this, _MessageStream_rejectEndPromise, reject, "f"); }), "f"); // Don't let these promises cause unhandled rejection errors. // we will manually cause an unhandled rejection error later // if the user hasn't registered any error listener or called // any promise-returning method. - tslib_classPrivateFieldGet(this, _BetaMessageStream_connectedPromise, "f").catch(() => { }); - tslib_classPrivateFieldGet(this, _BetaMessageStream_endPromise, "f").catch(() => { }); + tslib_classPrivateFieldGet(this, _MessageStream_connectedPromise, "f").catch(() => { }); + tslib_classPrivateFieldGet(this, _MessageStream_endPromise, "f").catch(() => { }); } get response() { - return tslib_classPrivateFieldGet(this, _BetaMessageStream_response, "f"); + return tslib_classPrivateFieldGet(this, _MessageStream_response, "f"); } get request_id() { - return tslib_classPrivateFieldGet(this, _BetaMessageStream_request_id, "f"); + return tslib_classPrivateFieldGet(this, _MessageStream_request_id, "f"); } /** * Returns the `MessageStream` data, the raw `Response` instance and the ID of the request, @@ -78196,7 +73174,7 @@ class BetaMessageStream { * as no `Response` is available. */ async withResponse() { - const response = await tslib_classPrivateFieldGet(this, _BetaMessageStream_connectedPromise, "f"); + const response = await tslib_classPrivateFieldGet(this, _MessageStream_connectedPromise, "f"); if (!response) { throw new Error('Could not resolve a `Response` object'); } @@ -78214,12 +73192,12 @@ class BetaMessageStream { * in this context. */ static fromReadableStream(stream) { - const runner = new BetaMessageStream(); + const runner = new MessageStream(); runner._run(() => runner._fromReadableStream(stream)); return runner; } static createMessage(messages, params, options) { - const runner = new BetaMessageStream(); + const runner = new MessageStream(); for (const message of params.messages) { runner._addMessageParam(message); } @@ -78230,7 +73208,7 @@ class BetaMessageStream { executor().then(() => { this._emitFinal(); this._emit('end'); - }, tslib_classPrivateFieldGet(this, _BetaMessageStream_handleError, "f")); + }, tslib_classPrivateFieldGet(this, _MessageStream_handleError, "f")); } _addMessageParam(message) { this.messages.push(message); @@ -78243,40 +73221,49 @@ class BetaMessageStream { } async _createMessage(messages, params, options) { const signal = options?.signal; + let abortHandler; if (signal) { if (signal.aborted) this.controller.abort(); - signal.addEventListener('abort', () => this.controller.abort()); + abortHandler = this.controller.abort.bind(this.controller); + signal.addEventListener('abort', abortHandler); } - tslib_classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_beginRequest).call(this); - const { response, data: stream } = await messages - .create({ ...params, stream: true }, { ...options, signal: this.controller.signal }) - .withResponse(); - this._connected(response); - for await (const event of stream) { - tslib_classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_addStreamEvent).call(this, event); + try { + tslib_classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_beginRequest).call(this); + const { response, data: stream } = await messages + .create({ ...params, stream: true }, { ...options, signal: this.controller.signal }) + .withResponse(); + this._connected(response); + for await (const event of stream) { + tslib_classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_addStreamEvent).call(this, event); + } + if (stream.controller.signal?.aborted) { + throw new error_APIUserAbortError(); + } + tslib_classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_endRequest).call(this); } - if (stream.controller.signal?.aborted) { - throw new error_APIUserAbortError(); + finally { + if (signal && abortHandler) { + signal.removeEventListener('abort', abortHandler); + } } - tslib_classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_endRequest).call(this); } _connected(response) { if (this.ended) return; - tslib_classPrivateFieldSet(this, _BetaMessageStream_response, response, "f"); - tslib_classPrivateFieldSet(this, _BetaMessageStream_request_id, response?.headers.get('request-id'), "f"); - tslib_classPrivateFieldGet(this, _BetaMessageStream_resolveConnectedPromise, "f").call(this, response); + tslib_classPrivateFieldSet(this, _MessageStream_response, response, "f"); + tslib_classPrivateFieldSet(this, _MessageStream_request_id, response?.headers.get('request-id'), "f"); + tslib_classPrivateFieldGet(this, _MessageStream_resolveConnectedPromise, "f").call(this, response); this._emit('connect'); } get ended() { - return tslib_classPrivateFieldGet(this, _BetaMessageStream_ended, "f"); + return tslib_classPrivateFieldGet(this, _MessageStream_ended, "f"); } get errored() { - return tslib_classPrivateFieldGet(this, _BetaMessageStream_errored, "f"); + return tslib_classPrivateFieldGet(this, _MessageStream_errored, "f"); } get aborted() { - return tslib_classPrivateFieldGet(this, _BetaMessageStream_aborted, "f"); + return tslib_classPrivateFieldGet(this, _MessageStream_aborted, "f"); } abort() { this.controller.abort(); @@ -78289,7 +73276,7 @@ class BetaMessageStream { * @returns this MessageStream, so that calls can be chained */ on(event, listener) { - const listeners = tslib_classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] || (tslib_classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] = []); + const listeners = tslib_classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] || (tslib_classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] = []); listeners.push({ listener }); return this; } @@ -78301,7 +73288,7 @@ class BetaMessageStream { * @returns this MessageStream, so that calls can be chained */ off(event, listener) { - const listeners = tslib_classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event]; + const listeners = tslib_classPrivateFieldGet(this, _MessageStream_listeners, "f")[event]; if (!listeners) return this; const index = listeners.findIndex((l) => l.listener === listener); @@ -78315,7 +73302,7 @@ class BetaMessageStream { * @returns this MessageStream, so that calls can be chained */ once(event, listener) { - const listeners = tslib_classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] || (tslib_classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] = []); + const listeners = tslib_classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] || (tslib_classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] = []); listeners.push({ listener, once: true }); return this; } @@ -78332,18 +73319,18 @@ class BetaMessageStream { */ emitted(event) { return new Promise((resolve, reject) => { - tslib_classPrivateFieldSet(this, _BetaMessageStream_catchingPromiseCreated, true, "f"); + tslib_classPrivateFieldSet(this, _MessageStream_catchingPromiseCreated, true, "f"); if (event !== 'error') this.once('error', reject); this.once(event, resolve); }); } async done() { - tslib_classPrivateFieldSet(this, _BetaMessageStream_catchingPromiseCreated, true, "f"); - await tslib_classPrivateFieldGet(this, _BetaMessageStream_endPromise, "f"); + tslib_classPrivateFieldSet(this, _MessageStream_catchingPromiseCreated, true, "f"); + await tslib_classPrivateFieldGet(this, _MessageStream_endPromise, "f"); } get currentMessage() { - return tslib_classPrivateFieldGet(this, _BetaMessageStream_currentMessageSnapshot, "f"); + return tslib_classPrivateFieldGet(this, _MessageStream_currentMessageSnapshot, "f"); } /** * @returns a promise that resolves with the the final assistant Message response, @@ -78351,7 +73338,7 @@ class BetaMessageStream { */ async finalMessage() { await this.done(); - return tslib_classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_getFinalMessage).call(this); + return tslib_classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_getFinalMessage).call(this); } /** * @returns a promise that resolves with the the final assistant Message's text response, concatenated @@ -78360,35 +73347,35 @@ class BetaMessageStream { */ async finalText() { await this.done(); - return tslib_classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_getFinalText).call(this); + return tslib_classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_getFinalText).call(this); } _emit(event, ...args) { // make sure we don't emit any MessageStreamEvents after end - if (tslib_classPrivateFieldGet(this, _BetaMessageStream_ended, "f")) + if (tslib_classPrivateFieldGet(this, _MessageStream_ended, "f")) return; if (event === 'end') { - tslib_classPrivateFieldSet(this, _BetaMessageStream_ended, true, "f"); - tslib_classPrivateFieldGet(this, _BetaMessageStream_resolveEndPromise, "f").call(this); + tslib_classPrivateFieldSet(this, _MessageStream_ended, true, "f"); + tslib_classPrivateFieldGet(this, _MessageStream_resolveEndPromise, "f").call(this); } - const listeners = tslib_classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event]; + const listeners = tslib_classPrivateFieldGet(this, _MessageStream_listeners, "f")[event]; if (listeners) { - tslib_classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] = listeners.filter((l) => !l.once); + tslib_classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] = listeners.filter((l) => !l.once); listeners.forEach(({ listener }) => listener(...args)); } if (event === 'abort') { const error = args[0]; - if (!tslib_classPrivateFieldGet(this, _BetaMessageStream_catchingPromiseCreated, "f") && !listeners?.length) { + if (!tslib_classPrivateFieldGet(this, _MessageStream_catchingPromiseCreated, "f") && !listeners?.length) { Promise.reject(error); } - tslib_classPrivateFieldGet(this, _BetaMessageStream_rejectConnectedPromise, "f").call(this, error); - tslib_classPrivateFieldGet(this, _BetaMessageStream_rejectEndPromise, "f").call(this, error); + tslib_classPrivateFieldGet(this, _MessageStream_rejectConnectedPromise, "f").call(this, error); + tslib_classPrivateFieldGet(this, _MessageStream_rejectEndPromise, "f").call(this, error); this._emit('end'); return; } if (event === 'error') { // NOTE: _emit('error', error) should only be called from #handleError(). const error = args[0]; - if (!tslib_classPrivateFieldGet(this, _BetaMessageStream_catchingPromiseCreated, "f") && !listeners?.length) { + if (!tslib_classPrivateFieldGet(this, _MessageStream_catchingPromiseCreated, "f") && !listeners?.length) { // Trigger an unhandled rejection if the user hasn't registered any error handlers. // If you are seeing stack traces here, make sure to handle errors via either: // - runner.on('error', () => ...) @@ -78397,41 +73384,50 @@ class BetaMessageStream { // - etc. Promise.reject(error); } - tslib_classPrivateFieldGet(this, _BetaMessageStream_rejectConnectedPromise, "f").call(this, error); - tslib_classPrivateFieldGet(this, _BetaMessageStream_rejectEndPromise, "f").call(this, error); + tslib_classPrivateFieldGet(this, _MessageStream_rejectConnectedPromise, "f").call(this, error); + tslib_classPrivateFieldGet(this, _MessageStream_rejectEndPromise, "f").call(this, error); this._emit('end'); } } _emitFinal() { const finalMessage = this.receivedMessages.at(-1); if (finalMessage) { - this._emit('finalMessage', tslib_classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_getFinalMessage).call(this)); + this._emit('finalMessage', tslib_classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_getFinalMessage).call(this)); } } async _fromReadableStream(readableStream, options) { const signal = options?.signal; + let abortHandler; if (signal) { if (signal.aborted) this.controller.abort(); - signal.addEventListener('abort', () => this.controller.abort()); + abortHandler = this.controller.abort.bind(this.controller); + signal.addEventListener('abort', abortHandler); } - tslib_classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_beginRequest).call(this); - this._connected(null); - const stream = streaming_Stream.fromReadableStream(readableStream, this.controller); - for await (const event of stream) { - tslib_classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_addStreamEvent).call(this, event); + try { + tslib_classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_beginRequest).call(this); + this._connected(null); + const stream = streaming_Stream.fromReadableStream(readableStream, this.controller); + for await (const event of stream) { + tslib_classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_addStreamEvent).call(this, event); + } + if (stream.controller.signal?.aborted) { + throw new error_APIUserAbortError(); + } + tslib_classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_endRequest).call(this); } - if (stream.controller.signal?.aborted) { - throw new error_APIUserAbortError(); + finally { + if (signal && abortHandler) { + signal.removeEventListener('abort', abortHandler); + } } - tslib_classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_endRequest).call(this); } - [(_BetaMessageStream_currentMessageSnapshot = new WeakMap(), _BetaMessageStream_connectedPromise = new WeakMap(), _BetaMessageStream_resolveConnectedPromise = new WeakMap(), _BetaMessageStream_rejectConnectedPromise = new WeakMap(), _BetaMessageStream_endPromise = new WeakMap(), _BetaMessageStream_resolveEndPromise = new WeakMap(), _BetaMessageStream_rejectEndPromise = new WeakMap(), _BetaMessageStream_listeners = new WeakMap(), _BetaMessageStream_ended = new WeakMap(), _BetaMessageStream_errored = new WeakMap(), _BetaMessageStream_aborted = new WeakMap(), _BetaMessageStream_catchingPromiseCreated = new WeakMap(), _BetaMessageStream_response = new WeakMap(), _BetaMessageStream_request_id = new WeakMap(), _BetaMessageStream_handleError = new WeakMap(), _BetaMessageStream_instances = new WeakSet(), _BetaMessageStream_getFinalMessage = function _BetaMessageStream_getFinalMessage() { + [(_MessageStream_currentMessageSnapshot = new WeakMap(), _MessageStream_connectedPromise = new WeakMap(), _MessageStream_resolveConnectedPromise = new WeakMap(), _MessageStream_rejectConnectedPromise = new WeakMap(), _MessageStream_endPromise = new WeakMap(), _MessageStream_resolveEndPromise = new WeakMap(), _MessageStream_rejectEndPromise = new WeakMap(), _MessageStream_listeners = new WeakMap(), _MessageStream_ended = new WeakMap(), _MessageStream_errored = new WeakMap(), _MessageStream_aborted = new WeakMap(), _MessageStream_catchingPromiseCreated = new WeakMap(), _MessageStream_response = new WeakMap(), _MessageStream_request_id = new WeakMap(), _MessageStream_handleError = new WeakMap(), _MessageStream_instances = new WeakSet(), _MessageStream_getFinalMessage = function _MessageStream_getFinalMessage() { if (this.receivedMessages.length === 0) { throw new error_AnthropicError('stream ended without producing a Message with role=assistant'); } return this.receivedMessages.at(-1); - }, _BetaMessageStream_getFinalText = function _BetaMessageStream_getFinalText() { + }, _MessageStream_getFinalText = function _MessageStream_getFinalText() { if (this.receivedMessages.length === 0) { throw new error_AnthropicError('stream ended without producing a Message with role=assistant'); } @@ -78443,14 +73439,14 @@ class BetaMessageStream { throw new error_AnthropicError('stream ended without producing a content block with type=text'); } return textBlocks.join(' '); - }, _BetaMessageStream_beginRequest = function _BetaMessageStream_beginRequest() { + }, _MessageStream_beginRequest = function _MessageStream_beginRequest() { if (this.ended) return; - tslib_classPrivateFieldSet(this, _BetaMessageStream_currentMessageSnapshot, undefined, "f"); - }, _BetaMessageStream_addStreamEvent = function _BetaMessageStream_addStreamEvent(event) { + tslib_classPrivateFieldSet(this, _MessageStream_currentMessageSnapshot, undefined, "f"); + }, _MessageStream_addStreamEvent = function _MessageStream_addStreamEvent(event) { if (this.ended) return; - const messageSnapshot = tslib_classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_accumulateMessage).call(this, event); + const messageSnapshot = tslib_classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_accumulateMessage).call(this, event); this._emit('streamEvent', event, messageSnapshot); switch (event.type) { case 'content_block_delta': { @@ -78469,7 +73465,7 @@ class BetaMessageStream { break; } case 'input_json_delta': { - if (content.type === 'tool_use' && content.input) { + if (MessageStream_tracksToolInput(content) && content.input) { this._emit('inputJson', event.delta.partial_json, content.input); } break; @@ -78487,7 +73483,7 @@ class BetaMessageStream { break; } default: - checkNever(event.delta); + MessageStream_checkNever(event.delta); } break; } @@ -78501,25 +73497,25 @@ class BetaMessageStream { break; } case 'message_start': { - tslib_classPrivateFieldSet(this, _BetaMessageStream_currentMessageSnapshot, messageSnapshot, "f"); + tslib_classPrivateFieldSet(this, _MessageStream_currentMessageSnapshot, messageSnapshot, "f"); break; } case 'content_block_start': case 'message_delta': break; } - }, _BetaMessageStream_endRequest = function _BetaMessageStream_endRequest() { + }, _MessageStream_endRequest = function _MessageStream_endRequest() { if (this.ended) { throw new error_AnthropicError(`stream has ended, this shouldn't happen`); } - const snapshot = tslib_classPrivateFieldGet(this, _BetaMessageStream_currentMessageSnapshot, "f"); + const snapshot = tslib_classPrivateFieldGet(this, _MessageStream_currentMessageSnapshot, "f"); if (!snapshot) { throw new error_AnthropicError(`request ended without sending any chunks`); } - tslib_classPrivateFieldSet(this, _BetaMessageStream_currentMessageSnapshot, undefined, "f"); + tslib_classPrivateFieldSet(this, _MessageStream_currentMessageSnapshot, undefined, "f"); return snapshot; - }, _BetaMessageStream_accumulateMessage = function _BetaMessageStream_accumulateMessage(event) { - let snapshot = tslib_classPrivateFieldGet(this, _BetaMessageStream_currentMessageSnapshot, "f"); + }, _MessageStream_accumulateMessage = function _MessageStream_accumulateMessage(event) { + let snapshot = tslib_classPrivateFieldGet(this, _MessageStream_currentMessageSnapshot, "f"); if (event.type === 'message_start') { if (snapshot) { throw new error_AnthropicError(`Unexpected event order, got ${event.type} before receiving "message_stop"`); @@ -78536,6 +73532,7 @@ class BetaMessageStream { snapshot.stop_reason = event.delta.stop_reason; snapshot.stop_sequence = event.delta.stop_sequence; snapshot.usage.output_tokens = event.usage.output_tokens; + // Update other usage fields if they exist in the event if (event.usage.input_tokens != null) { snapshot.usage.input_tokens = event.usage.input_tokens; } @@ -78550,56 +73547,69 @@ class BetaMessageStream { } return snapshot; case 'content_block_start': - snapshot.content.push(event.content_block); + snapshot.content.push({ ...event.content_block }); return snapshot; case 'content_block_delta': { const snapshotContent = snapshot.content.at(event.index); switch (event.delta.type) { case 'text_delta': { if (snapshotContent?.type === 'text') { - snapshotContent.text += event.delta.text; + snapshot.content[event.index] = { + ...snapshotContent, + text: (snapshotContent.text || '') + event.delta.text, + }; } break; } case 'citations_delta': { if (snapshotContent?.type === 'text') { - snapshotContent.citations ?? (snapshotContent.citations = []); - snapshotContent.citations.push(event.delta.citation); + snapshot.content[event.index] = { + ...snapshotContent, + citations: [...(snapshotContent.citations ?? []), event.delta.citation], + }; } break; } case 'input_json_delta': { - if (snapshotContent?.type === 'tool_use') { + if (snapshotContent && MessageStream_tracksToolInput(snapshotContent)) { // we need to keep track of the raw JSON string as well so that we can // re-parse it for each delta, for now we just store it as an untyped // non-enumerable property on the snapshot - let jsonBuf = snapshotContent[JSON_BUF_PROPERTY] || ''; + let jsonBuf = snapshotContent[MessageStream_JSON_BUF_PROPERTY] || ''; jsonBuf += event.delta.partial_json; - Object.defineProperty(snapshotContent, JSON_BUF_PROPERTY, { + const newContent = { ...snapshotContent }; + Object.defineProperty(newContent, MessageStream_JSON_BUF_PROPERTY, { value: jsonBuf, enumerable: false, writable: true, }); if (jsonBuf) { - snapshotContent.input = parser_partialParse(jsonBuf); + newContent.input = parser_partialParse(jsonBuf); } + snapshot.content[event.index] = newContent; } break; } case 'thinking_delta': { if (snapshotContent?.type === 'thinking') { - snapshotContent.thinking += event.delta.thinking; + snapshot.content[event.index] = { + ...snapshotContent, + thinking: snapshotContent.thinking + event.delta.thinking, + }; } break; } case 'signature_delta': { if (snapshotContent?.type === 'thinking') { - snapshotContent.signature = event.delta.signature; + snapshot.content[event.index] = { + ...snapshotContent, + signature: event.delta.signature, + }; } break; } default: - checkNever(event.delta); + MessageStream_checkNever(event.delta); } return snapshot; } @@ -78663,122 +73673,8 @@ class BetaMessageStream { } } // used to ensure exhaustive case matching without throwing a runtime error -function checkNever(x) { } -//# sourceMappingURL=BetaMessageStream.mjs.map -;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/resources/beta/messages/messages.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - -const DEPRECATED_MODELS = { - 'claude-1.3': 'November 6th, 2024', - 'claude-1.3-100k': 'November 6th, 2024', - 'claude-instant-1.1': 'November 6th, 2024', - 'claude-instant-1.1-100k': 'November 6th, 2024', - 'claude-instant-1.2': 'November 6th, 2024', - 'claude-3-sonnet-20240229': 'July 21st, 2025', - 'claude-2.1': 'July 21st, 2025', - 'claude-2.0': 'July 21st, 2025', -}; -class messages_messages_Messages extends resource_APIResource { - constructor() { - super(...arguments); - this.batches = new batches_Batches(this._client); - } - create(params, options) { - const { betas, ...body } = params; - if (body.model in DEPRECATED_MODELS) { - console.warn(`The model '${body.model}' is deprecated and will reach end-of-life on ${DEPRECATED_MODELS[body.model]}\nPlease migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`); - } - return this._client.post('/v1/messages?beta=true', { - body, - timeout: this._client._options.timeout ?? - (body.stream ? 600000 : this._client._calculateNonstreamingTimeout(body.max_tokens)), - ...options, - headers: buildHeaders([ - { ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) }, - options?.headers, - ]), - stream: params.stream ?? false, - }); - } - /** - * Create a Message stream - */ - stream(body, options) { - return BetaMessageStream.createMessage(this, body, options); - } - /** - * Count the number of tokens in a Message. - * - * The Token Count API can be used to count the number of tokens in a Message, - * including tools, images, and documents, without creating it. - * - * Learn more about token counting in our - * [user guide](/en/docs/build-with-claude/token-counting) - * - * @example - * ```ts - * const betaMessageTokensCount = - * await client.beta.messages.countTokens({ - * messages: [{ content: 'string', role: 'user' }], - * model: 'claude-3-7-sonnet-latest', - * }); - * ``` - */ - countTokens(params, options) { - const { betas, ...body } = params; - return this._client.post('/v1/messages/count_tokens?beta=true', { - body, - ...options, - headers: buildHeaders([ - { 'anthropic-beta': [...(betas ?? []), 'token-counting-2024-11-01'].toString() }, - options?.headers, - ]), - }); - } -} -messages_messages_Messages.Batches = batches_Batches; -//# sourceMappingURL=messages.mjs.map -;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/resources/beta/beta.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - -class beta_Beta extends resource_APIResource { - constructor() { - super(...arguments); - this.models = new models_Models(this._client); - this.messages = new messages_messages_Messages(this._client); - } -} -beta_Beta.Models = models_Models; -beta_Beta.Messages = messages_messages_Messages; -//# sourceMappingURL=beta.mjs.map -;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/resources/completions.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - -class resources_completions_Completions extends resource_APIResource { - create(params, options) { - const { betas, ...body } = params; - return this._client.post('/v1/complete', { - body, - timeout: this._client._options.timeout ?? 600000, - ...options, - headers: buildHeaders([ - { ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) }, - options?.headers, - ]), - stream: params.stream ?? false, - }); - } -} -//# sourceMappingURL=completions.mjs.map +function MessageStream_checkNever(x) { } +//# sourceMappingURL=MessageStream.mjs.map ;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/resources/messages/batches.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. @@ -78809,7 +73705,7 @@ class messages_batches_Batches extends resource_APIResource { * messages: [ * { content: 'Hello, world', role: 'user' }, * ], - * model: 'claude-3-7-sonnet-20250219', + * model: 'claude-sonnet-4-20250514', * }, * }, * ], @@ -78835,7 +73731,7 @@ class messages_batches_Batches extends resource_APIResource { * ``` */ retrieve(messageBatchID, options) { - return this._client.get(path `/v1/messages/batches/${messageBatchID}`, options); + return this._client.get(path_path `/v1/messages/batches/${messageBatchID}`, options); } /** * List all Message Batches within a Workspace. Most recently created batches are @@ -78871,7 +73767,7 @@ class messages_batches_Batches extends resource_APIResource { * ``` */ delete(messageBatchID, options) { - return this._client.delete(path `/v1/messages/batches/${messageBatchID}`, options); + return this._client.delete(path_path `/v1/messages/batches/${messageBatchID}`, options); } /** * Batches may be canceled any time before processing ends. Once cancellation is @@ -78895,7 +73791,7 @@ class messages_batches_Batches extends resource_APIResource { * ``` */ cancel(messageBatchID, options) { - return this._client.post(path `/v1/messages/batches/${messageBatchID}/cancel`, options); + return this._client.post(path_path `/v1/messages/batches/${messageBatchID}/cancel`, options); } /** * Streams the results of a Message Batch as a `.jsonl` file. @@ -78921,7 +73817,7 @@ class messages_batches_Batches extends resource_APIResource { return this._client .get(batch.results_url, { ...options, - headers: buildHeaders([{ Accept: 'application/binary' }, options?.headers]), + headers: headers_buildHeaders([{ Accept: 'application/binary' }, options?.headers]), stream: true, __binaryResponse: true, }) @@ -78929,14639 +73825,19527 @@ class messages_batches_Batches extends resource_APIResource { } } //# sourceMappingURL=batches.mjs.map -;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/lib/MessageStream.mjs -var _MessageStream_instances, _MessageStream_currentMessageSnapshot, _MessageStream_connectedPromise, _MessageStream_resolveConnectedPromise, _MessageStream_rejectConnectedPromise, _MessageStream_endPromise, _MessageStream_resolveEndPromise, _MessageStream_rejectEndPromise, _MessageStream_listeners, _MessageStream_ended, _MessageStream_errored, _MessageStream_aborted, _MessageStream_catchingPromiseCreated, _MessageStream_response, _MessageStream_request_id, _MessageStream_getFinalMessage, _MessageStream_getFinalText, _MessageStream_handleError, _MessageStream_beginRequest, _MessageStream_addStreamEvent, _MessageStream_endRequest, _MessageStream_accumulateMessage; +;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/resources/messages/messages.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -const MessageStream_JSON_BUF_PROPERTY = '__json_buf'; -class MessageStream { +class resources_messages_messages_Messages extends resource_APIResource { constructor() { - _MessageStream_instances.add(this); - this.messages = []; - this.receivedMessages = []; - _MessageStream_currentMessageSnapshot.set(this, void 0); - this.controller = new AbortController(); - _MessageStream_connectedPromise.set(this, void 0); - _MessageStream_resolveConnectedPromise.set(this, () => { }); - _MessageStream_rejectConnectedPromise.set(this, () => { }); - _MessageStream_endPromise.set(this, void 0); - _MessageStream_resolveEndPromise.set(this, () => { }); - _MessageStream_rejectEndPromise.set(this, () => { }); - _MessageStream_listeners.set(this, {}); - _MessageStream_ended.set(this, false); - _MessageStream_errored.set(this, false); - _MessageStream_aborted.set(this, false); - _MessageStream_catchingPromiseCreated.set(this, false); - _MessageStream_response.set(this, void 0); - _MessageStream_request_id.set(this, void 0); - _MessageStream_handleError.set(this, (error) => { - tslib_classPrivateFieldSet(this, _MessageStream_errored, true, "f"); - if (isAbortError(error)) { - error = new error_APIUserAbortError(); - } - if (error instanceof error_APIUserAbortError) { - tslib_classPrivateFieldSet(this, _MessageStream_aborted, true, "f"); - return this._emit('abort', error); - } - if (error instanceof error_AnthropicError) { - return this._emit('error', error); - } - if (error instanceof Error) { - const anthropicError = new error_AnthropicError(error.message); - // @ts-ignore - anthropicError.cause = error; - return this._emit('error', anthropicError); - } - return this._emit('error', new error_AnthropicError(String(error))); + super(...arguments); + this.batches = new messages_batches_Batches(this._client); + } + create(body, options) { + if (body.model in messages_DEPRECATED_MODELS) { + console.warn(`The model '${body.model}' is deprecated and will reach end-of-life on ${messages_DEPRECATED_MODELS[body.model]}\nPlease migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`); + } + let timeout = this._client._options.timeout; + if (!body.stream && timeout == null) { + const maxNonstreamingTokens = MODEL_NONSTREAMING_TOKENS[body.model] ?? undefined; + timeout = this._client.calculateNonstreamingTimeout(body.max_tokens, maxNonstreamingTokens); + } + return this._client.post('/v1/messages', { + body, + timeout: timeout ?? 600000, + ...options, + stream: body.stream ?? false, }); - tslib_classPrivateFieldSet(this, _MessageStream_connectedPromise, new Promise((resolve, reject) => { - tslib_classPrivateFieldSet(this, _MessageStream_resolveConnectedPromise, resolve, "f"); - tslib_classPrivateFieldSet(this, _MessageStream_rejectConnectedPromise, reject, "f"); - }), "f"); - tslib_classPrivateFieldSet(this, _MessageStream_endPromise, new Promise((resolve, reject) => { - tslib_classPrivateFieldSet(this, _MessageStream_resolveEndPromise, resolve, "f"); - tslib_classPrivateFieldSet(this, _MessageStream_rejectEndPromise, reject, "f"); - }), "f"); - // Don't let these promises cause unhandled rejection errors. - // we will manually cause an unhandled rejection error later - // if the user hasn't registered any error listener or called - // any promise-returning method. - tslib_classPrivateFieldGet(this, _MessageStream_connectedPromise, "f").catch(() => { }); - tslib_classPrivateFieldGet(this, _MessageStream_endPromise, "f").catch(() => { }); } - get response() { - return tslib_classPrivateFieldGet(this, _MessageStream_response, "f"); + /** + * Create a Message stream + */ + stream(body, options) { + return MessageStream.createMessage(this, body, options); } - get request_id() { - return tslib_classPrivateFieldGet(this, _MessageStream_request_id, "f"); + /** + * Count the number of tokens in a Message. + * + * The Token Count API can be used to count the number of tokens in a Message, + * including tools, images, and documents, without creating it. + * + * Learn more about token counting in our + * [user guide](/en/docs/build-with-claude/token-counting) + * + * @example + * ```ts + * const messageTokensCount = + * await client.messages.countTokens({ + * messages: [{ content: 'string', role: 'user' }], + * model: 'claude-3-7-sonnet-latest', + * }); + * ``` + */ + countTokens(body, options) { + return this._client.post('/v1/messages/count_tokens', { body, ...options }); + } +} +const messages_DEPRECATED_MODELS = { + 'claude-1.3': 'November 6th, 2024', + 'claude-1.3-100k': 'November 6th, 2024', + 'claude-instant-1.1': 'November 6th, 2024', + 'claude-instant-1.1-100k': 'November 6th, 2024', + 'claude-instant-1.2': 'November 6th, 2024', + 'claude-3-sonnet-20240229': 'July 21st, 2025', + 'claude-3-opus-20240229': 'January 5th, 2026', + 'claude-2.1': 'July 21st, 2025', + 'claude-2.0': 'July 21st, 2025', +}; +resources_messages_messages_Messages.Batches = messages_batches_Batches; +//# sourceMappingURL=messages.mjs.map +;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/resources/models.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + +class resources_models_Models extends resource_APIResource { + /** + * Get a specific model. + * + * The Models API response can be used to determine information about a specific + * model or resolve a model alias to a model ID. + */ + retrieve(modelID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.get(path_path `/v1/models/${modelID}`, { + ...options, + headers: headers_buildHeaders([ + { ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) }, + options?.headers, + ]), + }); + } + /** + * List available models. + * + * The Models API response can be used to determine which models are available for + * use in the API. More recently released models are listed first. + */ + list(params = {}, options) { + const { betas, ...query } = params ?? {}; + return this._client.getAPIList('/v1/models', (pagination_Page), { + query, + ...options, + headers: headers_buildHeaders([ + { ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) }, + options?.headers, + ]), + }); + } +} +//# sourceMappingURL=models.mjs.map +;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/resources/index.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + + +//# sourceMappingURL=index.mjs.map +;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/internal/utils/env.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +/** + * Read an environment variable. + * + * Trims beginning and trailing whitespace. + * + * Will return undefined if the environment variable doesn't exist or cannot be accessed. + */ +const env_readEnv = (env) => { + if (typeof globalThis.process !== 'undefined') { + return globalThis.process.env?.[env]?.trim() ?? undefined; + } + if (typeof globalThis.Deno !== 'undefined') { + return globalThis.Deno.env?.get?.(env)?.trim(); } + return undefined; +}; +//# sourceMappingURL=env.mjs.map +;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/client.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +var _BaseAnthropic_instances, sdk_client_a, _BaseAnthropic_encoder, _BaseAnthropic_baseURLOverridden; + + + + + + + + + + + + + + + + + + + + + + + +/** + * Base class for Anthropic API clients. + */ +class BaseAnthropic { /** - * Returns the `MessageStream` data, the raw `Response` instance and the ID of the request, - * returned vie the `request-id` header which is useful for debugging requests and resporting - * issues to Anthropic. - * - * This is the same as the `APIPromise.withResponse()` method. + * API Client for interfacing with the Anthropic API. * - * This method will raise an error if you created the stream using `MessageStream.fromReadableStream` - * as no `Response` is available. + * @param {string | null | undefined} [opts.apiKey=process.env['ANTHROPIC_API_KEY'] ?? null] + * @param {string | null | undefined} [opts.authToken=process.env['ANTHROPIC_AUTH_TOKEN'] ?? null] + * @param {string} [opts.baseURL=process.env['ANTHROPIC_BASE_URL'] ?? https://api.anthropic.com] - Override the default base URL for the API. + * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out. + * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls. + * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation. + * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request. + * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API. + * @param {Record} opts.defaultQuery - Default query parameters to include with every request to the API. + * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers. */ - async withResponse() { - const response = await tslib_classPrivateFieldGet(this, _MessageStream_connectedPromise, "f"); - if (!response) { - throw new Error('Could not resolve a `Response` object'); - } - return { - data: this, - response, - request_id: response.headers.get('request-id'), + constructor({ baseURL = env_readEnv('ANTHROPIC_BASE_URL'), apiKey = env_readEnv('ANTHROPIC_API_KEY') ?? null, authToken = env_readEnv('ANTHROPIC_AUTH_TOKEN') ?? null, ...opts } = {}) { + _BaseAnthropic_instances.add(this); + _BaseAnthropic_encoder.set(this, void 0); + const options = { + apiKey, + authToken, + ...opts, + baseURL: baseURL || `https://api.anthropic.com`, }; + if (!options.dangerouslyAllowBrowser && detect_platform_isRunningInBrowser()) { + throw new error_AnthropicError("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew Anthropic({ apiKey, dangerouslyAllowBrowser: true });\n"); + } + this.baseURL = options.baseURL; + this.timeout = options.timeout ?? sdk_client_a.DEFAULT_TIMEOUT /* 10 minutes */; + this.logger = options.logger ?? console; + const defaultLogLevel = 'warn'; + // Set default logLevel early so that we can log a warning in parseLogLevel. + this.logLevel = defaultLogLevel; + this.logLevel = + log_parseLogLevel(options.logLevel, 'ClientOptions.logLevel', this) ?? + log_parseLogLevel(env_readEnv('ANTHROPIC_LOG'), "process.env['ANTHROPIC_LOG']", this) ?? + defaultLogLevel; + this.fetchOptions = options.fetchOptions; + this.maxRetries = options.maxRetries ?? 2; + this.fetch = options.fetch ?? shims_getDefaultFetch(); + tslib_classPrivateFieldSet(this, _BaseAnthropic_encoder, request_options_FallbackEncoder, "f"); + this._options = options; + this.apiKey = apiKey; + this.authToken = authToken; } /** - * Intended for use on the frontend, consuming a stream produced with - * `.toReadableStream()` on the backend. - * - * Note that messages sent to the model do not appear in `.on('message')` - * in this context. + * Create a new client instance re-using the same options given to the current client with optional overriding. */ - static fromReadableStream(stream) { - const runner = new MessageStream(); - runner._run(() => runner._fromReadableStream(stream)); - return runner; - } - static createMessage(messages, params, options) { - const runner = new MessageStream(); - for (const message of params.messages) { - runner._addMessageParam(message); - } - runner._run(() => runner._createMessage(messages, { ...params, stream: true }, { ...options, headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' } })); - return runner; - } - _run(executor) { - executor().then(() => { - this._emitFinal(); - this._emit('end'); - }, tslib_classPrivateFieldGet(this, _MessageStream_handleError, "f")); - } - _addMessageParam(message) { - this.messages.push(message); + withOptions(options) { + const client = new this.constructor({ + ...this._options, + baseURL: this.baseURL, + maxRetries: this.maxRetries, + timeout: this.timeout, + logger: this.logger, + logLevel: this.logLevel, + fetch: this.fetch, + fetchOptions: this.fetchOptions, + apiKey: this.apiKey, + authToken: this.authToken, + ...options, + }); + return client; } - _addMessage(message, emit = true) { - this.receivedMessages.push(message); - if (emit) { - this._emit('message', message); - } + defaultQuery() { + return this._options.defaultQuery; } - async _createMessage(messages, params, options) { - const signal = options?.signal; - if (signal) { - if (signal.aborted) - this.controller.abort(); - signal.addEventListener('abort', () => this.controller.abort()); + validateHeaders({ values, nulls }) { + if (this.apiKey && values.get('x-api-key')) { + return; } - tslib_classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_beginRequest).call(this); - const { response, data: stream } = await messages - .create({ ...params, stream: true }, { ...options, signal: this.controller.signal }) - .withResponse(); - this._connected(response); - for await (const event of stream) { - tslib_classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_addStreamEvent).call(this, event); + if (nulls.has('x-api-key')) { + return; } - if (stream.controller.signal?.aborted) { - throw new error_APIUserAbortError(); + if (this.authToken && values.get('authorization')) { + return; } - tslib_classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_endRequest).call(this); - } - _connected(response) { - if (this.ended) + if (nulls.has('authorization')) { return; - tslib_classPrivateFieldSet(this, _MessageStream_response, response, "f"); - tslib_classPrivateFieldSet(this, _MessageStream_request_id, response?.headers.get('request-id'), "f"); - tslib_classPrivateFieldGet(this, _MessageStream_resolveConnectedPromise, "f").call(this, response); - this._emit('connect'); - } - get ended() { - return tslib_classPrivateFieldGet(this, _MessageStream_ended, "f"); + } + throw new Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted'); } - get errored() { - return tslib_classPrivateFieldGet(this, _MessageStream_errored, "f"); + async authHeaders(opts) { + return headers_buildHeaders([await this.apiKeyAuth(opts), await this.bearerAuth(opts)]); } - get aborted() { - return tslib_classPrivateFieldGet(this, _MessageStream_aborted, "f"); + async apiKeyAuth(opts) { + if (this.apiKey == null) { + return undefined; + } + return headers_buildHeaders([{ 'X-Api-Key': this.apiKey }]); } - abort() { - this.controller.abort(); + async bearerAuth(opts) { + if (this.authToken == null) { + return undefined; + } + return headers_buildHeaders([{ Authorization: `Bearer ${this.authToken}` }]); } /** - * Adds the listener function to the end of the listeners array for the event. - * No checks are made to see if the listener has already been added. Multiple calls passing - * the same combination of event and listener will result in the listener being added, and - * called, multiple times. - * @returns this MessageStream, so that calls can be chained + * Basic re-implementation of `qs.stringify` for primitive types. */ - on(event, listener) { - const listeners = tslib_classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] || (tslib_classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] = []); - listeners.push({ listener }); - return this; + stringifyQuery(query) { + return Object.entries(query) + .filter(([_, value]) => typeof value !== 'undefined') + .map(([key, value]) => { + if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { + return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`; + } + if (value === null) { + return `${encodeURIComponent(key)}=`; + } + throw new error_AnthropicError(`Cannot stringify type ${typeof value}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`); + }) + .join('&'); } - /** - * Removes the specified listener from the listener array for the event. - * off() will remove, at most, one instance of a listener from the listener array. If any single - * listener has been added multiple times to the listener array for the specified event, then - * off() must be called multiple times to remove each instance. - * @returns this MessageStream, so that calls can be chained - */ - off(event, listener) { - const listeners = tslib_classPrivateFieldGet(this, _MessageStream_listeners, "f")[event]; - if (!listeners) - return this; - const index = listeners.findIndex((l) => l.listener === listener); - if (index >= 0) - listeners.splice(index, 1); - return this; + getUserAgent() { + return `${this.constructor.name}/JS ${version_VERSION}`; + } + defaultIdempotencyKey() { + return `stainless-node-retry-${uuid_uuid4()}`; + } + makeStatusError(status, error, message, headers) { + return error_APIError.generate(status, error, message, headers); + } + buildURL(path, query, defaultBaseURL) { + const baseURL = (!tslib_classPrivateFieldGet(this, _BaseAnthropic_instances, "m", _BaseAnthropic_baseURLOverridden).call(this) && defaultBaseURL) || this.baseURL; + const url = values_isAbsoluteURL(path) ? + new URL(path) + : new URL(baseURL + (baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path)); + const defaultQuery = this.defaultQuery(); + if (!values_isEmptyObj(defaultQuery)) { + query = { ...defaultQuery, ...query }; + } + if (typeof query === 'object' && query && !Array.isArray(query)) { + url.search = this.stringifyQuery(query); + } + return url.toString(); + } + _calculateNonstreamingTimeout(maxTokens) { + const defaultTimeout = 10 * 60; + const expectedTimeout = (60 * 60 * maxTokens) / 128000; + if (expectedTimeout > defaultTimeout) { + throw new error_AnthropicError('Streaming is required for operations that may take longer than 10 minutes. ' + + 'See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details'); + } + return defaultTimeout * 1000; } /** - * Adds a one-time listener function for the event. The next time the event is triggered, - * this listener is removed and then invoked. - * @returns this MessageStream, so that calls can be chained + * Used as a callback for mutating the given `FinalRequestOptions` object. */ - once(event, listener) { - const listeners = tslib_classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] || (tslib_classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] = []); - listeners.push({ listener, once: true }); - return this; - } + async prepareOptions(options) { } /** - * This is similar to `.once()`, but returns a Promise that resolves the next time - * the event is triggered, instead of calling a listener callback. - * @returns a Promise that resolves the next time given event is triggered, - * or rejects if an error is emitted. (If you request the 'error' event, - * returns a promise that resolves with the error). - * - * Example: + * Used as a callback for mutating the given `RequestInit` object. * - * const message = await stream.emitted('message') // rejects if the stream errors + * This is useful for cases where you want to add certain headers based off of + * the request properties, e.g. `method` or `url`. */ - emitted(event) { - return new Promise((resolve, reject) => { - tslib_classPrivateFieldSet(this, _MessageStream_catchingPromiseCreated, true, "f"); - if (event !== 'error') - this.once('error', reject); - this.once(event, resolve); - }); + async prepareRequest(request, { url, options }) { } + get(path, opts) { + return this.methodRequest('get', path, opts); } - async done() { - tslib_classPrivateFieldSet(this, _MessageStream_catchingPromiseCreated, true, "f"); - await tslib_classPrivateFieldGet(this, _MessageStream_endPromise, "f"); + post(path, opts) { + return this.methodRequest('post', path, opts); } - get currentMessage() { - return tslib_classPrivateFieldGet(this, _MessageStream_currentMessageSnapshot, "f"); + patch(path, opts) { + return this.methodRequest('patch', path, opts); } - /** - * @returns a promise that resolves with the the final assistant Message response, - * or rejects if an error occurred or the stream ended prematurely without producing a Message. - */ - async finalMessage() { - await this.done(); - return tslib_classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_getFinalMessage).call(this); + put(path, opts) { + return this.methodRequest('put', path, opts); } - /** - * @returns a promise that resolves with the the final assistant Message's text response, concatenated - * together if there are more than one text blocks. - * Rejects if an error occurred or the stream ended prematurely without producing a Message. - */ - async finalText() { - await this.done(); - return tslib_classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_getFinalText).call(this); + delete(path, opts) { + return this.methodRequest('delete', path, opts); } - _emit(event, ...args) { - // make sure we don't emit any MessageStreamEvents after end - if (tslib_classPrivateFieldGet(this, _MessageStream_ended, "f")) - return; - if (event === 'end') { - tslib_classPrivateFieldSet(this, _MessageStream_ended, true, "f"); - tslib_classPrivateFieldGet(this, _MessageStream_resolveEndPromise, "f").call(this); - } - const listeners = tslib_classPrivateFieldGet(this, _MessageStream_listeners, "f")[event]; - if (listeners) { - tslib_classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] = listeners.filter((l) => !l.once); - listeners.forEach(({ listener }) => listener(...args)); - } - if (event === 'abort') { - const error = args[0]; - if (!tslib_classPrivateFieldGet(this, _MessageStream_catchingPromiseCreated, "f") && !listeners?.length) { - Promise.reject(error); - } - tslib_classPrivateFieldGet(this, _MessageStream_rejectConnectedPromise, "f").call(this, error); - tslib_classPrivateFieldGet(this, _MessageStream_rejectEndPromise, "f").call(this, error); - this._emit('end'); - return; - } - if (event === 'error') { - // NOTE: _emit('error', error) should only be called from #handleError(). - const error = args[0]; - if (!tslib_classPrivateFieldGet(this, _MessageStream_catchingPromiseCreated, "f") && !listeners?.length) { - // Trigger an unhandled rejection if the user hasn't registered any error handlers. - // If you are seeing stack traces here, make sure to handle errors via either: - // - runner.on('error', () => ...) - // - await runner.done() - // - await runner.final...() - // - etc. - Promise.reject(error); - } - tslib_classPrivateFieldGet(this, _MessageStream_rejectConnectedPromise, "f").call(this, error); - tslib_classPrivateFieldGet(this, _MessageStream_rejectEndPromise, "f").call(this, error); - this._emit('end'); - } + methodRequest(method, path, opts) { + return this.request(Promise.resolve(opts).then((opts) => { + return { method, path, ...opts }; + })); } - _emitFinal() { - const finalMessage = this.receivedMessages.at(-1); - if (finalMessage) { - this._emit('finalMessage', tslib_classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_getFinalMessage).call(this)); - } + request(options, remainingRetries = null) { + return new api_promise_APIPromise(this, this.makeRequest(options, remainingRetries, undefined)); } - async _fromReadableStream(readableStream, options) { - const signal = options?.signal; - if (signal) { - if (signal.aborted) - this.controller.abort(); - signal.addEventListener('abort', () => this.controller.abort()); - } - tslib_classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_beginRequest).call(this); - this._connected(null); - const stream = streaming_Stream.fromReadableStream(readableStream, this.controller); - for await (const event of stream) { - tslib_classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_addStreamEvent).call(this, event); + async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) { + const options = await optionsInput; + const maxRetries = options.maxRetries ?? this.maxRetries; + if (retriesRemaining == null) { + retriesRemaining = maxRetries; } - if (stream.controller.signal?.aborted) { + await this.prepareOptions(options); + const { req, url, timeout } = await this.buildRequest(options, { + retryCount: maxRetries - retriesRemaining, + }); + await this.prepareRequest(req, { url, options }); + /** Not an API request ID, just for correlating local log entries. */ + const requestLogID = 'log_' + ((Math.random() * (1 << 24)) | 0).toString(16).padStart(6, '0'); + const retryLogStr = retryOfRequestLogID === undefined ? '' : `, retryOf: ${retryOfRequestLogID}`; + const startTime = Date.now(); + log_loggerFor(this).debug(`[${requestLogID}] sending request`, log_formatRequestDetails({ + retryOfRequestLogID, + method: options.method, + url, + options, + headers: req.headers, + })); + if (options.signal?.aborted) { throw new error_APIUserAbortError(); } - tslib_classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_endRequest).call(this); - } - [(_MessageStream_currentMessageSnapshot = new WeakMap(), _MessageStream_connectedPromise = new WeakMap(), _MessageStream_resolveConnectedPromise = new WeakMap(), _MessageStream_rejectConnectedPromise = new WeakMap(), _MessageStream_endPromise = new WeakMap(), _MessageStream_resolveEndPromise = new WeakMap(), _MessageStream_rejectEndPromise = new WeakMap(), _MessageStream_listeners = new WeakMap(), _MessageStream_ended = new WeakMap(), _MessageStream_errored = new WeakMap(), _MessageStream_aborted = new WeakMap(), _MessageStream_catchingPromiseCreated = new WeakMap(), _MessageStream_response = new WeakMap(), _MessageStream_request_id = new WeakMap(), _MessageStream_handleError = new WeakMap(), _MessageStream_instances = new WeakSet(), _MessageStream_getFinalMessage = function _MessageStream_getFinalMessage() { - if (this.receivedMessages.length === 0) { - throw new error_AnthropicError('stream ended without producing a Message with role=assistant'); - } - return this.receivedMessages.at(-1); - }, _MessageStream_getFinalText = function _MessageStream_getFinalText() { - if (this.receivedMessages.length === 0) { - throw new error_AnthropicError('stream ended without producing a Message with role=assistant'); - } - const textBlocks = this.receivedMessages - .at(-1) - .content.filter((block) => block.type === 'text') - .map((block) => block.text); - if (textBlocks.length === 0) { - throw new error_AnthropicError('stream ended without producing a content block with type=text'); - } - return textBlocks.join(' '); - }, _MessageStream_beginRequest = function _MessageStream_beginRequest() { - if (this.ended) - return; - tslib_classPrivateFieldSet(this, _MessageStream_currentMessageSnapshot, undefined, "f"); - }, _MessageStream_addStreamEvent = function _MessageStream_addStreamEvent(event) { - if (this.ended) - return; - const messageSnapshot = tslib_classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_accumulateMessage).call(this, event); - this._emit('streamEvent', event, messageSnapshot); - switch (event.type) { - case 'content_block_delta': { - const content = messageSnapshot.content.at(-1); - switch (event.delta.type) { - case 'text_delta': { - if (content.type === 'text') { - this._emit('text', event.delta.text, content.text || ''); - } - break; - } - case 'citations_delta': { - if (content.type === 'text') { - this._emit('citation', event.delta.citation, content.citations ?? []); - } - break; - } - case 'input_json_delta': { - if (content.type === 'tool_use' && content.input) { - this._emit('inputJson', event.delta.partial_json, content.input); - } - break; - } - case 'thinking_delta': { - if (content.type === 'thinking') { - this._emit('thinking', event.delta.thinking, content.thinking); - } - break; - } - case 'signature_delta': { - if (content.type === 'thinking') { - this._emit('signature', content.signature); - } - break; - } - default: - MessageStream_checkNever(event.delta); - } - break; - } - case 'message_stop': { - this._addMessageParam(messageSnapshot); - this._addMessage(messageSnapshot, true); - break; + const controller = new AbortController(); + const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(errors_castToError); + const headersTime = Date.now(); + if (response instanceof Error) { + const retryMessage = `retrying, ${retriesRemaining} attempts remaining`; + if (options.signal?.aborted) { + throw new error_APIUserAbortError(); } - case 'content_block_stop': { - this._emit('contentBlock', messageSnapshot.content.at(-1)); - break; + // detect native connection timeout errors + // deno throws "TypeError: error sending request for url (https://example/): client error (Connect): tcp connect error: Operation timed out (os error 60): Operation timed out (os error 60)" + // undici throws "TypeError: fetch failed" with cause "ConnectTimeoutError: Connect Timeout Error (attempted address: example:443, timeout: 1ms)" + // others do not provide enough information to distinguish timeouts from other connection errors + const isTimeout = errors_isAbortError(response) || + /timed? ?out/i.test(String(response) + ('cause' in response ? String(response.cause) : '')); + if (retriesRemaining) { + log_loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - ${retryMessage}`); + log_loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (${retryMessage})`, log_formatRequestDetails({ + retryOfRequestLogID, + url, + durationMs: headersTime - startTime, + message: response.message, + })); + return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID); } - case 'message_start': { - tslib_classPrivateFieldSet(this, _MessageStream_currentMessageSnapshot, messageSnapshot, "f"); - break; + log_loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - error; no more retries left`); + log_loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (error; no more retries left)`, log_formatRequestDetails({ + retryOfRequestLogID, + url, + durationMs: headersTime - startTime, + message: response.message, + })); + if (isTimeout) { + throw new error_APIConnectionTimeoutError(); } - case 'content_block_start': - case 'message_delta': - break; + throw new error_APIConnectionError({ cause: response }); } - }, _MessageStream_endRequest = function _MessageStream_endRequest() { - if (this.ended) { - throw new error_AnthropicError(`stream has ended, this shouldn't happen`); + const specialHeaders = [...response.headers.entries()] + .filter(([name]) => name === 'request-id') + .map(([name, value]) => ', ' + name + ': ' + JSON.stringify(value)) + .join(''); + const responseInfo = `[${requestLogID}${retryLogStr}${specialHeaders}] ${req.method} ${url} ${response.ok ? 'succeeded' : 'failed'} with status ${response.status} in ${headersTime - startTime}ms`; + if (!response.ok) { + const shouldRetry = await this.shouldRetry(response); + if (retriesRemaining && shouldRetry) { + const retryMessage = `retrying, ${retriesRemaining} attempts remaining`; + // We don't need the body of this response. + await shims_CancelReadableStream(response.body); + log_loggerFor(this).info(`${responseInfo} - ${retryMessage}`); + log_loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, log_formatRequestDetails({ + retryOfRequestLogID, + url: response.url, + status: response.status, + headers: response.headers, + durationMs: headersTime - startTime, + })); + return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers); + } + const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`; + log_loggerFor(this).info(`${responseInfo} - ${retryMessage}`); + const errText = await response.text().catch((err) => errors_castToError(err).message); + const errJSON = values_safeJSON(errText); + const errMessage = errJSON ? undefined : errText; + log_loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, log_formatRequestDetails({ + retryOfRequestLogID, + url: response.url, + status: response.status, + headers: response.headers, + message: errMessage, + durationMs: Date.now() - startTime, + })); + const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers); + throw err; } - const snapshot = tslib_classPrivateFieldGet(this, _MessageStream_currentMessageSnapshot, "f"); - if (!snapshot) { - throw new error_AnthropicError(`request ended without sending any chunks`); + log_loggerFor(this).info(responseInfo); + log_loggerFor(this).debug(`[${requestLogID}] response start`, log_formatRequestDetails({ + retryOfRequestLogID, + url: response.url, + status: response.status, + headers: response.headers, + durationMs: headersTime - startTime, + })); + return { response, options, controller, requestLogID, retryOfRequestLogID, startTime }; + } + getAPIList(path, Page, opts) { + return this.requestAPIList(Page, { method: 'get', path, ...opts }); + } + requestAPIList(Page, options) { + const request = this.makeRequest(options, null, undefined); + return new pagination_PagePromise(this, request, Page); + } + async fetchWithTimeout(url, init, ms, controller) { + const { signal, method, ...options } = init || {}; + if (signal) + signal.addEventListener('abort', () => controller.abort()); + const timeout = setTimeout(() => controller.abort(), ms); + const isReadableBody = (globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream) || + (typeof options.body === 'object' && options.body !== null && Symbol.asyncIterator in options.body); + const fetchOptions = { + signal: controller.signal, + ...(isReadableBody ? { duplex: 'half' } : {}), + method: 'GET', + ...options, + }; + if (method) { + // Custom methods like 'patch' need to be uppercased + // See https://github.com/nodejs/undici/issues/2294 + fetchOptions.method = method.toUpperCase(); } - tslib_classPrivateFieldSet(this, _MessageStream_currentMessageSnapshot, undefined, "f"); - return snapshot; - }, _MessageStream_accumulateMessage = function _MessageStream_accumulateMessage(event) { - let snapshot = tslib_classPrivateFieldGet(this, _MessageStream_currentMessageSnapshot, "f"); - if (event.type === 'message_start') { - if (snapshot) { - throw new error_AnthropicError(`Unexpected event order, got ${event.type} before receiving "message_stop"`); - } - return event.message; + try { + // use undefined this binding; fetch errors if bound to something else in browser/cloudflare + return await this.fetch.call(undefined, url, fetchOptions); } - if (!snapshot) { - throw new error_AnthropicError(`Unexpected event order, got ${event.type} before "message_start"`); + finally { + clearTimeout(timeout); } - switch (event.type) { - case 'message_stop': - return snapshot; - case 'message_delta': - snapshot.stop_reason = event.delta.stop_reason; - snapshot.stop_sequence = event.delta.stop_sequence; - snapshot.usage.output_tokens = event.usage.output_tokens; - // Update other usage fields if they exist in the event - if (event.usage.input_tokens != null) { - snapshot.usage.input_tokens = event.usage.input_tokens; - } - if (event.usage.cache_creation_input_tokens != null) { - snapshot.usage.cache_creation_input_tokens = event.usage.cache_creation_input_tokens; - } - if (event.usage.cache_read_input_tokens != null) { - snapshot.usage.cache_read_input_tokens = event.usage.cache_read_input_tokens; - } - if (event.usage.server_tool_use != null) { - snapshot.usage.server_tool_use = event.usage.server_tool_use; - } - return snapshot; - case 'content_block_start': - snapshot.content.push(event.content_block); - return snapshot; - case 'content_block_delta': { - const snapshotContent = snapshot.content.at(event.index); - switch (event.delta.type) { - case 'text_delta': { - if (snapshotContent?.type === 'text') { - snapshotContent.text += event.delta.text; - } - break; - } - case 'citations_delta': { - if (snapshotContent?.type === 'text') { - snapshotContent.citations ?? (snapshotContent.citations = []); - snapshotContent.citations.push(event.delta.citation); - } - break; - } - case 'input_json_delta': { - if (snapshotContent?.type === 'tool_use') { - // we need to keep track of the raw JSON string as well so that we can - // re-parse it for each delta, for now we just store it as an untyped - // non-enumerable property on the snapshot - let jsonBuf = snapshotContent[MessageStream_JSON_BUF_PROPERTY] || ''; - jsonBuf += event.delta.partial_json; - Object.defineProperty(snapshotContent, MessageStream_JSON_BUF_PROPERTY, { - value: jsonBuf, - enumerable: false, - writable: true, - }); - if (jsonBuf) { - snapshotContent.input = parser_partialParse(jsonBuf); - } - } - break; - } - case 'thinking_delta': { - if (snapshotContent?.type === 'thinking') { - snapshotContent.thinking += event.delta.thinking; - } - break; - } - case 'signature_delta': { - if (snapshotContent?.type === 'thinking') { - snapshotContent.signature = event.delta.signature; - } - break; - } - default: - MessageStream_checkNever(event.delta); - } - return snapshot; + } + async shouldRetry(response) { + // Note this is not a standard header. + const shouldRetryHeader = response.headers.get('x-should-retry'); + // If the server explicitly says whether or not to retry, obey. + if (shouldRetryHeader === 'true') + return true; + if (shouldRetryHeader === 'false') + return false; + // Retry on request timeouts. + if (response.status === 408) + return true; + // Retry on lock timeouts. + if (response.status === 409) + return true; + // Retry on rate limits. + if (response.status === 429) + return true; + // Retry internal errors. + if (response.status >= 500) + return true; + return false; + } + async retryRequest(options, retriesRemaining, requestLogID, responseHeaders) { + let timeoutMillis; + // Note the `retry-after-ms` header may not be standard, but is a good idea and we'd like proactive support for it. + const retryAfterMillisHeader = responseHeaders?.get('retry-after-ms'); + if (retryAfterMillisHeader) { + const timeoutMs = parseFloat(retryAfterMillisHeader); + if (!Number.isNaN(timeoutMs)) { + timeoutMillis = timeoutMs; } - case 'content_block_stop': - return snapshot; } - }, Symbol.asyncIterator)]() { - const pushQueue = []; - const readQueue = []; - let done = false; - this.on('streamEvent', (event) => { - const reader = readQueue.shift(); - if (reader) { - reader.resolve(event); + // About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After + const retryAfterHeader = responseHeaders?.get('retry-after'); + if (retryAfterHeader && !timeoutMillis) { + const timeoutSeconds = parseFloat(retryAfterHeader); + if (!Number.isNaN(timeoutSeconds)) { + timeoutMillis = timeoutSeconds * 1000; } else { - pushQueue.push(event); - } - }); - this.on('end', () => { - done = true; - for (const reader of readQueue) { - reader.resolve(undefined); - } - readQueue.length = 0; - }); - this.on('abort', (err) => { - done = true; - for (const reader of readQueue) { - reader.reject(err); - } - readQueue.length = 0; - }); - this.on('error', (err) => { - done = true; - for (const reader of readQueue) { - reader.reject(err); + timeoutMillis = Date.parse(retryAfterHeader) - Date.now(); } - readQueue.length = 0; - }); - return { - next: async () => { - if (!pushQueue.length) { - if (done) { - return { value: undefined, done: true }; - } - return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((chunk) => (chunk ? { value: chunk, done: false } : { value: undefined, done: true })); - } - const chunk = pushQueue.shift(); - return { value: chunk, done: false }; - }, - return: async () => { - this.abort(); - return { value: undefined, done: true }; - }, + } + // If the API asks us to wait a certain amount of time (and it's a reasonable amount), + // just do what it says, but otherwise calculate a default + if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1000)) { + const maxRetries = options.maxRetries ?? this.maxRetries; + timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries); + } + await sleep_sleep(timeoutMillis); + return this.makeRequest(options, retriesRemaining - 1, requestLogID); + } + calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) { + const initialRetryDelay = 0.5; + const maxRetryDelay = 8.0; + const numRetries = maxRetries - retriesRemaining; + // Apply exponential backoff, but not more than the max. + const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay); + // Apply some jitter, take up to at most 25 percent of the retry time. + const jitter = 1 - Math.random() * 0.25; + return sleepSeconds * jitter * 1000; + } + calculateNonstreamingTimeout(maxTokens, maxNonstreamingTokens) { + const maxTime = 60 * 60 * 1000; // 10 minutes + const defaultTime = 60 * 10 * 1000; // 10 minutes + const expectedTime = (maxTime * maxTokens) / 128000; + if (expectedTime > defaultTime || (maxNonstreamingTokens != null && maxTokens > maxNonstreamingTokens)) { + throw new error_AnthropicError('Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details'); + } + return defaultTime; + } + async buildRequest(inputOptions, { retryCount = 0 } = {}) { + const options = { ...inputOptions }; + const { method, path, query, defaultBaseURL } = options; + const url = this.buildURL(path, query, defaultBaseURL); + if ('timeout' in options) + values_validatePositiveInteger('timeout', options.timeout); + options.timeout = options.timeout ?? this.timeout; + const { bodyHeaders, body } = this.buildBody({ options }); + const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount }); + const req = { + method, + headers: reqHeaders, + ...(options.signal && { signal: options.signal }), + ...(globalThis.ReadableStream && + body instanceof globalThis.ReadableStream && { duplex: 'half' }), + ...(body && { body }), + ...(this.fetchOptions ?? {}), + ...(options.fetchOptions ?? {}), }; + return { req, url, timeout: options.timeout }; } - toReadableStream() { - const stream = new streaming_Stream(this[Symbol.asyncIterator].bind(this), this.controller); - return stream.toReadableStream(); + async buildHeaders({ options, method, bodyHeaders, retryCount, }) { + let idempotencyHeaders = {}; + if (this.idempotencyHeader && method !== 'get') { + if (!options.idempotencyKey) + options.idempotencyKey = this.defaultIdempotencyKey(); + idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey; + } + const headers = headers_buildHeaders([ + idempotencyHeaders, + { + Accept: 'application/json', + 'User-Agent': this.getUserAgent(), + 'X-Stainless-Retry-Count': String(retryCount), + ...(options.timeout ? { 'X-Stainless-Timeout': String(Math.trunc(options.timeout / 1000)) } : {}), + ...detect_platform_getPlatformHeaders(), + ...(this._options.dangerouslyAllowBrowser ? + { 'anthropic-dangerous-direct-browser-access': 'true' } + : undefined), + 'anthropic-version': '2023-06-01', + }, + await this.authHeaders(options), + this._options.defaultHeaders, + bodyHeaders, + options.headers, + ]); + this.validateHeaders(headers); + return headers.values; + } + buildBody({ options: { body, headers: rawHeaders } }) { + if (!body) { + return { bodyHeaders: undefined, body: undefined }; + } + const headers = headers_buildHeaders([rawHeaders]); + if ( + // Pass raw type verbatim + ArrayBuffer.isView(body) || + body instanceof ArrayBuffer || + body instanceof DataView || + (typeof body === 'string' && + // Preserve legacy string encoding behavior for now + headers.values.has('content-type')) || + // `Blob` is superset of `File` + body instanceof Blob || + // `FormData` -> `multipart/form-data` + body instanceof FormData || + // `URLSearchParams` -> `application/x-www-form-urlencoded` + body instanceof URLSearchParams || + // Send chunked stream (each chunk has own `length`) + (globalThis.ReadableStream && body instanceof globalThis.ReadableStream)) { + return { bodyHeaders: undefined, body: body }; + } + else if (typeof body === 'object' && + (Symbol.asyncIterator in body || + (Symbol.iterator in body && 'next' in body && typeof body.next === 'function'))) { + return { bodyHeaders: undefined, body: shims_ReadableStreamFrom(body) }; + } + else { + return tslib_classPrivateFieldGet(this, _BaseAnthropic_encoder, "f").call(this, { body, headers }); + } } } -// used to ensure exhaustive case matching without throwing a runtime error -function MessageStream_checkNever(x) { } -//# sourceMappingURL=MessageStream.mjs.map -;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/resources/messages/messages.mjs +sdk_client_a = BaseAnthropic, _BaseAnthropic_encoder = new WeakMap(), _BaseAnthropic_instances = new WeakSet(), _BaseAnthropic_baseURLOverridden = function _BaseAnthropic_baseURLOverridden() { + return this.baseURL !== 'https://api.anthropic.com'; +}; +BaseAnthropic.Anthropic = sdk_client_a; +BaseAnthropic.HUMAN_PROMPT = '\n\nHuman:'; +BaseAnthropic.AI_PROMPT = '\n\nAssistant:'; +BaseAnthropic.DEFAULT_TIMEOUT = 600000; // 10 minutes +BaseAnthropic.AnthropicError = error_AnthropicError; +BaseAnthropic.APIError = error_APIError; +BaseAnthropic.APIConnectionError = error_APIConnectionError; +BaseAnthropic.APIConnectionTimeoutError = error_APIConnectionTimeoutError; +BaseAnthropic.APIUserAbortError = error_APIUserAbortError; +BaseAnthropic.NotFoundError = error_NotFoundError; +BaseAnthropic.ConflictError = error_ConflictError; +BaseAnthropic.RateLimitError = error_RateLimitError; +BaseAnthropic.BadRequestError = error_BadRequestError; +BaseAnthropic.AuthenticationError = error_AuthenticationError; +BaseAnthropic.InternalServerError = error_InternalServerError; +BaseAnthropic.PermissionDeniedError = error_PermissionDeniedError; +BaseAnthropic.UnprocessableEntityError = error_UnprocessableEntityError; +BaseAnthropic.toFile = to_file_toFile; +/** + * API Client for interfacing with the Anthropic API. + */ +class Anthropic extends BaseAnthropic { + constructor() { + super(...arguments); + this.completions = new resources_completions_Completions(this); + this.messages = new resources_messages_messages_Messages(this); + this.models = new resources_models_Models(this); + this.beta = new beta_Beta(this); + } +} +Anthropic.Completions = resources_completions_Completions; +Anthropic.Messages = resources_messages_messages_Messages; +Anthropic.Models = resources_models_Models; +Anthropic.Beta = beta_Beta; +const { HUMAN_PROMPT, AI_PROMPT } = Anthropic; +//# sourceMappingURL=client.mjs.map +;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/index.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -class resources_messages_messages_Messages extends resource_APIResource { - constructor() { - super(...arguments); - this.batches = new messages_batches_Batches(this._client); + +//# sourceMappingURL=index.mjs.map +// EXTERNAL MODULE: ./node_modules/uuid/dist/index.js +var dist = __nccwpck_require__(2048); +;// CONCATENATED MODULE: ./node_modules/uuid/wrapper.mjs + +const v1 = dist.v1; +const v1ToV6 = dist/* v1ToV6 */.bV; +const v3 = dist.v3; +const v4 = dist.v4; +const v5 = dist.v5; +const v6 = dist.v6; +const v6ToV1 = dist/* v6ToV1 */.JE; +const v7 = dist.v7; +const NIL = dist/* NIL */.wD; +const MAX = dist/* MAX */.Zu; +const version = dist/* version */.rE; +const wrapper_validate = dist/* validate */.tf; +const wrapper_stringify = dist/* stringify */.As; +const wrapper_parse = dist/* parse */.qg; + +// EXTERNAL MODULE: ./node_modules/@mistralai/mistralai/index.js +var mistralai = __nccwpck_require__(6611); +// EXTERNAL MODULE: ./node_modules/@mistralai/mistralai/lib/http.js +var http = __nccwpck_require__(1775); +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/json.js +function parseJsonMarkdown(s, parser = parsePartialJson) { + // eslint-disable-next-line no-param-reassign + s = s.trim(); + const firstFenceIndex = s.indexOf("```"); + if (firstFenceIndex === -1) { + return parser(s); } - create(body, options) { - if (body.model in messages_DEPRECATED_MODELS) { - console.warn(`The model '${body.model}' is deprecated and will reach end-of-life on ${messages_DEPRECATED_MODELS[body.model]}\nPlease migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`); - } - return this._client.post('/v1/messages', { - body, - timeout: this._client._options.timeout ?? - (body.stream ? 600000 : this._client._calculateNonstreamingTimeout(body.max_tokens)), - ...options, - stream: body.stream ?? false, - }); + let contentAfterFence = s.substring(firstFenceIndex + 3); + if (contentAfterFence.startsWith("json\n")) { + contentAfterFence = contentAfterFence.substring(5); } - /** - * Create a Message stream - */ - stream(body, options) { - return MessageStream.createMessage(this, body, options); + else if (contentAfterFence.startsWith("json")) { + contentAfterFence = contentAfterFence.substring(4); } - /** - * Count the number of tokens in a Message. - * - * The Token Count API can be used to count the number of tokens in a Message, - * including tools, images, and documents, without creating it. - * - * Learn more about token counting in our - * [user guide](/en/docs/build-with-claude/token-counting) - * - * @example - * ```ts - * const messageTokensCount = - * await client.messages.countTokens({ - * messages: [{ content: 'string', role: 'user' }], - * model: 'claude-3-7-sonnet-latest', - * }); - * ``` - */ - countTokens(body, options) { - return this._client.post('/v1/messages/count_tokens', { body, ...options }); + else if (contentAfterFence.startsWith("\n")) { + contentAfterFence = contentAfterFence.substring(1); } + const closingFenceIndex = contentAfterFence.indexOf("```"); + let finalContent = contentAfterFence; + if (closingFenceIndex !== -1) { + finalContent = contentAfterFence.substring(0, closingFenceIndex); + } + return parser(finalContent.trim()); } -const messages_DEPRECATED_MODELS = { - 'claude-1.3': 'November 6th, 2024', - 'claude-1.3-100k': 'November 6th, 2024', - 'claude-instant-1.1': 'November 6th, 2024', - 'claude-instant-1.1-100k': 'November 6th, 2024', - 'claude-instant-1.2': 'November 6th, 2024', - 'claude-3-sonnet-20240229': 'July 21st, 2025', - 'claude-2.1': 'July 21st, 2025', - 'claude-2.0': 'July 21st, 2025', -}; -resources_messages_messages_Messages.Batches = messages_batches_Batches; -//# sourceMappingURL=messages.mjs.map -;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/resources/models.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - -class resources_models_Models extends resource_APIResource { - /** - * Get a specific model. - * - * The Models API response can be used to determine information about a specific - * model or resolve a model alias to a model ID. - */ - retrieve(modelID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.get(path `/v1/models/${modelID}`, { - ...options, - headers: buildHeaders([ - { ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) }, - options?.headers, - ]), - }); +// Adapted from https://github.com/KillianLucas/open-interpreter/blob/main/interpreter/core/llm/utils/parse_partial_json.py +// MIT License +function parsePartialJson(s) { + // If the input is undefined, return null to indicate failure. + if (typeof s === "undefined") { + return null; + } + // Attempt to parse the string as-is. + try { + return JSON.parse(s); + } + catch (error) { + // Pass + } + // Initialize variables. + let new_s = ""; + const stack = []; + let isInsideString = false; + let escaped = false; + // Process each character in the string one at a time. + for (let char of s) { + if (isInsideString) { + if (char === '"' && !escaped) { + isInsideString = false; + } + else if (char === "\n" && !escaped) { + char = "\\n"; // Replace the newline character with the escape sequence. + } + else if (char === "\\") { + escaped = !escaped; + } + else { + escaped = false; + } + } + else { + if (char === '"') { + isInsideString = true; + escaped = false; + } + else if (char === "{") { + stack.push("}"); + } + else if (char === "[") { + stack.push("]"); + } + else if (char === "}" || char === "]") { + if (stack && stack[stack.length - 1] === char) { + stack.pop(); + } + else { + // Mismatched closing character; the input is malformed. + return null; + } + } + } + // Append the processed character to the new string. + new_s += char; + } + // If we're still inside a string at the end of processing, + // we need to close the string. + if (isInsideString) { + new_s += '"'; + } + // Close any remaining open structures in the reverse order that they were opened. + for (let i = stack.length - 1; i >= 0; i -= 1) { + new_s += stack[i]; } - /** - * List available models. - * - * The Models API response can be used to determine which models are available for - * use in the API. More recently released models are listed first. - */ - list(params = {}, options) { - const { betas, ...query } = params ?? {}; - return this._client.getAPIList('/v1/models', (pagination_Page), { - query, - ...options, - headers: buildHeaders([ - { ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) }, - options?.headers, - ]), - }); + // Attempt to parse the modified string as JSON. + try { + return JSON.parse(new_s); + } + catch (error) { + // If we still can't parse the string as JSON, return null to indicate failure. + return null; } } -//# sourceMappingURL=models.mjs.map -;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/resources/index.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +// EXTERNAL MODULE: ./node_modules/decamelize/index.js +var decamelize = __nccwpck_require__(8203); +// EXTERNAL MODULE: ./node_modules/camelcase/index.js +var camelcase = __nccwpck_require__(9890); +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/load/map_keys.js +function keyToJson(key, map) { + return map?.[key] || decamelize(key); +} +function keyFromJson(key, map) { + return map?.[key] || camelCase(key); +} +function mapKeys(fields, mapper, map) { + const mapped = {}; + for (const key in fields) { + if (Object.hasOwn(fields, key)) { + mapped[mapper(key, map)] = fields[key]; + } + } + return mapped; +} +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/load/serializable.js -//# sourceMappingURL=index.mjs.map -;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/internal/utils/env.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +function shallowCopy(obj) { + return Array.isArray(obj) ? [...obj] : { ...obj }; +} +function replaceSecrets(root, secretsMap) { + const result = shallowCopy(root); + for (const [path, secretId] of Object.entries(secretsMap)) { + const [last, ...partsReverse] = path.split(".").reverse(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let current = result; + for (const part of partsReverse.reverse()) { + if (current[part] === undefined) { + break; + } + current[part] = shallowCopy(current[part]); + current = current[part]; + } + if (current[last] !== undefined) { + current[last] = { + lc: 1, + type: "secret", + id: [secretId], + }; + } + } + return result; +} /** - * Read an environment variable. - * - * Trims beginning and trailing whitespace. - * - * Will return undefined if the environment variable doesn't exist or cannot be accessed. + * Get a unique name for the module, rather than parent class implementations. + * Should not be subclassed, subclass lc_name above instead. */ -const env_readEnv = (env) => { - if (typeof globalThis.process !== 'undefined') { - return globalThis.process.env?.[env]?.trim() ?? undefined; +function get_lc_unique_name( +// eslint-disable-next-line @typescript-eslint/no-use-before-define +serializableClass) { + // "super" here would refer to the parent class of Serializable, + // when we want the parent class of the module actually calling this method. + const parentClass = Object.getPrototypeOf(serializableClass); + const lcNameIsSubclassed = typeof serializableClass.lc_name === "function" && + (typeof parentClass.lc_name !== "function" || + serializableClass.lc_name() !== parentClass.lc_name()); + if (lcNameIsSubclassed) { + return serializableClass.lc_name(); } - if (typeof globalThis.Deno !== 'undefined') { - return globalThis.Deno.env?.get?.(env)?.trim(); + else { + return serializableClass.name; } - return undefined; -}; -//# sourceMappingURL=env.mjs.map -;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/client.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -var client_a, _BaseAnthropic_encoder; - - - - - - - - - - - - - - - - - - - - - - - - -class BaseAnthropic { +} +class Serializable { /** - * API Client for interfacing with the Anthropic API. + * The name of the serializable. Override to provide an alias or + * to preserve the serialized module name in minified environments. * - * @param {string | null | undefined} [opts.apiKey=process.env['ANTHROPIC_API_KEY'] ?? null] - * @param {string | null | undefined} [opts.authToken=process.env['ANTHROPIC_AUTH_TOKEN'] ?? null] - * @param {string} [opts.baseURL=process.env['ANTHROPIC_BASE_URL'] ?? https://api.anthropic.com] - Override the default base URL for the API. - * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out. - * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls. - * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation. - * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request. - * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API. - * @param {Record} opts.defaultQuery - Default query parameters to include with every request to the API. - * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers. + * Implemented as a static method to support loading logic. */ - constructor({ baseURL = env_readEnv('ANTHROPIC_BASE_URL'), apiKey = env_readEnv('ANTHROPIC_API_KEY') ?? null, authToken = env_readEnv('ANTHROPIC_AUTH_TOKEN') ?? null, ...opts } = {}) { - _BaseAnthropic_encoder.set(this, void 0); - const options = { - apiKey, - authToken, - ...opts, - baseURL: baseURL || `https://api.anthropic.com`, - }; - if (!options.dangerouslyAllowBrowser && detect_platform_isRunningInBrowser()) { - throw new error_AnthropicError("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew Anthropic({ apiKey, dangerouslyAllowBrowser: true });\n"); - } - this.baseURL = options.baseURL; - this.timeout = options.timeout ?? Anthropic.DEFAULT_TIMEOUT /* 10 minutes */; - this.logger = options.logger ?? console; - const defaultLogLevel = 'warn'; - // Set default logLevel early so that we can log a warning in parseLogLevel. - this.logLevel = defaultLogLevel; - this.logLevel = - parseLogLevel(options.logLevel, 'ClientOptions.logLevel', this) ?? - parseLogLevel(env_readEnv('ANTHROPIC_LOG'), "process.env['ANTHROPIC_LOG']", this) ?? - defaultLogLevel; - this.fetchOptions = options.fetchOptions; - this.maxRetries = options.maxRetries ?? 2; - this.fetch = options.fetch ?? getDefaultFetch(); - tslib_classPrivateFieldSet(this, _BaseAnthropic_encoder, FallbackEncoder, "f"); - this._options = options; - this.apiKey = apiKey; - this.authToken = authToken; + static lc_name() { + return this.name; } /** - * Create a new client instance re-using the same options given to the current client with optional overriding. + * The final serialized identifier for the module. */ - withOptions(options) { - return new this.constructor({ - ...this._options, - baseURL: this.baseURL, - maxRetries: this.maxRetries, - timeout: this.timeout, - logger: this.logger, - logLevel: this.logLevel, - fetchOptions: this.fetchOptions, - apiKey: this.apiKey, - authToken: this.authToken, - ...options, - }); - } - defaultQuery() { - return this._options.defaultQuery; - } - validateHeaders({ values, nulls }) { - if (this.apiKey && values.get('x-api-key')) { - return; - } - if (nulls.has('x-api-key')) { - return; - } - if (this.authToken && values.get('authorization')) { - return; - } - if (nulls.has('authorization')) { - return; - } - throw new Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted'); - } - authHeaders(opts) { - return buildHeaders([this.apiKeyAuth(opts), this.bearerAuth(opts)]); - } - apiKeyAuth(opts) { - if (this.apiKey == null) { - return undefined; - } - return buildHeaders([{ 'X-Api-Key': this.apiKey }]); - } - bearerAuth(opts) { - if (this.authToken == null) { - return undefined; - } - return buildHeaders([{ Authorization: `Bearer ${this.authToken}` }]); + get lc_id() { + return [ + ...this.lc_namespace, + get_lc_unique_name(this.constructor), + ]; } /** - * Basic re-implementation of `qs.stringify` for primitive types. + * A map of secrets, which will be omitted from serialization. + * Keys are paths to the secret in constructor args, e.g. "foo.bar.baz". + * Values are the secret ids, which will be used when deserializing. */ - stringifyQuery(query) { - return Object.entries(query) - .filter(([_, value]) => typeof value !== 'undefined') - .map(([key, value]) => { - if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { - return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`; - } - if (value === null) { - return `${encodeURIComponent(key)}=`; - } - throw new error_AnthropicError(`Cannot stringify type ${typeof value}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`); - }) - .join('&'); - } - getUserAgent() { - return `${this.constructor.name}/JS ${version_VERSION}`; - } - defaultIdempotencyKey() { - return `stainless-node-retry-${uuid_uuid4()}`; - } - makeStatusError(status, error, message, headers) { - return error_APIError.generate(status, error, message, headers); - } - buildURL(path, query) { - const url = values_isAbsoluteURL(path) ? - new URL(path) - : new URL(this.baseURL + (this.baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path)); - const defaultQuery = this.defaultQuery(); - if (!values_isEmptyObj(defaultQuery)) { - query = { ...defaultQuery, ...query }; - } - if (typeof query === 'object' && query && !Array.isArray(query)) { - url.search = this.stringifyQuery(query); - } - return url.toString(); - } - _calculateNonstreamingTimeout(maxTokens) { - const defaultTimeout = 10 * 60; - const expectedTimeout = (60 * 60 * maxTokens) / 128000; - if (expectedTimeout > defaultTimeout) { - throw new error_AnthropicError('Streaming is strongly recommended for operations that may take longer than 10 minutes. ' + - 'See https://github.com/anthropics/anthropic-sdk-python#streaming-responses for more details'); - } - return defaultTimeout * 1000; + get lc_secrets() { + return undefined; } /** - * Used as a callback for mutating the given `FinalRequestOptions` object. + * A map of additional attributes to merge with constructor args. + * Keys are the attribute names, e.g. "foo". + * Values are the attribute values, which will be serialized. + * These attributes need to be accepted by the constructor as arguments. */ - async prepareOptions(options) { } + get lc_attributes() { + return undefined; + } /** - * Used as a callback for mutating the given `RequestInit` object. - * - * This is useful for cases where you want to add certain headers based off of - * the request properties, e.g. `method` or `url`. + * A map of aliases for constructor args. + * Keys are the attribute names, e.g. "foo". + * Values are the alias that will replace the key in serialization. + * This is used to eg. make argument names match Python. */ - async prepareRequest(request, { url, options }) { } - get(path, opts) { - return this.methodRequest('get', path, opts); - } - post(path, opts) { - return this.methodRequest('post', path, opts); - } - patch(path, opts) { - return this.methodRequest('patch', path, opts); - } - put(path, opts) { - return this.methodRequest('put', path, opts); - } - delete(path, opts) { - return this.methodRequest('delete', path, opts); + get lc_aliases() { + return undefined; } - methodRequest(method, path, opts) { - return this.request(Promise.resolve(opts).then((opts) => { - return { method, path, ...opts }; - })); + /** + * A manual list of keys that should be serialized. + * If not overridden, all fields passed into the constructor will be serialized. + */ + get lc_serializable_keys() { + return undefined; } - request(options, remainingRetries = null) { - return new api_promise_APIPromise(this, this.makeRequest(options, remainingRetries, undefined)); + constructor(kwargs, ..._args) { + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "lc_kwargs", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + if (this.lc_serializable_keys !== undefined) { + this.lc_kwargs = Object.fromEntries(Object.entries(kwargs || {}).filter(([key]) => this.lc_serializable_keys?.includes(key))); + } + else { + this.lc_kwargs = kwargs ?? {}; + } } - async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) { - const options = await optionsInput; - const maxRetries = options.maxRetries ?? this.maxRetries; - if (retriesRemaining == null) { - retriesRemaining = maxRetries; + toJSON() { + if (!this.lc_serializable) { + return this.toJSONNotImplemented(); } - await this.prepareOptions(options); - const { req, url, timeout } = this.buildRequest(options, { retryCount: maxRetries - retriesRemaining }); - await this.prepareRequest(req, { url, options }); - /** Not an API request ID, just for correlating local log entries. */ - const requestLogID = 'log_' + ((Math.random() * (1 << 24)) | 0).toString(16).padStart(6, '0'); - const retryLogStr = retryOfRequestLogID === undefined ? '' : `, retryOf: ${retryOfRequestLogID}`; - const startTime = Date.now(); - loggerFor(this).debug(`[${requestLogID}] sending request`, formatRequestDetails({ - retryOfRequestLogID, - method: options.method, - url, - options, - headers: req.headers, - })); - if (options.signal?.aborted) { - throw new error_APIUserAbortError(); + if ( + // eslint-disable-next-line no-instanceof/no-instanceof + this.lc_kwargs instanceof Serializable || + typeof this.lc_kwargs !== "object" || + Array.isArray(this.lc_kwargs)) { + // We do not support serialization of classes with arg not a POJO + // I'm aware the check above isn't as strict as it could be + return this.toJSONNotImplemented(); } - const controller = new AbortController(); - const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(errors_castToError); - const headersTime = Date.now(); - if (response instanceof Error) { - const retryMessage = `retrying, ${retriesRemaining} attempts remaining`; - if (options.signal?.aborted) { - throw new error_APIUserAbortError(); - } - // detect native connection timeout errors - // deno throws "TypeError: error sending request for url (https://example/): client error (Connect): tcp connect error: Operation timed out (os error 60): Operation timed out (os error 60)" - // undici throws "TypeError: fetch failed" with cause "ConnectTimeoutError: Connect Timeout Error (attempted address: example:443, timeout: 1ms)" - // others do not provide enough information to distinguish timeouts from other connection errors - const isTimeout = isAbortError(response) || - /timed? ?out/i.test(String(response) + ('cause' in response ? String(response.cause) : '')); - if (retriesRemaining) { - loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - ${retryMessage}`); - loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (${retryMessage})`, formatRequestDetails({ - retryOfRequestLogID, - url, - durationMs: headersTime - startTime, - message: response.message, - })); - return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID); + const aliases = {}; + const secrets = {}; + const kwargs = Object.keys(this.lc_kwargs).reduce((acc, key) => { + acc[key] = key in this ? this[key] : this.lc_kwargs[key]; + return acc; + }, {}); + // get secrets, attributes and aliases from all superclasses + for ( + // eslint-disable-next-line @typescript-eslint/no-this-alias + let current = Object.getPrototypeOf(this); current; current = Object.getPrototypeOf(current)) { + Object.assign(aliases, Reflect.get(current, "lc_aliases", this)); + Object.assign(secrets, Reflect.get(current, "lc_secrets", this)); + Object.assign(kwargs, Reflect.get(current, "lc_attributes", this)); + } + // include all secrets used, even if not in kwargs, + // will be replaced with sentinel value in replaceSecrets + Object.keys(secrets).forEach((keyPath) => { + // eslint-disable-next-line @typescript-eslint/no-this-alias, @typescript-eslint/no-explicit-any + let read = this; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let write = kwargs; + const [last, ...partsReverse] = keyPath.split(".").reverse(); + for (const key of partsReverse.reverse()) { + if (!(key in read) || read[key] === undefined) + return; + if (!(key in write) || write[key] === undefined) { + if (typeof read[key] === "object" && read[key] != null) { + write[key] = {}; + } + else if (Array.isArray(read[key])) { + write[key] = []; + } + } + read = read[key]; + write = write[key]; } - loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - error; no more retries left`); - loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (error; no more retries left)`, formatRequestDetails({ - retryOfRequestLogID, - url, - durationMs: headersTime - startTime, - message: response.message, - })); - if (isTimeout) { - throw new error_APIConnectionTimeoutError(); + if (last in read && read[last] !== undefined) { + write[last] = write[last] || read[last]; } - throw new error_APIConnectionError({ cause: response }); - } - const specialHeaders = [...response.headers.entries()] - .filter(([name]) => name === 'request-id') - .map(([name, value]) => ', ' + name + ': ' + JSON.stringify(value)) - .join(''); - const responseInfo = `[${requestLogID}${retryLogStr}${specialHeaders}] ${req.method} ${url} ${response.ok ? 'succeeded' : 'failed'} with status ${response.status} in ${headersTime - startTime}ms`; - if (!response.ok) { - const shouldRetry = this.shouldRetry(response); - if (retriesRemaining && shouldRetry) { - const retryMessage = `retrying, ${retriesRemaining} attempts remaining`; - // We don't need the body of this response. - await CancelReadableStream(response.body); - loggerFor(this).info(`${responseInfo} - ${retryMessage}`); - loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({ - retryOfRequestLogID, - url: response.url, - status: response.status, - headers: response.headers, - durationMs: headersTime - startTime, - })); - return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers); + }); + return { + lc: 1, + type: "constructor", + id: this.lc_id, + kwargs: mapKeys(Object.keys(secrets).length ? replaceSecrets(kwargs, secrets) : kwargs, keyToJson, aliases), + }; + } + toJSONNotImplemented() { + return { + lc: 1, + type: "not_implemented", + id: this.lc_id, + }; + } +} + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/content_blocks.js +function isDataContentBlock(content_block) { + return (typeof content_block === "object" && + content_block !== null && + "type" in content_block && + typeof content_block.type === "string" && + "source_type" in content_block && + (content_block.source_type === "url" || + content_block.source_type === "base64" || + content_block.source_type === "text" || + content_block.source_type === "id")); +} +function isURLContentBlock(content_block) { + return (isDataContentBlock(content_block) && + content_block.source_type === "url" && + "url" in content_block && + typeof content_block.url === "string"); +} +function isBase64ContentBlock(content_block) { + return (isDataContentBlock(content_block) && + content_block.source_type === "base64" && + "data" in content_block && + typeof content_block.data === "string"); +} +function isPlainTextContentBlock(content_block) { + return (isDataContentBlock(content_block) && + content_block.source_type === "text" && + "text" in content_block && + typeof content_block.text === "string"); +} +function isIDContentBlock(content_block) { + return (isDataContentBlock(content_block) && + content_block.source_type === "id" && + "id" in content_block && + typeof content_block.id === "string"); +} +function convertToOpenAIImageBlock(content_block) { + if (isDataContentBlock(content_block)) { + if (content_block.source_type === "url") { + return { + type: "image_url", + image_url: { + url: content_block.url, + }, + }; + } + if (content_block.source_type === "base64") { + if (!content_block.mime_type) { + throw new Error("mime_type key is required for base64 data."); } - const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`; - loggerFor(this).info(`${responseInfo} - ${retryMessage}`); - const errText = await response.text().catch((err) => errors_castToError(err).message); - const errJSON = values_safeJSON(errText); - const errMessage = errJSON ? undefined : errText; - loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({ - retryOfRequestLogID, - url: response.url, - status: response.status, - headers: response.headers, - message: errMessage, - durationMs: Date.now() - startTime, - })); - const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers); - throw err; + const mime_type = content_block.mime_type; + return { + type: "image_url", + image_url: { + url: `data:${mime_type};base64,${content_block.data}`, + }, + }; } - loggerFor(this).info(responseInfo); - loggerFor(this).debug(`[${requestLogID}] response start`, formatRequestDetails({ - retryOfRequestLogID, - url: response.url, - status: response.status, - headers: response.headers, - durationMs: headersTime - startTime, - })); - return { response, options, controller, requestLogID, retryOfRequestLogID, startTime }; } - getAPIList(path, Page, opts) { - return this.requestAPIList(Page, { method: 'get', path, ...opts }); + throw new Error("Unsupported source type. Only 'url' and 'base64' are supported."); +} +/** + * Utility function for ChatModelProviders. Parses a mime type into a type, subtype, and parameters. + * + * @param mime_type - The mime type to parse. + * @returns An object containing the type, subtype, and parameters. + */ +function parseMimeType(mime_type) { + const parts = mime_type.split(";")[0].split("/"); + if (parts.length !== 2) { + throw new Error(`Invalid mime type: "${mime_type}" - does not match type/subtype format.`); } - requestAPIList(Page, options) { - const request = this.makeRequest(options, null, undefined); - return new pagination_PagePromise(this, request, Page); + const type = parts[0].trim(); + const subtype = parts[1].trim(); + if (type === "" || subtype === "") { + throw new Error(`Invalid mime type: "${mime_type}" - type or subtype is empty.`); } - async fetchWithTimeout(url, init, ms, controller) { - const { signal, method, ...options } = init || {}; - if (signal) - signal.addEventListener('abort', () => controller.abort()); - const timeout = setTimeout(() => controller.abort(), ms); - const isReadableBody = (globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream) || - (typeof options.body === 'object' && options.body !== null && Symbol.asyncIterator in options.body); - const fetchOptions = { - signal: controller.signal, - ...(isReadableBody ? { duplex: 'half' } : {}), - method: 'GET', - ...options, - }; - if (method) { - // Custom methods like 'patch' need to be uppercased - // See https://github.com/nodejs/undici/issues/2294 - fetchOptions.method = method.toUpperCase(); - } - try { - // use undefined this binding; fetch errors if bound to something else in browser/cloudflare - return await this.fetch.call(undefined, url, fetchOptions); + const parameters = {}; + for (const parameterKvp of mime_type.split(";").slice(1)) { + const parameterParts = parameterKvp.split("="); + if (parameterParts.length !== 2) { + throw new Error(`Invalid parameter syntax in mime type: "${mime_type}".`); } - finally { - clearTimeout(timeout); + const key = parameterParts[0].trim(); + const value = parameterParts[1].trim(); + if (key === "") { + throw new Error(`Invalid parameter syntax in mime type: "${mime_type}".`); } + parameters[key] = value; } - shouldRetry(response) { - // Note this is not a standard header. - const shouldRetryHeader = response.headers.get('x-should-retry'); - // If the server explicitly says whether or not to retry, obey. - if (shouldRetryHeader === 'true') - return true; - if (shouldRetryHeader === 'false') - return false; - // Retry on request timeouts. - if (response.status === 408) - return true; - // Retry on lock timeouts. - if (response.status === 409) - return true; - // Retry on rate limits. - if (response.status === 429) - return true; - // Retry internal errors. - if (response.status >= 500) - return true; - return false; + return { + type, + subtype, + parameters, + }; +} +/** + * Utility function for ChatModelProviders. Parses a base64 data URL into a typed array or string. + * + * @param dataUrl - The base64 data URL to parse. + * @param asTypedArray - Whether to return the data as a typed array. + * @returns The parsed data and mime type, or undefined if the data URL is invalid. + */ +function parseBase64DataUrl({ dataUrl: data_url, asTypedArray = false, }) { + const formatMatch = data_url.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/); + let mime_type; + if (formatMatch) { + mime_type = formatMatch[1].toLowerCase(); + const data = asTypedArray + ? Uint8Array.from(atob(formatMatch[2]), (c) => c.charCodeAt(0)) + : formatMatch[2]; + return { + mime_type, + data, + }; } - async retryRequest(options, retriesRemaining, requestLogID, responseHeaders) { - let timeoutMillis; - // Note the `retry-after-ms` header may not be standard, but is a good idea and we'd like proactive support for it. - const retryAfterMillisHeader = responseHeaders?.get('retry-after-ms'); - if (retryAfterMillisHeader) { - const timeoutMs = parseFloat(retryAfterMillisHeader); - if (!Number.isNaN(timeoutMs)) { - timeoutMillis = timeoutMs; - } - } - // About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After - const retryAfterHeader = responseHeaders?.get('retry-after'); - if (retryAfterHeader && !timeoutMillis) { - const timeoutSeconds = parseFloat(retryAfterHeader); - if (!Number.isNaN(timeoutSeconds)) { - timeoutMillis = timeoutSeconds * 1000; - } - else { - timeoutMillis = Date.parse(retryAfterHeader) - Date.now(); - } + return undefined; +} +/** + * Convert from a standard data content block to a provider's proprietary data content block format. + * + * Don't override this method. Instead, override the more specific conversion methods and use this + * method unmodified. + * + * @param block - The standard data content block to convert. + * @returns The provider data content block. + * @throws An error if the standard data content block type is not supported. + */ +function convertToProviderContentBlock(block, converter) { + if (block.type === "text") { + if (!converter.fromStandardTextBlock) { + throw new Error(`Converter for ${converter.providerName} does not implement \`fromStandardTextBlock\` method.`); } - // If the API asks us to wait a certain amount of time (and it's a reasonable amount), - // just do what it says, but otherwise calculate a default - if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1000)) { - const maxRetries = options.maxRetries ?? this.maxRetries; - timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries); + return converter.fromStandardTextBlock(block); + } + if (block.type === "image") { + if (!converter.fromStandardImageBlock) { + throw new Error(`Converter for ${converter.providerName} does not implement \`fromStandardImageBlock\` method.`); } - await sleep_sleep(timeoutMillis); - return this.makeRequest(options, retriesRemaining - 1, requestLogID); + return converter.fromStandardImageBlock(block); } - calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) { - const initialRetryDelay = 0.5; - const maxRetryDelay = 8.0; - const numRetries = maxRetries - retriesRemaining; - // Apply exponential backoff, but not more than the max. - const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay); - // Apply some jitter, take up to at most 25 percent of the retry time. - const jitter = 1 - Math.random() * 0.25; - return sleepSeconds * jitter * 1000; + if (block.type === "audio") { + if (!converter.fromStandardAudioBlock) { + throw new Error(`Converter for ${converter.providerName} does not implement \`fromStandardAudioBlock\` method.`); + } + return converter.fromStandardAudioBlock(block); } - buildRequest(inputOptions, { retryCount = 0 } = {}) { - const options = { ...inputOptions }; - const { method, path, query } = options; - const url = this.buildURL(path, query); - if ('timeout' in options) - values_validatePositiveInteger('timeout', options.timeout); - options.timeout = options.timeout ?? this.timeout; - const { bodyHeaders, body } = this.buildBody({ options }); - const reqHeaders = this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount }); - const req = { - method, - headers: reqHeaders, - ...(options.signal && { signal: options.signal }), - ...(globalThis.ReadableStream && - body instanceof globalThis.ReadableStream && { duplex: 'half' }), - ...(body && { body }), - ...(this.fetchOptions ?? {}), - ...(options.fetchOptions ?? {}), - }; - return { req, url, timeout: options.timeout }; + if (block.type === "file") { + if (!converter.fromStandardFileBlock) { + throw new Error(`Converter for ${converter.providerName} does not implement \`fromStandardFileBlock\` method.`); + } + return converter.fromStandardFileBlock(block); } - buildHeaders({ options, method, bodyHeaders, retryCount, }) { - let idempotencyHeaders = {}; - if (this.idempotencyHeader && method !== 'get') { - if (!options.idempotencyKey) - options.idempotencyKey = this.defaultIdempotencyKey(); - idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey; + throw new Error(`Unable to convert content block type '${block.type}' to provider-specific format: not recognized.`); +} + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/base.js + + +function mergeContent(firstContent, secondContent) { + // If first content is a string + if (typeof firstContent === "string") { + if (firstContent === "") { + return secondContent; } - const headers = buildHeaders([ - idempotencyHeaders, - { - Accept: 'application/json', - 'User-Agent': this.getUserAgent(), - 'X-Stainless-Retry-Count': String(retryCount), - ...(options.timeout ? { 'X-Stainless-Timeout': String(Math.trunc(options.timeout / 1000)) } : {}), - ...detect_platform_getPlatformHeaders(), - ...(this._options.dangerouslyAllowBrowser ? - { 'anthropic-dangerous-direct-browser-access': 'true' } - : undefined), - 'anthropic-version': '2023-06-01', - }, - this.authHeaders(options), - this._options.defaultHeaders, - bodyHeaders, - options.headers, + if (typeof secondContent === "string") { + return firstContent + secondContent; + } + else if (Array.isArray(secondContent) && + secondContent.some((c) => isDataContentBlock(c))) { + return [ + { + type: "text", + source_type: "text", + text: firstContent, + }, + ...secondContent, + ]; + } + else { + return [{ type: "text", text: firstContent }, ...secondContent]; + } + // If both are arrays + } + else if (Array.isArray(secondContent)) { + return (_mergeLists(firstContent, secondContent) ?? [ + ...firstContent, + ...secondContent, ]); - this.validateHeaders(headers); - return headers.values; } - buildBody({ options: { body, headers: rawHeaders } }) { - if (!body) { - return { bodyHeaders: undefined, body: undefined }; - } - const headers = buildHeaders([rawHeaders]); - if ( - // Pass raw type verbatim - ArrayBuffer.isView(body) || - body instanceof ArrayBuffer || - body instanceof DataView || - (typeof body === 'string' && - // Preserve legacy string encoding behavior for now - headers.values.has('content-type')) || - // `Blob` is superset of `File` - body instanceof Blob || - // `FormData` -> `multipart/form-data` - body instanceof FormData || - // `URLSearchParams` -> `application/x-www-form-urlencoded` - body instanceof URLSearchParams || - // Send chunked stream (each chunk has own `length`) - (globalThis.ReadableStream && body instanceof globalThis.ReadableStream)) { - return { bodyHeaders: undefined, body: body }; + else { + if (secondContent === "") { + return firstContent; } - else if (typeof body === 'object' && - (Symbol.asyncIterator in body || - (Symbol.iterator in body && 'next' in body && typeof body.next === 'function'))) { - return { bodyHeaders: undefined, body: shims_ReadableStreamFrom(body) }; + else if (Array.isArray(firstContent) && + firstContent.some((c) => isDataContentBlock(c))) { + return [ + ...firstContent, + { + type: "file", + source_type: "text", + text: secondContent, + }, + ]; } else { - return tslib_classPrivateFieldGet(this, _BaseAnthropic_encoder, "f").call(this, { body, headers }); + return [...firstContent, { type: "text", text: secondContent }]; } } } -client_a = BaseAnthropic, _BaseAnthropic_encoder = new WeakMap(); -BaseAnthropic.Anthropic = client_a; -BaseAnthropic.HUMAN_PROMPT = '\n\nHuman:'; -BaseAnthropic.AI_PROMPT = '\n\nAssistant:'; -BaseAnthropic.DEFAULT_TIMEOUT = 600000; // 10 minutes -BaseAnthropic.AnthropicError = error_AnthropicError; -BaseAnthropic.APIError = error_APIError; -BaseAnthropic.APIConnectionError = error_APIConnectionError; -BaseAnthropic.APIConnectionTimeoutError = error_APIConnectionTimeoutError; -BaseAnthropic.APIUserAbortError = error_APIUserAbortError; -BaseAnthropic.NotFoundError = error_NotFoundError; -BaseAnthropic.ConflictError = error_ConflictError; -BaseAnthropic.RateLimitError = error_RateLimitError; -BaseAnthropic.BadRequestError = error_BadRequestError; -BaseAnthropic.AuthenticationError = error_AuthenticationError; -BaseAnthropic.InternalServerError = error_InternalServerError; -BaseAnthropic.PermissionDeniedError = error_PermissionDeniedError; -BaseAnthropic.UnprocessableEntityError = error_UnprocessableEntityError; -BaseAnthropic.toFile = to_file_toFile; /** - * API Client for interfacing with the Anthropic API. + * 'Merge' two statuses. If either value passed is 'error', it will return 'error'. Else + * it will return 'success'. + * + * @param {"success" | "error" | undefined} left The existing value to 'merge' with the new value. + * @param {"success" | "error" | undefined} right The new value to 'merge' with the existing value + * @returns {"success" | "error"} The 'merged' value. */ -class Anthropic extends BaseAnthropic { - constructor() { - super(...arguments); - this.completions = new resources_completions_Completions(this); - this.messages = new resources_messages_messages_Messages(this); - this.models = new resources_models_Models(this); - this.beta = new beta_Beta(this); +function _mergeStatus(left, right) { + if (left === "error" || right === "error") { + return "error"; } + return "success"; } -Anthropic.Completions = resources_completions_Completions; -Anthropic.Messages = resources_messages_messages_Messages; -Anthropic.Models = resources_models_Models; -Anthropic.Beta = beta_Beta; -const { HUMAN_PROMPT, AI_PROMPT } = Anthropic; -//# sourceMappingURL=client.mjs.map -;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/index.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - - -//# sourceMappingURL=index.mjs.map -// EXTERNAL MODULE: ./node_modules/uuid/dist/index.js -var dist = __nccwpck_require__(2048); -;// CONCATENATED MODULE: ./node_modules/uuid/wrapper.mjs - -const v1 = dist.v1; -const v1ToV6 = dist/* v1ToV6 */.bV; -const v3 = dist.v3; -const v4 = dist.v4; -const v5 = dist.v5; -const v6 = dist.v6; -const v6ToV1 = dist/* v6ToV1 */.JE; -const v7 = dist.v7; -const NIL = dist/* NIL */.wD; -const MAX = dist/* MAX */.Zu; -const version = dist/* version */.rE; -const wrapper_validate = dist/* validate */.tf; -const wrapper_stringify = dist/* stringify */.As; -const parse = dist/* parse */.qg; - -// EXTERNAL MODULE: ./node_modules/@mistralai/mistralai/index.js -var mistralai = __nccwpck_require__(6611); -// EXTERNAL MODULE: ./node_modules/@mistralai/mistralai/lib/http.js -var http = __nccwpck_require__(1775); -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/json.js -function parseJsonMarkdown(s, parser = parsePartialJson) { - // eslint-disable-next-line no-param-reassign - s = s.trim(); - const firstFenceIndex = s.indexOf("```"); - if (firstFenceIndex === -1) { - return parser(s); +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function stringifyWithDepthLimit(obj, depthLimit) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + function helper(obj, currentDepth) { + if (typeof obj !== "object" || obj === null || obj === undefined) { + return obj; + } + if (currentDepth >= depthLimit) { + if (Array.isArray(obj)) { + return "[Array]"; + } + return "[Object]"; + } + if (Array.isArray(obj)) { + return obj.map((item) => helper(item, currentDepth + 1)); + } + const result = {}; + for (const key of Object.keys(obj)) { + result[key] = helper(obj[key], currentDepth + 1); + } + return result; } - let contentAfterFence = s.substring(firstFenceIndex + 3); - if (contentAfterFence.startsWith("json\n")) { - contentAfterFence = contentAfterFence.substring(5); + return JSON.stringify(helper(obj, 0), null, 2); +} +/** + * Base class for all types of messages in a conversation. It includes + * properties like `content`, `name`, and `additional_kwargs`. It also + * includes methods like `toDict()` and `_getType()`. + */ +class BaseMessage extends Serializable { + get lc_aliases() { + // exclude snake case conversion to pascal case + return { + additional_kwargs: "additional_kwargs", + response_metadata: "response_metadata", + }; + } + /** + * Get text content of the message. + */ + get text() { + if (typeof this.content === "string") { + return this.content; + } + if (!Array.isArray(this.content)) + return ""; + return this.content + .map((c) => { + if (typeof c === "string") + return c; + if (c.type === "text") + return c.text; + return ""; + }) + .join(""); + } + /** The type of the message. */ + getType() { + return this._getType(); + } + constructor(fields, + /** @deprecated */ + kwargs) { + if (typeof fields === "string") { + // eslint-disable-next-line no-param-reassign + fields = { + content: fields, + additional_kwargs: kwargs, + response_metadata: {}, + }; + } + // Make sure the default value for additional_kwargs is passed into super() for serialization + if (!fields.additional_kwargs) { + // eslint-disable-next-line no-param-reassign + fields.additional_kwargs = {}; + } + if (!fields.response_metadata) { + // eslint-disable-next-line no-param-reassign + fields.response_metadata = {}; + } + super(fields); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain_core", "messages"] + }); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + /** The content of the message. */ + Object.defineProperty(this, "content", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + /** The name of the message sender in a multi-user chat. */ + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + /** Additional keyword arguments */ + Object.defineProperty(this, "additional_kwargs", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + /** Response metadata. For example: response headers, logprobs, token counts, model name. */ + Object.defineProperty(this, "response_metadata", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + /** + * An optional unique identifier for the message. This should ideally be + * provided by the provider/model which created the message. + */ + Object.defineProperty(this, "id", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.name = fields.name; + this.content = fields.content; + this.additional_kwargs = fields.additional_kwargs; + this.response_metadata = fields.response_metadata; + this.id = fields.id; } - else if (contentAfterFence.startsWith("json")) { - contentAfterFence = contentAfterFence.substring(4); + toDict() { + return { + type: this._getType(), + data: this.toJSON() + .kwargs, + }; } - else if (contentAfterFence.startsWith("\n")) { - contentAfterFence = contentAfterFence.substring(1); + static lc_name() { + return "BaseMessage"; } - const closingFenceIndex = contentAfterFence.indexOf("```"); - let finalContent = contentAfterFence; - if (closingFenceIndex !== -1) { - finalContent = contentAfterFence.substring(0, closingFenceIndex); + // Can't be protected for silly reasons + get _printableFields() { + return { + id: this.id, + content: this.content, + name: this.name, + additional_kwargs: this.additional_kwargs, + response_metadata: this.response_metadata, + }; } - return parser(finalContent.trim()); -} -// Adapted from https://github.com/KillianLucas/open-interpreter/blob/main/interpreter/core/llm/utils/parse_partial_json.py -// MIT License -function parsePartialJson(s) { - // If the input is undefined, return null to indicate failure. - if (typeof s === "undefined") { - return null; + // this private method is used to update the ID for the runtime + // value as well as in lc_kwargs for serialisation + _updateId(value) { + this.id = value; + // lc_attributes wouldn't work here, because jest compares the + // whole object + this.lc_kwargs.id = value; } - // Attempt to parse the string as-is. - try { - return JSON.parse(s); + get [Symbol.toStringTag]() { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return this.constructor.lc_name(); } - catch (error) { - // Pass + // Override the default behavior of console.log + [Symbol.for("nodejs.util.inspect.custom")](depth) { + if (depth === null) { + return this; + } + const printable = stringifyWithDepthLimit(this._printableFields, Math.max(4, depth)); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return `${this.constructor.lc_name()} ${printable}`; } - // Initialize variables. - let new_s = ""; - const stack = []; - let isInsideString = false; - let escaped = false; - // Process each character in the string one at a time. - for (let char of s) { - if (isInsideString) { - if (char === '"' && !escaped) { - isInsideString = false; - } - else if (char === "\n" && !escaped) { - char = "\\n"; // Replace the newline character with the escape sequence. - } - else if (char === "\\") { - escaped = !escaped; - } - else { - escaped = false; +} +function isOpenAIToolCallArray(value) { + return (Array.isArray(value) && + value.every((v) => typeof v.index === "number")); +} +function _mergeDicts( +// eslint-disable-next-line @typescript-eslint/no-explicit-any +left, +// eslint-disable-next-line @typescript-eslint/no-explicit-any +right +// eslint-disable-next-line @typescript-eslint/no-explicit-any +) { + const merged = { ...left }; + for (const [key, value] of Object.entries(right)) { + if (merged[key] == null) { + merged[key] = value; + } + else if (value == null) { + continue; + } + else if (typeof merged[key] !== typeof value || + Array.isArray(merged[key]) !== Array.isArray(value)) { + throw new Error(`field[${key}] already exists in the message chunk, but with a different type.`); + } + else if (typeof merged[key] === "string") { + if (key === "type") { + // Do not merge 'type' fields + continue; } + merged[key] += value; + } + else if (typeof merged[key] === "object" && !Array.isArray(merged[key])) { + merged[key] = _mergeDicts(merged[key], value); + } + else if (Array.isArray(merged[key])) { + merged[key] = _mergeLists(merged[key], value); + } + else if (merged[key] === value) { + continue; } else { - if (char === '"') { - isInsideString = true; - escaped = false; - } - else if (char === "{") { - stack.push("}"); - } - else if (char === "[") { - stack.push("]"); - } - else if (char === "}" || char === "]") { - if (stack && stack[stack.length - 1] === char) { - stack.pop(); + console.warn(`field[${key}] already exists in this message chunk and value has unsupported type.`); + } + } + return merged; +} +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function _mergeLists(left, right) { + if (left === undefined && right === undefined) { + return undefined; + } + else if (left === undefined || right === undefined) { + return left || right; + } + else { + const merged = [...left]; + for (const item of right) { + if (typeof item === "object" && + "index" in item && + typeof item.index === "number") { + const toMerge = merged.findIndex((leftItem) => leftItem.index === item.index); + if (toMerge !== -1) { + merged[toMerge] = _mergeDicts(merged[toMerge], item); } else { - // Mismatched closing character; the input is malformed. - return null; + merged.push(item); } } + else if (typeof item === "object" && + "text" in item && + item.text === "") { + // No-op - skip empty text blocks + continue; + } + else { + merged.push(item); + } } - // Append the processed character to the new string. - new_s += char; + return merged; } - // If we're still inside a string at the end of processing, - // we need to close the string. - if (isInsideString) { - new_s += '"'; +} +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function _mergeObj(left, right) { + if (!left && !right) { + throw new Error("Cannot merge two undefined objects."); } - // Close any remaining open structures in the reverse order that they were opened. - for (let i = stack.length - 1; i >= 0; i -= 1) { - new_s += stack[i]; + if (!left || !right) { + return left || right; } - // Attempt to parse the modified string as JSON. - try { - return JSON.parse(new_s); + else if (typeof left !== typeof right) { + throw new Error(`Cannot merge objects of different types.\nLeft ${typeof left}\nRight ${typeof right}`); } - catch (error) { - // If we still can't parse the string as JSON, return null to indicate failure. - return null; + else if (typeof left === "string" && typeof right === "string") { + return (left + right); + } + else if (Array.isArray(left) && Array.isArray(right)) { + return _mergeLists(left, right); + } + else if (typeof left === "object" && typeof right === "object") { + return _mergeDicts(left, right); + } + else if (left === right) { + return left; + } + else { + throw new Error(`Can not merge objects of different types.\nLeft ${left}\nRight ${right}`); } } - -// EXTERNAL MODULE: ./node_modules/decamelize/index.js -var decamelize = __nccwpck_require__(8203); -// EXTERNAL MODULE: ./node_modules/camelcase/index.js -var camelcase = __nccwpck_require__(9890); -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/load/map_keys.js - - -function keyToJson(key, map) { - return map?.[key] || decamelize(key); +/** + * Represents a chunk of a message, which can be concatenated with other + * message chunks. It includes a method `_merge_kwargs_dict()` for merging + * additional keyword arguments from another `BaseMessageChunk` into this + * one. It also overrides the `__add__()` method to support concatenation + * of `BaseMessageChunk` instances. + */ +class BaseMessageChunk extends BaseMessage { } -function keyFromJson(key, map) { - return map?.[key] || camelCase(key); +function _isMessageFieldWithRole(x) { + return typeof x.role === "string"; } -function mapKeys(fields, mapper, map) { - const mapped = {}; - for (const key in fields) { - if (Object.hasOwn(fields, key)) { - mapped[mapper(key, map)] = fields[key]; - } - } - return mapped; +function isBaseMessage(messageLike) { + return typeof messageLike?._getType === "function"; +} +function base_isBaseMessageChunk(messageLike) { + return (isBaseMessage(messageLike) && + typeof messageLike.concat === "function"); } -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/load/serializable.js +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/tool.js -function shallowCopy(obj) { - return Array.isArray(obj) ? [...obj] : { ...obj }; +function isDirectToolOutput(x) { + return (x != null && + typeof x === "object" && + "lc_direct_tool_output" in x && + x.lc_direct_tool_output === true); } -function replaceSecrets(root, secretsMap) { - const result = shallowCopy(root); - for (const [path, secretId] of Object.entries(secretsMap)) { - const [last, ...partsReverse] = path.split(".").reverse(); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - let current = result; - for (const part of partsReverse.reverse()) { - if (current[part] === undefined) { - break; - } - current[part] = shallowCopy(current[part]); - current = current[part]; - } - if (current[last] !== undefined) { - current[last] = { - lc: 1, - type: "secret", - id: [secretId], - }; +/** + * Represents a tool message in a conversation. + */ +class tool_ToolMessage extends BaseMessage { + static lc_name() { + return "ToolMessage"; + } + get lc_aliases() { + // exclude snake case conversion to pascal case + return { tool_call_id: "tool_call_id" }; + } + constructor(fields, tool_call_id, name) { + if (typeof fields === "string") { + // eslint-disable-next-line no-param-reassign, @typescript-eslint/no-non-null-assertion + fields = { content: fields, name, tool_call_id: tool_call_id }; } + super(fields); + Object.defineProperty(this, "lc_direct_tool_output", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + /** + * Status of the tool invocation. + * @version 0.2.19 + */ + Object.defineProperty(this, "status", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "tool_call_id", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "metadata", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + /** + * Artifact of the Tool execution which is not meant to be sent to the model. + * + * Should only be specified if it is different from the message content, e.g. if only + * a subset of the full tool output is being passed as message content but the full + * output is needed in other parts of the code. + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + Object.defineProperty(this, "artifact", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.tool_call_id = fields.tool_call_id; + this.artifact = fields.artifact; + this.status = fields.status; + this.metadata = fields.metadata; + } + _getType() { + return "tool"; + } + static isInstance(message) { + return message._getType() === "tool"; + } + get _printableFields() { + return { + ...super._printableFields, + tool_call_id: this.tool_call_id, + artifact: this.artifact, + }; } - return result; } /** - * Get a unique name for the module, rather than parent class implementations. - * Should not be subclassed, subclass lc_name above instead. + * Represents a chunk of a tool message, which can be concatenated + * with other tool message chunks. */ -function get_lc_unique_name( -// eslint-disable-next-line @typescript-eslint/no-use-before-define -serializableClass) { - // "super" here would refer to the parent class of Serializable, - // when we want the parent class of the module actually calling this method. - const parentClass = Object.getPrototypeOf(serializableClass); - const lcNameIsSubclassed = typeof serializableClass.lc_name === "function" && - (typeof parentClass.lc_name !== "function" || - serializableClass.lc_name() !== parentClass.lc_name()); - if (lcNameIsSubclassed) { - return serializableClass.lc_name(); - } - else { - return serializableClass.name; +class tool_ToolMessageChunk extends BaseMessageChunk { + constructor(fields) { + super(fields); + Object.defineProperty(this, "tool_call_id", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + /** + * Status of the tool invocation. + * @version 0.2.19 + */ + Object.defineProperty(this, "status", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + /** + * Artifact of the Tool execution which is not meant to be sent to the model. + * + * Should only be specified if it is different from the message content, e.g. if only + * a subset of the full tool output is being passed as message content but the full + * output is needed in other parts of the code. + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + Object.defineProperty(this, "artifact", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.tool_call_id = fields.tool_call_id; + this.artifact = fields.artifact; + this.status = fields.status; } -} -class Serializable { - /** - * The name of the serializable. Override to provide an alias or - * to preserve the serialized module name in minified environments. - * - * Implemented as a static method to support loading logic. - */ static lc_name() { - return this.name; + return "ToolMessageChunk"; } - /** - * The final serialized identifier for the module. - */ - get lc_id() { - return [ - ...this.lc_namespace, - get_lc_unique_name(this.constructor), - ]; + _getType() { + return "tool"; } - /** - * A map of secrets, which will be omitted from serialization. - * Keys are paths to the secret in constructor args, e.g. "foo.bar.baz". - * Values are the secret ids, which will be used when deserializing. - */ - get lc_secrets() { - return undefined; + concat(chunk) { + return new tool_ToolMessageChunk({ + content: mergeContent(this.content, chunk.content), + additional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs), + response_metadata: _mergeDicts(this.response_metadata, chunk.response_metadata), + artifact: _mergeObj(this.artifact, chunk.artifact), + tool_call_id: this.tool_call_id, + id: this.id ?? chunk.id, + status: _mergeStatus(this.status, chunk.status), + }); } - /** - * A map of additional attributes to merge with constructor args. - * Keys are the attribute names, e.g. "foo". - * Values are the attribute values, which will be serialized. - * These attributes need to be accepted by the constructor as arguments. - */ - get lc_attributes() { - return undefined; + get _printableFields() { + return { + ...super._printableFields, + tool_call_id: this.tool_call_id, + artifact: this.artifact, + }; } - /** - * A map of aliases for constructor args. - * Keys are the attribute names, e.g. "foo". - * Values are the alias that will replace the key in serialization. - * This is used to eg. make argument names match Python. - */ +} +function defaultToolCallParser( +// eslint-disable-next-line @typescript-eslint/no-explicit-any +rawToolCalls) { + const toolCalls = []; + const invalidToolCalls = []; + for (const toolCall of rawToolCalls) { + if (!toolCall.function) { + continue; + } + else { + const functionName = toolCall.function.name; + try { + const functionArgs = JSON.parse(toolCall.function.arguments); + const parsed = { + name: functionName || "", + args: functionArgs || {}, + id: toolCall.id, + }; + toolCalls.push(parsed); + } + catch (error) { + invalidToolCalls.push({ + name: functionName, + args: toolCall.function.arguments, + id: toolCall.id, + error: "Malformed args.", + }); + } + } + } + return [toolCalls, invalidToolCalls]; +} +function tool_isToolMessage(x) { + return x._getType() === "tool"; +} +function isToolMessageChunk(x) { + return x._getType() === "tool"; +} + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/ai.js + + + +/** + * Represents an AI message in a conversation. + */ +class ai_AIMessage extends BaseMessage { get lc_aliases() { - return undefined; - } - /** - * A manual list of keys that should be serialized. - * If not overridden, all fields passed into the constructor will be serialized. - */ - get lc_serializable_keys() { - return undefined; + // exclude snake case conversion to pascal case + return { + ...super.lc_aliases, + tool_calls: "tool_calls", + invalid_tool_calls: "invalid_tool_calls", + }; } - constructor(kwargs, ..._args) { - Object.defineProperty(this, "lc_serializable", { + constructor(fields, + /** @deprecated */ + kwargs) { + let initParams; + if (typeof fields === "string") { + initParams = { + content: fields, + tool_calls: [], + invalid_tool_calls: [], + additional_kwargs: kwargs ?? {}, + }; + } + else { + initParams = fields; + const rawToolCalls = initParams.additional_kwargs?.tool_calls; + const toolCalls = initParams.tool_calls; + if (!(rawToolCalls == null) && + rawToolCalls.length > 0 && + (toolCalls === undefined || toolCalls.length === 0)) { + console.warn([ + "New LangChain packages are available that more efficiently handle", + "tool calling.\n\nPlease upgrade your packages to versions that set", + "message tool calls. e.g., `yarn add @langchain/anthropic`,", + "yarn add @langchain/openai`, etc.", + ].join(" ")); + } + try { + if (!(rawToolCalls == null) && toolCalls === undefined) { + const [toolCalls, invalidToolCalls] = defaultToolCallParser(rawToolCalls); + initParams.tool_calls = toolCalls ?? []; + initParams.invalid_tool_calls = invalidToolCalls ?? []; + } + else { + initParams.tool_calls = initParams.tool_calls ?? []; + initParams.invalid_tool_calls = initParams.invalid_tool_calls ?? []; + } + } + catch (e) { + // Do nothing if parsing fails + initParams.tool_calls = []; + initParams.invalid_tool_calls = []; + } + } + // Sadly, TypeScript only allows super() calls at root if the class has + // properties with initializers, so we have to check types twice. + super(initParams); + // These are typed as optional to avoid breaking changes and allow for casting + // from BaseMessage. + Object.defineProperty(this, "tool_calls", { enumerable: true, configurable: true, writable: true, - value: false + value: [] }); - Object.defineProperty(this, "lc_kwargs", { + Object.defineProperty(this, "invalid_tool_calls", { + enumerable: true, + configurable: true, + writable: true, + value: [] + }); + /** + * If provided, token usage information associated with the message. + */ + Object.defineProperty(this, "usage_metadata", { enumerable: true, configurable: true, writable: true, value: void 0 }); - if (this.lc_serializable_keys !== undefined) { - this.lc_kwargs = Object.fromEntries(Object.entries(kwargs || {}).filter(([key]) => this.lc_serializable_keys?.includes(key))); - } - else { - this.lc_kwargs = kwargs ?? {}; + if (typeof initParams !== "string") { + this.tool_calls = initParams.tool_calls ?? this.tool_calls; + this.invalid_tool_calls = + initParams.invalid_tool_calls ?? this.invalid_tool_calls; } + this.usage_metadata = initParams.usage_metadata; } - toJSON() { - if (!this.lc_serializable) { - return this.toJSONNotImplemented(); - } - if ( - // eslint-disable-next-line no-instanceof/no-instanceof - this.lc_kwargs instanceof Serializable || - typeof this.lc_kwargs !== "object" || - Array.isArray(this.lc_kwargs)) { - // We do not support serialization of classes with arg not a POJO - // I'm aware the check above isn't as strict as it could be - return this.toJSONNotImplemented(); + static lc_name() { + return "AIMessage"; + } + _getType() { + return "ai"; + } + get _printableFields() { + return { + ...super._printableFields, + tool_calls: this.tool_calls, + invalid_tool_calls: this.invalid_tool_calls, + usage_metadata: this.usage_metadata, + }; + } +} +function isAIMessage(x) { + return x._getType() === "ai"; +} +function isAIMessageChunk(x) { + return x._getType() === "ai"; +} +/** + * Represents a chunk of an AI message, which can be concatenated with + * other AI message chunks. + */ +class ai_AIMessageChunk extends BaseMessageChunk { + constructor(fields) { + let initParams; + if (typeof fields === "string") { + initParams = { + content: fields, + tool_calls: [], + invalid_tool_calls: [], + tool_call_chunks: [], + }; } - const aliases = {}; - const secrets = {}; - const kwargs = Object.keys(this.lc_kwargs).reduce((acc, key) => { - acc[key] = key in this ? this[key] : this.lc_kwargs[key]; - return acc; - }, {}); - // get secrets, attributes and aliases from all superclasses - for ( - // eslint-disable-next-line @typescript-eslint/no-this-alias - let current = Object.getPrototypeOf(this); current; current = Object.getPrototypeOf(current)) { - Object.assign(aliases, Reflect.get(current, "lc_aliases", this)); - Object.assign(secrets, Reflect.get(current, "lc_secrets", this)); - Object.assign(kwargs, Reflect.get(current, "lc_attributes", this)); + else if (fields.tool_call_chunks === undefined) { + initParams = { + ...fields, + tool_calls: fields.tool_calls ?? [], + invalid_tool_calls: [], + tool_call_chunks: [], + usage_metadata: fields.usage_metadata !== undefined + ? fields.usage_metadata + : undefined, + }; } - // include all secrets used, even if not in kwargs, - // will be replaced with sentinel value in replaceSecrets - Object.keys(secrets).forEach((keyPath) => { - // eslint-disable-next-line @typescript-eslint/no-this-alias, @typescript-eslint/no-explicit-any - let read = this; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - let write = kwargs; - const [last, ...partsReverse] = keyPath.split(".").reverse(); - for (const key of partsReverse.reverse()) { - if (!(key in read) || read[key] === undefined) - return; - if (!(key in write) || write[key] === undefined) { - if (typeof read[key] === "object" && read[key] != null) { - write[key] = {}; - } - else if (Array.isArray(read[key])) { - write[key] = []; + else { + const groupedToolCallChunk = fields.tool_call_chunks.reduce((acc, chunk) => { + // Assign a fallback ID if the chunk doesn't have one + // This can happen with tools that have empty schemas + const chunkId = chunk.id || `fallback-${chunk.index || 0}`; + acc[chunkId] = acc[chunkId] ?? []; + acc[chunkId].push(chunk); + return acc; + }, {}); + const toolCalls = []; + const invalidToolCalls = []; + for (const [id, chunks] of Object.entries(groupedToolCallChunk)) { + let parsedArgs = {}; + const name = chunks[0]?.name ?? ""; + const joinedArgs = chunks.map((c) => c.args || "").join(""); + const argsStr = joinedArgs.length ? joinedArgs : "{}"; + // Use the original ID from the first chunk if it exists, otherwise use the grouped ID + const originalId = chunks[0]?.id || id; + try { + parsedArgs = parsePartialJson(argsStr); + if (parsedArgs === null || + typeof parsedArgs !== "object" || + Array.isArray(parsedArgs)) { + throw new Error("Malformed tool call chunk args."); } + toolCalls.push({ + name, + args: parsedArgs, + id: originalId, + type: "tool_call", + }); + } + catch (e) { + invalidToolCalls.push({ + name, + args: argsStr, + id: originalId, + error: "Malformed args.", + type: "invalid_tool_call", + }); } - read = read[key]; - write = write[key]; - } - if (last in read && read[last] !== undefined) { - write[last] = write[last] || read[last]; } + initParams = { + ...fields, + tool_calls: toolCalls, + invalid_tool_calls: invalidToolCalls, + usage_metadata: fields.usage_metadata !== undefined + ? fields.usage_metadata + : undefined, + }; + } + // Sadly, TypeScript only allows super() calls at root if the class has + // properties with initializers, so we have to check types twice. + super(initParams); + // Must redeclare tool call fields since there is no multiple inheritance in JS. + // These are typed as optional to avoid breaking changes and allow for casting + // from BaseMessage. + Object.defineProperty(this, "tool_calls", { + enumerable: true, + configurable: true, + writable: true, + value: [] + }); + Object.defineProperty(this, "invalid_tool_calls", { + enumerable: true, + configurable: true, + writable: true, + value: [] + }); + Object.defineProperty(this, "tool_call_chunks", { + enumerable: true, + configurable: true, + writable: true, + value: [] + }); + /** + * If provided, token usage information associated with the message. + */ + Object.defineProperty(this, "usage_metadata", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 }); + this.tool_call_chunks = + initParams.tool_call_chunks ?? this.tool_call_chunks; + this.tool_calls = initParams.tool_calls ?? this.tool_calls; + this.invalid_tool_calls = + initParams.invalid_tool_calls ?? this.invalid_tool_calls; + this.usage_metadata = initParams.usage_metadata; + } + get lc_aliases() { + // exclude snake case conversion to pascal case return { - lc: 1, - type: "constructor", - id: this.lc_id, - kwargs: mapKeys(Object.keys(secrets).length ? replaceSecrets(kwargs, secrets) : kwargs, keyToJson, aliases), + ...super.lc_aliases, + tool_calls: "tool_calls", + invalid_tool_calls: "invalid_tool_calls", + tool_call_chunks: "tool_call_chunks", }; } - toJSONNotImplemented() { + static lc_name() { + return "AIMessageChunk"; + } + _getType() { + return "ai"; + } + get _printableFields() { return { - lc: 1, - type: "not_implemented", - id: this.lc_id, + ...super._printableFields, + tool_calls: this.tool_calls, + tool_call_chunks: this.tool_call_chunks, + invalid_tool_calls: this.invalid_tool_calls, + usage_metadata: this.usage_metadata, }; } -} - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/content_blocks.js -function isDataContentBlock(content_block) { - return (typeof content_block === "object" && - content_block !== null && - "type" in content_block && - typeof content_block.type === "string" && - "source_type" in content_block && - (content_block.source_type === "url" || - content_block.source_type === "base64" || - content_block.source_type === "text" || - content_block.source_type === "id")); -} -function isURLContentBlock(content_block) { - return (isDataContentBlock(content_block) && - content_block.source_type === "url" && - "url" in content_block && - typeof content_block.url === "string"); -} -function isBase64ContentBlock(content_block) { - return (isDataContentBlock(content_block) && - content_block.source_type === "base64" && - "data" in content_block && - typeof content_block.data === "string"); -} -function isPlainTextContentBlock(content_block) { - return (isDataContentBlock(content_block) && - content_block.source_type === "text" && - "text" in content_block && - typeof content_block.text === "string"); -} -function isIDContentBlock(content_block) { - return (isDataContentBlock(content_block) && - content_block.source_type === "id" && - "id" in content_block && - typeof content_block.id === "string"); -} -function convertToOpenAIImageBlock(content_block) { - if (isDataContentBlock(content_block)) { - if (content_block.source_type === "url") { - return { - type: "image_url", - image_url: { - url: content_block.url, - }, - }; - } - if (content_block.source_type === "base64") { - if (!content_block.mime_type) { - throw new Error("mime_type key is required for base64 data."); + concat(chunk) { + const combinedFields = { + content: mergeContent(this.content, chunk.content), + additional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs), + response_metadata: _mergeDicts(this.response_metadata, chunk.response_metadata), + tool_call_chunks: [], + id: this.id ?? chunk.id, + }; + if (this.tool_call_chunks !== undefined || + chunk.tool_call_chunks !== undefined) { + const rawToolCalls = _mergeLists(this.tool_call_chunks, chunk.tool_call_chunks); + if (rawToolCalls !== undefined && rawToolCalls.length > 0) { + combinedFields.tool_call_chunks = rawToolCalls; } - const mime_type = content_block.mime_type; - return { - type: "image_url", - image_url: { - url: `data:${mime_type};base64,${content_block.data}`, - }, + } + if (this.usage_metadata !== undefined || + chunk.usage_metadata !== undefined) { + const inputTokenDetails = { + ...((this.usage_metadata?.input_token_details?.audio !== undefined || + chunk.usage_metadata?.input_token_details?.audio !== undefined) && { + audio: (this.usage_metadata?.input_token_details?.audio ?? 0) + + (chunk.usage_metadata?.input_token_details?.audio ?? 0), + }), + ...((this.usage_metadata?.input_token_details?.cache_read !== + undefined || + chunk.usage_metadata?.input_token_details?.cache_read !== + undefined) && { + cache_read: (this.usage_metadata?.input_token_details?.cache_read ?? 0) + + (chunk.usage_metadata?.input_token_details?.cache_read ?? 0), + }), + ...((this.usage_metadata?.input_token_details?.cache_creation !== + undefined || + chunk.usage_metadata?.input_token_details?.cache_creation !== + undefined) && { + cache_creation: (this.usage_metadata?.input_token_details?.cache_creation ?? 0) + + (chunk.usage_metadata?.input_token_details?.cache_creation ?? 0), + }), + }; + const outputTokenDetails = { + ...((this.usage_metadata?.output_token_details?.audio !== undefined || + chunk.usage_metadata?.output_token_details?.audio !== undefined) && { + audio: (this.usage_metadata?.output_token_details?.audio ?? 0) + + (chunk.usage_metadata?.output_token_details?.audio ?? 0), + }), + ...((this.usage_metadata?.output_token_details?.reasoning !== + undefined || + chunk.usage_metadata?.output_token_details?.reasoning !== + undefined) && { + reasoning: (this.usage_metadata?.output_token_details?.reasoning ?? 0) + + (chunk.usage_metadata?.output_token_details?.reasoning ?? 0), + }), + }; + const left = this.usage_metadata ?? { + input_tokens: 0, + output_tokens: 0, + total_tokens: 0, + }; + const right = chunk.usage_metadata ?? { + input_tokens: 0, + output_tokens: 0, + total_tokens: 0, }; + const usage_metadata = { + input_tokens: left.input_tokens + right.input_tokens, + output_tokens: left.output_tokens + right.output_tokens, + total_tokens: left.total_tokens + right.total_tokens, + // Do not include `input_token_details` / `output_token_details` keys in combined fields + // unless their values are defined. + ...(Object.keys(inputTokenDetails).length > 0 && { + input_token_details: inputTokenDetails, + }), + ...(Object.keys(outputTokenDetails).length > 0 && { + output_token_details: outputTokenDetails, + }), + }; + combinedFields.usage_metadata = usage_metadata; } + return new ai_AIMessageChunk(combinedFields); } - throw new Error("Unsupported source type. Only 'url' and 'base64' are supported."); } + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/chat.js + /** - * Utility function for ChatModelProviders. Parses a mime type into a type, subtype, and parameters. - * - * @param mime_type - The mime type to parse. - * @returns An object containing the type, subtype, and parameters. + * Represents a chat message in a conversation. */ -function parseMimeType(mime_type) { - const parts = mime_type.split(";")[0].split("/"); - if (parts.length !== 2) { - throw new Error(`Invalid mime type: "${mime_type}" - does not match type/subtype format.`); +class chat_ChatMessage extends BaseMessage { + static lc_name() { + return "ChatMessage"; } - const type = parts[0].trim(); - const subtype = parts[1].trim(); - if (type === "" || subtype === "") { - throw new Error(`Invalid mime type: "${mime_type}" - type or subtype is empty.`); + static _chatMessageClass() { + return chat_ChatMessage; } - const parameters = {}; - for (const parameterKvp of mime_type.split(";").slice(1)) { - const parameterParts = parameterKvp.split("="); - if (parameterParts.length !== 2) { - throw new Error(`Invalid parameter syntax in mime type: "${mime_type}".`); - } - const key = parameterParts[0].trim(); - const value = parameterParts[1].trim(); - if (key === "") { - throw new Error(`Invalid parameter syntax in mime type: "${mime_type}".`); + constructor(fields, role) { + if (typeof fields === "string") { + // eslint-disable-next-line no-param-reassign, @typescript-eslint/no-non-null-assertion + fields = { content: fields, role: role }; } - parameters[key] = value; + super(fields); + Object.defineProperty(this, "role", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.role = fields.role; + } + _getType() { + return "generic"; + } + static isInstance(message) { + return message._getType() === "generic"; + } + get _printableFields() { + return { + ...super._printableFields, + role: this.role, + }; } - return { - type, - subtype, - parameters, - }; } /** - * Utility function for ChatModelProviders. Parses a base64 data URL into a typed array or string. - * - * @param dataUrl - The base64 data URL to parse. - * @param asTypedArray - Whether to return the data as a typed array. - * @returns The parsed data and mime type, or undefined if the data URL is invalid. + * Represents a chunk of a chat message, which can be concatenated with + * other chat message chunks. */ -function parseBase64DataUrl({ dataUrl: data_url, asTypedArray = false, }) { - const formatMatch = data_url.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/); - let mime_type; - if (formatMatch) { - mime_type = formatMatch[1].toLowerCase(); - const data = asTypedArray - ? Uint8Array.from(atob(formatMatch[2]), (c) => c.charCodeAt(0)) - : formatMatch[2]; +class chat_ChatMessageChunk extends BaseMessageChunk { + static lc_name() { + return "ChatMessageChunk"; + } + constructor(fields, role) { + if (typeof fields === "string") { + // eslint-disable-next-line no-param-reassign, @typescript-eslint/no-non-null-assertion + fields = { content: fields, role: role }; + } + super(fields); + Object.defineProperty(this, "role", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.role = fields.role; + } + _getType() { + return "generic"; + } + concat(chunk) { + return new chat_ChatMessageChunk({ + content: mergeContent(this.content, chunk.content), + additional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs), + response_metadata: _mergeDicts(this.response_metadata, chunk.response_metadata), + role: this.role, + id: this.id ?? chunk.id, + }); + } + get _printableFields() { return { - mime_type, - data, + ...super._printableFields, + role: this.role, }; } - return undefined; } +function isChatMessage(x) { + return x._getType() === "generic"; +} +function isChatMessageChunk(x) { + return x._getType() === "generic"; +} + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/function.js + /** - * Convert from a standard data content block to a provider's proprietary data content block format. - * - * Don't override this method. Instead, override the more specific conversion methods and use this - * method unmodified. - * - * @param block - The standard data content block to convert. - * @returns The provider data content block. - * @throws An error if the standard data content block type is not supported. + * Represents a function message in a conversation. */ -function convertToProviderContentBlock(block, converter) { - if (block.type === "text") { - if (!converter.fromStandardTextBlock) { - throw new Error(`Converter for ${converter.providerName} does not implement \`fromStandardTextBlock\` method.`); - } - return converter.fromStandardTextBlock(block); +class function_FunctionMessage extends BaseMessage { + static lc_name() { + return "FunctionMessage"; } - if (block.type === "image") { - if (!converter.fromStandardImageBlock) { - throw new Error(`Converter for ${converter.providerName} does not implement \`fromStandardImageBlock\` method.`); + constructor(fields, + /** @deprecated */ + name) { + if (typeof fields === "string") { + // eslint-disable-next-line no-param-reassign, @typescript-eslint/no-non-null-assertion + fields = { content: fields, name: name }; } - return converter.fromStandardImageBlock(block); + super(fields); } - if (block.type === "audio") { - if (!converter.fromStandardAudioBlock) { - throw new Error(`Converter for ${converter.providerName} does not implement \`fromStandardAudioBlock\` method.`); - } - return converter.fromStandardAudioBlock(block); + _getType() { + return "function"; } - if (block.type === "file") { - if (!converter.fromStandardFileBlock) { - throw new Error(`Converter for ${converter.providerName} does not implement \`fromStandardFileBlock\` method.`); - } - return converter.fromStandardFileBlock(block); +} +/** + * Represents a chunk of a function message, which can be concatenated + * with other function message chunks. + */ +class function_FunctionMessageChunk extends BaseMessageChunk { + static lc_name() { + return "FunctionMessageChunk"; + } + _getType() { + return "function"; + } + concat(chunk) { + return new function_FunctionMessageChunk({ + content: mergeContent(this.content, chunk.content), + additional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs), + response_metadata: _mergeDicts(this.response_metadata, chunk.response_metadata), + name: this.name ?? "", + id: this.id ?? chunk.id, + }); } - throw new Error(`Unable to convert content block type '${block.type}' to provider-specific format: not recognized.`); +} +function isFunctionMessage(x) { + return x._getType() === "function"; +} +function isFunctionMessageChunk(x) { + return x._getType() === "function"; } -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/base.js - +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/human.js -function mergeContent(firstContent, secondContent) { - // If first content is a string - if (typeof firstContent === "string") { - if (firstContent === "") { - return secondContent; - } - if (typeof secondContent === "string") { - return firstContent + secondContent; - } - else if (Array.isArray(secondContent) && - secondContent.some((c) => isDataContentBlock(c))) { - return [ - { - type: "text", - source_type: "text", - text: firstContent, - }, - ...secondContent, - ]; - } - else { - return [{ type: "text", text: firstContent }, ...secondContent]; - } - // If both are arrays +/** + * Represents a human message in a conversation. + */ +class human_HumanMessage extends BaseMessage { + static lc_name() { + return "HumanMessage"; } - else if (Array.isArray(secondContent)) { - return (_mergeLists(firstContent, secondContent) ?? [ - ...firstContent, - ...secondContent, - ]); + _getType() { + return "human"; } - else { - if (secondContent === "") { - return firstContent; - } - else if (Array.isArray(firstContent) && - firstContent.some((c) => isDataContentBlock(c))) { - return [ - ...firstContent, - { - type: "file", - source_type: "text", - text: secondContent, - }, - ]; - } - else { - return [...firstContent, { type: "text", text: secondContent }]; - } + constructor(fields, + /** @deprecated */ + kwargs) { + super(fields, kwargs); } } /** - * 'Merge' two statuses. If either value passed is 'error', it will return 'error'. Else - * it will return 'success'. - * - * @param {"success" | "error" | undefined} left The existing value to 'merge' with the new value. - * @param {"success" | "error" | undefined} right The new value to 'merge' with the existing value - * @returns {"success" | "error"} The 'merged' value. + * Represents a chunk of a human message, which can be concatenated with + * other human message chunks. */ -function _mergeStatus(left, right) { - if (left === "error" || right === "error") { - return "error"; +class human_HumanMessageChunk extends BaseMessageChunk { + static lc_name() { + return "HumanMessageChunk"; } - return "success"; -} -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function stringifyWithDepthLimit(obj, depthLimit) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - function helper(obj, currentDepth) { - if (typeof obj !== "object" || obj === null || obj === undefined) { - return obj; - } - if (currentDepth >= depthLimit) { - if (Array.isArray(obj)) { - return "[Array]"; - } - return "[Object]"; - } - if (Array.isArray(obj)) { - return obj.map((item) => helper(item, currentDepth + 1)); - } - const result = {}; - for (const key of Object.keys(obj)) { - result[key] = helper(obj[key], currentDepth + 1); - } - return result; + _getType() { + return "human"; } - return JSON.stringify(helper(obj, 0), null, 2); + constructor(fields, + /** @deprecated */ + kwargs) { + super(fields, kwargs); + } + concat(chunk) { + return new human_HumanMessageChunk({ + content: mergeContent(this.content, chunk.content), + additional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs), + response_metadata: _mergeDicts(this.response_metadata, chunk.response_metadata), + id: this.id ?? chunk.id, + }); + } +} +function isHumanMessage(x) { + return x.getType() === "human"; +} +function isHumanMessageChunk(x) { + return x.getType() === "human"; } + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/system.js + /** - * Base class for all types of messages in a conversation. It includes - * properties like `content`, `name`, and `additional_kwargs`. It also - * includes methods like `toDict()` and `_getType()`. + * Represents a system message in a conversation. */ -class BaseMessage extends Serializable { - get lc_aliases() { - // exclude snake case conversion to pascal case - return { - additional_kwargs: "additional_kwargs", - response_metadata: "response_metadata", - }; +class system_SystemMessage extends BaseMessage { + static lc_name() { + return "SystemMessage"; } - /** - * Get text content of the message. - */ - get text() { - if (typeof this.content === "string") { - return this.content; - } - if (!Array.isArray(this.content)) - return ""; - return this.content - .map((c) => { - if (typeof c === "string") - return c; - if (c.type === "text") - return c.text; - return ""; - }) - .join(""); + _getType() { + return "system"; } - /** The type of the message. */ - getType() { - return this._getType(); + constructor(fields, + /** @deprecated */ + kwargs) { + super(fields, kwargs); + } +} +/** + * Represents a chunk of a system message, which can be concatenated with + * other system message chunks. + */ +class system_SystemMessageChunk extends BaseMessageChunk { + static lc_name() { + return "SystemMessageChunk"; + } + _getType() { + return "system"; } constructor(fields, /** @deprecated */ kwargs) { - if (typeof fields === "string") { - // eslint-disable-next-line no-param-reassign - fields = { - content: fields, - additional_kwargs: kwargs, - response_metadata: {}, - }; - } - // Make sure the default value for additional_kwargs is passed into super() for serialization - if (!fields.additional_kwargs) { - // eslint-disable-next-line no-param-reassign - fields.additional_kwargs = {}; - } - if (!fields.response_metadata) { - // eslint-disable-next-line no-param-reassign - fields.response_metadata = {}; - } - super(fields); - Object.defineProperty(this, "lc_namespace", { - enumerable: true, - configurable: true, - writable: true, - value: ["langchain_core", "messages"] - }); - Object.defineProperty(this, "lc_serializable", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - /** The content of the message. */ - Object.defineProperty(this, "content", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - /** The name of the message sender in a multi-user chat. */ - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - /** Additional keyword arguments */ - Object.defineProperty(this, "additional_kwargs", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - /** Response metadata. For example: response headers, logprobs, token counts. */ - Object.defineProperty(this, "response_metadata", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 + super(fields, kwargs); + } + concat(chunk) { + return new system_SystemMessageChunk({ + content: mergeContent(this.content, chunk.content), + additional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs), + response_metadata: _mergeDicts(this.response_metadata, chunk.response_metadata), + id: this.id ?? chunk.id, }); - /** - * An optional unique identifier for the message. This should ideally be - * provided by the provider/model which created the message. - */ - Object.defineProperty(this, "id", { + } +} +function isSystemMessage(x) { + return x._getType() === "system"; +} +function isSystemMessageChunk(x) { + return x._getType() === "system"; +} + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/errors/index.js +/* eslint-disable @typescript-eslint/no-explicit-any */ +/* eslint-disable no-param-reassign */ +function addLangChainErrorFields(error, lc_error_code) { + error.lc_error_code = lc_error_code; + error.message = `${error.message}\n\nTroubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${lc_error_code}/\n`; + return error; +} + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/tools/utils.js +function _isToolCall(toolCall) { + return !!(toolCall && + typeof toolCall === "object" && + "type" in toolCall && + toolCall.type === "tool_call"); +} +function _configHasToolCallId(config) { + return !!(config && + typeof config === "object" && + "toolCall" in config && + config.toolCall != null && + typeof config.toolCall === "object" && + "id" in config.toolCall && + typeof config.toolCall.id === "string"); +} +/** + * Custom error class used to handle exceptions related to tool input parsing. + * It extends the built-in `Error` class and adds an optional `output` + * property that can hold the output that caused the exception. + */ +class ToolInputParsingException extends Error { + constructor(message, output) { + super(message); + Object.defineProperty(this, "output", { enumerable: true, configurable: true, writable: true, value: void 0 }); - this.name = fields.name; - this.content = fields.content; - this.additional_kwargs = fields.additional_kwargs; - this.response_metadata = fields.response_metadata; - this.id = fields.id; + this.output = output; } - toDict() { +} + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/utils.js + + + + + + + + + +function _coerceToolCall(toolCall) { + if (_isToolCall(toolCall)) { + return toolCall; + } + else if (typeof toolCall.id === "string" && + toolCall.type === "function" && + typeof toolCall.function === "object" && + toolCall.function !== null && + "arguments" in toolCall.function && + typeof toolCall.function.arguments === "string" && + "name" in toolCall.function && + typeof toolCall.function.name === "string") { + // Handle OpenAI tool call format return { - type: this._getType(), - data: this.toJSON() - .kwargs, + id: toolCall.id, + args: JSON.parse(toolCall.function.arguments), + name: toolCall.function.name, + type: "tool_call", }; } - static lc_name() { - return "BaseMessage"; + else { + // TODO: Throw an error? + return toolCall; } - // Can't be protected for silly reasons - get _printableFields() { - return { - id: this.id, - content: this.content, - name: this.name, - additional_kwargs: this.additional_kwargs, - response_metadata: this.response_metadata, - }; +} +function isSerializedConstructor(x) { + return (typeof x === "object" && + x != null && + x.lc === 1 && + Array.isArray(x.id) && + x.kwargs != null && + typeof x.kwargs === "object"); +} +function _constructMessageFromParams(params) { + let type; + let rest; + // Support serialized messages + if (isSerializedConstructor(params)) { + const className = params.id.at(-1); + if (className === "HumanMessage" || className === "HumanMessageChunk") { + type = "user"; + } + else if (className === "AIMessage" || className === "AIMessageChunk") { + type = "assistant"; + } + else if (className === "SystemMessage" || + className === "SystemMessageChunk") { + type = "system"; + } + else if (className === "FunctionMessage" || + className === "FunctionMessageChunk") { + type = "function"; + } + else if (className === "ToolMessage" || + className === "ToolMessageChunk") { + type = "tool"; + } + else { + type = "unknown"; + } + rest = params.kwargs; + } + else { + const { type: extractedType, ...otherParams } = params; + type = extractedType; + rest = otherParams; + } + if (type === "human" || type === "user") { + return new human_HumanMessage(rest); + } + else if (type === "ai" || type === "assistant") { + const { tool_calls: rawToolCalls, ...other } = rest; + if (!Array.isArray(rawToolCalls)) { + return new ai_AIMessage(rest); + } + const tool_calls = rawToolCalls.map(_coerceToolCall); + return new ai_AIMessage({ ...other, tool_calls }); + } + else if (type === "system") { + return new system_SystemMessage(rest); + } + else if (type === "developer") { + return new system_SystemMessage({ + ...rest, + additional_kwargs: { + ...rest.additional_kwargs, + __openai_role__: "developer", + }, + }); + } + else if (type === "tool" && "tool_call_id" in rest) { + return new tool_ToolMessage({ + ...rest, + content: rest.content, + tool_call_id: rest.tool_call_id, + name: rest.name, + }); + } + else { + const error = addLangChainErrorFields(new Error(`Unable to coerce message from array: only human, AI, system, developer, or tool message coercion is currently supported.\n\nReceived: ${JSON.stringify(params, null, 2)}`), "MESSAGE_COERCION_FAILURE"); + throw error; + } +} +function coerceMessageLikeToMessage(messageLike) { + if (typeof messageLike === "string") { + return new human_HumanMessage(messageLike); } - // this private method is used to update the ID for the runtime - // value as well as in lc_kwargs for serialisation - _updateId(value) { - this.id = value; - // lc_attributes wouldn't work here, because jest compares the - // whole object - this.lc_kwargs.id = value; + else if (isBaseMessage(messageLike)) { + return messageLike; } - get [Symbol.toStringTag]() { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - return this.constructor.lc_name(); + if (Array.isArray(messageLike)) { + const [type, content] = messageLike; + return _constructMessageFromParams({ type, content }); } - // Override the default behavior of console.log - [Symbol.for("nodejs.util.inspect.custom")](depth) { - if (depth === null) { - return this; - } - const printable = stringifyWithDepthLimit(this._printableFields, Math.max(4, depth)); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - return `${this.constructor.lc_name()} ${printable}`; + else if (_isMessageFieldWithRole(messageLike)) { + const { role: type, ...rest } = messageLike; + return _constructMessageFromParams({ ...rest, type }); + } + else { + return _constructMessageFromParams(messageLike); } } -function isOpenAIToolCallArray(value) { - return (Array.isArray(value) && - value.every((v) => typeof v.index === "number")); -} -function _mergeDicts( -// eslint-disable-next-line @typescript-eslint/no-explicit-any -left, -// eslint-disable-next-line @typescript-eslint/no-explicit-any -right -// eslint-disable-next-line @typescript-eslint/no-explicit-any -) { - const merged = { ...left }; - for (const [key, value] of Object.entries(right)) { - if (merged[key] == null) { - merged[key] = value; - } - else if (value == null) { - continue; +/** + * This function is used by memory classes to get a string representation + * of the chat message history, based on the message content and role. + */ +function getBufferString(messages, humanPrefix = "Human", aiPrefix = "AI") { + const string_messages = []; + for (const m of messages) { + let role; + if (m._getType() === "human") { + role = humanPrefix; } - else if (typeof merged[key] !== typeof value || - Array.isArray(merged[key]) !== Array.isArray(value)) { - throw new Error(`field[${key}] already exists in the message chunk, but with a different type.`); + else if (m._getType() === "ai") { + role = aiPrefix; } - else if (typeof merged[key] === "string") { - if (key === "type") { - // Do not merge 'type' fields - continue; - } - merged[key] += value; + else if (m._getType() === "system") { + role = "System"; } - else if (typeof merged[key] === "object" && !Array.isArray(merged[key])) { - merged[key] = _mergeDicts(merged[key], value); + else if (m._getType() === "function") { + role = "Function"; } - else if (Array.isArray(merged[key])) { - merged[key] = _mergeLists(merged[key], value); + else if (m._getType() === "tool") { + role = "Tool"; } - else if (merged[key] === value) { - continue; + else if (m._getType() === "generic") { + role = m.role; } else { - console.warn(`field[${key}] already exists in this message chunk and value has unsupported type.`); + throw new Error(`Got unsupported message type: ${m._getType()}`); } + const nameStr = m.name ? `${m.name}, ` : ""; + const readableContent = typeof m.content === "string" + ? m.content + : JSON.stringify(m.content, null, 2); + string_messages.push(`${role}: ${nameStr}${readableContent}`); } - return merged; + return string_messages.join("\n"); } -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function _mergeLists(left, right) { - if (left === undefined && right === undefined) { - return undefined; - } - else if (left === undefined || right === undefined) { - return left || right; +/** + * Maps messages from an older format (V1) to the current `StoredMessage` + * format. If the message is already in the `StoredMessage` format, it is + * returned as is. Otherwise, it transforms the V1 message into a + * `StoredMessage`. This function is important for maintaining + * compatibility with older message formats. + */ +function mapV1MessageToStoredMessage(message) { + // TODO: Remove this mapper when we deprecate the old message format. + if (message.data !== undefined) { + return message; } else { - const merged = [...left]; - for (const item of right) { - if (typeof item === "object" && - "index" in item && - typeof item.index === "number") { - const toMerge = merged.findIndex((leftItem) => leftItem.index === item.index); - if (toMerge !== -1) { - merged[toMerge] = _mergeDicts(merged[toMerge], item); - } - else { - merged.push(item); - } + const v1Message = message; + return { + type: v1Message.type, + data: { + content: v1Message.text, + role: v1Message.role, + name: undefined, + tool_call_id: undefined, + }, + }; + } +} +function utils_mapStoredMessageToChatMessage(message) { + const storedMessage = mapV1MessageToStoredMessage(message); + switch (storedMessage.type) { + case "human": + return new HumanMessage(storedMessage.data); + case "ai": + return new AIMessage(storedMessage.data); + case "system": + return new SystemMessage(storedMessage.data); + case "function": + if (storedMessage.data.name === undefined) { + throw new Error("Name must be defined for function messages"); } - else if (typeof item === "object" && - "text" in item && - item.text === "") { - // No-op - skip empty text blocks - continue; + return new FunctionMessage(storedMessage.data); + case "tool": + if (storedMessage.data.tool_call_id === undefined) { + throw new Error("Tool call ID must be defined for tool messages"); } - else { - merged.push(item); + return new ToolMessage(storedMessage.data); + case "generic": { + if (storedMessage.data.role === undefined) { + throw new Error("Role must be defined for chat messages"); } + return new ChatMessage(storedMessage.data); } - return merged; + default: + throw new Error(`Got unexpected type: ${storedMessage.type}`); } } -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function _mergeObj(left, right) { - if (!left && !right) { - throw new Error("Cannot merge two undefined objects."); - } - if (!left || !right) { - return left || right; - } - else if (typeof left !== typeof right) { - throw new Error(`Cannot merge objects of different types.\nLeft ${typeof left}\nRight ${typeof right}`); +/** + * Transforms an array of `StoredMessage` instances into an array of + * `BaseMessage` instances. It uses the `mapV1MessageToStoredMessage` + * function to ensure all messages are in the `StoredMessage` format, then + * creates new instances of the appropriate `BaseMessage` subclass based + * on the type of each message. This function is used to prepare stored + * messages for use in a chat context. + */ +function mapStoredMessagesToChatMessages(messages) { + return messages.map(utils_mapStoredMessageToChatMessage); +} +/** + * Transforms an array of `BaseMessage` instances into an array of + * `StoredMessage` instances. It does this by calling the `toDict` method + * on each `BaseMessage`, which returns a `StoredMessage`. This function + * is used to prepare chat messages for storage. + */ +function mapChatMessagesToStoredMessages(messages) { + return messages.map((message) => message.toDict()); +} +function utils_convertToChunk(message) { + const type = message._getType(); + if (type === "human") { + // eslint-disable-next-line @typescript-eslint/no-use-before-define + return new human_HumanMessageChunk({ ...message }); } - else if (typeof left === "string" && typeof right === "string") { - return (left + right); + else if (type === "ai") { + let aiChunkFields = { + ...message, + }; + if ("tool_calls" in aiChunkFields) { + aiChunkFields = { + ...aiChunkFields, + tool_call_chunks: aiChunkFields.tool_calls?.map((tc) => ({ + ...tc, + type: "tool_call_chunk", + index: undefined, + args: JSON.stringify(tc.args), + })), + }; + } + // eslint-disable-next-line @typescript-eslint/no-use-before-define + return new ai_AIMessageChunk({ ...aiChunkFields }); } - else if (Array.isArray(left) && Array.isArray(right)) { - return _mergeLists(left, right); + else if (type === "system") { + // eslint-disable-next-line @typescript-eslint/no-use-before-define + return new system_SystemMessageChunk({ ...message }); } - else if (typeof left === "object" && typeof right === "object") { - return _mergeDicts(left, right); + else if (type === "function") { + // eslint-disable-next-line @typescript-eslint/no-use-before-define + return new function_FunctionMessageChunk({ ...message }); + // eslint-disable-next-line @typescript-eslint/no-use-before-define } - else if (left === right) { - return left; + else if (chat_ChatMessage.isInstance(message)) { + // eslint-disable-next-line @typescript-eslint/no-use-before-define + return new chat_ChatMessageChunk({ ...message }); } else { - throw new Error(`Can not merge objects of different types.\nLeft ${left}\nRight ${right}`); + throw new Error("Unknown message type."); } } -/** - * Represents a chunk of a message, which can be concatenated with other - * message chunks. It includes a method `_merge_kwargs_dict()` for merging - * additional keyword arguments from another `BaseMessageChunk` into this - * one. It also overrides the `__add__()` method to support concatenation - * of `BaseMessageChunk` instances. - */ -class BaseMessageChunk extends BaseMessage { -} -function _isMessageFieldWithRole(x) { - return typeof x.role === "string"; -} -function isBaseMessage(messageLike) { - return typeof messageLike?._getType === "function"; -} -function base_isBaseMessageChunk(messageLike) { - return (isBaseMessage(messageLike) && - typeof messageLike.concat === "function"); -} - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/tool.js -function isDirectToolOutput(x) { - return (x != null && - typeof x === "object" && - "lc_direct_tool_output" in x && - x.lc_direct_tool_output === true); -} -/** - * Represents a tool message in a conversation. - */ -class tool_ToolMessage extends BaseMessage { - static lc_name() { - return "ToolMessage"; - } - get lc_aliases() { - // exclude snake case conversion to pascal case - return { tool_call_id: "tool_call_id" }; +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v3/helpers/util.js +var util_util; +(function (util) { + util.assertEqual = (_) => { }; + function assertIs(_arg) { } + util.assertIs = assertIs; + function assertNever(_x) { + throw new Error(); } - constructor(fields, tool_call_id, name) { - if (typeof fields === "string") { - // eslint-disable-next-line no-param-reassign, @typescript-eslint/no-non-null-assertion - fields = { content: fields, name, tool_call_id: tool_call_id }; + util.assertNever = assertNever; + util.arrayToEnum = (items) => { + const obj = {}; + for (const item of items) { + obj[item] = item; } - super(fields); - Object.defineProperty(this, "lc_direct_tool_output", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - /** - * Status of the tool invocation. - * @version 0.2.19 - */ - Object.defineProperty(this, "status", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "tool_call_id", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - /** - * Artifact of the Tool execution which is not meant to be sent to the model. - * - * Should only be specified if it is different from the message content, e.g. if only - * a subset of the full tool output is being passed as message content but the full - * output is needed in other parts of the code. - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - Object.defineProperty(this, "artifact", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 + return obj; + }; + util.getValidEnumValues = (obj) => { + const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number"); + const filtered = {}; + for (const k of validKeys) { + filtered[k] = obj[k]; + } + return util.objectValues(filtered); + }; + util.objectValues = (obj) => { + return util.objectKeys(obj).map(function (e) { + return obj[e]; }); - this.tool_call_id = fields.tool_call_id; - this.artifact = fields.artifact; - this.status = fields.status; + }; + util.objectKeys = typeof Object.keys === "function" // eslint-disable-line ban/ban + ? (obj) => Object.keys(obj) // eslint-disable-line ban/ban + : (object) => { + const keys = []; + for (const key in object) { + if (Object.prototype.hasOwnProperty.call(object, key)) { + keys.push(key); + } + } + return keys; + }; + util.find = (arr, checker) => { + for (const item of arr) { + if (checker(item)) + return item; + } + return undefined; + }; + util.isInteger = typeof Number.isInteger === "function" + ? (val) => Number.isInteger(val) // eslint-disable-line ban/ban + : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val; + function joinValues(array, separator = " | ") { + return array.map((val) => (typeof val === "string" ? `'${val}'` : val)).join(separator); } - _getType() { - return "tool"; + util.joinValues = joinValues; + util.jsonStringifyReplacer = (_, value) => { + if (typeof value === "bigint") { + return value.toString(); + } + return value; + }; +})(util_util || (util_util = {})); +var objectUtil; +(function (objectUtil) { + objectUtil.mergeShapes = (first, second) => { + return { + ...first, + ...second, // second overwrites first + }; + }; +})(objectUtil || (objectUtil = {})); +const ZodParsedType = util_util.arrayToEnum([ + "string", + "nan", + "number", + "integer", + "float", + "boolean", + "date", + "bigint", + "symbol", + "function", + "undefined", + "null", + "array", + "object", + "unknown", + "promise", + "void", + "never", + "map", + "set", +]); +const getParsedType = (data) => { + const t = typeof data; + switch (t) { + case "undefined": + return ZodParsedType.undefined; + case "string": + return ZodParsedType.string; + case "number": + return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number; + case "boolean": + return ZodParsedType.boolean; + case "function": + return ZodParsedType.function; + case "bigint": + return ZodParsedType.bigint; + case "symbol": + return ZodParsedType.symbol; + case "object": + if (Array.isArray(data)) { + return ZodParsedType.array; + } + if (data === null) { + return ZodParsedType.null; + } + if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { + return ZodParsedType.promise; + } + if (typeof Map !== "undefined" && data instanceof Map) { + return ZodParsedType.map; + } + if (typeof Set !== "undefined" && data instanceof Set) { + return ZodParsedType.set; + } + if (typeof Date !== "undefined" && data instanceof Date) { + return ZodParsedType.date; + } + return ZodParsedType.object; + default: + return ZodParsedType.unknown; } - static isInstance(message) { - return message._getType() === "tool"; +}; + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v3/ZodError.js + +const ZodIssueCode = util_util.arrayToEnum([ + "invalid_type", + "invalid_literal", + "custom", + "invalid_union", + "invalid_union_discriminator", + "invalid_enum_value", + "unrecognized_keys", + "invalid_arguments", + "invalid_return_type", + "invalid_date", + "invalid_string", + "too_small", + "too_big", + "invalid_intersection_types", + "not_multiple_of", + "not_finite", +]); +const quotelessJson = (obj) => { + const json = JSON.stringify(obj, null, 2); + return json.replace(/"([^"]+)":/g, "$1:"); +}; +class ZodError extends Error { + get errors() { + return this.issues; } - get _printableFields() { - return { - ...super._printableFields, - tool_call_id: this.tool_call_id, - artifact: this.artifact, + constructor(issues) { + super(); + this.issues = []; + this.addIssue = (sub) => { + this.issues = [...this.issues, sub]; + }; + this.addIssues = (subs = []) => { + this.issues = [...this.issues, ...subs]; + }; + const actualProto = new.target.prototype; + if (Object.setPrototypeOf) { + // eslint-disable-next-line ban/ban + Object.setPrototypeOf(this, actualProto); + } + else { + this.__proto__ = actualProto; + } + this.name = "ZodError"; + this.issues = issues; + } + format(_mapper) { + const mapper = _mapper || + function (issue) { + return issue.message; + }; + const fieldErrors = { _errors: [] }; + const processError = (error) => { + for (const issue of error.issues) { + if (issue.code === "invalid_union") { + issue.unionErrors.map(processError); + } + else if (issue.code === "invalid_return_type") { + processError(issue.returnTypeError); + } + else if (issue.code === "invalid_arguments") { + processError(issue.argumentsError); + } + else if (issue.path.length === 0) { + fieldErrors._errors.push(mapper(issue)); + } + else { + let curr = fieldErrors; + let i = 0; + while (i < issue.path.length) { + const el = issue.path[i]; + const terminal = i === issue.path.length - 1; + if (!terminal) { + curr[el] = curr[el] || { _errors: [] }; + // if (typeof el === "string") { + // curr[el] = curr[el] || { _errors: [] }; + // } else if (typeof el === "number") { + // const errorArray: any = []; + // errorArray._errors = []; + // curr[el] = curr[el] || errorArray; + // } + } + else { + curr[el] = curr[el] || { _errors: [] }; + curr[el]._errors.push(mapper(issue)); + } + curr = curr[el]; + i++; + } + } + } }; + processError(this); + return fieldErrors; } -} -/** - * Represents a chunk of a tool message, which can be concatenated - * with other tool message chunks. - */ -class tool_ToolMessageChunk extends BaseMessageChunk { - constructor(fields) { - super(fields); - Object.defineProperty(this, "tool_call_id", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - /** - * Status of the tool invocation. - * @version 0.2.19 - */ - Object.defineProperty(this, "status", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - /** - * Artifact of the Tool execution which is not meant to be sent to the model. - * - * Should only be specified if it is different from the message content, e.g. if only - * a subset of the full tool output is being passed as message content but the full - * output is needed in other parts of the code. - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - Object.defineProperty(this, "artifact", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.tool_call_id = fields.tool_call_id; - this.artifact = fields.artifact; - this.status = fields.status; - } - static lc_name() { - return "ToolMessageChunk"; + static assert(value) { + if (!(value instanceof ZodError)) { + throw new Error(`Not a ZodError: ${value}`); + } } - _getType() { - return "tool"; + toString() { + return this.message; } - concat(chunk) { - return new tool_ToolMessageChunk({ - content: mergeContent(this.content, chunk.content), - additional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs), - response_metadata: _mergeDicts(this.response_metadata, chunk.response_metadata), - artifact: _mergeObj(this.artifact, chunk.artifact), - tool_call_id: this.tool_call_id, - id: this.id ?? chunk.id, - status: _mergeStatus(this.status, chunk.status), - }); + get message() { + return JSON.stringify(this.issues, util_util.jsonStringifyReplacer, 2); } - get _printableFields() { - return { - ...super._printableFields, - tool_call_id: this.tool_call_id, - artifact: this.artifact, - }; + get isEmpty() { + return this.issues.length === 0; } -} -function defaultToolCallParser( -// eslint-disable-next-line @typescript-eslint/no-explicit-any -rawToolCalls) { - const toolCalls = []; - const invalidToolCalls = []; - for (const toolCall of rawToolCalls) { - if (!toolCall.function) { - continue; - } - else { - const functionName = toolCall.function.name; - try { - const functionArgs = JSON.parse(toolCall.function.arguments); - const parsed = { - name: functionName || "", - args: functionArgs || {}, - id: toolCall.id, - }; - toolCalls.push(parsed); + flatten(mapper = (issue) => issue.message) { + const fieldErrors = {}; + const formErrors = []; + for (const sub of this.issues) { + if (sub.path.length > 0) { + fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; + fieldErrors[sub.path[0]].push(mapper(sub)); } - catch (error) { - invalidToolCalls.push({ - name: functionName, - args: toolCall.function.arguments, - id: toolCall.id, - error: "Malformed args.", - }); + else { + formErrors.push(mapper(sub)); } } + return { formErrors, fieldErrors }; + } + get formErrors() { + return this.flatten(); } - return [toolCalls, invalidToolCalls]; -} -function tool_isToolMessage(x) { - return x._getType() === "tool"; -} -function isToolMessageChunk(x) { - return x._getType() === "tool"; } +ZodError.create = (issues) => { + const error = new ZodError(issues); + return error; +}; -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/ai.js - +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v3/locales/en.js -/** - * Represents an AI message in a conversation. - */ -class ai_AIMessage extends BaseMessage { - get lc_aliases() { - // exclude snake case conversion to pascal case - return { - ...super.lc_aliases, - tool_calls: "tool_calls", - invalid_tool_calls: "invalid_tool_calls", - }; - } - constructor(fields, - /** @deprecated */ - kwargs) { - let initParams; - if (typeof fields === "string") { - initParams = { - content: fields, - tool_calls: [], - invalid_tool_calls: [], - additional_kwargs: kwargs ?? {}, - }; - } - else { - initParams = fields; - const rawToolCalls = initParams.additional_kwargs?.tool_calls; - const toolCalls = initParams.tool_calls; - if (!(rawToolCalls == null) && - rawToolCalls.length > 0 && - (toolCalls === undefined || toolCalls.length === 0)) { - console.warn([ - "New LangChain packages are available that more efficiently handle", - "tool calling.\n\nPlease upgrade your packages to versions that set", - "message tool calls. e.g., `yarn add @langchain/anthropic`,", - "yarn add @langchain/openai`, etc.", - ].join(" ")); +const errorMap = (issue, _ctx) => { + let message; + switch (issue.code) { + case ZodIssueCode.invalid_type: + if (issue.received === ZodParsedType.undefined) { + message = "Required"; } - try { - if (!(rawToolCalls == null) && toolCalls === undefined) { - const [toolCalls, invalidToolCalls] = defaultToolCallParser(rawToolCalls); - initParams.tool_calls = toolCalls ?? []; - initParams.invalid_tool_calls = invalidToolCalls ?? []; + else { + message = `Expected ${issue.expected}, received ${issue.received}`; + } + break; + case ZodIssueCode.invalid_literal: + message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util_util.jsonStringifyReplacer)}`; + break; + case ZodIssueCode.unrecognized_keys: + message = `Unrecognized key(s) in object: ${util_util.joinValues(issue.keys, ", ")}`; + break; + case ZodIssueCode.invalid_union: + message = `Invalid input`; + break; + case ZodIssueCode.invalid_union_discriminator: + message = `Invalid discriminator value. Expected ${util_util.joinValues(issue.options)}`; + break; + case ZodIssueCode.invalid_enum_value: + message = `Invalid enum value. Expected ${util_util.joinValues(issue.options)}, received '${issue.received}'`; + break; + case ZodIssueCode.invalid_arguments: + message = `Invalid function arguments`; + break; + case ZodIssueCode.invalid_return_type: + message = `Invalid function return type`; + break; + case ZodIssueCode.invalid_date: + message = `Invalid date`; + break; + case ZodIssueCode.invalid_string: + if (typeof issue.validation === "object") { + if ("includes" in issue.validation) { + message = `Invalid input: must include "${issue.validation.includes}"`; + if (typeof issue.validation.position === "number") { + message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`; + } + } + else if ("startsWith" in issue.validation) { + message = `Invalid input: must start with "${issue.validation.startsWith}"`; + } + else if ("endsWith" in issue.validation) { + message = `Invalid input: must end with "${issue.validation.endsWith}"`; } else { - initParams.tool_calls = initParams.tool_calls ?? []; - initParams.invalid_tool_calls = initParams.invalid_tool_calls ?? []; + util_util.assertNever(issue.validation); } } - catch (e) { - // Do nothing if parsing fails - initParams.tool_calls = []; - initParams.invalid_tool_calls = []; + else if (issue.validation !== "regex") { + message = `Invalid ${issue.validation}`; } - } - // Sadly, TypeScript only allows super() calls at root if the class has - // properties with initializers, so we have to check types twice. - super(initParams); - // These are typed as optional to avoid breaking changes and allow for casting - // from BaseMessage. - Object.defineProperty(this, "tool_calls", { - enumerable: true, - configurable: true, - writable: true, - value: [] - }); - Object.defineProperty(this, "invalid_tool_calls", { - enumerable: true, - configurable: true, - writable: true, - value: [] - }); - /** - * If provided, token usage information associated with the message. - */ - Object.defineProperty(this, "usage_metadata", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - if (typeof initParams !== "string") { - this.tool_calls = initParams.tool_calls ?? this.tool_calls; - this.invalid_tool_calls = - initParams.invalid_tool_calls ?? this.invalid_tool_calls; - } - this.usage_metadata = initParams.usage_metadata; - } - static lc_name() { - return "AIMessage"; - } - _getType() { - return "ai"; + else { + message = "Invalid"; + } + break; + case ZodIssueCode.too_small: + if (issue.type === "array") + message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`; + else if (issue.type === "string") + message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`; + else if (issue.type === "number") + message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`; + else if (issue.type === "date") + message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`; + else + message = "Invalid input"; + break; + case ZodIssueCode.too_big: + if (issue.type === "array") + message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`; + else if (issue.type === "string") + message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`; + else if (issue.type === "number") + message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; + else if (issue.type === "bigint") + message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; + else if (issue.type === "date") + message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`; + else + message = "Invalid input"; + break; + case ZodIssueCode.custom: + message = `Invalid input`; + break; + case ZodIssueCode.invalid_intersection_types: + message = `Intersection results could not be merged`; + break; + case ZodIssueCode.not_multiple_of: + message = `Number must be a multiple of ${issue.multipleOf}`; + break; + case ZodIssueCode.not_finite: + message = "Number must be finite"; + break; + default: + message = _ctx.defaultError; + util_util.assertNever(issue); } - get _printableFields() { + return { message }; +}; +/* harmony default export */ const en = (errorMap); + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v3/errors.js + +let overrideErrorMap = en; + +function setErrorMap(map) { + overrideErrorMap = map; +} +function getErrorMap() { + return overrideErrorMap; +} + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v3/helpers/parseUtil.js + + +const makeIssue = (params) => { + const { data, path, errorMaps, issueData } = params; + const fullPath = [...path, ...(issueData.path || [])]; + const fullIssue = { + ...issueData, + path: fullPath, + }; + if (issueData.message !== undefined) { return { - ...super._printableFields, - tool_calls: this.tool_calls, - invalid_tool_calls: this.invalid_tool_calls, - usage_metadata: this.usage_metadata, + ...issueData, + path: fullPath, + message: issueData.message, }; } + let errorMessage = ""; + const maps = errorMaps + .filter((m) => !!m) + .slice() + .reverse(); + for (const map of maps) { + errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message; + } + return { + ...issueData, + path: fullPath, + message: errorMessage, + }; +}; +const EMPTY_PATH = []; +function addIssueToContext(ctx, issueData) { + const overrideMap = getErrorMap(); + const issue = makeIssue({ + issueData: issueData, + data: ctx.data, + path: ctx.path, + errorMaps: [ + ctx.common.contextualErrorMap, // contextual error map is first priority + ctx.schemaErrorMap, // then schema-bound map if available + overrideMap, // then global override map + overrideMap === en ? undefined : en, // then global default map + ].filter((x) => !!x), + }); + ctx.common.issues.push(issue); } -function isAIMessage(x) { - return x._getType() === "ai"; -} -function isAIMessageChunk(x) { - return x._getType() === "ai"; -} -/** - * Represents a chunk of an AI message, which can be concatenated with - * other AI message chunks. - */ -class ai_AIMessageChunk extends BaseMessageChunk { - constructor(fields) { - let initParams; - if (typeof fields === "string") { - initParams = { - content: fields, - tool_calls: [], - invalid_tool_calls: [], - tool_call_chunks: [], - }; +class ParseStatus { + constructor() { + this.value = "valid"; + } + dirty() { + if (this.value === "valid") + this.value = "dirty"; + } + abort() { + if (this.value !== "aborted") + this.value = "aborted"; + } + static mergeArray(status, results) { + const arrayValue = []; + for (const s of results) { + if (s.status === "aborted") + return INVALID; + if (s.status === "dirty") + status.dirty(); + arrayValue.push(s.value); } - else if (fields.tool_call_chunks === undefined) { - initParams = { - ...fields, - tool_calls: fields.tool_calls ?? [], - invalid_tool_calls: [], - tool_call_chunks: [], - usage_metadata: fields.usage_metadata !== undefined - ? fields.usage_metadata - : undefined, - }; + return { status: status.value, value: arrayValue }; + } + static async mergeObjectAsync(status, pairs) { + const syncPairs = []; + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + syncPairs.push({ + key, + value, + }); } - else { - const toolCalls = []; - const invalidToolCalls = []; - for (const toolCallChunk of fields.tool_call_chunks) { - let parsedArgs = {}; - try { - parsedArgs = parsePartialJson(toolCallChunk.args || "{}"); - if (parsedArgs === null || - typeof parsedArgs !== "object" || - Array.isArray(parsedArgs)) { - throw new Error("Malformed tool call chunk args."); - } - toolCalls.push({ - name: toolCallChunk.name ?? "", - args: parsedArgs, - id: toolCallChunk.id, - type: "tool_call", - }); - } - catch (e) { - invalidToolCalls.push({ - name: toolCallChunk.name, - args: toolCallChunk.args, - id: toolCallChunk.id, - error: "Malformed args.", - type: "invalid_tool_call", - }); - } + return ParseStatus.mergeObjectSync(status, syncPairs); + } + static mergeObjectSync(status, pairs) { + const finalObject = {}; + for (const pair of pairs) { + const { key, value } = pair; + if (key.status === "aborted") + return INVALID; + if (value.status === "aborted") + return INVALID; + if (key.status === "dirty") + status.dirty(); + if (value.status === "dirty") + status.dirty(); + if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) { + finalObject[key.value] = value.value; + } + } + return { status: status.value, value: finalObject }; + } +} +const INVALID = Object.freeze({ + status: "aborted", +}); +const DIRTY = (value) => ({ status: "dirty", value }); +const OK = (value) => ({ status: "valid", value }); +const isAborted = (x) => x.status === "aborted"; +const isDirty = (x) => x.status === "dirty"; +const isValid = (x) => x.status === "valid"; +const isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise; + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v3/helpers/errorUtil.js +var errorUtil; +(function (errorUtil) { + errorUtil.errToObj = (message) => typeof message === "string" ? { message } : message || {}; + // biome-ignore lint: + errorUtil.toString = (message) => typeof message === "string" ? message : message?.message; +})(errorUtil || (errorUtil = {})); + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v3/types.js + + + + + +class ParseInputLazyPath { + constructor(parent, value, path, key) { + this._cachedPath = []; + this.parent = parent; + this.data = value; + this._path = path; + this._key = key; + } + get path() { + if (!this._cachedPath.length) { + if (Array.isArray(this._key)) { + this._cachedPath.push(...this._path, ...this._key); + } + else { + this._cachedPath.push(...this._path, this._key); } - initParams = { - ...fields, - tool_calls: toolCalls, - invalid_tool_calls: invalidToolCalls, - usage_metadata: fields.usage_metadata !== undefined - ? fields.usage_metadata - : undefined, - }; } - // Sadly, TypeScript only allows super() calls at root if the class has - // properties with initializers, so we have to check types twice. - super(initParams); - // Must redeclare tool call fields since there is no multiple inheritance in JS. - // These are typed as optional to avoid breaking changes and allow for casting - // from BaseMessage. - Object.defineProperty(this, "tool_calls", { - enumerable: true, - configurable: true, - writable: true, - value: [] - }); - Object.defineProperty(this, "invalid_tool_calls", { - enumerable: true, - configurable: true, - writable: true, - value: [] - }); - Object.defineProperty(this, "tool_call_chunks", { - enumerable: true, - configurable: true, - writable: true, - value: [] - }); - /** - * If provided, token usage information associated with the message. - */ - Object.defineProperty(this, "usage_metadata", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.tool_call_chunks = - initParams.tool_call_chunks ?? this.tool_call_chunks; - this.tool_calls = initParams.tool_calls ?? this.tool_calls; - this.invalid_tool_calls = - initParams.invalid_tool_calls ?? this.invalid_tool_calls; - this.usage_metadata = initParams.usage_metadata; + return this._cachedPath; } - get lc_aliases() { - // exclude snake case conversion to pascal case +} +const handleResult = (ctx, result) => { + if (isValid(result)) { + return { success: true, data: result.value }; + } + else { + if (!ctx.common.issues.length) { + throw new Error("Validation failed but no issues detected."); + } return { - ...super.lc_aliases, - tool_calls: "tool_calls", - invalid_tool_calls: "invalid_tool_calls", - tool_call_chunks: "tool_call_chunks", + success: false, + get error() { + if (this._error) + return this._error; + const error = new ZodError(ctx.common.issues); + this._error = error; + return this._error; + }, }; } - static lc_name() { - return "AIMessageChunk"; +}; +function processCreateParams(params) { + if (!params) + return {}; + const { errorMap, invalid_type_error, required_error, description } = params; + if (errorMap && (invalid_type_error || required_error)) { + throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); } - _getType() { - return "ai"; + if (errorMap) + return { errorMap: errorMap, description }; + const customMap = (iss, ctx) => { + const { message } = params; + if (iss.code === "invalid_enum_value") { + return { message: message ?? ctx.defaultError }; + } + if (typeof ctx.data === "undefined") { + return { message: message ?? required_error ?? ctx.defaultError }; + } + if (iss.code !== "invalid_type") + return { message: ctx.defaultError }; + return { message: message ?? invalid_type_error ?? ctx.defaultError }; + }; + return { errorMap: customMap, description }; +} +class ZodType { + get description() { + return this._def.description; } - get _printableFields() { + _getType(input) { + return getParsedType(input.data); + } + _getOrReturnCtx(input, ctx) { + return (ctx || { + common: input.parent.common, + data: input.data, + parsedType: getParsedType(input.data), + schemaErrorMap: this._def.errorMap, + path: input.path, + parent: input.parent, + }); + } + _processInputParams(input) { return { - ...super._printableFields, - tool_calls: this.tool_calls, - tool_call_chunks: this.tool_call_chunks, - invalid_tool_calls: this.invalid_tool_calls, - usage_metadata: this.usage_metadata, + status: new ParseStatus(), + ctx: { + common: input.parent.common, + data: input.data, + parsedType: getParsedType(input.data), + schemaErrorMap: this._def.errorMap, + path: input.path, + parent: input.parent, + }, }; } - concat(chunk) { - const combinedFields = { - content: mergeContent(this.content, chunk.content), - additional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs), - response_metadata: _mergeDicts(this.response_metadata, chunk.response_metadata), - tool_call_chunks: [], - id: this.id ?? chunk.id, + _parseSync(input) { + const result = this._parse(input); + if (isAsync(result)) { + throw new Error("Synchronous parse encountered promise."); + } + return result; + } + _parseAsync(input) { + const result = this._parse(input); + return Promise.resolve(result); + } + parse(data, params) { + const result = this.safeParse(data, params); + if (result.success) + return result.data; + throw result.error; + } + safeParse(data, params) { + const ctx = { + common: { + issues: [], + async: params?.async ?? false, + contextualErrorMap: params?.errorMap, + }, + path: params?.path || [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: getParsedType(data), }; - if (this.tool_call_chunks !== undefined || - chunk.tool_call_chunks !== undefined) { - const rawToolCalls = _mergeLists(this.tool_call_chunks, chunk.tool_call_chunks); - if (rawToolCalls !== undefined && rawToolCalls.length > 0) { - combinedFields.tool_call_chunks = rawToolCalls; + const result = this._parseSync({ data, path: ctx.path, parent: ctx }); + return handleResult(ctx, result); + } + "~validate"(data) { + const ctx = { + common: { + issues: [], + async: !!this["~standard"].async, + }, + path: [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: getParsedType(data), + }; + if (!this["~standard"].async) { + try { + const result = this._parseSync({ data, path: [], parent: ctx }); + return isValid(result) + ? { + value: result.value, + } + : { + issues: ctx.common.issues, + }; + } + catch (err) { + if (err?.message?.toLowerCase()?.includes("encountered")) { + this["~standard"].async = true; + } + ctx.common = { + issues: [], + async: true, + }; } } - if (this.usage_metadata !== undefined || - chunk.usage_metadata !== undefined) { - const inputTokenDetails = { - ...((this.usage_metadata?.input_token_details?.audio !== undefined || - chunk.usage_metadata?.input_token_details?.audio !== undefined) && { - audio: (this.usage_metadata?.input_token_details?.audio ?? 0) + - (chunk.usage_metadata?.input_token_details?.audio ?? 0), - }), - ...((this.usage_metadata?.input_token_details?.cache_read !== - undefined || - chunk.usage_metadata?.input_token_details?.cache_read !== - undefined) && { - cache_read: (this.usage_metadata?.input_token_details?.cache_read ?? 0) + - (chunk.usage_metadata?.input_token_details?.cache_read ?? 0), - }), - ...((this.usage_metadata?.input_token_details?.cache_creation !== - undefined || - chunk.usage_metadata?.input_token_details?.cache_creation !== - undefined) && { - cache_creation: (this.usage_metadata?.input_token_details?.cache_creation ?? 0) + - (chunk.usage_metadata?.input_token_details?.cache_creation ?? 0), - }), - }; - const outputTokenDetails = { - ...((this.usage_metadata?.output_token_details?.audio !== undefined || - chunk.usage_metadata?.output_token_details?.audio !== undefined) && { - audio: (this.usage_metadata?.output_token_details?.audio ?? 0) + - (chunk.usage_metadata?.output_token_details?.audio ?? 0), - }), - ...((this.usage_metadata?.output_token_details?.reasoning !== - undefined || - chunk.usage_metadata?.output_token_details?.reasoning !== - undefined) && { - reasoning: (this.usage_metadata?.output_token_details?.reasoning ?? 0) + - (chunk.usage_metadata?.output_token_details?.reasoning ?? 0), - }), - }; - const left = this.usage_metadata ?? { - input_tokens: 0, - output_tokens: 0, - total_tokens: 0, - }; - const right = chunk.usage_metadata ?? { - input_tokens: 0, - output_tokens: 0, - total_tokens: 0, - }; - const usage_metadata = { - input_tokens: left.input_tokens + right.input_tokens, - output_tokens: left.output_tokens + right.output_tokens, - total_tokens: left.total_tokens + right.total_tokens, - // Do not include `input_token_details` / `output_token_details` keys in combined fields - // unless their values are defined. - ...(Object.keys(inputTokenDetails).length > 0 && { - input_token_details: inputTokenDetails, - }), - ...(Object.keys(outputTokenDetails).length > 0 && { - output_token_details: outputTokenDetails, - }), - }; - combinedFields.usage_metadata = usage_metadata; - } - return new ai_AIMessageChunk(combinedFields); + return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) + ? { + value: result.value, + } + : { + issues: ctx.common.issues, + }); } -} - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/chat.js - -/** - * Represents a chat message in a conversation. - */ -class chat_ChatMessage extends BaseMessage { - static lc_name() { - return "ChatMessage"; + async parseAsync(data, params) { + const result = await this.safeParseAsync(data, params); + if (result.success) + return result.data; + throw result.error; } - static _chatMessageClass() { - return chat_ChatMessage; + async safeParseAsync(data, params) { + const ctx = { + common: { + issues: [], + contextualErrorMap: params?.errorMap, + async: true, + }, + path: params?.path || [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: getParsedType(data), + }; + const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }); + const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult)); + return handleResult(ctx, result); } - constructor(fields, role) { - if (typeof fields === "string") { - // eslint-disable-next-line no-param-reassign, @typescript-eslint/no-non-null-assertion - fields = { content: fields, role: role }; - } - super(fields); - Object.defineProperty(this, "role", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 + refine(check, message) { + const getIssueProperties = (val) => { + if (typeof message === "string" || typeof message === "undefined") { + return { message }; + } + else if (typeof message === "function") { + return message(val); + } + else { + return message; + } + }; + return this._refinement((val, ctx) => { + const result = check(val); + const setError = () => ctx.addIssue({ + code: ZodIssueCode.custom, + ...getIssueProperties(val), + }); + if (typeof Promise !== "undefined" && result instanceof Promise) { + return result.then((data) => { + if (!data) { + setError(); + return false; + } + else { + return true; + } + }); + } + if (!result) { + setError(); + return false; + } + else { + return true; + } }); - this.role = fields.role; } - _getType() { - return "generic"; + refinement(check, refinementData) { + return this._refinement((val, ctx) => { + if (!check(val)) { + ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData); + return false; + } + else { + return true; + } + }); } - static isInstance(message) { - return message._getType() === "generic"; + _refinement(refinement) { + return new ZodEffects({ + schema: this, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect: { type: "refinement", refinement }, + }); } - get _printableFields() { - return { - ...super._printableFields, - role: this.role, + superRefine(refinement) { + return this._refinement(refinement); + } + constructor(def) { + /** Alias of safeParseAsync */ + this.spa = this.safeParseAsync; + this._def = def; + this.parse = this.parse.bind(this); + this.safeParse = this.safeParse.bind(this); + this.parseAsync = this.parseAsync.bind(this); + this.safeParseAsync = this.safeParseAsync.bind(this); + this.spa = this.spa.bind(this); + this.refine = this.refine.bind(this); + this.refinement = this.refinement.bind(this); + this.superRefine = this.superRefine.bind(this); + this.optional = this.optional.bind(this); + this.nullable = this.nullable.bind(this); + this.nullish = this.nullish.bind(this); + this.array = this.array.bind(this); + this.promise = this.promise.bind(this); + this.or = this.or.bind(this); + this.and = this.and.bind(this); + this.transform = this.transform.bind(this); + this.brand = this.brand.bind(this); + this.default = this.default.bind(this); + this.catch = this.catch.bind(this); + this.describe = this.describe.bind(this); + this.pipe = this.pipe.bind(this); + this.readonly = this.readonly.bind(this); + this.isNullable = this.isNullable.bind(this); + this.isOptional = this.isOptional.bind(this); + this["~standard"] = { + version: 1, + vendor: "zod", + validate: (data) => this["~validate"](data), }; } -} -/** - * Represents a chunk of a chat message, which can be concatenated with - * other chat message chunks. - */ -class chat_ChatMessageChunk extends BaseMessageChunk { - static lc_name() { - return "ChatMessageChunk"; + optional() { + return ZodOptional.create(this, this._def); } - constructor(fields, role) { - if (typeof fields === "string") { - // eslint-disable-next-line no-param-reassign, @typescript-eslint/no-non-null-assertion - fields = { content: fields, role: role }; - } - super(fields); - Object.defineProperty(this, "role", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.role = fields.role; + nullable() { + return ZodNullable.create(this, this._def); } - _getType() { - return "generic"; + nullish() { + return this.nullable().optional(); } - concat(chunk) { - return new chat_ChatMessageChunk({ - content: mergeContent(this.content, chunk.content), - additional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs), - response_metadata: _mergeDicts(this.response_metadata, chunk.response_metadata), - role: this.role, - id: this.id ?? chunk.id, - }); + array() { + return ZodArray.create(this); } - get _printableFields() { - return { - ...super._printableFields, - role: this.role, - }; + promise() { + return ZodPromise.create(this, this._def); } -} -function isChatMessage(x) { - return x._getType() === "generic"; -} -function isChatMessageChunk(x) { - return x._getType() === "generic"; -} - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/function.js - -/** - * Represents a function message in a conversation. - */ -class function_FunctionMessage extends BaseMessage { - static lc_name() { - return "FunctionMessage"; + or(option) { + return ZodUnion.create([this, option], this._def); } - constructor(fields, - /** @deprecated */ - name) { - if (typeof fields === "string") { - // eslint-disable-next-line no-param-reassign, @typescript-eslint/no-non-null-assertion - fields = { content: fields, name: name }; - } - super(fields); + and(incoming) { + return ZodIntersection.create(this, incoming, this._def); } - _getType() { - return "function"; + transform(transform) { + return new ZodEffects({ + ...processCreateParams(this._def), + schema: this, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect: { type: "transform", transform }, + }); } -} -/** - * Represents a chunk of a function message, which can be concatenated - * with other function message chunks. - */ -class function_FunctionMessageChunk extends BaseMessageChunk { - static lc_name() { - return "FunctionMessageChunk"; + default(def) { + const defaultValueFunc = typeof def === "function" ? def : () => def; + return new ZodDefault({ + ...processCreateParams(this._def), + innerType: this, + defaultValue: defaultValueFunc, + typeName: ZodFirstPartyTypeKind.ZodDefault, + }); } - _getType() { - return "function"; + brand() { + return new ZodBranded({ + typeName: ZodFirstPartyTypeKind.ZodBranded, + type: this, + ...processCreateParams(this._def), + }); } - concat(chunk) { - return new function_FunctionMessageChunk({ - content: mergeContent(this.content, chunk.content), - additional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs), - response_metadata: _mergeDicts(this.response_metadata, chunk.response_metadata), - name: this.name ?? "", - id: this.id ?? chunk.id, + catch(def) { + const catchValueFunc = typeof def === "function" ? def : () => def; + return new ZodCatch({ + ...processCreateParams(this._def), + innerType: this, + catchValue: catchValueFunc, + typeName: ZodFirstPartyTypeKind.ZodCatch, }); } -} -function function_isFunctionMessage(x) { - return x._getType() === "function"; -} -function isFunctionMessageChunk(x) { - return x._getType() === "function"; -} - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/human.js - -/** - * Represents a human message in a conversation. - */ -class human_HumanMessage extends BaseMessage { - static lc_name() { - return "HumanMessage"; + describe(description) { + const This = this.constructor; + return new This({ + ...this._def, + description, + }); } - _getType() { - return "human"; + pipe(target) { + return ZodPipeline.create(this, target); } - constructor(fields, - /** @deprecated */ - kwargs) { - super(fields, kwargs); + readonly() { + return ZodReadonly.create(this); } -} -/** - * Represents a chunk of a human message, which can be concatenated with - * other human message chunks. - */ -class human_HumanMessageChunk extends BaseMessageChunk { - static lc_name() { - return "HumanMessageChunk"; + isOptional() { + return this.safeParse(undefined).success; } - _getType() { - return "human"; + isNullable() { + return this.safeParse(null).success; } - constructor(fields, - /** @deprecated */ - kwargs) { - super(fields, kwargs); +} +const cuidRegex = /^c[^\s-]{8,}$/i; +const cuid2Regex = /^[0-9a-z]+$/; +const ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i; +// const uuidRegex = +// /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i; +const uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i; +const nanoidRegex = /^[a-z0-9_-]{21}$/i; +const jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/; +const durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; +// from https://stackoverflow.com/a/46181/1550155 +// old version: too slow, didn't support unicode +// const emailRegex = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i; +//old email regex +// const emailRegex = /^(([^<>()[\].,;:\s@"]+(\.[^<>()[\].,;:\s@"]+)*)|(".+"))@((?!-)([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{1,})[^-<>()[\].,;:\s@"]$/i; +// eslint-disable-next-line +// const emailRegex = +// /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\])|(\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\.[A-Za-z]{2,})+))$/; +// const emailRegex = +// /^[a-zA-Z0-9\.\!\#\$\%\&\'\*\+\/\=\?\^\_\`\{\|\}\~\-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; +// const emailRegex = +// /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$/i; +const emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; +// const emailRegex = +// /^[a-z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\.[a-z0-9\-]+)*$/i; +// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression +const _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; +let emojiRegex; +// faster, simpler, safer +const ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; +const ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/; +// const ipv6Regex = +// /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/; +const ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/; +const ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; +// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript +const base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; +// https://base64.guru/standards/base64url +const base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/; +// simple +// const dateRegexSource = `\\d{4}-\\d{2}-\\d{2}`; +// no leap year validation +// const dateRegexSource = `\\d{4}-((0[13578]|10|12)-31|(0[13-9]|1[0-2])-30|(0[1-9]|1[0-2])-(0[1-9]|1\\d|2\\d))`; +// with leap year validation +const dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`; +const dateRegex = new RegExp(`^${dateRegexSource}$`); +function timeRegexSource(args) { + let secondsRegexSource = `[0-5]\\d`; + if (args.precision) { + secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`; } - concat(chunk) { - return new human_HumanMessageChunk({ - content: mergeContent(this.content, chunk.content), - additional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs), - response_metadata: _mergeDicts(this.response_metadata, chunk.response_metadata), - id: this.id ?? chunk.id, - }); + else if (args.precision == null) { + secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`; } + const secondsQuantifier = args.precision ? "+" : "?"; // require seconds if precision is nonzero + return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`; } -function isHumanMessage(x) { - return x.getType() === "human"; +function timeRegex(args) { + return new RegExp(`^${timeRegexSource(args)}$`); } -function isHumanMessageChunk(x) { - return x.getType() === "human"; +// Adapted from https://stackoverflow.com/a/3143231 +function datetimeRegex(args) { + let regex = `${dateRegexSource}T${timeRegexSource(args)}`; + const opts = []; + opts.push(args.local ? `Z?` : `Z`); + if (args.offset) + opts.push(`([+-]\\d{2}:?\\d{2})`); + regex = `${regex}(${opts.join("|")})`; + return new RegExp(`^${regex}$`); } - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/system.js - -/** - * Represents a system message in a conversation. - */ -class system_SystemMessage extends BaseMessage { - static lc_name() { - return "SystemMessage"; +function isValidIP(ip, version) { + if ((version === "v4" || !version) && ipv4Regex.test(ip)) { + return true; } - _getType() { - return "system"; + if ((version === "v6" || !version) && ipv6Regex.test(ip)) { + return true; } - constructor(fields, - /** @deprecated */ - kwargs) { - super(fields, kwargs); + return false; +} +function isValidJWT(jwt, alg) { + if (!jwtRegex.test(jwt)) + return false; + try { + const [header] = jwt.split("."); + // Convert base64url to base64 + const base64 = header + .replace(/-/g, "+") + .replace(/_/g, "/") + .padEnd(header.length + ((4 - (header.length % 4)) % 4), "="); + const decoded = JSON.parse(atob(base64)); + if (typeof decoded !== "object" || decoded === null) + return false; + if ("typ" in decoded && decoded?.typ !== "JWT") + return false; + if (!decoded.alg) + return false; + if (alg && decoded.alg !== alg) + return false; + return true; + } + catch { + return false; } } -/** - * Represents a chunk of a system message, which can be concatenated with - * other system message chunks. - */ -class system_SystemMessageChunk extends BaseMessageChunk { - static lc_name() { - return "SystemMessageChunk"; +function isValidCidr(ip, version) { + if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) { + return true; } - _getType() { - return "system"; + if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) { + return true; } - constructor(fields, - /** @deprecated */ - kwargs) { - super(fields, kwargs); + return false; +} +class ZodString extends ZodType { + _parse(input) { + if (this._def.coerce) { + input.data = String(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.string) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.string, + received: ctx.parsedType, + }); + return INVALID; + } + const status = new ParseStatus(); + let ctx = undefined; + for (const check of this._def.checks) { + if (check.kind === "min") { + if (input.data.length < check.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: check.value, + type: "string", + inclusive: true, + exact: false, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "max") { + if (input.data.length > check.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: check.value, + type: "string", + inclusive: true, + exact: false, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "length") { + const tooBig = input.data.length > check.value; + const tooSmall = input.data.length < check.value; + if (tooBig || tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + if (tooBig) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: check.value, + type: "string", + inclusive: true, + exact: true, + message: check.message, + }); + } + else if (tooSmall) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: check.value, + type: "string", + inclusive: true, + exact: true, + message: check.message, + }); + } + status.dirty(); + } + } + else if (check.kind === "email") { + if (!emailRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "email", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "emoji") { + if (!emojiRegex) { + emojiRegex = new RegExp(_emojiRegex, "u"); + } + if (!emojiRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "emoji", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "uuid") { + if (!uuidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "uuid", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "nanoid") { + if (!nanoidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "nanoid", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "cuid") { + if (!cuidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "cuid", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "cuid2") { + if (!cuid2Regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "cuid2", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "ulid") { + if (!ulidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "ulid", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "url") { + try { + new URL(input.data); + } + catch { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "url", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "regex") { + check.regex.lastIndex = 0; + const testResult = check.regex.test(input.data); + if (!testResult) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "regex", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "trim") { + input.data = input.data.trim(); + } + else if (check.kind === "includes") { + if (!input.data.includes(check.value, check.position)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: { includes: check.value, position: check.position }, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "toLowerCase") { + input.data = input.data.toLowerCase(); + } + else if (check.kind === "toUpperCase") { + input.data = input.data.toUpperCase(); + } + else if (check.kind === "startsWith") { + if (!input.data.startsWith(check.value)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: { startsWith: check.value }, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "endsWith") { + if (!input.data.endsWith(check.value)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: { endsWith: check.value }, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "datetime") { + const regex = datetimeRegex(check); + if (!regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: "datetime", + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "date") { + const regex = dateRegex; + if (!regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: "date", + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "time") { + const regex = timeRegex(check); + if (!regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: "time", + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "duration") { + if (!durationRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "duration", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "ip") { + if (!isValidIP(input.data, check.version)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "ip", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "jwt") { + if (!isValidJWT(input.data, check.alg)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "jwt", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "cidr") { + if (!isValidCidr(input.data, check.version)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "cidr", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "base64") { + if (!base64Regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "base64", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "base64url") { + if (!base64urlRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "base64url", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else { + util_util.assertNever(check); + } + } + return { status: status.value, value: input.data }; } - concat(chunk) { - return new system_SystemMessageChunk({ - content: mergeContent(this.content, chunk.content), - additional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs), - response_metadata: _mergeDicts(this.response_metadata, chunk.response_metadata), - id: this.id ?? chunk.id, + _regex(regex, validation, message) { + return this.refinement((data) => regex.test(data), { + validation, + code: ZodIssueCode.invalid_string, + ...errorUtil.errToObj(message), }); } -} -function isSystemMessage(x) { - return x._getType() === "system"; -} -function isSystemMessageChunk(x) { - return x._getType() === "system"; -} - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/errors/index.js -/* eslint-disable @typescript-eslint/no-explicit-any */ -/* eslint-disable no-param-reassign */ -function addLangChainErrorFields(error, lc_error_code) { - error.lc_error_code = lc_error_code; - error.message = `${error.message}\n\nTroubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${lc_error_code}/\n`; - return error; -} - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/tools/utils.js -function _isToolCall(toolCall) { - return !!(toolCall && - typeof toolCall === "object" && - "type" in toolCall && - toolCall.type === "tool_call"); -} -function _configHasToolCallId(config) { - return !!(config && - typeof config === "object" && - "toolCall" in config && - config.toolCall != null && - typeof config.toolCall === "object" && - "id" in config.toolCall && - typeof config.toolCall.id === "string"); -} -/** - * Custom error class used to handle exceptions related to tool input parsing. - * It extends the built-in `Error` class and adds an optional `output` - * property that can hold the output that caused the exception. - */ -class ToolInputParsingException extends Error { - constructor(message, output) { - super(message); - Object.defineProperty(this, "output", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 + _addCheck(check) { + return new ZodString({ + ...this._def, + checks: [...this._def.checks, check], }); - this.output = output; } -} - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/utils.js - - - - - - - - - -function _coerceToolCall(toolCall) { - if (_isToolCall(toolCall)) { - return toolCall; + email(message) { + return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) }); } - else if (typeof toolCall.id === "string" && - toolCall.type === "function" && - typeof toolCall.function === "object" && - toolCall.function !== null && - "arguments" in toolCall.function && - typeof toolCall.function.arguments === "string" && - "name" in toolCall.function && - typeof toolCall.function.name === "string") { - // Handle OpenAI tool call format - return { - id: toolCall.id, - args: JSON.parse(toolCall.function.arguments), - name: toolCall.function.name, - type: "tool_call", - }; + url(message) { + return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) }); } - else { - // TODO: Throw an error? - return toolCall; + emoji(message) { + return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) }); } -} -function isSerializedConstructor(x) { - return (typeof x === "object" && - x != null && - x.lc === 1 && - Array.isArray(x.id) && - x.kwargs != null && - typeof x.kwargs === "object"); -} -function _constructMessageFromParams(params) { - let type; - let rest; - // Support serialized messages - if (isSerializedConstructor(params)) { - const className = params.id.at(-1); - if (className === "HumanMessage" || className === "HumanMessageChunk") { - type = "user"; - } - else if (className === "AIMessage" || className === "AIMessageChunk") { - type = "assistant"; - } - else if (className === "SystemMessage" || - className === "SystemMessageChunk") { - type = "system"; - } - else if (className === "FunctionMessage" || - className === "FunctionMessageChunk") { - type = "function"; - } - else if (className === "ToolMessage" || - className === "ToolMessageChunk") { - type = "tool"; - } - else { - type = "unknown"; - } - rest = params.kwargs; + uuid(message) { + return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) }); } - else { - const { type: extractedType, ...otherParams } = params; - type = extractedType; - rest = otherParams; + nanoid(message) { + return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) }); } - if (type === "human" || type === "user") { - return new human_HumanMessage(rest); + cuid(message) { + return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) }); } - else if (type === "ai" || type === "assistant") { - const { tool_calls: rawToolCalls, ...other } = rest; - if (!Array.isArray(rawToolCalls)) { - return new ai_AIMessage(rest); - } - const tool_calls = rawToolCalls.map(_coerceToolCall); - return new ai_AIMessage({ ...other, tool_calls }); + cuid2(message) { + return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) }); } - else if (type === "system") { - return new system_SystemMessage(rest); + ulid(message) { + return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) }); } - else if (type === "developer") { - return new system_SystemMessage({ - ...rest, - additional_kwargs: { - ...rest.additional_kwargs, - __openai_role__: "developer", - }, - }); + base64(message) { + return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) }); } - else if (type === "tool" && "tool_call_id" in rest) { - return new tool_ToolMessage({ - ...rest, - content: rest.content, - tool_call_id: rest.tool_call_id, - name: rest.name, + base64url(message) { + // base64url encoding is a modification of base64 that can safely be used in URLs and filenames + return this._addCheck({ + kind: "base64url", + ...errorUtil.errToObj(message), }); } - else { - const error = addLangChainErrorFields(new Error(`Unable to coerce message from array: only human, AI, system, developer, or tool message coercion is currently supported.\n\nReceived: ${JSON.stringify(params, null, 2)}`), "MESSAGE_COERCION_FAILURE"); - throw error; - } -} -function coerceMessageLikeToMessage(messageLike) { - if (typeof messageLike === "string") { - return new human_HumanMessage(messageLike); + jwt(options) { + return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) }); } - else if (isBaseMessage(messageLike)) { - return messageLike; + ip(options) { + return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) }); } - if (Array.isArray(messageLike)) { - const [type, content] = messageLike; - return _constructMessageFromParams({ type, content }); + cidr(options) { + return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) }); } - else if (_isMessageFieldWithRole(messageLike)) { - const { role: type, ...rest } = messageLike; - return _constructMessageFromParams({ ...rest, type }); + datetime(options) { + if (typeof options === "string") { + return this._addCheck({ + kind: "datetime", + precision: null, + offset: false, + local: false, + message: options, + }); + } + return this._addCheck({ + kind: "datetime", + precision: typeof options?.precision === "undefined" ? null : options?.precision, + offset: options?.offset ?? false, + local: options?.local ?? false, + ...errorUtil.errToObj(options?.message), + }); } - else { - return _constructMessageFromParams(messageLike); + date(message) { + return this._addCheck({ kind: "date", message }); } -} -/** - * This function is used by memory classes to get a string representation - * of the chat message history, based on the message content and role. - */ -function getBufferString(messages, humanPrefix = "Human", aiPrefix = "AI") { - const string_messages = []; - for (const m of messages) { - let role; - if (m._getType() === "human") { - role = humanPrefix; - } - else if (m._getType() === "ai") { - role = aiPrefix; - } - else if (m._getType() === "system") { - role = "System"; - } - else if (m._getType() === "function") { - role = "Function"; - } - else if (m._getType() === "tool") { - role = "Tool"; - } - else if (m._getType() === "generic") { - role = m.role; - } - else { - throw new Error(`Got unsupported message type: ${m._getType()}`); + time(options) { + if (typeof options === "string") { + return this._addCheck({ + kind: "time", + precision: null, + message: options, + }); } - const nameStr = m.name ? `${m.name}, ` : ""; - const readableContent = typeof m.content === "string" - ? m.content - : JSON.stringify(m.content, null, 2); - string_messages.push(`${role}: ${nameStr}${readableContent}`); + return this._addCheck({ + kind: "time", + precision: typeof options?.precision === "undefined" ? null : options?.precision, + ...errorUtil.errToObj(options?.message), + }); } - return string_messages.join("\n"); -} -/** - * Maps messages from an older format (V1) to the current `StoredMessage` - * format. If the message is already in the `StoredMessage` format, it is - * returned as is. Otherwise, it transforms the V1 message into a - * `StoredMessage`. This function is important for maintaining - * compatibility with older message formats. - */ -function mapV1MessageToStoredMessage(message) { - // TODO: Remove this mapper when we deprecate the old message format. - if (message.data !== undefined) { - return message; + duration(message) { + return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) }); } - else { - const v1Message = message; - return { - type: v1Message.type, - data: { - content: v1Message.text, - role: v1Message.role, - name: undefined, - tool_call_id: undefined, - }, - }; + regex(regex, message) { + return this._addCheck({ + kind: "regex", + regex: regex, + ...errorUtil.errToObj(message), + }); } -} -function utils_mapStoredMessageToChatMessage(message) { - const storedMessage = mapV1MessageToStoredMessage(message); - switch (storedMessage.type) { - case "human": - return new HumanMessage(storedMessage.data); - case "ai": - return new AIMessage(storedMessage.data); - case "system": - return new SystemMessage(storedMessage.data); - case "function": - if (storedMessage.data.name === undefined) { - throw new Error("Name must be defined for function messages"); - } - return new FunctionMessage(storedMessage.data); - case "tool": - if (storedMessage.data.tool_call_id === undefined) { - throw new Error("Tool call ID must be defined for tool messages"); - } - return new ToolMessage(storedMessage.data); - case "generic": { - if (storedMessage.data.role === undefined) { - throw new Error("Role must be defined for chat messages"); - } - return new ChatMessage(storedMessage.data); - } - default: - throw new Error(`Got unexpected type: ${storedMessage.type}`); + includes(value, options) { + return this._addCheck({ + kind: "includes", + value: value, + position: options?.position, + ...errorUtil.errToObj(options?.message), + }); } -} -/** - * Transforms an array of `StoredMessage` instances into an array of - * `BaseMessage` instances. It uses the `mapV1MessageToStoredMessage` - * function to ensure all messages are in the `StoredMessage` format, then - * creates new instances of the appropriate `BaseMessage` subclass based - * on the type of each message. This function is used to prepare stored - * messages for use in a chat context. - */ -function mapStoredMessagesToChatMessages(messages) { - return messages.map(utils_mapStoredMessageToChatMessage); -} -/** - * Transforms an array of `BaseMessage` instances into an array of - * `StoredMessage` instances. It does this by calling the `toDict` method - * on each `BaseMessage`, which returns a `StoredMessage`. This function - * is used to prepare chat messages for storage. - */ -function mapChatMessagesToStoredMessages(messages) { - return messages.map((message) => message.toDict()); -} -function utils_convertToChunk(message) { - const type = message._getType(); - if (type === "human") { - // eslint-disable-next-line @typescript-eslint/no-use-before-define - return new human_HumanMessageChunk({ ...message }); + startsWith(value, message) { + return this._addCheck({ + kind: "startsWith", + value: value, + ...errorUtil.errToObj(message), + }); } - else if (type === "ai") { - let aiChunkFields = { - ...message, - }; - if ("tool_calls" in aiChunkFields) { - aiChunkFields = { - ...aiChunkFields, - tool_call_chunks: aiChunkFields.tool_calls?.map((tc) => ({ - ...tc, - type: "tool_call_chunk", - index: undefined, - args: JSON.stringify(tc.args), - })), - }; - } - // eslint-disable-next-line @typescript-eslint/no-use-before-define - return new ai_AIMessageChunk({ ...aiChunkFields }); + endsWith(value, message) { + return this._addCheck({ + kind: "endsWith", + value: value, + ...errorUtil.errToObj(message), + }); } - else if (type === "system") { - // eslint-disable-next-line @typescript-eslint/no-use-before-define - return new system_SystemMessageChunk({ ...message }); + min(minLength, message) { + return this._addCheck({ + kind: "min", + value: minLength, + ...errorUtil.errToObj(message), + }); } - else if (type === "function") { - // eslint-disable-next-line @typescript-eslint/no-use-before-define - return new function_FunctionMessageChunk({ ...message }); - // eslint-disable-next-line @typescript-eslint/no-use-before-define + max(maxLength, message) { + return this._addCheck({ + kind: "max", + value: maxLength, + ...errorUtil.errToObj(message), + }); } - else if (chat_ChatMessage.isInstance(message)) { - // eslint-disable-next-line @typescript-eslint/no-use-before-define - return new chat_ChatMessageChunk({ ...message }); + length(len, message) { + return this._addCheck({ + kind: "length", + value: len, + ...errorUtil.errToObj(message), + }); } - else { - throw new Error("Unknown message type."); + /** + * Equivalent to `.min(1)` + */ + nonempty(message) { + return this.min(1, errorUtil.errToObj(message)); } -} - -;// CONCATENATED MODULE: ./node_modules/zod/lib/index.mjs -var util; -(function (util) { - util.assertEqual = (val) => val; - function assertIs(_arg) { } - util.assertIs = assertIs; - function assertNever(_x) { - throw new Error(); + trim() { + return new ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "trim" }], + }); } - util.assertNever = assertNever; - util.arrayToEnum = (items) => { - const obj = {}; - for (const item of items) { - obj[item] = item; - } - return obj; - }; - util.getValidEnumValues = (obj) => { - const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number"); - const filtered = {}; - for (const k of validKeys) { - filtered[k] = obj[k]; - } - return util.objectValues(filtered); - }; - util.objectValues = (obj) => { - return util.objectKeys(obj).map(function (e) { - return obj[e]; + toLowerCase() { + return new ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "toLowerCase" }], }); - }; - util.objectKeys = typeof Object.keys === "function" // eslint-disable-line ban/ban - ? (obj) => Object.keys(obj) // eslint-disable-line ban/ban - : (object) => { - const keys = []; - for (const key in object) { - if (Object.prototype.hasOwnProperty.call(object, key)) { - keys.push(key); - } - } - return keys; - }; - util.find = (arr, checker) => { - for (const item of arr) { - if (checker(item)) - return item; - } - return undefined; - }; - util.isInteger = typeof Number.isInteger === "function" - ? (val) => Number.isInteger(val) // eslint-disable-line ban/ban - : (val) => typeof val === "number" && isFinite(val) && Math.floor(val) === val; - function joinValues(array, separator = " | ") { - return array - .map((val) => (typeof val === "string" ? `'${val}'` : val)) - .join(separator); } - util.joinValues = joinValues; - util.jsonStringifyReplacer = (_, value) => { - if (typeof value === "bigint") { - return value.toString(); - } - return value; - }; -})(util || (util = {})); -var objectUtil; -(function (objectUtil) { - objectUtil.mergeShapes = (first, second) => { - return { - ...first, - ...second, // second overwrites first - }; - }; -})(objectUtil || (objectUtil = {})); -const ZodParsedType = util.arrayToEnum([ - "string", - "nan", - "number", - "integer", - "float", - "boolean", - "date", - "bigint", - "symbol", - "function", - "undefined", - "null", - "array", - "object", - "unknown", - "promise", - "void", - "never", - "map", - "set", -]); -const getParsedType = (data) => { - const t = typeof data; - switch (t) { - case "undefined": - return ZodParsedType.undefined; - case "string": - return ZodParsedType.string; - case "number": - return isNaN(data) ? ZodParsedType.nan : ZodParsedType.number; - case "boolean": - return ZodParsedType.boolean; - case "function": - return ZodParsedType.function; - case "bigint": - return ZodParsedType.bigint; - case "symbol": - return ZodParsedType.symbol; - case "object": - if (Array.isArray(data)) { - return ZodParsedType.array; - } - if (data === null) { - return ZodParsedType.null; - } - if (data.then && - typeof data.then === "function" && - data.catch && - typeof data.catch === "function") { - return ZodParsedType.promise; - } - if (typeof Map !== "undefined" && data instanceof Map) { - return ZodParsedType.map; - } - if (typeof Set !== "undefined" && data instanceof Set) { - return ZodParsedType.set; - } - if (typeof Date !== "undefined" && data instanceof Date) { - return ZodParsedType.date; - } - return ZodParsedType.object; - default: - return ZodParsedType.unknown; + toUpperCase() { + return new ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "toUpperCase" }], + }); + } + get isDatetime() { + return !!this._def.checks.find((ch) => ch.kind === "datetime"); + } + get isDate() { + return !!this._def.checks.find((ch) => ch.kind === "date"); } -}; - -const ZodIssueCode = util.arrayToEnum([ - "invalid_type", - "invalid_literal", - "custom", - "invalid_union", - "invalid_union_discriminator", - "invalid_enum_value", - "unrecognized_keys", - "invalid_arguments", - "invalid_return_type", - "invalid_date", - "invalid_string", - "too_small", - "too_big", - "invalid_intersection_types", - "not_multiple_of", - "not_finite", -]); -const quotelessJson = (obj) => { - const json = JSON.stringify(obj, null, 2); - return json.replace(/"([^"]+)":/g, "$1:"); -}; -class ZodError extends Error { - get errors() { - return this.issues; + get isTime() { + return !!this._def.checks.find((ch) => ch.kind === "time"); } - constructor(issues) { - super(); - this.issues = []; - this.addIssue = (sub) => { - this.issues = [...this.issues, sub]; - }; - this.addIssues = (subs = []) => { - this.issues = [...this.issues, ...subs]; - }; - const actualProto = new.target.prototype; - if (Object.setPrototypeOf) { - // eslint-disable-next-line ban/ban - Object.setPrototypeOf(this, actualProto); - } - else { - this.__proto__ = actualProto; - } - this.name = "ZodError"; - this.issues = issues; + get isDuration() { + return !!this._def.checks.find((ch) => ch.kind === "duration"); } - format(_mapper) { - const mapper = _mapper || - function (issue) { - return issue.message; - }; - const fieldErrors = { _errors: [] }; - const processError = (error) => { - for (const issue of error.issues) { - if (issue.code === "invalid_union") { - issue.unionErrors.map(processError); - } - else if (issue.code === "invalid_return_type") { - processError(issue.returnTypeError); - } - else if (issue.code === "invalid_arguments") { - processError(issue.argumentsError); - } - else if (issue.path.length === 0) { - fieldErrors._errors.push(mapper(issue)); - } - else { - let curr = fieldErrors; - let i = 0; - while (i < issue.path.length) { - const el = issue.path[i]; - const terminal = i === issue.path.length - 1; - if (!terminal) { - curr[el] = curr[el] || { _errors: [] }; - // if (typeof el === "string") { - // curr[el] = curr[el] || { _errors: [] }; - // } else if (typeof el === "number") { - // const errorArray: any = []; - // errorArray._errors = []; - // curr[el] = curr[el] || errorArray; - // } - } - else { - curr[el] = curr[el] || { _errors: [] }; - curr[el]._errors.push(mapper(issue)); - } - curr = curr[el]; - i++; - } - } - } - }; - processError(this); - return fieldErrors; + get isEmail() { + return !!this._def.checks.find((ch) => ch.kind === "email"); } - static assert(value) { - if (!(value instanceof ZodError)) { - throw new Error(`Not a ZodError: ${value}`); - } + get isURL() { + return !!this._def.checks.find((ch) => ch.kind === "url"); } - toString() { - return this.message; + get isEmoji() { + return !!this._def.checks.find((ch) => ch.kind === "emoji"); } - get message() { - return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2); + get isUUID() { + return !!this._def.checks.find((ch) => ch.kind === "uuid"); } - get isEmpty() { - return this.issues.length === 0; + get isNANOID() { + return !!this._def.checks.find((ch) => ch.kind === "nanoid"); } - flatten(mapper = (issue) => issue.message) { - const fieldErrors = {}; - const formErrors = []; - for (const sub of this.issues) { - if (sub.path.length > 0) { - fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; - fieldErrors[sub.path[0]].push(mapper(sub)); - } - else { - formErrors.push(mapper(sub)); + get isCUID() { + return !!this._def.checks.find((ch) => ch.kind === "cuid"); + } + get isCUID2() { + return !!this._def.checks.find((ch) => ch.kind === "cuid2"); + } + get isULID() { + return !!this._def.checks.find((ch) => ch.kind === "ulid"); + } + get isIP() { + return !!this._def.checks.find((ch) => ch.kind === "ip"); + } + get isCIDR() { + return !!this._def.checks.find((ch) => ch.kind === "cidr"); + } + get isBase64() { + return !!this._def.checks.find((ch) => ch.kind === "base64"); + } + get isBase64url() { + // base64url encoding is a modification of base64 that can safely be used in URLs and filenames + return !!this._def.checks.find((ch) => ch.kind === "base64url"); + } + get minLength() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; } } - return { formErrors, fieldErrors }; + return min; } - get formErrors() { - return this.flatten(); + get maxLength() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; } } -ZodError.create = (issues) => { - const error = new ZodError(issues); - return error; +ZodString.create = (params) => { + return new ZodString({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodString, + coerce: params?.coerce ?? false, + ...processCreateParams(params), + }); }; - -const errorMap = (issue, _ctx) => { - let message; - switch (issue.code) { - case ZodIssueCode.invalid_type: - if (issue.received === ZodParsedType.undefined) { - message = "Required"; - } - else { - message = `Expected ${issue.expected}, received ${issue.received}`; - } - break; - case ZodIssueCode.invalid_literal: - message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`; - break; - case ZodIssueCode.unrecognized_keys: - message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`; - break; - case ZodIssueCode.invalid_union: - message = `Invalid input`; - break; - case ZodIssueCode.invalid_union_discriminator: - message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`; - break; - case ZodIssueCode.invalid_enum_value: - message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`; - break; - case ZodIssueCode.invalid_arguments: - message = `Invalid function arguments`; - break; - case ZodIssueCode.invalid_return_type: - message = `Invalid function return type`; - break; - case ZodIssueCode.invalid_date: - message = `Invalid date`; - break; - case ZodIssueCode.invalid_string: - if (typeof issue.validation === "object") { - if ("includes" in issue.validation) { - message = `Invalid input: must include "${issue.validation.includes}"`; - if (typeof issue.validation.position === "number") { - message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`; - } +// https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034 +function floatSafeRemainder(val, step) { + const valDecCount = (val.toString().split(".")[1] || "").length; + const stepDecCount = (step.toString().split(".")[1] || "").length; + const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; + const valInt = Number.parseInt(val.toFixed(decCount).replace(".", "")); + const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", "")); + return (valInt % stepInt) / 10 ** decCount; +} +class ZodNumber extends ZodType { + constructor() { + super(...arguments); + this.min = this.gte; + this.max = this.lte; + this.step = this.multipleOf; + } + _parse(input) { + if (this._def.coerce) { + input.data = Number(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.number) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.number, + received: ctx.parsedType, + }); + return INVALID; + } + let ctx = undefined; + const status = new ParseStatus(); + for (const check of this._def.checks) { + if (check.kind === "int") { + if (!util_util.isInteger(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: "integer", + received: "float", + message: check.message, + }); + status.dirty(); } - else if ("startsWith" in issue.validation) { - message = `Invalid input: must start with "${issue.validation.startsWith}"`; + } + else if (check.kind === "min") { + const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; + if (tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: check.value, + type: "number", + inclusive: check.inclusive, + exact: false, + message: check.message, + }); + status.dirty(); } - else if ("endsWith" in issue.validation) { - message = `Invalid input: must end with "${issue.validation.endsWith}"`; + } + else if (check.kind === "max") { + const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; + if (tooBig) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: check.value, + type: "number", + inclusive: check.inclusive, + exact: false, + message: check.message, + }); + status.dirty(); } - else { - util.assertNever(issue.validation); + } + else if (check.kind === "multipleOf") { + if (floatSafeRemainder(input.data, check.value) !== 0) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.not_multiple_of, + multipleOf: check.value, + message: check.message, + }); + status.dirty(); } } - else if (issue.validation !== "regex") { - message = `Invalid ${issue.validation}`; + else if (check.kind === "finite") { + if (!Number.isFinite(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.not_finite, + message: check.message, + }); + status.dirty(); + } } else { - message = "Invalid"; + util_util.assertNever(check); } - break; - case ZodIssueCode.too_small: - if (issue.type === "array") - message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`; - else if (issue.type === "string") - message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`; - else if (issue.type === "number") - message = `Number must be ${issue.exact - ? `exactly equal to ` - : issue.inclusive - ? `greater than or equal to ` - : `greater than `}${issue.minimum}`; - else if (issue.type === "date") - message = `Date must be ${issue.exact - ? `exactly equal to ` - : issue.inclusive - ? `greater than or equal to ` - : `greater than `}${new Date(Number(issue.minimum))}`; - else - message = "Invalid input"; - break; - case ZodIssueCode.too_big: - if (issue.type === "array") - message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`; - else if (issue.type === "string") - message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`; - else if (issue.type === "number") - message = `Number must be ${issue.exact - ? `exactly` - : issue.inclusive - ? `less than or equal to` - : `less than`} ${issue.maximum}`; - else if (issue.type === "bigint") - message = `BigInt must be ${issue.exact - ? `exactly` - : issue.inclusive - ? `less than or equal to` - : `less than`} ${issue.maximum}`; - else if (issue.type === "date") - message = `Date must be ${issue.exact - ? `exactly` - : issue.inclusive - ? `smaller than or equal to` - : `smaller than`} ${new Date(Number(issue.maximum))}`; - else - message = "Invalid input"; - break; - case ZodIssueCode.custom: - message = `Invalid input`; - break; - case ZodIssueCode.invalid_intersection_types: - message = `Intersection results could not be merged`; - break; - case ZodIssueCode.not_multiple_of: - message = `Number must be a multiple of ${issue.multipleOf}`; - break; - case ZodIssueCode.not_finite: - message = "Number must be finite"; - break; - default: - message = _ctx.defaultError; - util.assertNever(issue); + } + return { status: status.value, value: input.data }; } - return { message }; -}; - -let overrideErrorMap = errorMap; -function setErrorMap(map) { - overrideErrorMap = map; -} -function getErrorMap() { - return overrideErrorMap; -} - -const makeIssue = (params) => { - const { data, path, errorMaps, issueData } = params; - const fullPath = [...path, ...(issueData.path || [])]; - const fullIssue = { - ...issueData, - path: fullPath, - }; - if (issueData.message !== undefined) { - return { - ...issueData, - path: fullPath, - message: issueData.message, - }; + gte(value, message) { + return this.setLimit("min", value, true, errorUtil.toString(message)); } - let errorMessage = ""; - const maps = errorMaps - .filter((m) => !!m) - .slice() - .reverse(); - for (const map of maps) { - errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message; + gt(value, message) { + return this.setLimit("min", value, false, errorUtil.toString(message)); + } + lte(value, message) { + return this.setLimit("max", value, true, errorUtil.toString(message)); + } + lt(value, message) { + return this.setLimit("max", value, false, errorUtil.toString(message)); + } + setLimit(kind, value, inclusive, message) { + return new ZodNumber({ + ...this._def, + checks: [ + ...this._def.checks, + { + kind, + value, + inclusive, + message: errorUtil.toString(message), + }, + ], + }); + } + _addCheck(check) { + return new ZodNumber({ + ...this._def, + checks: [...this._def.checks, check], + }); + } + int(message) { + return this._addCheck({ + kind: "int", + message: errorUtil.toString(message), + }); + } + positive(message) { + return this._addCheck({ + kind: "min", + value: 0, + inclusive: false, + message: errorUtil.toString(message), + }); + } + negative(message) { + return this._addCheck({ + kind: "max", + value: 0, + inclusive: false, + message: errorUtil.toString(message), + }); + } + nonpositive(message) { + return this._addCheck({ + kind: "max", + value: 0, + inclusive: true, + message: errorUtil.toString(message), + }); } - return { - ...issueData, - path: fullPath, - message: errorMessage, - }; -}; -const EMPTY_PATH = []; -function addIssueToContext(ctx, issueData) { - const overrideMap = getErrorMap(); - const issue = makeIssue({ - issueData: issueData, - data: ctx.data, - path: ctx.path, - errorMaps: [ - ctx.common.contextualErrorMap, // contextual error map is first priority - ctx.schemaErrorMap, // then schema-bound map if available - overrideMap, // then global override map - overrideMap === errorMap ? undefined : errorMap, // then global default map - ].filter((x) => !!x), - }); - ctx.common.issues.push(issue); -} -class ParseStatus { - constructor() { - this.value = "valid"; + nonnegative(message) { + return this._addCheck({ + kind: "min", + value: 0, + inclusive: true, + message: errorUtil.toString(message), + }); } - dirty() { - if (this.value === "valid") - this.value = "dirty"; + multipleOf(value, message) { + return this._addCheck({ + kind: "multipleOf", + value: value, + message: errorUtil.toString(message), + }); } - abort() { - if (this.value !== "aborted") - this.value = "aborted"; + finite(message) { + return this._addCheck({ + kind: "finite", + message: errorUtil.toString(message), + }); } - static mergeArray(status, results) { - const arrayValue = []; - for (const s of results) { - if (s.status === "aborted") - return INVALID; - if (s.status === "dirty") - status.dirty(); - arrayValue.push(s.value); + safe(message) { + return this._addCheck({ + kind: "min", + inclusive: true, + value: Number.MIN_SAFE_INTEGER, + message: errorUtil.toString(message), + })._addCheck({ + kind: "max", + inclusive: true, + value: Number.MAX_SAFE_INTEGER, + message: errorUtil.toString(message), + }); + } + get minValue() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } } - return { status: status.value, value: arrayValue }; + return min; } - static async mergeObjectAsync(status, pairs) { - const syncPairs = []; - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - syncPairs.push({ - key, - value, - }); + get maxValue() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } } - return ParseStatus.mergeObjectSync(status, syncPairs); + return max; } - static mergeObjectSync(status, pairs) { - const finalObject = {}; - for (const pair of pairs) { - const { key, value } = pair; - if (key.status === "aborted") - return INVALID; - if (value.status === "aborted") - return INVALID; - if (key.status === "dirty") - status.dirty(); - if (value.status === "dirty") - status.dirty(); - if (key.value !== "__proto__" && - (typeof value.value !== "undefined" || pair.alwaysSet)) { - finalObject[key.value] = value.value; + get isInt() { + return !!this._def.checks.find((ch) => ch.kind === "int" || (ch.kind === "multipleOf" && util_util.isInteger(ch.value))); + } + get isFinite() { + let max = null; + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") { + return true; + } + else if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + else if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; } } - return { status: status.value, value: finalObject }; + return Number.isFinite(min) && Number.isFinite(max); } } -const INVALID = Object.freeze({ - status: "aborted", -}); -const DIRTY = (value) => ({ status: "dirty", value }); -const OK = (value) => ({ status: "valid", value }); -const isAborted = (x) => x.status === "aborted"; -const isDirty = (x) => x.status === "dirty"; -const isValid = (x) => x.status === "valid"; -const isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise; - -/****************************************************************************** -Copyright (c) Microsoft Corporation. - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY -AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR -OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -PERFORMANCE OF THIS SOFTWARE. -***************************************************************************** */ - -function lib_classPrivateFieldGet(receiver, state, kind, f) { - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); -} - -function lib_classPrivateFieldSet(receiver, state, value, kind, f) { - if (kind === "m") throw new TypeError("Private method is not writable"); - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); - return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; -} - -typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { - var e = new Error(message); - return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; +ZodNumber.create = (params) => { + return new ZodNumber({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodNumber, + coerce: params?.coerce || false, + ...processCreateParams(params), + }); }; - -var errorUtil; -(function (errorUtil) { - errorUtil.errToObj = (message) => typeof message === "string" ? { message } : message || {}; - errorUtil.toString = (message) => typeof message === "string" ? message : message === null || message === void 0 ? void 0 : message.message; -})(errorUtil || (errorUtil = {})); - -var _ZodEnum_cache, _ZodNativeEnum_cache; -class ParseInputLazyPath { - constructor(parent, value, path, key) { - this._cachedPath = []; - this.parent = parent; - this.data = value; - this._path = path; - this._key = key; +class ZodBigInt extends ZodType { + constructor() { + super(...arguments); + this.min = this.gte; + this.max = this.lte; } - get path() { - if (!this._cachedPath.length) { - if (this._key instanceof Array) { - this._cachedPath.push(...this._path, ...this._key); + _parse(input) { + if (this._def.coerce) { + try { + input.data = BigInt(input.data); + } + catch { + return this._getInvalidInput(input); + } + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.bigint) { + return this._getInvalidInput(input); + } + let ctx = undefined; + const status = new ParseStatus(); + for (const check of this._def.checks) { + if (check.kind === "min") { + const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; + if (tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + type: "bigint", + minimum: check.value, + inclusive: check.inclusive, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "max") { + const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; + if (tooBig) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + type: "bigint", + maximum: check.value, + inclusive: check.inclusive, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "multipleOf") { + if (input.data % check.value !== BigInt(0)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.not_multiple_of, + multipleOf: check.value, + message: check.message, + }); + status.dirty(); + } } else { - this._cachedPath.push(...this._path, this._key); + util_util.assertNever(check); } } - return this._cachedPath; + return { status: status.value, value: input.data }; } -} -const handleResult = (ctx, result) => { - if (isValid(result)) { - return { success: true, data: result.value }; + _getInvalidInput(input) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.bigint, + received: ctx.parsedType, + }); + return INVALID; } - else { - if (!ctx.common.issues.length) { - throw new Error("Validation failed but no issues detected."); - } - return { - success: false, - get error() { - if (this._error) - return this._error; - const error = new ZodError(ctx.common.issues); - this._error = error; - return this._error; - }, - }; + gte(value, message) { + return this.setLimit("min", value, true, errorUtil.toString(message)); } -}; -function processCreateParams(params) { - if (!params) - return {}; - const { errorMap, invalid_type_error, required_error, description } = params; - if (errorMap && (invalid_type_error || required_error)) { - throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); + gt(value, message) { + return this.setLimit("min", value, false, errorUtil.toString(message)); } - if (errorMap) - return { errorMap: errorMap, description }; - const customMap = (iss, ctx) => { - var _a, _b; - const { message } = params; - if (iss.code === "invalid_enum_value") { - return { message: message !== null && message !== void 0 ? message : ctx.defaultError }; - } - if (typeof ctx.data === "undefined") { - return { message: (_a = message !== null && message !== void 0 ? message : required_error) !== null && _a !== void 0 ? _a : ctx.defaultError }; - } - if (iss.code !== "invalid_type") - return { message: ctx.defaultError }; - return { message: (_b = message !== null && message !== void 0 ? message : invalid_type_error) !== null && _b !== void 0 ? _b : ctx.defaultError }; - }; - return { errorMap: customMap, description }; -} -class ZodType { - get description() { - return this._def.description; + lte(value, message) { + return this.setLimit("max", value, true, errorUtil.toString(message)); } - _getType(input) { - return getParsedType(input.data); + lt(value, message) { + return this.setLimit("max", value, false, errorUtil.toString(message)); } - _getOrReturnCtx(input, ctx) { - return (ctx || { - common: input.parent.common, - data: input.data, - parsedType: getParsedType(input.data), - schemaErrorMap: this._def.errorMap, - path: input.path, - parent: input.parent, + setLimit(kind, value, inclusive, message) { + return new ZodBigInt({ + ...this._def, + checks: [ + ...this._def.checks, + { + kind, + value, + inclusive, + message: errorUtil.toString(message), + }, + ], }); } - _processInputParams(input) { - return { - status: new ParseStatus(), - ctx: { - common: input.parent.common, - data: input.data, - parsedType: getParsedType(input.data), - schemaErrorMap: this._def.errorMap, - path: input.path, - parent: input.parent, - }, - }; + _addCheck(check) { + return new ZodBigInt({ + ...this._def, + checks: [...this._def.checks, check], + }); } - _parseSync(input) { - const result = this._parse(input); - if (isAsync(result)) { - throw new Error("Synchronous parse encountered promise."); - } - return result; + positive(message) { + return this._addCheck({ + kind: "min", + value: BigInt(0), + inclusive: false, + message: errorUtil.toString(message), + }); } - _parseAsync(input) { - const result = this._parse(input); - return Promise.resolve(result); + negative(message) { + return this._addCheck({ + kind: "max", + value: BigInt(0), + inclusive: false, + message: errorUtil.toString(message), + }); } - parse(data, params) { - const result = this.safeParse(data, params); - if (result.success) - return result.data; - throw result.error; + nonpositive(message) { + return this._addCheck({ + kind: "max", + value: BigInt(0), + inclusive: true, + message: errorUtil.toString(message), + }); } - safeParse(data, params) { - var _a; - const ctx = { - common: { - issues: [], - async: (_a = params === null || params === void 0 ? void 0 : params.async) !== null && _a !== void 0 ? _a : false, - contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap, - }, - path: (params === null || params === void 0 ? void 0 : params.path) || [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: getParsedType(data), - }; - const result = this._parseSync({ data, path: ctx.path, parent: ctx }); - return handleResult(ctx, result); + nonnegative(message) { + return this._addCheck({ + kind: "min", + value: BigInt(0), + inclusive: true, + message: errorUtil.toString(message), + }); } - "~validate"(data) { - var _a, _b; - const ctx = { - common: { - issues: [], - async: !!this["~standard"].async, - }, - path: [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: getParsedType(data), - }; - if (!this["~standard"].async) { - try { - const result = this._parseSync({ data, path: [], parent: ctx }); - return isValid(result) - ? { - value: result.value, - } - : { - issues: ctx.common.issues, - }; - } - catch (err) { - if ((_b = (_a = err === null || err === void 0 ? void 0 : err.message) === null || _a === void 0 ? void 0 : _a.toLowerCase()) === null || _b === void 0 ? void 0 : _b.includes("encountered")) { - this["~standard"].async = true; - } - ctx.common = { - issues: [], - async: true, - }; + multipleOf(value, message) { + return this._addCheck({ + kind: "multipleOf", + value, + message: errorUtil.toString(message), + }); + } + get minValue() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; } } - return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) - ? { - value: result.value, - } - : { - issues: ctx.common.issues, - }); + return min; } - async parseAsync(data, params) { - const result = await this.safeParseAsync(data, params); - if (result.success) - return result.data; - throw result.error; + get maxValue() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; } - async safeParseAsync(data, params) { - const ctx = { - common: { - issues: [], - contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap, - async: true, - }, - path: (params === null || params === void 0 ? void 0 : params.path) || [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: getParsedType(data), - }; - const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }); - const result = await (isAsync(maybeAsyncResult) - ? maybeAsyncResult - : Promise.resolve(maybeAsyncResult)); - return handleResult(ctx, result); +} +ZodBigInt.create = (params) => { + return new ZodBigInt({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodBigInt, + coerce: params?.coerce ?? false, + ...processCreateParams(params), + }); +}; +class ZodBoolean extends ZodType { + _parse(input) { + if (this._def.coerce) { + input.data = Boolean(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.boolean) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.boolean, + received: ctx.parsedType, + }); + return INVALID; + } + return OK(input.data); } - refine(check, message) { - const getIssueProperties = (val) => { - if (typeof message === "string" || typeof message === "undefined") { - return { message }; - } - else if (typeof message === "function") { - return message(val); - } - else { - return message; - } - }; - return this._refinement((val, ctx) => { - const result = check(val); - const setError = () => ctx.addIssue({ - code: ZodIssueCode.custom, - ...getIssueProperties(val), +} +ZodBoolean.create = (params) => { + return new ZodBoolean({ + typeName: ZodFirstPartyTypeKind.ZodBoolean, + coerce: params?.coerce || false, + ...processCreateParams(params), + }); +}; +class ZodDate extends ZodType { + _parse(input) { + if (this._def.coerce) { + input.data = new Date(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.date) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.date, + received: ctx.parsedType, + }); + return INVALID; + } + if (Number.isNaN(input.data.getTime())) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_date, }); - if (typeof Promise !== "undefined" && result instanceof Promise) { - return result.then((data) => { - if (!data) { - setError(); - return false; - } - else { - return true; - } - }); + return INVALID; + } + const status = new ParseStatus(); + let ctx = undefined; + for (const check of this._def.checks) { + if (check.kind === "min") { + if (input.data.getTime() < check.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + message: check.message, + inclusive: true, + exact: false, + minimum: check.value, + type: "date", + }); + status.dirty(); + } } - if (!result) { - setError(); - return false; + else if (check.kind === "max") { + if (input.data.getTime() > check.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + message: check.message, + inclusive: true, + exact: false, + maximum: check.value, + type: "date", + }); + status.dirty(); + } } else { - return true; + util_util.assertNever(check); } + } + return { + status: status.value, + value: new Date(input.data.getTime()), + }; + } + _addCheck(check) { + return new ZodDate({ + ...this._def, + checks: [...this._def.checks, check], }); } - refinement(check, refinementData) { - return this._refinement((val, ctx) => { - if (!check(val)) { - ctx.addIssue(typeof refinementData === "function" - ? refinementData(val, ctx) - : refinementData); - return false; - } - else { - return true; - } + min(minDate, message) { + return this._addCheck({ + kind: "min", + value: minDate.getTime(), + message: errorUtil.toString(message), }); } - _refinement(refinement) { - return new ZodEffects({ - schema: this, - typeName: ZodFirstPartyTypeKind.ZodEffects, - effect: { type: "refinement", refinement }, + max(maxDate, message) { + return this._addCheck({ + kind: "max", + value: maxDate.getTime(), + message: errorUtil.toString(message), }); } - superRefine(refinement) { - return this._refinement(refinement); + get minDate() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min != null ? new Date(min) : null; } - constructor(def) { - /** Alias of safeParseAsync */ - this.spa = this.safeParseAsync; - this._def = def; - this.parse = this.parse.bind(this); - this.safeParse = this.safeParse.bind(this); - this.parseAsync = this.parseAsync.bind(this); - this.safeParseAsync = this.safeParseAsync.bind(this); - this.spa = this.spa.bind(this); - this.refine = this.refine.bind(this); - this.refinement = this.refinement.bind(this); - this.superRefine = this.superRefine.bind(this); - this.optional = this.optional.bind(this); - this.nullable = this.nullable.bind(this); - this.nullish = this.nullish.bind(this); - this.array = this.array.bind(this); - this.promise = this.promise.bind(this); - this.or = this.or.bind(this); - this.and = this.and.bind(this); - this.transform = this.transform.bind(this); - this.brand = this.brand.bind(this); - this.default = this.default.bind(this); - this.catch = this.catch.bind(this); - this.describe = this.describe.bind(this); - this.pipe = this.pipe.bind(this); - this.readonly = this.readonly.bind(this); - this.isNullable = this.isNullable.bind(this); - this.isOptional = this.isOptional.bind(this); - this["~standard"] = { - version: 1, - vendor: "zod", - validate: (data) => this["~validate"](data), - }; + get maxDate() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max != null ? new Date(max) : null; } - optional() { - return ZodOptional.create(this, this._def); +} +ZodDate.create = (params) => { + return new ZodDate({ + checks: [], + coerce: params?.coerce || false, + typeName: ZodFirstPartyTypeKind.ZodDate, + ...processCreateParams(params), + }); +}; +class ZodSymbol extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.symbol) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.symbol, + received: ctx.parsedType, + }); + return INVALID; + } + return OK(input.data); } - nullable() { - return ZodNullable.create(this, this._def); +} +ZodSymbol.create = (params) => { + return new ZodSymbol({ + typeName: ZodFirstPartyTypeKind.ZodSymbol, + ...processCreateParams(params), + }); +}; +class ZodUndefined extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.undefined) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.undefined, + received: ctx.parsedType, + }); + return INVALID; + } + return OK(input.data); } - nullish() { - return this.nullable().optional(); +} +ZodUndefined.create = (params) => { + return new ZodUndefined({ + typeName: ZodFirstPartyTypeKind.ZodUndefined, + ...processCreateParams(params), + }); +}; +class ZodNull extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.null) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.null, + received: ctx.parsedType, + }); + return INVALID; + } + return OK(input.data); } - array() { - return ZodArray.create(this); +} +ZodNull.create = (params) => { + return new ZodNull({ + typeName: ZodFirstPartyTypeKind.ZodNull, + ...processCreateParams(params), + }); +}; +class ZodAny extends ZodType { + constructor() { + super(...arguments); + // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject. + this._any = true; } - promise() { - return ZodPromise.create(this, this._def); + _parse(input) { + return OK(input.data); } - or(option) { - return ZodUnion.create([this, option], this._def); +} +ZodAny.create = (params) => { + return new ZodAny({ + typeName: ZodFirstPartyTypeKind.ZodAny, + ...processCreateParams(params), + }); +}; +class ZodUnknown extends ZodType { + constructor() { + super(...arguments); + // required + this._unknown = true; } - and(incoming) { - return ZodIntersection.create(this, incoming, this._def); + _parse(input) { + return OK(input.data); } - transform(transform) { - return new ZodEffects({ - ...processCreateParams(this._def), - schema: this, - typeName: ZodFirstPartyTypeKind.ZodEffects, - effect: { type: "transform", transform }, +} +ZodUnknown.create = (params) => { + return new ZodUnknown({ + typeName: ZodFirstPartyTypeKind.ZodUnknown, + ...processCreateParams(params), + }); +}; +class ZodNever extends ZodType { + _parse(input) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.never, + received: ctx.parsedType, }); + return INVALID; } - default(def) { - const defaultValueFunc = typeof def === "function" ? def : () => def; - return new ZodDefault({ - ...processCreateParams(this._def), - innerType: this, - defaultValue: defaultValueFunc, - typeName: ZodFirstPartyTypeKind.ZodDefault, - }); +} +ZodNever.create = (params) => { + return new ZodNever({ + typeName: ZodFirstPartyTypeKind.ZodNever, + ...processCreateParams(params), + }); +}; +class ZodVoid extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.undefined) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.void, + received: ctx.parsedType, + }); + return INVALID; + } + return OK(input.data); } - brand() { - return new ZodBranded({ - typeName: ZodFirstPartyTypeKind.ZodBranded, - type: this, - ...processCreateParams(this._def), +} +ZodVoid.create = (params) => { + return new ZodVoid({ + typeName: ZodFirstPartyTypeKind.ZodVoid, + ...processCreateParams(params), + }); +}; +class ZodArray extends ZodType { + _parse(input) { + const { ctx, status } = this._processInputParams(input); + const def = this._def; + if (ctx.parsedType !== ZodParsedType.array) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.array, + received: ctx.parsedType, + }); + return INVALID; + } + if (def.exactLength !== null) { + const tooBig = ctx.data.length > def.exactLength.value; + const tooSmall = ctx.data.length < def.exactLength.value; + if (tooBig || tooSmall) { + addIssueToContext(ctx, { + code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small, + minimum: (tooSmall ? def.exactLength.value : undefined), + maximum: (tooBig ? def.exactLength.value : undefined), + type: "array", + inclusive: true, + exact: true, + message: def.exactLength.message, + }); + status.dirty(); + } + } + if (def.minLength !== null) { + if (ctx.data.length < def.minLength.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: def.minLength.value, + type: "array", + inclusive: true, + exact: false, + message: def.minLength.message, + }); + status.dirty(); + } + } + if (def.maxLength !== null) { + if (ctx.data.length > def.maxLength.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: def.maxLength.value, + type: "array", + inclusive: true, + exact: false, + message: def.maxLength.message, + }); + status.dirty(); + } + } + if (ctx.common.async) { + return Promise.all([...ctx.data].map((item, i) => { + return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i)); + })).then((result) => { + return ParseStatus.mergeArray(status, result); + }); + } + const result = [...ctx.data].map((item, i) => { + return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i)); }); + return ParseStatus.mergeArray(status, result); } - catch(def) { - const catchValueFunc = typeof def === "function" ? def : () => def; - return new ZodCatch({ - ...processCreateParams(this._def), - innerType: this, - catchValue: catchValueFunc, - typeName: ZodFirstPartyTypeKind.ZodCatch, - }); + get element() { + return this._def.type; } - describe(description) { - const This = this.constructor; - return new This({ + min(minLength, message) { + return new ZodArray({ ...this._def, - description, + minLength: { value: minLength, message: errorUtil.toString(message) }, }); } - pipe(target) { - return ZodPipeline.create(this, target); - } - readonly() { - return ZodReadonly.create(this); - } - isOptional() { - return this.safeParse(undefined).success; - } - isNullable() { - return this.safeParse(null).success; - } -} -const cuidRegex = /^c[^\s-]{8,}$/i; -const cuid2Regex = /^[0-9a-z]+$/; -const ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i; -// const uuidRegex = -// /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i; -const uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i; -const nanoidRegex = /^[a-z0-9_-]{21}$/i; -const jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/; -const durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; -// from https://stackoverflow.com/a/46181/1550155 -// old version: too slow, didn't support unicode -// const emailRegex = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i; -//old email regex -// const emailRegex = /^(([^<>()[\].,;:\s@"]+(\.[^<>()[\].,;:\s@"]+)*)|(".+"))@((?!-)([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{1,})[^-<>()[\].,;:\s@"]$/i; -// eslint-disable-next-line -// const emailRegex = -// /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\])|(\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\.[A-Za-z]{2,})+))$/; -// const emailRegex = -// /^[a-zA-Z0-9\.\!\#\$\%\&\'\*\+\/\=\?\^\_\`\{\|\}\~\-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; -// const emailRegex = -// /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$/i; -const emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; -// const emailRegex = -// /^[a-z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\.[a-z0-9\-]+)*$/i; -// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression -const _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; -let emojiRegex; -// faster, simpler, safer -const ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; -const ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/; -// const ipv6Regex = -// /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/; -const ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/; -const ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; -// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript -const base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; -// https://base64.guru/standards/base64url -const base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/; -// simple -// const dateRegexSource = `\\d{4}-\\d{2}-\\d{2}`; -// no leap year validation -// const dateRegexSource = `\\d{4}-((0[13578]|10|12)-31|(0[13-9]|1[0-2])-30|(0[1-9]|1[0-2])-(0[1-9]|1\\d|2\\d))`; -// with leap year validation -const dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`; -const dateRegex = new RegExp(`^${dateRegexSource}$`); -function timeRegexSource(args) { - let secondsRegexSource = `[0-5]\\d`; - if (args.precision) { - secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`; - } - else if (args.precision == null) { - secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`; + max(maxLength, message) { + return new ZodArray({ + ...this._def, + maxLength: { value: maxLength, message: errorUtil.toString(message) }, + }); } - const secondsQuantifier = args.precision ? "+" : "?"; // require seconds if precision is nonzero - return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`; -} -function timeRegex(args) { - return new RegExp(`^${timeRegexSource(args)}$`); -} -// Adapted from https://stackoverflow.com/a/3143231 -function datetimeRegex(args) { - let regex = `${dateRegexSource}T${timeRegexSource(args)}`; - const opts = []; - opts.push(args.local ? `Z?` : `Z`); - if (args.offset) - opts.push(`([+-]\\d{2}:?\\d{2})`); - regex = `${regex}(${opts.join("|")})`; - return new RegExp(`^${regex}$`); -} -function isValidIP(ip, version) { - if ((version === "v4" || !version) && ipv4Regex.test(ip)) { - return true; + length(len, message) { + return new ZodArray({ + ...this._def, + exactLength: { value: len, message: errorUtil.toString(message) }, + }); } - if ((version === "v6" || !version) && ipv6Regex.test(ip)) { - return true; + nonempty(message) { + return this.min(1, message); } - return false; } -function isValidJWT(jwt, alg) { - if (!jwtRegex.test(jwt)) - return false; - try { - const [header] = jwt.split("."); - // Convert base64url to base64 - const base64 = header - .replace(/-/g, "+") - .replace(/_/g, "/") - .padEnd(header.length + ((4 - (header.length % 4)) % 4), "="); - const decoded = JSON.parse(atob(base64)); - if (typeof decoded !== "object" || decoded === null) - return false; - if (!decoded.typ || !decoded.alg) - return false; - if (alg && decoded.alg !== alg) - return false; - return true; +ZodArray.create = (schema, params) => { + return new ZodArray({ + type: schema, + minLength: null, + maxLength: null, + exactLength: null, + typeName: ZodFirstPartyTypeKind.ZodArray, + ...processCreateParams(params), + }); +}; +function deepPartialify(schema) { + if (schema instanceof ZodObject) { + const newShape = {}; + for (const key in schema.shape) { + const fieldSchema = schema.shape[key]; + newShape[key] = ZodOptional.create(deepPartialify(fieldSchema)); + } + return new ZodObject({ + ...schema._def, + shape: () => newShape, + }); } - catch (_a) { - return false; + else if (schema instanceof ZodArray) { + return new ZodArray({ + ...schema._def, + type: deepPartialify(schema.element), + }); } -} -function isValidCidr(ip, version) { - if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) { - return true; + else if (schema instanceof ZodOptional) { + return ZodOptional.create(deepPartialify(schema.unwrap())); } - if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) { - return true; + else if (schema instanceof ZodNullable) { + return ZodNullable.create(deepPartialify(schema.unwrap())); + } + else if (schema instanceof ZodTuple) { + return ZodTuple.create(schema.items.map((item) => deepPartialify(item))); + } + else { + return schema; } - return false; } -class ZodString extends ZodType { +class ZodObject extends ZodType { + constructor() { + super(...arguments); + this._cached = null; + /** + * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped. + * If you want to pass through unknown properties, use `.passthrough()` instead. + */ + this.nonstrict = this.passthrough; + // extend< + // Augmentation extends ZodRawShape, + // NewOutput extends util.flatten<{ + // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation + // ? Augmentation[k]["_output"] + // : k extends keyof Output + // ? Output[k] + // : never; + // }>, + // NewInput extends util.flatten<{ + // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation + // ? Augmentation[k]["_input"] + // : k extends keyof Input + // ? Input[k] + // : never; + // }> + // >( + // augmentation: Augmentation + // ): ZodObject< + // extendShape, + // UnknownKeys, + // Catchall, + // NewOutput, + // NewInput + // > { + // return new ZodObject({ + // ...this._def, + // shape: () => ({ + // ...this._def.shape(), + // ...augmentation, + // }), + // }) as any; + // } + /** + * @deprecated Use `.extend` instead + * */ + this.augment = this.extend; + } + _getCached() { + if (this._cached !== null) + return this._cached; + const shape = this._def.shape(); + const keys = util_util.objectKeys(shape); + this._cached = { shape, keys }; + return this._cached; + } _parse(input) { - if (this._def.coerce) { - input.data = String(input.data); - } const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.string) { + if (parsedType !== ZodParsedType.object) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, - expected: ZodParsedType.string, + expected: ZodParsedType.object, received: ctx.parsedType, }); return INVALID; } - const status = new ParseStatus(); - let ctx = undefined; - for (const check of this._def.checks) { - if (check.kind === "min") { - if (input.data.length < check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: check.value, - type: "string", - inclusive: true, - exact: false, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "max") { - if (input.data.length > check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: check.value, - type: "string", - inclusive: true, - exact: false, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "length") { - const tooBig = input.data.length > check.value; - const tooSmall = input.data.length < check.value; - if (tooBig || tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - if (tooBig) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: check.value, - type: "string", - inclusive: true, - exact: true, - message: check.message, - }); - } - else if (tooSmall) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: check.value, - type: "string", - inclusive: true, - exact: true, - message: check.message, - }); - } - status.dirty(); - } - } - else if (check.kind === "email") { - if (!emailRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "email", - code: ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "emoji") { - if (!emojiRegex) { - emojiRegex = new RegExp(_emojiRegex, "u"); - } - if (!emojiRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "emoji", - code: ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "uuid") { - if (!uuidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "uuid", - code: ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "nanoid") { - if (!nanoidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "nanoid", - code: ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "cuid") { - if (!cuidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "cuid", - code: ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); + const { status, ctx } = this._processInputParams(input); + const { shape, keys: shapeKeys } = this._getCached(); + const extraKeys = []; + if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) { + for (const key in ctx.data) { + if (!shapeKeys.includes(key)) { + extraKeys.push(key); } } - else if (check.kind === "cuid2") { - if (!cuid2Regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "cuid2", - code: ZodIssueCode.invalid_string, - message: check.message, + } + const pairs = []; + for (const key of shapeKeys) { + const keyValidator = shape[key]; + const value = ctx.data[key]; + pairs.push({ + key: { status: "valid", value: key }, + value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), + alwaysSet: key in ctx.data, + }); + } + if (this._def.catchall instanceof ZodNever) { + const unknownKeys = this._def.unknownKeys; + if (unknownKeys === "passthrough") { + for (const key of extraKeys) { + pairs.push({ + key: { status: "valid", value: key }, + value: { status: "valid", value: ctx.data[key] }, }); - status.dirty(); } } - else if (check.kind === "ulid") { - if (!ulidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); + else if (unknownKeys === "strict") { + if (extraKeys.length > 0) { addIssueToContext(ctx, { - validation: "ulid", - code: ZodIssueCode.invalid_string, - message: check.message, + code: ZodIssueCode.unrecognized_keys, + keys: extraKeys, }); status.dirty(); } } - else if (check.kind === "url") { - try { - new URL(input.data); - } - catch (_a) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "url", - code: ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } + else if (unknownKeys === "strip") { } - else if (check.kind === "regex") { - check.regex.lastIndex = 0; - const testResult = check.regex.test(input.data); - if (!testResult) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "regex", - code: ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } + else { + throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); } - else if (check.kind === "trim") { - input.data = input.data.trim(); + } + else { + // run catchall validation + const catchall = this._def.catchall; + for (const key of extraKeys) { + const value = ctx.data[key]; + pairs.push({ + key: { status: "valid", value: key }, + value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value) + ), + alwaysSet: key in ctx.data, + }); } - else if (check.kind === "includes") { - if (!input.data.includes(check.value, check.position)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: { includes: check.value, position: check.position }, - message: check.message, + } + if (ctx.common.async) { + return Promise.resolve() + .then(async () => { + const syncPairs = []; + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + syncPairs.push({ + key, + value, + alwaysSet: pair.alwaysSet, }); - status.dirty(); } - } - else if (check.kind === "toLowerCase") { - input.data = input.data.toLowerCase(); - } - else if (check.kind === "toUpperCase") { - input.data = input.data.toUpperCase(); - } - else if (check.kind === "startsWith") { - if (!input.data.startsWith(check.value)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: { startsWith: check.value }, - message: check.message, - }); - status.dirty(); + return syncPairs; + }) + .then((syncPairs) => { + return ParseStatus.mergeObjectSync(status, syncPairs); + }); + } + else { + return ParseStatus.mergeObjectSync(status, pairs); + } + } + get shape() { + return this._def.shape(); + } + strict(message) { + errorUtil.errToObj; + return new ZodObject({ + ...this._def, + unknownKeys: "strict", + ...(message !== undefined + ? { + errorMap: (issue, ctx) => { + const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError; + if (issue.code === "unrecognized_keys") + return { + message: errorUtil.errToObj(message).message ?? defaultError, + }; + return { + message: defaultError, + }; + }, } + : {}), + }); + } + strip() { + return new ZodObject({ + ...this._def, + unknownKeys: "strip", + }); + } + passthrough() { + return new ZodObject({ + ...this._def, + unknownKeys: "passthrough", + }); + } + // const AugmentFactory = + // (def: Def) => + // ( + // augmentation: Augmentation + // ): ZodObject< + // extendShape, Augmentation>, + // Def["unknownKeys"], + // Def["catchall"] + // > => { + // return new ZodObject({ + // ...def, + // shape: () => ({ + // ...def.shape(), + // ...augmentation, + // }), + // }) as any; + // }; + extend(augmentation) { + return new ZodObject({ + ...this._def, + shape: () => ({ + ...this._def.shape(), + ...augmentation, + }), + }); + } + /** + * Prior to zod@1.0.12 there was a bug in the + * inferred type of merged objects. Please + * upgrade if you are experiencing issues. + */ + merge(merging) { + const merged = new ZodObject({ + unknownKeys: merging._def.unknownKeys, + catchall: merging._def.catchall, + shape: () => ({ + ...this._def.shape(), + ...merging._def.shape(), + }), + typeName: ZodFirstPartyTypeKind.ZodObject, + }); + return merged; + } + // merge< + // Incoming extends AnyZodObject, + // Augmentation extends Incoming["shape"], + // NewOutput extends { + // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation + // ? Augmentation[k]["_output"] + // : k extends keyof Output + // ? Output[k] + // : never; + // }, + // NewInput extends { + // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation + // ? Augmentation[k]["_input"] + // : k extends keyof Input + // ? Input[k] + // : never; + // } + // >( + // merging: Incoming + // ): ZodObject< + // extendShape>, + // Incoming["_def"]["unknownKeys"], + // Incoming["_def"]["catchall"], + // NewOutput, + // NewInput + // > { + // const merged: any = new ZodObject({ + // unknownKeys: merging._def.unknownKeys, + // catchall: merging._def.catchall, + // shape: () => + // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), + // typeName: ZodFirstPartyTypeKind.ZodObject, + // }) as any; + // return merged; + // } + setKey(key, schema) { + return this.augment({ [key]: schema }); + } + // merge( + // merging: Incoming + // ): //ZodObject = (merging) => { + // ZodObject< + // extendShape>, + // Incoming["_def"]["unknownKeys"], + // Incoming["_def"]["catchall"] + // > { + // // const mergedShape = objectUtil.mergeShapes( + // // this._def.shape(), + // // merging._def.shape() + // // ); + // const merged: any = new ZodObject({ + // unknownKeys: merging._def.unknownKeys, + // catchall: merging._def.catchall, + // shape: () => + // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), + // typeName: ZodFirstPartyTypeKind.ZodObject, + // }) as any; + // return merged; + // } + catchall(index) { + return new ZodObject({ + ...this._def, + catchall: index, + }); + } + pick(mask) { + const shape = {}; + for (const key of util_util.objectKeys(mask)) { + if (mask[key] && this.shape[key]) { + shape[key] = this.shape[key]; } - else if (check.kind === "endsWith") { - if (!input.data.endsWith(check.value)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: { endsWith: check.value }, - message: check.message, - }); - status.dirty(); - } + } + return new ZodObject({ + ...this._def, + shape: () => shape, + }); + } + omit(mask) { + const shape = {}; + for (const key of util_util.objectKeys(this.shape)) { + if (!mask[key]) { + shape[key] = this.shape[key]; } - else if (check.kind === "datetime") { - const regex = datetimeRegex(check); - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: "datetime", - message: check.message, - }); - status.dirty(); - } + } + return new ZodObject({ + ...this._def, + shape: () => shape, + }); + } + /** + * @deprecated + */ + deepPartial() { + return deepPartialify(this); + } + partial(mask) { + const newShape = {}; + for (const key of util_util.objectKeys(this.shape)) { + const fieldSchema = this.shape[key]; + if (mask && !mask[key]) { + newShape[key] = fieldSchema; } - else if (check.kind === "date") { - const regex = dateRegex; - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: "date", - message: check.message, - }); - status.dirty(); - } + else { + newShape[key] = fieldSchema.optional(); } - else if (check.kind === "time") { - const regex = timeRegex(check); - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: "time", - message: check.message, - }); - status.dirty(); - } + } + return new ZodObject({ + ...this._def, + shape: () => newShape, + }); + } + required(mask) { + const newShape = {}; + for (const key of util_util.objectKeys(this.shape)) { + if (mask && !mask[key]) { + newShape[key] = this.shape[key]; } - else if (check.kind === "duration") { - if (!durationRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "duration", - code: ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); + else { + const fieldSchema = this.shape[key]; + let newField = fieldSchema; + while (newField instanceof ZodOptional) { + newField = newField._def.innerType; } + newShape[key] = newField; } - else if (check.kind === "ip") { - if (!isValidIP(input.data, check.version)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "ip", - code: ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); + } + return new ZodObject({ + ...this._def, + shape: () => newShape, + }); + } + keyof() { + return createZodEnum(util_util.objectKeys(this.shape)); + } +} +ZodObject.create = (shape, params) => { + return new ZodObject({ + shape: () => shape, + unknownKeys: "strip", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params), + }); +}; +ZodObject.strictCreate = (shape, params) => { + return new ZodObject({ + shape: () => shape, + unknownKeys: "strict", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params), + }); +}; +ZodObject.lazycreate = (shape, params) => { + return new ZodObject({ + shape, + unknownKeys: "strip", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params), + }); +}; +class ZodUnion extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + const options = this._def.options; + function handleResults(results) { + // return first issue-free validation if it exists + for (const result of results) { + if (result.result.status === "valid") { + return result.result; } } - else if (check.kind === "jwt") { - if (!isValidJWT(input.data, check.alg)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "jwt", - code: ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); + for (const result of results) { + if (result.result.status === "dirty") { + // add issues from dirty option + ctx.common.issues.push(...result.ctx.common.issues); + return result.result; } } - else if (check.kind === "cidr") { - if (!isValidCidr(input.data, check.version)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "cidr", - code: ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); + // return invalid + const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues)); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_union, + unionErrors, + }); + return INVALID; + } + if (ctx.common.async) { + return Promise.all(options.map(async (option) => { + const childCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [], + }, + parent: null, + }; + return { + result: await option._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: childCtx, + }), + ctx: childCtx, + }; + })).then(handleResults); + } + else { + let dirty = undefined; + const issues = []; + for (const option of options) { + const childCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [], + }, + parent: null, + }; + const result = option._parseSync({ + data: ctx.data, + path: ctx.path, + parent: childCtx, + }); + if (result.status === "valid") { + return result; } - } - else if (check.kind === "base64") { - if (!base64Regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "base64", - code: ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); + else if (result.status === "dirty" && !dirty) { + dirty = { result, ctx: childCtx }; } - } - else if (check.kind === "base64url") { - if (!base64urlRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "base64url", - code: ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); + if (childCtx.common.issues.length) { + issues.push(childCtx.common.issues); } } - else { - util.assertNever(check); + if (dirty) { + ctx.common.issues.push(...dirty.ctx.common.issues); + return dirty.result; } + const unionErrors = issues.map((issues) => new ZodError(issues)); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_union, + unionErrors, + }); + return INVALID; } - return { status: status.value, value: input.data }; } - _regex(regex, validation, message) { - return this.refinement((data) => regex.test(data), { - validation, - code: ZodIssueCode.invalid_string, - ...errorUtil.errToObj(message), - }); + get options() { + return this._def.options; } - _addCheck(check) { - return new ZodString({ - ...this._def, - checks: [...this._def.checks, check], - }); +} +ZodUnion.create = (types, params) => { + return new ZodUnion({ + options: types, + typeName: ZodFirstPartyTypeKind.ZodUnion, + ...processCreateParams(params), + }); +}; +///////////////////////////////////////////////////// +///////////////////////////////////////////////////// +////////// ////////// +////////// ZodDiscriminatedUnion ////////// +////////// ////////// +///////////////////////////////////////////////////// +///////////////////////////////////////////////////// +const getDiscriminator = (type) => { + if (type instanceof ZodLazy) { + return getDiscriminator(type.schema); } - email(message) { - return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) }); + else if (type instanceof ZodEffects) { + return getDiscriminator(type.innerType()); } - url(message) { - return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) }); + else if (type instanceof ZodLiteral) { + return [type.value]; } - emoji(message) { - return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) }); + else if (type instanceof ZodEnum) { + return type.options; } - uuid(message) { - return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) }); + else if (type instanceof ZodNativeEnum) { + // eslint-disable-next-line ban/ban + return util_util.objectValues(type.enum); } - nanoid(message) { - return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) }); + else if (type instanceof ZodDefault) { + return getDiscriminator(type._def.innerType); } - cuid(message) { - return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) }); + else if (type instanceof ZodUndefined) { + return [undefined]; } - cuid2(message) { - return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) }); + else if (type instanceof ZodNull) { + return [null]; } - ulid(message) { - return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) }); + else if (type instanceof ZodOptional) { + return [undefined, ...getDiscriminator(type.unwrap())]; + } + else if (type instanceof ZodNullable) { + return [null, ...getDiscriminator(type.unwrap())]; + } + else if (type instanceof ZodBranded) { + return getDiscriminator(type.unwrap()); + } + else if (type instanceof ZodReadonly) { + return getDiscriminator(type.unwrap()); + } + else if (type instanceof ZodCatch) { + return getDiscriminator(type._def.innerType); + } + else { + return []; + } +}; +class ZodDiscriminatedUnion extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.object) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ctx.parsedType, + }); + return INVALID; + } + const discriminator = this.discriminator; + const discriminatorValue = ctx.data[discriminator]; + const option = this.optionsMap.get(discriminatorValue); + if (!option) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_union_discriminator, + options: Array.from(this.optionsMap.keys()), + path: [discriminator], + }); + return INVALID; + } + if (ctx.common.async) { + return option._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + } + else { + return option._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + } + } + get discriminator() { + return this._def.discriminator; + } + get options() { + return this._def.options; + } + get optionsMap() { + return this._def.optionsMap; + } + /** + * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor. + * However, it only allows a union of objects, all of which need to share a discriminator property. This property must + * have a different value for each object in the union. + * @param discriminator the name of the discriminator property + * @param types an array of object schemas + * @param params + */ + static create(discriminator, options, params) { + // Get all the valid discriminator values + const optionsMap = new Map(); + // try { + for (const type of options) { + const discriminatorValues = getDiscriminator(type.shape[discriminator]); + if (!discriminatorValues.length) { + throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); + } + for (const value of discriminatorValues) { + if (optionsMap.has(value)) { + throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); + } + optionsMap.set(value, type); + } + } + return new ZodDiscriminatedUnion({ + typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion, + discriminator, + options, + optionsMap, + ...processCreateParams(params), + }); + } +} +function mergeValues(a, b) { + const aType = getParsedType(a); + const bType = getParsedType(b); + if (a === b) { + return { valid: true, data: a }; + } + else if (aType === ZodParsedType.object && bType === ZodParsedType.object) { + const bKeys = util_util.objectKeys(b); + const sharedKeys = util_util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1); + const newObj = { ...a, ...b }; + for (const key of sharedKeys) { + const sharedValue = mergeValues(a[key], b[key]); + if (!sharedValue.valid) { + return { valid: false }; + } + newObj[key] = sharedValue.data; + } + return { valid: true, data: newObj }; + } + else if (aType === ZodParsedType.array && bType === ZodParsedType.array) { + if (a.length !== b.length) { + return { valid: false }; + } + const newArray = []; + for (let index = 0; index < a.length; index++) { + const itemA = a[index]; + const itemB = b[index]; + const sharedValue = mergeValues(itemA, itemB); + if (!sharedValue.valid) { + return { valid: false }; + } + newArray.push(sharedValue.data); + } + return { valid: true, data: newArray }; + } + else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) { + return { valid: true, data: a }; + } + else { + return { valid: false }; + } +} +class ZodIntersection extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + const handleParsed = (parsedLeft, parsedRight) => { + if (isAborted(parsedLeft) || isAborted(parsedRight)) { + return INVALID; + } + const merged = mergeValues(parsedLeft.value, parsedRight.value); + if (!merged.valid) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_intersection_types, + }); + return INVALID; + } + if (isDirty(parsedLeft) || isDirty(parsedRight)) { + status.dirty(); + } + return { status: status.value, value: merged.data }; + }; + if (ctx.common.async) { + return Promise.all([ + this._def.left._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }), + this._def.right._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }), + ]).then(([left, right]) => handleParsed(left, right)); + } + else { + return handleParsed(this._def.left._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }), this._def.right._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + })); + } + } +} +ZodIntersection.create = (left, right, params) => { + return new ZodIntersection({ + left: left, + right: right, + typeName: ZodFirstPartyTypeKind.ZodIntersection, + ...processCreateParams(params), + }); +}; +// type ZodTupleItems = [ZodTypeAny, ...ZodTypeAny[]]; +class ZodTuple extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.array) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.array, + received: ctx.parsedType, + }); + return INVALID; + } + if (ctx.data.length < this._def.items.length) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: this._def.items.length, + inclusive: true, + exact: false, + type: "array", + }); + return INVALID; + } + const rest = this._def.rest; + if (!rest && ctx.data.length > this._def.items.length) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: this._def.items.length, + inclusive: true, + exact: false, + type: "array", + }); + status.dirty(); + } + const items = [...ctx.data] + .map((item, itemIndex) => { + const schema = this._def.items[itemIndex] || this._def.rest; + if (!schema) + return null; + return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)); + }) + .filter((x) => !!x); // filter nulls + if (ctx.common.async) { + return Promise.all(items).then((results) => { + return ParseStatus.mergeArray(status, results); + }); + } + else { + return ParseStatus.mergeArray(status, items); + } } - base64(message) { - return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) }); + get items() { + return this._def.items; } - base64url(message) { - // base64url encoding is a modification of base64 that can safely be used in URLs and filenames - return this._addCheck({ - kind: "base64url", - ...errorUtil.errToObj(message), + rest(rest) { + return new ZodTuple({ + ...this._def, + rest, }); } - jwt(options) { - return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) }); +} +ZodTuple.create = (schemas, params) => { + if (!Array.isArray(schemas)) { + throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); } - ip(options) { - return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) }); + return new ZodTuple({ + items: schemas, + typeName: ZodFirstPartyTypeKind.ZodTuple, + rest: null, + ...processCreateParams(params), + }); +}; +class ZodRecord extends ZodType { + get keySchema() { + return this._def.keyType; } - cidr(options) { - return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) }); + get valueSchema() { + return this._def.valueType; } - datetime(options) { - var _a, _b; - if (typeof options === "string") { - return this._addCheck({ - kind: "datetime", - precision: null, - offset: false, - local: false, - message: options, + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.object) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ctx.parsedType, }); + return INVALID; + } + const pairs = []; + const keyType = this._def.keyType; + const valueType = this._def.valueType; + for (const key in ctx.data) { + pairs.push({ + key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)), + value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)), + alwaysSet: key in ctx.data, + }); + } + if (ctx.common.async) { + return ParseStatus.mergeObjectAsync(status, pairs); + } + else { + return ParseStatus.mergeObjectSync(status, pairs); } - return this._addCheck({ - kind: "datetime", - precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision, - offset: (_a = options === null || options === void 0 ? void 0 : options.offset) !== null && _a !== void 0 ? _a : false, - local: (_b = options === null || options === void 0 ? void 0 : options.local) !== null && _b !== void 0 ? _b : false, - ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message), - }); } - date(message) { - return this._addCheck({ kind: "date", message }); + get element() { + return this._def.valueType; } - time(options) { - if (typeof options === "string") { - return this._addCheck({ - kind: "time", - precision: null, - message: options, + static create(first, second, third) { + if (second instanceof ZodType) { + return new ZodRecord({ + keyType: first, + valueType: second, + typeName: ZodFirstPartyTypeKind.ZodRecord, + ...processCreateParams(third), }); } - return this._addCheck({ - kind: "time", - precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision, - ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message), + return new ZodRecord({ + keyType: ZodString.create(), + valueType: first, + typeName: ZodFirstPartyTypeKind.ZodRecord, + ...processCreateParams(second), }); } - duration(message) { - return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) }); - } - regex(regex, message) { - return this._addCheck({ - kind: "regex", - regex: regex, - ...errorUtil.errToObj(message), - }); +} +class ZodMap extends ZodType { + get keySchema() { + return this._def.keyType; } - includes(value, options) { - return this._addCheck({ - kind: "includes", - value: value, - position: options === null || options === void 0 ? void 0 : options.position, - ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message), - }); + get valueSchema() { + return this._def.valueType; } - startsWith(value, message) { - return this._addCheck({ - kind: "startsWith", - value: value, - ...errorUtil.errToObj(message), + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.map) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.map, + received: ctx.parsedType, + }); + return INVALID; + } + const keyType = this._def.keyType; + const valueType = this._def.valueType; + const pairs = [...ctx.data.entries()].map(([key, value], index) => { + return { + key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])), + value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])), + }; }); + if (ctx.common.async) { + const finalMap = new Map(); + return Promise.resolve().then(async () => { + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + if (key.status === "aborted" || value.status === "aborted") { + return INVALID; + } + if (key.status === "dirty" || value.status === "dirty") { + status.dirty(); + } + finalMap.set(key.value, value.value); + } + return { status: status.value, value: finalMap }; + }); + } + else { + const finalMap = new Map(); + for (const pair of pairs) { + const key = pair.key; + const value = pair.value; + if (key.status === "aborted" || value.status === "aborted") { + return INVALID; + } + if (key.status === "dirty" || value.status === "dirty") { + status.dirty(); + } + finalMap.set(key.value, value.value); + } + return { status: status.value, value: finalMap }; + } } - endsWith(value, message) { - return this._addCheck({ - kind: "endsWith", - value: value, - ...errorUtil.errToObj(message), - }); +} +ZodMap.create = (keyType, valueType, params) => { + return new ZodMap({ + valueType, + keyType, + typeName: ZodFirstPartyTypeKind.ZodMap, + ...processCreateParams(params), + }); +}; +class ZodSet extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.set) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.set, + received: ctx.parsedType, + }); + return INVALID; + } + const def = this._def; + if (def.minSize !== null) { + if (ctx.data.size < def.minSize.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: def.minSize.value, + type: "set", + inclusive: true, + exact: false, + message: def.minSize.message, + }); + status.dirty(); + } + } + if (def.maxSize !== null) { + if (ctx.data.size > def.maxSize.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: def.maxSize.value, + type: "set", + inclusive: true, + exact: false, + message: def.maxSize.message, + }); + status.dirty(); + } + } + const valueType = this._def.valueType; + function finalizeSet(elements) { + const parsedSet = new Set(); + for (const element of elements) { + if (element.status === "aborted") + return INVALID; + if (element.status === "dirty") + status.dirty(); + parsedSet.add(element.value); + } + return { status: status.value, value: parsedSet }; + } + const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i))); + if (ctx.common.async) { + return Promise.all(elements).then((elements) => finalizeSet(elements)); + } + else { + return finalizeSet(elements); + } } - min(minLength, message) { - return this._addCheck({ - kind: "min", - value: minLength, - ...errorUtil.errToObj(message), + min(minSize, message) { + return new ZodSet({ + ...this._def, + minSize: { value: minSize, message: errorUtil.toString(message) }, }); } - max(maxLength, message) { - return this._addCheck({ - kind: "max", - value: maxLength, - ...errorUtil.errToObj(message), + max(maxSize, message) { + return new ZodSet({ + ...this._def, + maxSize: { value: maxSize, message: errorUtil.toString(message) }, }); } - length(len, message) { - return this._addCheck({ - kind: "length", - value: len, - ...errorUtil.errToObj(message), - }); + size(size, message) { + return this.min(size, message).max(size, message); } - /** - * Equivalent to `.min(1)` - */ nonempty(message) { - return this.min(1, errorUtil.errToObj(message)); + return this.min(1, message); } - trim() { - return new ZodString({ - ...this._def, - checks: [...this._def.checks, { kind: "trim" }], - }); +} +ZodSet.create = (valueType, params) => { + return new ZodSet({ + valueType, + minSize: null, + maxSize: null, + typeName: ZodFirstPartyTypeKind.ZodSet, + ...processCreateParams(params), + }); +}; +class ZodFunction extends ZodType { + constructor() { + super(...arguments); + this.validate = this.implement; } - toLowerCase() { - return new ZodString({ + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.function) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.function, + received: ctx.parsedType, + }); + return INVALID; + } + function makeArgsIssue(args, error) { + return makeIssue({ + data: args, + path: ctx.path, + errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en].filter((x) => !!x), + issueData: { + code: ZodIssueCode.invalid_arguments, + argumentsError: error, + }, + }); + } + function makeReturnsIssue(returns, error) { + return makeIssue({ + data: returns, + path: ctx.path, + errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en].filter((x) => !!x), + issueData: { + code: ZodIssueCode.invalid_return_type, + returnTypeError: error, + }, + }); + } + const params = { errorMap: ctx.common.contextualErrorMap }; + const fn = ctx.data; + if (this._def.returns instanceof ZodPromise) { + // Would love a way to avoid disabling this rule, but we need + // an alias (using an arrow function was what caused 2651). + // eslint-disable-next-line @typescript-eslint/no-this-alias + const me = this; + return OK(async function (...args) { + const error = new ZodError([]); + const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => { + error.addIssue(makeArgsIssue(args, e)); + throw error; + }); + const result = await Reflect.apply(fn, this, parsedArgs); + const parsedReturns = await me._def.returns._def.type + .parseAsync(result, params) + .catch((e) => { + error.addIssue(makeReturnsIssue(result, e)); + throw error; + }); + return parsedReturns; + }); + } + else { + // Would love a way to avoid disabling this rule, but we need + // an alias (using an arrow function was what caused 2651). + // eslint-disable-next-line @typescript-eslint/no-this-alias + const me = this; + return OK(function (...args) { + const parsedArgs = me._def.args.safeParse(args, params); + if (!parsedArgs.success) { + throw new ZodError([makeArgsIssue(args, parsedArgs.error)]); + } + const result = Reflect.apply(fn, this, parsedArgs.data); + const parsedReturns = me._def.returns.safeParse(result, params); + if (!parsedReturns.success) { + throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]); + } + return parsedReturns.data; + }); + } + } + parameters() { + return this._def.args; + } + returnType() { + return this._def.returns; + } + args(...items) { + return new ZodFunction({ ...this._def, - checks: [...this._def.checks, { kind: "toLowerCase" }], + args: ZodTuple.create(items).rest(ZodUnknown.create()), }); } - toUpperCase() { - return new ZodString({ + returns(returnType) { + return new ZodFunction({ ...this._def, - checks: [...this._def.checks, { kind: "toUpperCase" }], + returns: returnType, }); } - get isDatetime() { - return !!this._def.checks.find((ch) => ch.kind === "datetime"); - } - get isDate() { - return !!this._def.checks.find((ch) => ch.kind === "date"); - } - get isTime() { - return !!this._def.checks.find((ch) => ch.kind === "time"); + implement(func) { + const validatedFunc = this.parse(func); + return validatedFunc; } - get isDuration() { - return !!this._def.checks.find((ch) => ch.kind === "duration"); + strictImplement(func) { + const validatedFunc = this.parse(func); + return validatedFunc; } - get isEmail() { - return !!this._def.checks.find((ch) => ch.kind === "email"); + static create(args, returns, params) { + return new ZodFunction({ + args: (args ? args : ZodTuple.create([]).rest(ZodUnknown.create())), + returns: returns || ZodUnknown.create(), + typeName: ZodFirstPartyTypeKind.ZodFunction, + ...processCreateParams(params), + }); } - get isURL() { - return !!this._def.checks.find((ch) => ch.kind === "url"); +} +class ZodLazy extends ZodType { + get schema() { + return this._def.getter(); } - get isEmoji() { - return !!this._def.checks.find((ch) => ch.kind === "emoji"); + _parse(input) { + const { ctx } = this._processInputParams(input); + const lazySchema = this._def.getter(); + return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); } - get isUUID() { - return !!this._def.checks.find((ch) => ch.kind === "uuid"); +} +ZodLazy.create = (getter, params) => { + return new ZodLazy({ + getter: getter, + typeName: ZodFirstPartyTypeKind.ZodLazy, + ...processCreateParams(params), + }); +}; +class ZodLiteral extends ZodType { + _parse(input) { + if (input.data !== this._def.value) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode.invalid_literal, + expected: this._def.value, + }); + return INVALID; + } + return { status: "valid", value: input.data }; } - get isNANOID() { - return !!this._def.checks.find((ch) => ch.kind === "nanoid"); + get value() { + return this._def.value; } - get isCUID() { - return !!this._def.checks.find((ch) => ch.kind === "cuid"); +} +ZodLiteral.create = (value, params) => { + return new ZodLiteral({ + value: value, + typeName: ZodFirstPartyTypeKind.ZodLiteral, + ...processCreateParams(params), + }); +}; +function createZodEnum(values, params) { + return new ZodEnum({ + values, + typeName: ZodFirstPartyTypeKind.ZodEnum, + ...processCreateParams(params), + }); +} +class ZodEnum extends ZodType { + _parse(input) { + if (typeof input.data !== "string") { + const ctx = this._getOrReturnCtx(input); + const expectedValues = this._def.values; + addIssueToContext(ctx, { + expected: util_util.joinValues(expectedValues), + received: ctx.parsedType, + code: ZodIssueCode.invalid_type, + }); + return INVALID; + } + if (!this._cache) { + this._cache = new Set(this._def.values); + } + if (!this._cache.has(input.data)) { + const ctx = this._getOrReturnCtx(input); + const expectedValues = this._def.values; + addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode.invalid_enum_value, + options: expectedValues, + }); + return INVALID; + } + return OK(input.data); } - get isCUID2() { - return !!this._def.checks.find((ch) => ch.kind === "cuid2"); + get options() { + return this._def.values; } - get isULID() { - return !!this._def.checks.find((ch) => ch.kind === "ulid"); + get enum() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues; } - get isIP() { - return !!this._def.checks.find((ch) => ch.kind === "ip"); + get Values() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues; } - get isCIDR() { - return !!this._def.checks.find((ch) => ch.kind === "cidr"); + get Enum() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues; } - get isBase64() { - return !!this._def.checks.find((ch) => ch.kind === "base64"); + extract(values, newDef = this._def) { + return ZodEnum.create(values, { + ...this._def, + ...newDef, + }); } - get isBase64url() { - // base64url encoding is a modification of base64 that can safely be used in URLs and filenames - return !!this._def.checks.find((ch) => ch.kind === "base64url"); + exclude(values, newDef = this._def) { + return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), { + ...this._def, + ...newDef, + }); } - get minLength() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } +} +ZodEnum.create = createZodEnum; +class ZodNativeEnum extends ZodType { + _parse(input) { + const nativeEnumValues = util_util.getValidEnumValues(this._def.values); + const ctx = this._getOrReturnCtx(input); + if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) { + const expectedValues = util_util.objectValues(nativeEnumValues); + addIssueToContext(ctx, { + expected: util_util.joinValues(expectedValues), + received: ctx.parsedType, + code: ZodIssueCode.invalid_type, + }); + return INVALID; } - return min; - } - get maxLength() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } + if (!this._cache) { + this._cache = new Set(util_util.getValidEnumValues(this._def.values)); } - return max; + if (!this._cache.has(input.data)) { + const expectedValues = util_util.objectValues(nativeEnumValues); + addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode.invalid_enum_value, + options: expectedValues, + }); + return INVALID; + } + return OK(input.data); + } + get enum() { + return this._def.values; } } -ZodString.create = (params) => { - var _a; - return new ZodString({ - checks: [], - typeName: ZodFirstPartyTypeKind.ZodString, - coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false, +ZodNativeEnum.create = (values, params) => { + return new ZodNativeEnum({ + values: values, + typeName: ZodFirstPartyTypeKind.ZodNativeEnum, ...processCreateParams(params), }); }; -// https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034 -function floatSafeRemainder(val, step) { - const valDecCount = (val.toString().split(".")[1] || "").length; - const stepDecCount = (step.toString().split(".")[1] || "").length; - const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; - const valInt = parseInt(val.toFixed(decCount).replace(".", "")); - const stepInt = parseInt(step.toFixed(decCount).replace(".", "")); - return (valInt % stepInt) / Math.pow(10, decCount); -} -class ZodNumber extends ZodType { - constructor() { - super(...arguments); - this.min = this.gte; - this.max = this.lte; - this.step = this.multipleOf; +class ZodPromise extends ZodType { + unwrap() { + return this._def.type; } _parse(input) { - if (this._def.coerce) { - input.data = Number(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.number) { - const ctx = this._getOrReturnCtx(input); + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, - expected: ZodParsedType.number, + expected: ZodParsedType.promise, received: ctx.parsedType, }); return INVALID; } - let ctx = undefined; - const status = new ParseStatus(); - for (const check of this._def.checks) { - if (check.kind === "int") { - if (!util.isInteger(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: "integer", - received: "float", - message: check.message, - }); - status.dirty(); + const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data); + return OK(promisified.then((data) => { + return this._def.type.parseAsync(data, { + path: ctx.path, + errorMap: ctx.common.contextualErrorMap, + }); + })); + } +} +ZodPromise.create = (schema, params) => { + return new ZodPromise({ + type: schema, + typeName: ZodFirstPartyTypeKind.ZodPromise, + ...processCreateParams(params), + }); +}; +class ZodEffects extends ZodType { + innerType() { + return this._def.schema; + } + sourceType() { + return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects + ? this._def.schema.sourceType() + : this._def.schema; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + const effect = this._def.effect || null; + const checkCtx = { + addIssue: (arg) => { + addIssueToContext(ctx, arg); + if (arg.fatal) { + status.abort(); } - } - else if (check.kind === "min") { - const tooSmall = check.inclusive - ? input.data < check.value - : input.data <= check.value; - if (tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: check.value, - type: "number", - inclusive: check.inclusive, - exact: false, - message: check.message, - }); + else { status.dirty(); } - } - else if (check.kind === "max") { - const tooBig = check.inclusive - ? input.data > check.value - : input.data >= check.value; - if (tooBig) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: check.value, - type: "number", - inclusive: check.inclusive, - exact: false, - message: check.message, + }, + get path() { + return ctx.path; + }, + }; + checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); + if (effect.type === "preprocess") { + const processed = effect.transform(ctx.data, checkCtx); + if (ctx.common.async) { + return Promise.resolve(processed).then(async (processed) => { + if (status.value === "aborted") + return INVALID; + const result = await this._def.schema._parseAsync({ + data: processed, + path: ctx.path, + parent: ctx, }); - status.dirty(); - } + if (result.status === "aborted") + return INVALID; + if (result.status === "dirty") + return DIRTY(result.value); + if (status.value === "dirty") + return DIRTY(result.value); + return result; + }); } - else if (check.kind === "multipleOf") { - if (floatSafeRemainder(input.data, check.value) !== 0) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.not_multiple_of, - multipleOf: check.value, - message: check.message, - }); - status.dirty(); + else { + if (status.value === "aborted") + return INVALID; + const result = this._def.schema._parseSync({ + data: processed, + path: ctx.path, + parent: ctx, + }); + if (result.status === "aborted") + return INVALID; + if (result.status === "dirty") + return DIRTY(result.value); + if (status.value === "dirty") + return DIRTY(result.value); + return result; + } + } + if (effect.type === "refinement") { + const executeRefinement = (acc) => { + const result = effect.refinement(acc, checkCtx); + if (ctx.common.async) { + return Promise.resolve(result); + } + if (result instanceof Promise) { + throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); } + return acc; + }; + if (ctx.common.async === false) { + const inner = this._def.schema._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + if (inner.status === "aborted") + return INVALID; + if (inner.status === "dirty") + status.dirty(); + // return value is ignored + executeRefinement(inner.value); + return { status: status.value, value: inner.value }; } - else if (check.kind === "finite") { - if (!Number.isFinite(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.not_finite, - message: check.message, + else { + return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => { + if (inner.status === "aborted") + return INVALID; + if (inner.status === "dirty") + status.dirty(); + return executeRefinement(inner.value).then(() => { + return { status: status.value, value: inner.value }; }); - status.dirty(); + }); + } + } + if (effect.type === "transform") { + if (ctx.common.async === false) { + const base = this._def.schema._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + if (!isValid(base)) + return INVALID; + const result = effect.transform(base.value, checkCtx); + if (result instanceof Promise) { + throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); } + return { status: status.value, value: result }; } else { - util.assertNever(check); + return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => { + if (!isValid(base)) + return INVALID; + return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ + status: status.value, + value: result, + })); + }); } } - return { status: status.value, value: input.data }; - } - gte(value, message) { - return this.setLimit("min", value, true, errorUtil.toString(message)); - } - gt(value, message) { - return this.setLimit("min", value, false, errorUtil.toString(message)); - } - lte(value, message) { - return this.setLimit("max", value, true, errorUtil.toString(message)); - } - lt(value, message) { - return this.setLimit("max", value, false, errorUtil.toString(message)); - } - setLimit(kind, value, inclusive, message) { - return new ZodNumber({ - ...this._def, - checks: [ - ...this._def.checks, - { - kind, - value, - inclusive, - message: errorUtil.toString(message), - }, - ], - }); - } - _addCheck(check) { - return new ZodNumber({ - ...this._def, - checks: [...this._def.checks, check], - }); - } - int(message) { - return this._addCheck({ - kind: "int", - message: errorUtil.toString(message), - }); + util_util.assertNever(effect); } - positive(message) { - return this._addCheck({ - kind: "min", - value: 0, - inclusive: false, - message: errorUtil.toString(message), - }); +} +ZodEffects.create = (schema, effect, params) => { + return new ZodEffects({ + schema, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect, + ...processCreateParams(params), + }); +}; +ZodEffects.createWithPreprocess = (preprocess, schema, params) => { + return new ZodEffects({ + schema, + effect: { type: "preprocess", transform: preprocess }, + typeName: ZodFirstPartyTypeKind.ZodEffects, + ...processCreateParams(params), + }); +}; + +class ZodOptional extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType === ZodParsedType.undefined) { + return OK(undefined); + } + return this._def.innerType._parse(input); } - negative(message) { - return this._addCheck({ - kind: "max", - value: 0, - inclusive: false, - message: errorUtil.toString(message), - }); + unwrap() { + return this._def.innerType; } - nonpositive(message) { - return this._addCheck({ - kind: "max", - value: 0, - inclusive: true, - message: errorUtil.toString(message), - }); +} +ZodOptional.create = (type, params) => { + return new ZodOptional({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodOptional, + ...processCreateParams(params), + }); +}; +class ZodNullable extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType === ZodParsedType.null) { + return OK(null); + } + return this._def.innerType._parse(input); } - nonnegative(message) { - return this._addCheck({ - kind: "min", - value: 0, - inclusive: true, - message: errorUtil.toString(message), - }); + unwrap() { + return this._def.innerType; } - multipleOf(value, message) { - return this._addCheck({ - kind: "multipleOf", - value: value, - message: errorUtil.toString(message), +} +ZodNullable.create = (type, params) => { + return new ZodNullable({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodNullable, + ...processCreateParams(params), + }); +}; +class ZodDefault extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + let data = ctx.data; + if (ctx.parsedType === ZodParsedType.undefined) { + data = this._def.defaultValue(); + } + return this._def.innerType._parse({ + data, + path: ctx.path, + parent: ctx, }); } - finite(message) { - return this._addCheck({ - kind: "finite", - message: errorUtil.toString(message), - }); + removeDefault() { + return this._def.innerType; } - safe(message) { - return this._addCheck({ - kind: "min", - inclusive: true, - value: Number.MIN_SAFE_INTEGER, - message: errorUtil.toString(message), - })._addCheck({ - kind: "max", - inclusive: true, - value: Number.MAX_SAFE_INTEGER, - message: errorUtil.toString(message), +} +ZodDefault.create = (type, params) => { + return new ZodDefault({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodDefault, + defaultValue: typeof params.default === "function" ? params.default : () => params.default, + ...processCreateParams(params), + }); +}; +class ZodCatch extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + // newCtx is used to not collect issues from inner types in ctx + const newCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [], + }, + }; + const result = this._def.innerType._parse({ + data: newCtx.data, + path: newCtx.path, + parent: { + ...newCtx, + }, }); - } - get minValue() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } + if (isAsync(result)) { + return result.then((result) => { + return { + status: "valid", + value: result.status === "valid" + ? result.value + : this._def.catchValue({ + get error() { + return new ZodError(newCtx.common.issues); + }, + input: newCtx.data, + }), + }; + }); } - return min; - } - get maxValue() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } + else { + return { + status: "valid", + value: result.status === "valid" + ? result.value + : this._def.catchValue({ + get error() { + return new ZodError(newCtx.common.issues); + }, + input: newCtx.data, + }), + }; } - return max; } - get isInt() { - return !!this._def.checks.find((ch) => ch.kind === "int" || - (ch.kind === "multipleOf" && util.isInteger(ch.value))); + removeCatch() { + return this._def.innerType; } - get isFinite() { - let max = null, min = null; - for (const ch of this._def.checks) { - if (ch.kind === "finite" || - ch.kind === "int" || - ch.kind === "multipleOf") { - return true; - } - else if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - else if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } +} +ZodCatch.create = (type, params) => { + return new ZodCatch({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodCatch, + catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, + ...processCreateParams(params), + }); +}; +class ZodNaN extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.nan) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.nan, + received: ctx.parsedType, + }); + return INVALID; } - return Number.isFinite(min) && Number.isFinite(max); + return { status: "valid", value: input.data }; } } -ZodNumber.create = (params) => { - return new ZodNumber({ - checks: [], - typeName: ZodFirstPartyTypeKind.ZodNumber, - coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, +ZodNaN.create = (params) => { + return new ZodNaN({ + typeName: ZodFirstPartyTypeKind.ZodNaN, ...processCreateParams(params), }); }; -class ZodBigInt extends ZodType { - constructor() { - super(...arguments); - this.min = this.gte; - this.max = this.lte; +const BRAND = Symbol("zod_brand"); +class ZodBranded extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + const data = ctx.data; + return this._def.type._parse({ + data, + path: ctx.path, + parent: ctx, + }); } + unwrap() { + return this._def.type; + } +} +class ZodPipeline extends ZodType { _parse(input) { - if (this._def.coerce) { - try { - input.data = BigInt(input.data); - } - catch (_a) { - return this._getInvalidInput(input); - } - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.bigint) { - return this._getInvalidInput(input); - } - let ctx = undefined; - const status = new ParseStatus(); - for (const check of this._def.checks) { - if (check.kind === "min") { - const tooSmall = check.inclusive - ? input.data < check.value - : input.data <= check.value; - if (tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - type: "bigint", - minimum: check.value, - inclusive: check.inclusive, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "max") { - const tooBig = check.inclusive - ? input.data > check.value - : input.data >= check.value; - if (tooBig) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - type: "bigint", - maximum: check.value, - inclusive: check.inclusive, - message: check.message, - }); + const { status, ctx } = this._processInputParams(input); + if (ctx.common.async) { + const handleAsync = async () => { + const inResult = await this._def.in._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + if (inResult.status === "aborted") + return INVALID; + if (inResult.status === "dirty") { status.dirty(); + return DIRTY(inResult.value); } - } - else if (check.kind === "multipleOf") { - if (input.data % check.value !== BigInt(0)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.not_multiple_of, - multipleOf: check.value, - message: check.message, + else { + return this._def.out._parseAsync({ + data: inResult.value, + path: ctx.path, + parent: ctx, }); - status.dirty(); } + }; + return handleAsync(); + } + else { + const inResult = this._def.in._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + if (inResult.status === "aborted") + return INVALID; + if (inResult.status === "dirty") { + status.dirty(); + return { + status: "dirty", + value: inResult.value, + }; } else { - util.assertNever(check); + return this._def.out._parseSync({ + data: inResult.value, + path: ctx.path, + parent: ctx, + }); } } - return { status: status.value, value: input.data }; } - _getInvalidInput(input) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.bigint, - received: ctx.parsedType, + static create(a, b) { + return new ZodPipeline({ + in: a, + out: b, + typeName: ZodFirstPartyTypeKind.ZodPipeline, }); - return INVALID; - } - gte(value, message) { - return this.setLimit("min", value, true, errorUtil.toString(message)); - } - gt(value, message) { - return this.setLimit("min", value, false, errorUtil.toString(message)); } - lte(value, message) { - return this.setLimit("max", value, true, errorUtil.toString(message)); +} +class ZodReadonly extends ZodType { + _parse(input) { + const result = this._def.innerType._parse(input); + const freeze = (data) => { + if (isValid(data)) { + data.value = Object.freeze(data.value); + } + return data; + }; + return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result); } - lt(value, message) { - return this.setLimit("max", value, false, errorUtil.toString(message)); + unwrap() { + return this._def.innerType; } - setLimit(kind, value, inclusive, message) { - return new ZodBigInt({ - ...this._def, - checks: [ - ...this._def.checks, - { - kind, - value, - inclusive, - message: errorUtil.toString(message), - }, - ], +} +ZodReadonly.create = (type, params) => { + return new ZodReadonly({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodReadonly, + ...processCreateParams(params), + }); +}; +//////////////////////////////////////// +//////////////////////////////////////// +////////// ////////// +////////// z.custom ////////// +////////// ////////// +//////////////////////////////////////// +//////////////////////////////////////// +function cleanParams(params, data) { + const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params; + const p2 = typeof p === "string" ? { message: p } : p; + return p2; +} +function custom(check, _params = {}, +/** + * @deprecated + * + * Pass `fatal` into the params object instead: + * + * ```ts + * z.string().custom((val) => val.length > 5, { fatal: false }) + * ``` + * + */ +fatal) { + if (check) + return ZodAny.create().superRefine((data, ctx) => { + const r = check(data); + if (r instanceof Promise) { + return r.then((r) => { + if (!r) { + const params = cleanParams(_params, data); + const _fatal = params.fatal ?? fatal ?? true; + ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); + } + }); + } + if (!r) { + const params = cleanParams(_params, data); + const _fatal = params.fatal ?? fatal ?? true; + ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); + } + return; }); + return ZodAny.create(); +} + +const late = { + object: ZodObject.lazycreate, +}; +var ZodFirstPartyTypeKind; +(function (ZodFirstPartyTypeKind) { + ZodFirstPartyTypeKind["ZodString"] = "ZodString"; + ZodFirstPartyTypeKind["ZodNumber"] = "ZodNumber"; + ZodFirstPartyTypeKind["ZodNaN"] = "ZodNaN"; + ZodFirstPartyTypeKind["ZodBigInt"] = "ZodBigInt"; + ZodFirstPartyTypeKind["ZodBoolean"] = "ZodBoolean"; + ZodFirstPartyTypeKind["ZodDate"] = "ZodDate"; + ZodFirstPartyTypeKind["ZodSymbol"] = "ZodSymbol"; + ZodFirstPartyTypeKind["ZodUndefined"] = "ZodUndefined"; + ZodFirstPartyTypeKind["ZodNull"] = "ZodNull"; + ZodFirstPartyTypeKind["ZodAny"] = "ZodAny"; + ZodFirstPartyTypeKind["ZodUnknown"] = "ZodUnknown"; + ZodFirstPartyTypeKind["ZodNever"] = "ZodNever"; + ZodFirstPartyTypeKind["ZodVoid"] = "ZodVoid"; + ZodFirstPartyTypeKind["ZodArray"] = "ZodArray"; + ZodFirstPartyTypeKind["ZodObject"] = "ZodObject"; + ZodFirstPartyTypeKind["ZodUnion"] = "ZodUnion"; + ZodFirstPartyTypeKind["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; + ZodFirstPartyTypeKind["ZodIntersection"] = "ZodIntersection"; + ZodFirstPartyTypeKind["ZodTuple"] = "ZodTuple"; + ZodFirstPartyTypeKind["ZodRecord"] = "ZodRecord"; + ZodFirstPartyTypeKind["ZodMap"] = "ZodMap"; + ZodFirstPartyTypeKind["ZodSet"] = "ZodSet"; + ZodFirstPartyTypeKind["ZodFunction"] = "ZodFunction"; + ZodFirstPartyTypeKind["ZodLazy"] = "ZodLazy"; + ZodFirstPartyTypeKind["ZodLiteral"] = "ZodLiteral"; + ZodFirstPartyTypeKind["ZodEnum"] = "ZodEnum"; + ZodFirstPartyTypeKind["ZodEffects"] = "ZodEffects"; + ZodFirstPartyTypeKind["ZodNativeEnum"] = "ZodNativeEnum"; + ZodFirstPartyTypeKind["ZodOptional"] = "ZodOptional"; + ZodFirstPartyTypeKind["ZodNullable"] = "ZodNullable"; + ZodFirstPartyTypeKind["ZodDefault"] = "ZodDefault"; + ZodFirstPartyTypeKind["ZodCatch"] = "ZodCatch"; + ZodFirstPartyTypeKind["ZodPromise"] = "ZodPromise"; + ZodFirstPartyTypeKind["ZodBranded"] = "ZodBranded"; + ZodFirstPartyTypeKind["ZodPipeline"] = "ZodPipeline"; + ZodFirstPartyTypeKind["ZodReadonly"] = "ZodReadonly"; +})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {})); +// requires TS 4.4+ +class Class { + constructor(..._) { } +} +const instanceOfType = ( +// const instanceOfType = any>( +cls, params = { + message: `Input not instance of ${cls.name}`, +}) => custom((data) => data instanceof cls, params); +const stringType = ZodString.create; +const numberType = ZodNumber.create; +const nanType = ZodNaN.create; +const bigIntType = ZodBigInt.create; +const booleanType = ZodBoolean.create; +const dateType = ZodDate.create; +const symbolType = ZodSymbol.create; +const undefinedType = ZodUndefined.create; +const nullType = ZodNull.create; +const anyType = ZodAny.create; +const unknownType = ZodUnknown.create; +const neverType = ZodNever.create; +const voidType = ZodVoid.create; +const arrayType = ZodArray.create; +const objectType = ZodObject.create; +const strictObjectType = ZodObject.strictCreate; +const unionType = ZodUnion.create; +const discriminatedUnionType = ZodDiscriminatedUnion.create; +const intersectionType = ZodIntersection.create; +const tupleType = ZodTuple.create; +const recordType = ZodRecord.create; +const mapType = ZodMap.create; +const setType = ZodSet.create; +const functionType = ZodFunction.create; +const lazyType = ZodLazy.create; +const literalType = ZodLiteral.create; +const enumType = ZodEnum.create; +const nativeEnumType = ZodNativeEnum.create; +const promiseType = ZodPromise.create; +const effectsType = ZodEffects.create; +const optionalType = ZodOptional.create; +const nullableType = ZodNullable.create; +const preprocessType = ZodEffects.createWithPreprocess; +const pipelineType = ZodPipeline.create; +const ostring = () => stringType().optional(); +const onumber = () => numberType().optional(); +const oboolean = () => booleanType().optional(); +const coerce = { + string: ((arg) => ZodString.create({ ...arg, coerce: true })), + number: ((arg) => ZodNumber.create({ ...arg, coerce: true })), + boolean: ((arg) => ZodBoolean.create({ + ...arg, + coerce: true, + })), + bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })), + date: ((arg) => ZodDate.create({ ...arg, coerce: true })), +}; + +const NEVER = INVALID; + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v3/external.js + + + + + + + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v3/index.js + + + +/* harmony default export */ const esm_v3 = ((/* unused pure expression or super */ null && (z))); + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/index.js + + +/* harmony default export */ const esm = ((/* unused pure expression or super */ null && (z3))); + +// EXTERNAL MODULE: ./node_modules/p-retry/index.js +var p_retry = __nccwpck_require__(2103); +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/singletons/traceable.js +class MockAsyncLocalStorage { + getStore() { + return undefined; } - _addCheck(check) { - return new ZodBigInt({ - ...this._def, - checks: [...this._def.checks, check], - }); + run(_, callback) { + return callback(); } - positive(message) { - return this._addCheck({ - kind: "min", - value: BigInt(0), - inclusive: false, - message: errorUtil.toString(message), - }); +} +const TRACING_ALS_KEY = Symbol.for("ls:tracing_async_local_storage"); +const mockAsyncLocalStorage = new MockAsyncLocalStorage(); +class AsyncLocalStorageProvider { + getInstance() { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return globalThis[TRACING_ALS_KEY] ?? mockAsyncLocalStorage; } - negative(message) { - return this._addCheck({ - kind: "max", - value: BigInt(0), - inclusive: false, - message: errorUtil.toString(message), - }); + initializeGlobalInstance(instance) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + if (globalThis[TRACING_ALS_KEY] === undefined) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + globalThis[TRACING_ALS_KEY] = instance; + } } - nonpositive(message) { - return this._addCheck({ - kind: "max", - value: BigInt(0), - inclusive: true, - message: errorUtil.toString(message), - }); +} +const AsyncLocalStorageProviderSingleton = new AsyncLocalStorageProvider(); +function getCurrentRunTree(permitAbsentRunTree = false) { + const runTree = AsyncLocalStorageProviderSingleton.getInstance().getStore(); + if (!permitAbsentRunTree && runTree === undefined) { + throw new Error("Could not get the current run tree.\n\nPlease make sure you are calling this method within a traceable function and that tracing is enabled."); } - nonnegative(message) { - return this._addCheck({ - kind: "min", - value: BigInt(0), - inclusive: true, - message: errorUtil.toString(message), - }); + return runTree; +} +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function withRunTree(runTree, fn) { + const storage = AsyncLocalStorageProviderSingleton.getInstance(); + return new Promise((resolve, reject) => { + storage.run(runTree, () => void Promise.resolve(fn()).then(resolve).catch(reject)); + }); +} +const ROOT = Symbol.for("langsmith:traceable:root"); +function isTraceableFunction(x +// eslint-disable-next-line @typescript-eslint/no-explicit-any +) { + return typeof x === "function" && "langsmith:traceable" in x; +} + +;// CONCATENATED MODULE: ./node_modules/langsmith/singletons/traceable.js + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/fast-json-patch/src/helpers.js +// @ts-nocheck +// Inlined because of ESM import issues +/*! + * https://github.com/Starcounter-Jack/JSON-Patch + * (c) 2017-2022 Joachim Wester + * MIT licensed + */ +const _hasOwnProperty = Object.prototype.hasOwnProperty; +function helpers_hasOwnProperty(obj, key) { + return _hasOwnProperty.call(obj, key); +} +function _objectKeys(obj) { + if (Array.isArray(obj)) { + const keys = new Array(obj.length); + for (let k = 0; k < keys.length; k++) { + keys[k] = "" + k; + } + return keys; } - multipleOf(value, message) { - return this._addCheck({ - kind: "multipleOf", - value, - message: errorUtil.toString(message), - }); + if (Object.keys) { + return Object.keys(obj); } - get minValue() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } + let keys = []; + for (let i in obj) { + if (helpers_hasOwnProperty(obj, i)) { + keys.push(i); } - return min; } - get maxValue() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max; + return keys; +} +/** + * Deeply clone the object. + * https://jsperf.com/deep-copy-vs-json-stringify-json-parse/25 (recursiveDeepCopy) + * @param {any} obj value to clone + * @return {any} cloned obj + */ +function helpers_deepClone(obj) { + switch (typeof obj) { + case "object": + return JSON.parse(JSON.stringify(obj)); //Faster than ES5 clone - http://jsperf.com/deep-cloning-of-objects/5 + case "undefined": + return null; //this is how JSON.stringify behaves for array items + default: + return obj; //no need to clone primitives } } -ZodBigInt.create = (params) => { - var _a; - return new ZodBigInt({ - checks: [], - typeName: ZodFirstPartyTypeKind.ZodBigInt, - coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false, - ...processCreateParams(params), - }); -}; -class ZodBoolean extends ZodType { - _parse(input) { - if (this._def.coerce) { - input.data = Boolean(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.boolean) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.boolean, - received: ctx.parsedType, - }); - return INVALID; +//3x faster than cached /^\d+$/.test(str) +function isInteger(str) { + let i = 0; + const len = str.length; + let charCode; + while (i < len) { + charCode = str.charCodeAt(i); + if (charCode >= 48 && charCode <= 57) { + i++; + continue; } - return OK(input.data); + return false; } + return true; } -ZodBoolean.create = (params) => { - return new ZodBoolean({ - typeName: ZodFirstPartyTypeKind.ZodBoolean, - coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, - ...processCreateParams(params), - }); -}; -class ZodDate extends ZodType { - _parse(input) { - if (this._def.coerce) { - input.data = new Date(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.date) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.date, - received: ctx.parsedType, - }); - return INVALID; - } - if (isNaN(input.data.getTime())) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_date, - }); - return INVALID; - } - const status = new ParseStatus(); - let ctx = undefined; - for (const check of this._def.checks) { - if (check.kind === "min") { - if (input.data.getTime() < check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - message: check.message, - inclusive: true, - exact: false, - minimum: check.value, - type: "date", - }); - status.dirty(); - } +/** + * Escapes a json pointer path + * @param path The raw pointer + * @return the Escaped path + */ +function escapePathComponent(path) { + if (path.indexOf("/") === -1 && path.indexOf("~") === -1) + return path; + return path.replace(/~/g, "~0").replace(/\//g, "~1"); +} +/** + * Unescapes a json pointer path + * @param path The escaped pointer + * @return The unescaped path + */ +function unescapePathComponent(path) { + return path.replace(/~1/g, "/").replace(/~0/g, "~"); +} +function _getPathRecursive(root, obj) { + let found; + for (let key in root) { + if (helpers_hasOwnProperty(root, key)) { + if (root[key] === obj) { + return escapePathComponent(key) + "/"; } - else if (check.kind === "max") { - if (input.data.getTime() > check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - message: check.message, - inclusive: true, - exact: false, - maximum: check.value, - type: "date", - }); - status.dirty(); + else if (typeof root[key] === "object") { + found = _getPathRecursive(root[key], obj); + if (found != "") { + return escapePathComponent(key) + "/" + found; } } - else { - util.assertNever(check); - } } - return { - status: status.value, - value: new Date(input.data.getTime()), - }; } - _addCheck(check) { - return new ZodDate({ - ...this._def, - checks: [...this._def.checks, check], - }); + return ""; +} +function getPath(root, obj) { + if (root === obj) { + return "/"; } - min(minDate, message) { - return this._addCheck({ - kind: "min", - value: minDate.getTime(), - message: errorUtil.toString(message), - }); + const path = _getPathRecursive(root, obj); + if (path === "") { + throw new Error("Object not found in root"); } - max(maxDate, message) { - return this._addCheck({ - kind: "max", - value: maxDate.getTime(), - message: errorUtil.toString(message), - }); + return `/${path}`; +} +/** + * Recursively checks whether an object has any undefined values inside. + */ +function hasUndefined(obj) { + if (obj === undefined) { + return true; } - get minDate() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; + if (obj) { + if (Array.isArray(obj)) { + for (let i = 0, len = obj.length; i < len; i++) { + if (hasUndefined(obj[i])) { + return true; + } } } - return min != null ? new Date(min) : null; - } - get maxDate() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; + else if (typeof obj === "object") { + const objKeys = _objectKeys(obj); + const objKeysLength = objKeys.length; + for (var i = 0; i < objKeysLength; i++) { + if (hasUndefined(obj[objKeys[i]])) { + return true; + } } } - return max != null ? new Date(max) : null; } + return false; } -ZodDate.create = (params) => { - return new ZodDate({ - checks: [], - coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, - typeName: ZodFirstPartyTypeKind.ZodDate, - ...processCreateParams(params), - }); -}; -class ZodSymbol extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.symbol) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.symbol, - received: ctx.parsedType, - }); - return INVALID; +function patchErrorMessageFormatter(message, args) { + const messageParts = [message]; + for (const key in args) { + const value = typeof args[key] === "object" + ? JSON.stringify(args[key], null, 2) + : args[key]; // pretty print + if (typeof value !== "undefined") { + messageParts.push(`${key}: ${value}`); } - return OK(input.data); } + return messageParts.join("\n"); } -ZodSymbol.create = (params) => { - return new ZodSymbol({ - typeName: ZodFirstPartyTypeKind.ZodSymbol, - ...processCreateParams(params), - }); -}; -class ZodUndefined extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.undefined) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.undefined, - received: ctx.parsedType, - }); - return INVALID; - } - return OK(input.data); +class PatchError extends Error { + constructor(message, name, index, operation, tree) { + super(patchErrorMessageFormatter(message, { name, index, operation, tree })); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: name + }); + Object.defineProperty(this, "index", { + enumerable: true, + configurable: true, + writable: true, + value: index + }); + Object.defineProperty(this, "operation", { + enumerable: true, + configurable: true, + writable: true, + value: operation + }); + Object.defineProperty(this, "tree", { + enumerable: true, + configurable: true, + writable: true, + value: tree + }); + Object.setPrototypeOf(this, new.target.prototype); // restore prototype chain, see https://stackoverflow.com/a/48342359 + this.message = patchErrorMessageFormatter(message, { + name, + index, + operation, + tree, + }); } } -ZodUndefined.create = (params) => { - return new ZodUndefined({ - typeName: ZodFirstPartyTypeKind.ZodUndefined, - ...processCreateParams(params), - }); -}; -class ZodNull extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.null) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.null, - received: ctx.parsedType, - }); - return INVALID; + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/fast-json-patch/src/core.js +// @ts-nocheck + +const JsonPatchError = PatchError; +const deepClone = helpers_deepClone; +/* We use a Javascript hash to store each + function. Each hash entry (property) uses + the operation identifiers specified in rfc6902. + In this way, we can map each patch operation + to its dedicated function in efficient way. + */ +/* The operations applicable to an object */ +const objOps = { + add: function (obj, key, document) { + obj[key] = this.value; + return { newDocument: document }; + }, + remove: function (obj, key, document) { + var removed = obj[key]; + delete obj[key]; + return { newDocument: document, removed }; + }, + replace: function (obj, key, document) { + var removed = obj[key]; + obj[key] = this.value; + return { newDocument: document, removed }; + }, + move: function (obj, key, document) { + /* in case move target overwrites an existing value, + return the removed value, this can be taxing performance-wise, + and is potentially unneeded */ + let removed = getValueByPointer(document, this.path); + if (removed) { + removed = helpers_deepClone(removed); } - return OK(input.data); - } -} -ZodNull.create = (params) => { - return new ZodNull({ - typeName: ZodFirstPartyTypeKind.ZodNull, - ...processCreateParams(params), - }); -}; -class ZodAny extends ZodType { - constructor() { - super(...arguments); - // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject. - this._any = true; - } - _parse(input) { - return OK(input.data); - } -} -ZodAny.create = (params) => { - return new ZodAny({ - typeName: ZodFirstPartyTypeKind.ZodAny, - ...processCreateParams(params), - }); + const originalValue = applyOperation(document, { + op: "remove", + path: this.from, + }).removed; + applyOperation(document, { + op: "add", + path: this.path, + value: originalValue, + }); + return { newDocument: document, removed }; + }, + copy: function (obj, key, document) { + const valueToCopy = getValueByPointer(document, this.from); + // enforce copy by value so further operations don't affect source (see issue #177) + applyOperation(document, { + op: "add", + path: this.path, + value: helpers_deepClone(valueToCopy), + }); + return { newDocument: document }; + }, + test: function (obj, key, document) { + return { newDocument: document, test: _areEquals(obj[key], this.value) }; + }, + _get: function (obj, key, document) { + this.value = obj[key]; + return { newDocument: document }; + }, }; -class ZodUnknown extends ZodType { - constructor() { - super(...arguments); - // required - this._unknown = true; - } - _parse(input) { - return OK(input.data); - } -} -ZodUnknown.create = (params) => { - return new ZodUnknown({ - typeName: ZodFirstPartyTypeKind.ZodUnknown, - ...processCreateParams(params), - }); +/* The operations applicable to an array. Many are the same as for the object */ +var arrOps = { + add: function (arr, i, document) { + if (isInteger(i)) { + arr.splice(i, 0, this.value); + } + else { + // array props + arr[i] = this.value; + } + // this may be needed when using '-' in an array + return { newDocument: document, index: i }; + }, + remove: function (arr, i, document) { + var removedList = arr.splice(i, 1); + return { newDocument: document, removed: removedList[0] }; + }, + replace: function (arr, i, document) { + var removed = arr[i]; + arr[i] = this.value; + return { newDocument: document, removed }; + }, + move: objOps.move, + copy: objOps.copy, + test: objOps.test, + _get: objOps._get, }; -class ZodNever extends ZodType { - _parse(input) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.never, - received: ctx.parsedType, - }); - return INVALID; +/** + * Retrieves a value from a JSON document by a JSON pointer. + * Returns the value. + * + * @param document The document to get the value from + * @param pointer an escaped JSON pointer + * @return The retrieved value + */ +function getValueByPointer(document, pointer) { + if (pointer == "") { + return document; } + var getOriginalDestination = { op: "_get", path: pointer }; + applyOperation(document, getOriginalDestination); + return getOriginalDestination.value; } -ZodNever.create = (params) => { - return new ZodNever({ - typeName: ZodFirstPartyTypeKind.ZodNever, - ...processCreateParams(params), - }); -}; -class ZodVoid extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.undefined) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.void, - received: ctx.parsedType, - }); - return INVALID; +/** + * Apply a single JSON Patch Operation on a JSON document. + * Returns the {newDocument, result} of the operation. + * It modifies the `document` and `operation` objects - it gets the values by reference. + * If you would like to avoid touching your values, clone them: + * `jsonpatch.applyOperation(document, jsonpatch._deepClone(operation))`. + * + * @param document The document to patch + * @param operation The operation to apply + * @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. + * @param mutateDocument Whether to mutate the original document or clone it before applying + * @param banPrototypeModifications Whether to ban modifications to `__proto__`, defaults to `true`. + * @return `{newDocument, result}` after the operation + */ +function applyOperation(document, operation, validateOperation = false, mutateDocument = true, banPrototypeModifications = true, index = 0) { + if (validateOperation) { + if (typeof validateOperation == "function") { + validateOperation(operation, 0, document, operation.path); + } + else { + validator(operation, 0); } - return OK(input.data); } -} -ZodVoid.create = (params) => { - return new ZodVoid({ - typeName: ZodFirstPartyTypeKind.ZodVoid, - ...processCreateParams(params), - }); -}; -class ZodArray extends ZodType { - _parse(input) { - const { ctx, status } = this._processInputParams(input); - const def = this._def; - if (ctx.parsedType !== ZodParsedType.array) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.array, - received: ctx.parsedType, - }); - return INVALID; + /* ROOT OPERATIONS */ + if (operation.path === "") { + let returnValue = { newDocument: document }; + if (operation.op === "add") { + returnValue.newDocument = operation.value; + return returnValue; } - if (def.exactLength !== null) { - const tooBig = ctx.data.length > def.exactLength.value; - const tooSmall = ctx.data.length < def.exactLength.value; - if (tooBig || tooSmall) { - addIssueToContext(ctx, { - code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small, - minimum: (tooSmall ? def.exactLength.value : undefined), - maximum: (tooBig ? def.exactLength.value : undefined), - type: "array", - inclusive: true, - exact: true, - message: def.exactLength.message, - }); - status.dirty(); + else if (operation.op === "replace") { + returnValue.newDocument = operation.value; + returnValue.removed = document; //document we removed + return returnValue; + } + else if (operation.op === "move" || operation.op === "copy") { + // it's a move or copy to root + returnValue.newDocument = getValueByPointer(document, operation.from); // get the value by json-pointer in `from` field + if (operation.op === "move") { + // report removed item + returnValue.removed = document; + } + return returnValue; + } + else if (operation.op === "test") { + returnValue.test = _areEquals(document, operation.value); + if (returnValue.test === false) { + throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index, operation, document); + } + returnValue.newDocument = document; + return returnValue; + } + else if (operation.op === "remove") { + // a remove on root + returnValue.removed = document; + returnValue.newDocument = null; + return returnValue; + } + else if (operation.op === "_get") { + operation.value = document; + return returnValue; + } + else { + /* bad operation */ + if (validateOperation) { + throw new JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902", "OPERATION_OP_INVALID", index, operation, document); } - } - if (def.minLength !== null) { - if (ctx.data.length < def.minLength.value) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: def.minLength.value, - type: "array", - inclusive: true, - exact: false, - message: def.minLength.message, - }); - status.dirty(); + else { + return returnValue; } } - if (def.maxLength !== null) { - if (ctx.data.length > def.maxLength.value) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: def.maxLength.value, - type: "array", - inclusive: true, - exact: false, - message: def.maxLength.message, - }); - status.dirty(); - } + } /* END ROOT OPERATIONS */ + else { + if (!mutateDocument) { + document = helpers_deepClone(document); } - if (ctx.common.async) { - return Promise.all([...ctx.data].map((item, i) => { - return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i)); - })).then((result) => { - return ParseStatus.mergeArray(status, result); - }); + const path = operation.path || ""; + const keys = path.split("/"); + let obj = document; + let t = 1; //skip empty element - http://jsperf.com/to-shift-or-not-to-shift + let len = keys.length; + let existingPathFragment = undefined; + let key; + let validateFunction; + if (typeof validateOperation == "function") { + validateFunction = validateOperation; + } + else { + validateFunction = validator; + } + while (true) { + key = keys[t]; + if (key && key.indexOf("~") != -1) { + key = unescapePathComponent(key); + } + if (banPrototypeModifications && + (key == "__proto__" || + (key == "prototype" && t > 0 && keys[t - 1] == "constructor"))) { + throw new TypeError("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"); + } + if (validateOperation) { + if (existingPathFragment === undefined) { + if (obj[key] === undefined) { + existingPathFragment = keys.slice(0, t).join("/"); + } + else if (t == len - 1) { + existingPathFragment = operation.path; + } + if (existingPathFragment !== undefined) { + validateFunction(operation, 0, document, existingPathFragment); + } + } + } + t++; + if (Array.isArray(obj)) { + if (key === "-") { + key = obj.length; + } + else { + if (validateOperation && !isInteger(key)) { + throw new JsonPatchError("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index", "OPERATION_PATH_ILLEGAL_ARRAY_INDEX", index, operation, document); + } // only parse key when it's an integer for `arr.prop` to work + else if (isInteger(key)) { + key = ~~key; + } + } + if (t >= len) { + if (validateOperation && operation.op === "add" && key > obj.length) { + throw new JsonPatchError("The specified index MUST NOT be greater than the number of elements in the array", "OPERATION_VALUE_OUT_OF_BOUNDS", index, operation, document); + } + const returnValue = arrOps[operation.op].call(operation, obj, key, document); // Apply patch + if (returnValue.test === false) { + throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index, operation, document); + } + return returnValue; + } + } + else { + if (t >= len) { + const returnValue = objOps[operation.op].call(operation, obj, key, document); // Apply patch + if (returnValue.test === false) { + throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index, operation, document); + } + return returnValue; + } + } + obj = obj[key]; + // If we have more keys in the path, but the next value isn't a non-null object, + // throw an OPERATION_PATH_UNRESOLVABLE error instead of iterating again. + if (validateOperation && t < len && (!obj || typeof obj !== "object")) { + throw new JsonPatchError("Cannot perform operation at the desired path", "OPERATION_PATH_UNRESOLVABLE", index, operation, document); + } } - const result = [...ctx.data].map((item, i) => { - return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i)); - }); - return ParseStatus.mergeArray(status, result); - } - get element() { - return this._def.type; - } - min(minLength, message) { - return new ZodArray({ - ...this._def, - minLength: { value: minLength, message: errorUtil.toString(message) }, - }); } - max(maxLength, message) { - return new ZodArray({ - ...this._def, - maxLength: { value: maxLength, message: errorUtil.toString(message) }, - }); +} +/** + * Apply a full JSON Patch array on a JSON document. + * Returns the {newDocument, result} of the patch. + * It modifies the `document` object and `patch` - it gets the values by reference. + * If you would like to avoid touching your values, clone them: + * `jsonpatch.applyPatch(document, jsonpatch._deepClone(patch))`. + * + * @param document The document to patch + * @param patch The patch to apply + * @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. + * @param mutateDocument Whether to mutate the original document or clone it before applying + * @param banPrototypeModifications Whether to ban modifications to `__proto__`, defaults to `true`. + * @return An array of `{newDocument, result}` after the patch + */ +function core_applyPatch(document, patch, validateOperation, mutateDocument = true, banPrototypeModifications = true) { + if (validateOperation) { + if (!Array.isArray(patch)) { + throw new JsonPatchError("Patch sequence must be an array", "SEQUENCE_NOT_AN_ARRAY"); + } } - length(len, message) { - return new ZodArray({ - ...this._def, - exactLength: { value: len, message: errorUtil.toString(message) }, - }); + if (!mutateDocument) { + document = helpers_deepClone(document); } - nonempty(message) { - return this.min(1, message); + const results = new Array(patch.length); + for (let i = 0, length = patch.length; i < length; i++) { + // we don't need to pass mutateDocument argument because if it was true, we already deep cloned the object, we'll just pass `true` + results[i] = applyOperation(document, patch[i], validateOperation, true, banPrototypeModifications, i); + document = results[i].newDocument; // in case root was replaced } + results.newDocument = document; + return results; } -ZodArray.create = (schema, params) => { - return new ZodArray({ - type: schema, - minLength: null, - maxLength: null, - exactLength: null, - typeName: ZodFirstPartyTypeKind.ZodArray, - ...processCreateParams(params), - }); -}; -function deepPartialify(schema) { - if (schema instanceof ZodObject) { - const newShape = {}; - for (const key in schema.shape) { - const fieldSchema = schema.shape[key]; - newShape[key] = ZodOptional.create(deepPartialify(fieldSchema)); - } - return new ZodObject({ - ...schema._def, - shape: () => newShape, - }); +/** + * Apply a single JSON Patch Operation on a JSON document. + * Returns the updated document. + * Suitable as a reducer. + * + * @param document The document to patch + * @param operation The operation to apply + * @return The updated document + */ +function applyReducer(document, operation, index) { + const operationResult = applyOperation(document, operation); + if (operationResult.test === false) { + // failed test + throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index, operation, document); } - else if (schema instanceof ZodArray) { - return new ZodArray({ - ...schema._def, - type: deepPartialify(schema.element), - }); + return operationResult.newDocument; +} +/** + * Validates a single operation. Called from `jsonpatch.validate`. Throws `JsonPatchError` in case of an error. + * @param {object} operation - operation object (patch) + * @param {number} index - index of operation in the sequence + * @param {object} [document] - object where the operation is supposed to be applied + * @param {string} [existingPathFragment] - comes along with `document` + */ +function validator(operation, index, document, existingPathFragment) { + if (typeof operation !== "object" || + operation === null || + Array.isArray(operation)) { + throw new JsonPatchError("Operation is not an object", "OPERATION_NOT_AN_OBJECT", index, operation, document); } - else if (schema instanceof ZodOptional) { - return ZodOptional.create(deepPartialify(schema.unwrap())); + else if (!objOps[operation.op]) { + throw new JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902", "OPERATION_OP_INVALID", index, operation, document); } - else if (schema instanceof ZodNullable) { - return ZodNullable.create(deepPartialify(schema.unwrap())); + else if (typeof operation.path !== "string") { + throw new JsonPatchError("Operation `path` property is not a string", "OPERATION_PATH_INVALID", index, operation, document); } - else if (schema instanceof ZodTuple) { - return ZodTuple.create(schema.items.map((item) => deepPartialify(item))); + else if (operation.path.indexOf("/") !== 0 && operation.path.length > 0) { + // paths that aren't empty string should start with "/" + throw new JsonPatchError('Operation `path` property must start with "/"', "OPERATION_PATH_INVALID", index, operation, document); } - else { - return schema; + else if ((operation.op === "move" || operation.op === "copy") && + typeof operation.from !== "string") { + throw new JsonPatchError("Operation `from` property is not present (applicable in `move` and `copy` operations)", "OPERATION_FROM_REQUIRED", index, operation, document); } -} -class ZodObject extends ZodType { - constructor() { - super(...arguments); - this._cached = null; - /** - * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped. - * If you want to pass through unknown properties, use `.passthrough()` instead. - */ - this.nonstrict = this.passthrough; - // extend< - // Augmentation extends ZodRawShape, - // NewOutput extends util.flatten<{ - // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation - // ? Augmentation[k]["_output"] - // : k extends keyof Output - // ? Output[k] - // : never; - // }>, - // NewInput extends util.flatten<{ - // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation - // ? Augmentation[k]["_input"] - // : k extends keyof Input - // ? Input[k] - // : never; - // }> - // >( - // augmentation: Augmentation - // ): ZodObject< - // extendShape, - // UnknownKeys, - // Catchall, - // NewOutput, - // NewInput - // > { - // return new ZodObject({ - // ...this._def, - // shape: () => ({ - // ...this._def.shape(), - // ...augmentation, - // }), - // }) as any; - // } - /** - * @deprecated Use `.extend` instead - * */ - this.augment = this.extend; + else if ((operation.op === "add" || + operation.op === "replace" || + operation.op === "test") && + operation.value === undefined) { + throw new JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)", "OPERATION_VALUE_REQUIRED", index, operation, document); } - _getCached() { - if (this._cached !== null) - return this._cached; - const shape = this._def.shape(); - const keys = util.objectKeys(shape); - return (this._cached = { shape, keys }); + else if ((operation.op === "add" || + operation.op === "replace" || + operation.op === "test") && + hasUndefined(operation.value)) { + throw new JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)", "OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED", index, operation, document); } - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.object) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.object, - received: ctx.parsedType, - }); - return INVALID; - } - const { status, ctx } = this._processInputParams(input); - const { shape, keys: shapeKeys } = this._getCached(); - const extraKeys = []; - if (!(this._def.catchall instanceof ZodNever && - this._def.unknownKeys === "strip")) { - for (const key in ctx.data) { - if (!shapeKeys.includes(key)) { - extraKeys.push(key); - } + else if (document) { + if (operation.op == "add") { + var pathLen = operation.path.split("/").length; + var existingPathLen = existingPathFragment.split("/").length; + if (pathLen !== existingPathLen + 1 && pathLen !== existingPathLen) { + throw new JsonPatchError("Cannot perform an `add` operation at the desired path", "OPERATION_PATH_CANNOT_ADD", index, operation, document); } } - const pairs = []; - for (const key of shapeKeys) { - const keyValidator = shape[key]; - const value = ctx.data[key]; - pairs.push({ - key: { status: "valid", value: key }, - value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), - alwaysSet: key in ctx.data, - }); - } - if (this._def.catchall instanceof ZodNever) { - const unknownKeys = this._def.unknownKeys; - if (unknownKeys === "passthrough") { - for (const key of extraKeys) { - pairs.push({ - key: { status: "valid", value: key }, - value: { status: "valid", value: ctx.data[key] }, - }); - } - } - else if (unknownKeys === "strict") { - if (extraKeys.length > 0) { - addIssueToContext(ctx, { - code: ZodIssueCode.unrecognized_keys, - keys: extraKeys, - }); - status.dirty(); - } + else if (operation.op === "replace" || + operation.op === "remove" || + operation.op === "_get") { + if (operation.path !== existingPathFragment) { + throw new JsonPatchError("Cannot perform the operation at a path that does not exist", "OPERATION_PATH_UNRESOLVABLE", index, operation, document); } - else if (unknownKeys === "strip") ; - else { - throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); + } + else if (operation.op === "move" || operation.op === "copy") { + var existingValue = { + op: "_get", + path: operation.from, + value: undefined, + }; + var error = core_validate([existingValue], document); + if (error && error.name === "OPERATION_PATH_UNRESOLVABLE") { + throw new JsonPatchError("Cannot perform the operation from a path that does not exist", "OPERATION_FROM_UNRESOLVABLE", index, operation, document); } } + } +} +/** + * Validates a sequence of operations. If `document` parameter is provided, the sequence is additionally validated against the object document. + * If error is encountered, returns a JsonPatchError object + * @param sequence + * @param document + * @returns {JsonPatchError|undefined} + */ +function core_validate(sequence, document, externalValidator) { + try { + if (!Array.isArray(sequence)) { + throw new JsonPatchError("Patch sequence must be an array", "SEQUENCE_NOT_AN_ARRAY"); + } + if (document) { + //clone document and sequence so that we can safely try applying operations + core_applyPatch(helpers_deepClone(document), helpers_deepClone(sequence), externalValidator || true); + } else { - // run catchall validation - const catchall = this._def.catchall; - for (const key of extraKeys) { - const value = ctx.data[key]; - pairs.push({ - key: { status: "valid", value: key }, - value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value) - ), - alwaysSet: key in ctx.data, - }); + externalValidator = externalValidator || validator; + for (var i = 0; i < sequence.length; i++) { + externalValidator(sequence[i], i, document, undefined); } } - if (ctx.common.async) { - return Promise.resolve() - .then(async () => { - const syncPairs = []; - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - syncPairs.push({ - key, - value, - alwaysSet: pair.alwaysSet, - }); - } - return syncPairs; - }) - .then((syncPairs) => { - return ParseStatus.mergeObjectSync(status, syncPairs); - }); + } + catch (e) { + if (e instanceof JsonPatchError) { + return e; } else { - return ParseStatus.mergeObjectSync(status, pairs); + throw e; } } - get shape() { - return this._def.shape(); +} +// based on https://github.com/epoberezkin/fast-deep-equal +// MIT License +// Copyright (c) 2017 Evgeny Poberezkin +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. +function _areEquals(a, b) { + if (a === b) + return true; + if (a && b && typeof a == "object" && typeof b == "object") { + var arrA = Array.isArray(a), arrB = Array.isArray(b), i, length, key; + if (arrA && arrB) { + length = a.length; + if (length != b.length) + return false; + for (i = length; i-- !== 0;) + if (!_areEquals(a[i], b[i])) + return false; + return true; + } + if (arrA != arrB) + return false; + var keys = Object.keys(a); + length = keys.length; + if (length !== Object.keys(b).length) + return false; + for (i = length; i-- !== 0;) + if (!b.hasOwnProperty(keys[i])) + return false; + for (i = length; i-- !== 0;) { + key = keys[i]; + if (!_areEquals(a[key], b[key])) + return false; + } + return true; } - strict(message) { - errorUtil.errToObj; - return new ZodObject({ - ...this._def, - unknownKeys: "strict", - ...(message !== undefined - ? { - errorMap: (issue, ctx) => { - var _a, _b, _c, _d; - const defaultError = (_c = (_b = (_a = this._def).errorMap) === null || _b === void 0 ? void 0 : _b.call(_a, issue, ctx).message) !== null && _c !== void 0 ? _c : ctx.defaultError; - if (issue.code === "unrecognized_keys") - return { - message: (_d = errorUtil.errToObj(message).message) !== null && _d !== void 0 ? _d : defaultError, - }; - return { - message: defaultError, - }; - }, - } - : {}), + return a !== a && b !== b; +} + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/fast-json-patch/src/duplex.js +// @ts-nocheck +// Inlined because of ESM import issues +/*! + * https://github.com/Starcounter-Jack/JSON-Patch + * (c) 2013-2021 Joachim Wester + * MIT license + */ + + +var beforeDict = new WeakMap(); +class Mirror { + constructor(obj) { + Object.defineProperty(this, "obj", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 }); - } - strip() { - return new ZodObject({ - ...this._def, - unknownKeys: "strip", + Object.defineProperty(this, "observers", { + enumerable: true, + configurable: true, + writable: true, + value: new Map() }); - } - passthrough() { - return new ZodObject({ - ...this._def, - unknownKeys: "passthrough", + Object.defineProperty(this, "value", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 }); + this.obj = obj; } - // const AugmentFactory = - // (def: Def) => - // ( - // augmentation: Augmentation - // ): ZodObject< - // extendShape, Augmentation>, - // Def["unknownKeys"], - // Def["catchall"] - // > => { - // return new ZodObject({ - // ...def, - // shape: () => ({ - // ...def.shape(), - // ...augmentation, - // }), - // }) as any; - // }; - extend(augmentation) { - return new ZodObject({ - ...this._def, - shape: () => ({ - ...this._def.shape(), - ...augmentation, - }), +} +class ObserverInfo { + constructor(callback, observer) { + Object.defineProperty(this, "callback", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 }); - } - /** - * Prior to zod@1.0.12 there was a bug in the - * inferred type of merged objects. Please - * upgrade if you are experiencing issues. - */ - merge(merging) { - const merged = new ZodObject({ - unknownKeys: merging._def.unknownKeys, - catchall: merging._def.catchall, - shape: () => ({ - ...this._def.shape(), - ...merging._def.shape(), - }), - typeName: ZodFirstPartyTypeKind.ZodObject, + Object.defineProperty(this, "observer", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 }); - return merged; + this.callback = callback; + this.observer = observer; } - // merge< - // Incoming extends AnyZodObject, - // Augmentation extends Incoming["shape"], - // NewOutput extends { - // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation - // ? Augmentation[k]["_output"] - // : k extends keyof Output - // ? Output[k] - // : never; - // }, - // NewInput extends { - // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation - // ? Augmentation[k]["_input"] - // : k extends keyof Input - // ? Input[k] - // : never; - // } - // >( - // merging: Incoming - // ): ZodObject< - // extendShape>, - // Incoming["_def"]["unknownKeys"], - // Incoming["_def"]["catchall"], - // NewOutput, - // NewInput - // > { - // const merged: any = new ZodObject({ - // unknownKeys: merging._def.unknownKeys, - // catchall: merging._def.catchall, - // shape: () => - // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), - // typeName: ZodFirstPartyTypeKind.ZodObject, - // }) as any; - // return merged; - // } - setKey(key, schema) { - return this.augment({ [key]: schema }); +} +function getMirror(obj) { + return beforeDict.get(obj); +} +function getObserverFromMirror(mirror, callback) { + return mirror.observers.get(callback); +} +function removeObserverFromMirror(mirror, observer) { + mirror.observers.delete(observer.callback); +} +/** + * Detach an observer from an object + */ +function unobserve(root, observer) { + observer.unobserve(); +} +/** + * Observes changes made to an object, which can then be retrieved using generate + */ +function observe(obj, callback) { + var patches = []; + var observer; + var mirror = getMirror(obj); + if (!mirror) { + mirror = new Mirror(obj); + beforeDict.set(obj, mirror); } - // merge( - // merging: Incoming - // ): //ZodObject = (merging) => { - // ZodObject< - // extendShape>, - // Incoming["_def"]["unknownKeys"], - // Incoming["_def"]["catchall"] - // > { - // // const mergedShape = objectUtil.mergeShapes( - // // this._def.shape(), - // // merging._def.shape() - // // ); - // const merged: any = new ZodObject({ - // unknownKeys: merging._def.unknownKeys, - // catchall: merging._def.catchall, - // shape: () => - // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), - // typeName: ZodFirstPartyTypeKind.ZodObject, - // }) as any; - // return merged; - // } - catchall(index) { - return new ZodObject({ - ...this._def, - catchall: index, - }); + else { + const observerInfo = getObserverFromMirror(mirror, callback); + observer = observerInfo && observerInfo.observer; } - pick(mask) { - const shape = {}; - util.objectKeys(mask).forEach((key) => { - if (mask[key] && this.shape[key]) { - shape[key] = this.shape[key]; - } - }); - return new ZodObject({ - ...this._def, - shape: () => shape, - }); + if (observer) { + return observer; } - omit(mask) { - const shape = {}; - util.objectKeys(this.shape).forEach((key) => { - if (!mask[key]) { - shape[key] = this.shape[key]; - } - }); - return new ZodObject({ - ...this._def, - shape: () => shape, - }); + observer = {}; + mirror.value = _deepClone(obj); + if (callback) { + observer.callback = callback; + observer.next = null; + var dirtyCheck = () => { + duplex_generate(observer); + }; + var fastCheck = () => { + clearTimeout(observer.next); + observer.next = setTimeout(dirtyCheck); + }; + if (typeof window !== "undefined") { + //not Node + window.addEventListener("mouseup", fastCheck); + window.addEventListener("keyup", fastCheck); + window.addEventListener("mousedown", fastCheck); + window.addEventListener("keydown", fastCheck); + window.addEventListener("change", fastCheck); + } } - /** - * @deprecated - */ - deepPartial() { - return deepPartialify(this); + observer.patches = patches; + observer.object = obj; + observer.unobserve = () => { + duplex_generate(observer); + clearTimeout(observer.next); + removeObserverFromMirror(mirror, observer); + if (typeof window !== "undefined") { + window.removeEventListener("mouseup", fastCheck); + window.removeEventListener("keyup", fastCheck); + window.removeEventListener("mousedown", fastCheck); + window.removeEventListener("keydown", fastCheck); + window.removeEventListener("change", fastCheck); + } + }; + mirror.observers.set(callback, new ObserverInfo(callback, observer)); + return observer; +} +/** + * Generate an array of patches from an observer + */ +function duplex_generate(observer, invertible = false) { + var mirror = beforeDict.get(observer.object); + _generate(mirror.value, observer.object, observer.patches, "", invertible); + if (observer.patches.length) { + applyPatch(mirror.value, observer.patches); } - partial(mask) { - const newShape = {}; - util.objectKeys(this.shape).forEach((key) => { - const fieldSchema = this.shape[key]; - if (mask && !mask[key]) { - newShape[key] = fieldSchema; - } - else { - newShape[key] = fieldSchema.optional(); - } - }); - return new ZodObject({ - ...this._def, - shape: () => newShape, - }); + var temp = observer.patches; + if (temp.length > 0) { + observer.patches = []; + if (observer.callback) { + observer.callback(temp); + } } - required(mask) { - const newShape = {}; - util.objectKeys(this.shape).forEach((key) => { - if (mask && !mask[key]) { - newShape[key] = this.shape[key]; - } - else { - const fieldSchema = this.shape[key]; - let newField = fieldSchema; - while (newField instanceof ZodOptional) { - newField = newField._def.innerType; - } - newShape[key] = newField; - } - }); - return new ZodObject({ - ...this._def, - shape: () => newShape, - }); + return temp; +} +// Dirty check if obj is different from mirror, generate patches and update mirror +function _generate(mirror, obj, patches, path, invertible) { + if (obj === mirror) { + return; } - keyof() { - return createZodEnum(util.objectKeys(this.shape)); + if (typeof obj.toJSON === "function") { + obj = obj.toJSON(); } -} -ZodObject.create = (shape, params) => { - return new ZodObject({ - shape: () => shape, - unknownKeys: "strip", - catchall: ZodNever.create(), - typeName: ZodFirstPartyTypeKind.ZodObject, - ...processCreateParams(params), - }); -}; -ZodObject.strictCreate = (shape, params) => { - return new ZodObject({ - shape: () => shape, - unknownKeys: "strict", - catchall: ZodNever.create(), - typeName: ZodFirstPartyTypeKind.ZodObject, - ...processCreateParams(params), - }); -}; -ZodObject.lazycreate = (shape, params) => { - return new ZodObject({ - shape, - unknownKeys: "strip", - catchall: ZodNever.create(), - typeName: ZodFirstPartyTypeKind.ZodObject, - ...processCreateParams(params), - }); -}; -class ZodUnion extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - const options = this._def.options; - function handleResults(results) { - // return first issue-free validation if it exists - for (const result of results) { - if (result.result.status === "valid") { - return result.result; - } + var newKeys = _objectKeys(obj); + var oldKeys = _objectKeys(mirror); + var changed = false; + var deleted = false; + //if ever "move" operation is implemented here, make sure this test runs OK: "should not generate the same patch twice (move)" + for (var t = oldKeys.length - 1; t >= 0; t--) { + var key = oldKeys[t]; + var oldVal = mirror[key]; + if (helpers_hasOwnProperty(obj, key) && + !(obj[key] === undefined && + oldVal !== undefined && + Array.isArray(obj) === false)) { + var newVal = obj[key]; + if (typeof oldVal == "object" && + oldVal != null && + typeof newVal == "object" && + newVal != null && + Array.isArray(oldVal) === Array.isArray(newVal)) { + _generate(oldVal, newVal, patches, path + "/" + escapePathComponent(key), invertible); } - for (const result of results) { - if (result.result.status === "dirty") { - // add issues from dirty option - ctx.common.issues.push(...result.ctx.common.issues); - return result.result; + else { + if (oldVal !== newVal) { + changed = true; + if (invertible) { + patches.push({ + op: "test", + path: path + "/" + escapePathComponent(key), + value: helpers_deepClone(oldVal), + }); + } + patches.push({ + op: "replace", + path: path + "/" + escapePathComponent(key), + value: helpers_deepClone(newVal), + }); } } - // return invalid - const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues)); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_union, - unionErrors, - }); - return INVALID; - } - if (ctx.common.async) { - return Promise.all(options.map(async (option) => { - const childCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [], - }, - parent: null, - }; - return { - result: await option._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: childCtx, - }), - ctx: childCtx, - }; - })).then(handleResults); } - else { - let dirty = undefined; - const issues = []; - for (const option of options) { - const childCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [], - }, - parent: null, - }; - const result = option._parseSync({ - data: ctx.data, - path: ctx.path, - parent: childCtx, + else if (Array.isArray(mirror) === Array.isArray(obj)) { + if (invertible) { + patches.push({ + op: "test", + path: path + "/" + escapePathComponent(key), + value: helpers_deepClone(oldVal), }); - if (result.status === "valid") { - return result; - } - else if (result.status === "dirty" && !dirty) { - dirty = { result, ctx: childCtx }; - } - if (childCtx.common.issues.length) { - issues.push(childCtx.common.issues); - } } - if (dirty) { - ctx.common.issues.push(...dirty.ctx.common.issues); - return dirty.result; + patches.push({ + op: "remove", + path: path + "/" + escapePathComponent(key), + }); + deleted = true; // property has been deleted + } + else { + if (invertible) { + patches.push({ op: "test", path, value: mirror }); } - const unionErrors = issues.map((issues) => new ZodError(issues)); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_union, - unionErrors, + patches.push({ op: "replace", path, value: obj }); + changed = true; + } + } + if (!deleted && newKeys.length == oldKeys.length) { + return; + } + for (var t = 0; t < newKeys.length; t++) { + var key = newKeys[t]; + if (!helpers_hasOwnProperty(mirror, key) && obj[key] !== undefined) { + patches.push({ + op: "add", + path: path + "/" + escapePathComponent(key), + value: helpers_deepClone(obj[key]), }); - return INVALID; } } - get options() { - return this._def.options; +} +/** + * Create an array of patches from the differences in two objects + */ +function compare(tree1, tree2, invertible = false) { + var patches = []; + _generate(tree1, tree2, patches, "", invertible); + return patches; +} + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/fast-json-patch/index.js + + + +/** + * Default export for backwards compat + */ + + +/* harmony default export */ const fast_json_patch = ({ + ...src_core_namespaceObject, + // ...duplex, + JsonPatchError: PatchError, + deepClone: helpers_deepClone, + escapePathComponent: escapePathComponent, + unescapePathComponent: unescapePathComponent, +}); + +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/experimental/otel/constants.js +// OpenTelemetry GenAI semantic convention attribute names +const GEN_AI_OPERATION_NAME = "gen_ai.operation.name"; +const GEN_AI_SYSTEM = "gen_ai.system"; +const GEN_AI_REQUEST_MODEL = "gen_ai.request.model"; +const GEN_AI_RESPONSE_MODEL = "gen_ai.response.model"; +const GEN_AI_USAGE_INPUT_TOKENS = "gen_ai.usage.input_tokens"; +const GEN_AI_USAGE_OUTPUT_TOKENS = "gen_ai.usage.output_tokens"; +const GEN_AI_USAGE_TOTAL_TOKENS = "gen_ai.usage.total_tokens"; +const GEN_AI_REQUEST_MAX_TOKENS = "gen_ai.request.max_tokens"; +const GEN_AI_REQUEST_TEMPERATURE = "gen_ai.request.temperature"; +const GEN_AI_REQUEST_TOP_P = "gen_ai.request.top_p"; +const GEN_AI_REQUEST_FREQUENCY_PENALTY = "gen_ai.request.frequency_penalty"; +const GEN_AI_REQUEST_PRESENCE_PENALTY = "gen_ai.request.presence_penalty"; +const GEN_AI_RESPONSE_FINISH_REASONS = "gen_ai.response.finish_reasons"; +const GENAI_PROMPT = "gen_ai.prompt"; +const GENAI_COMPLETION = "gen_ai.completion"; +const GEN_AI_REQUEST_EXTRA_QUERY = "gen_ai.request.extra_query"; +const GEN_AI_REQUEST_EXTRA_BODY = "gen_ai.request.extra_body"; +const GEN_AI_SERIALIZED_NAME = "gen_ai.serialized.name"; +const GEN_AI_SERIALIZED_SIGNATURE = "gen_ai.serialized.signature"; +const GEN_AI_SERIALIZED_DOC = "gen_ai.serialized.doc"; +const GEN_AI_RESPONSE_ID = "gen_ai.response.id"; +const GEN_AI_RESPONSE_SERVICE_TIER = "gen_ai.response.service_tier"; +const GEN_AI_RESPONSE_SYSTEM_FINGERPRINT = "gen_ai.response.system_fingerprint"; +const GEN_AI_USAGE_INPUT_TOKEN_DETAILS = "gen_ai.usage.input_token_details"; +const GEN_AI_USAGE_OUTPUT_TOKEN_DETAILS = "gen_ai.usage.output_token_details"; +// LangSmith custom attributes +const LANGSMITH_SESSION_ID = "langsmith.trace.session_id"; +const LANGSMITH_SESSION_NAME = "langsmith.trace.session_name"; +const LANGSMITH_RUN_TYPE = "langsmith.span.kind"; +const LANGSMITH_NAME = "langsmith.trace.name"; +const LANGSMITH_METADATA = "langsmith.metadata"; +const LANGSMITH_TAGS = "langsmith.span.tags"; +const LANGSMITH_RUNTIME = "langsmith.span.runtime"; +const LANGSMITH_REQUEST_STREAMING = "langsmith.request.streaming"; +const LANGSMITH_REQUEST_HEADERS = "langsmith.request.headers"; +const LANGSMITH_RUN_ID = "langsmith.span.id"; +const LANGSMITH_TRACE_ID = "langsmith.trace.id"; +const LANGSMITH_DOTTED_ORDER = "langsmith.span.dotted_order"; +const LANGSMITH_PARENT_RUN_ID = "langsmith.span.parent_id"; +const LANGSMITH_USAGE_METADATA = "langsmith.usage_metadata"; +const LANGSMITH_REFERENCE_EXAMPLE_ID = "langsmith.reference_example_id"; +const LANGSMITH_TRACEABLE = "langsmith.traceable"; +const LANGSMITH_IS_ROOT = "langsmith.is_root"; +const LANGSMITH_TRACEABLE_PARENT_OTEL_SPAN_ID = "langsmith.traceable_parent_otel_span_id"; +// GenAI event names +const GEN_AI_SYSTEM_MESSAGE = "gen_ai.system.message"; +const GEN_AI_USER_MESSAGE = "gen_ai.user.message"; +const GEN_AI_ASSISTANT_MESSAGE = "gen_ai.assistant.message"; +const GEN_AI_CHOICE = "gen_ai.choice"; +const AI_SDK_LLM_OPERATIONS = (/* unused pure expression or super */ null && ([ + "ai.generateText.doGenerate", + "ai.streamText.doStream", + "ai.generateObject.doGenerate", + "ai.streamObject.doStream", +])); +const AI_SDK_TOOL_OPERATIONS = (/* unused pure expression or super */ null && (["ai.toolCall"])); + +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/singletons/fetch.js + +// Wrap the default fetch call due to issues with illegal invocations +// in some environments: +// https://stackoverflow.com/questions/69876859/why-does-bind-fix-failed-to-execute-fetch-on-window-illegal-invocation-err +// @ts-expect-error Broad typing to support a range of fetch implementations +const DEFAULT_FETCH_IMPLEMENTATION = (...args) => fetch(...args); +const LANGSMITH_FETCH_IMPLEMENTATION_KEY = Symbol.for("ls:fetch_implementation"); +/** + * Overrides the fetch implementation used for LangSmith calls. + * You should use this if you need to use an implementation of fetch + * other than the default global (e.g. for dealing with proxies). + * @param fetch The new fetch functino to use. + */ +const overrideFetchImplementation = (fetch) => { + globalThis[LANGSMITH_FETCH_IMPLEMENTATION_KEY] = fetch; +}; +const _globalFetchImplementationIsNodeFetch = () => { + const fetchImpl = globalThis[LANGSMITH_FETCH_IMPLEMENTATION_KEY]; + if (!fetchImpl) + return false; + // Check if the implementation has node-fetch specific properties + return (typeof fetchImpl === "function" && + "Headers" in fetchImpl && + "Request" in fetchImpl && + "Response" in fetchImpl); +}; +/** + * @internal + */ +const _getFetchImplementation = (debug) => { + return async (...args) => { + if (debug || getLangSmithEnvironmentVariable("DEBUG") === "true") { + const [url, options] = args; + console.log(`→ ${options?.method || "GET"} ${url}`); + } + const res = await (globalThis[LANGSMITH_FETCH_IMPLEMENTATION_KEY] ?? + DEFAULT_FETCH_IMPLEMENTATION)(...args); + if (debug || getLangSmithEnvironmentVariable("DEBUG") === "true") { + console.log(`← ${res.status} ${res.statusText} ${res.url}`); + } + return res; + }; +}; + +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/project.js + +const getDefaultProjectName = () => { + return (getLangSmithEnvironmentVariable("PROJECT") ?? + getEnvironmentVariable("LANGCHAIN_SESSION") ?? // TODO: Deprecate + "default"); +}; + +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/index.js + + + + +// Update using yarn bump-version +const __version__ = "0.3.55"; + +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/env.js +// Inlined from https://github.com/flexdinesh/browser-or-node + +let globalEnv; +const isBrowser = () => typeof window !== "undefined" && typeof window.document !== "undefined"; +const isWebWorker = () => typeof globalThis === "object" && + globalThis.constructor && + globalThis.constructor.name === "DedicatedWorkerGlobalScope"; +const isJsDom = () => (typeof window !== "undefined" && window.name === "nodejs") || + (typeof navigator !== "undefined" && navigator.userAgent.includes("jsdom")); +// Supabase Edge Function provides a `Deno` global object +// without `version` property +const isDeno = () => typeof Deno !== "undefined"; +// Mark not-as-node if in Supabase Edge Function +const isNode = () => typeof process !== "undefined" && + typeof process.versions !== "undefined" && + typeof process.versions.node !== "undefined" && + !isDeno(); +const getEnv = () => { + if (globalEnv) { + return globalEnv; + } + if (isBrowser()) { + globalEnv = "browser"; } -} -ZodUnion.create = (types, params) => { - return new ZodUnion({ - options: types, - typeName: ZodFirstPartyTypeKind.ZodUnion, - ...processCreateParams(params), - }); -}; -///////////////////////////////////////////////////// -///////////////////////////////////////////////////// -////////// ////////// -////////// ZodDiscriminatedUnion ////////// -////////// ////////// -///////////////////////////////////////////////////// -///////////////////////////////////////////////////// -const getDiscriminator = (type) => { - if (type instanceof ZodLazy) { - return getDiscriminator(type.schema); + else if (isNode()) { + globalEnv = "node"; } - else if (type instanceof ZodEffects) { - return getDiscriminator(type.innerType()); + else if (isWebWorker()) { + globalEnv = "webworker"; } - else if (type instanceof ZodLiteral) { - return [type.value]; + else if (isJsDom()) { + globalEnv = "jsdom"; } - else if (type instanceof ZodEnum) { - return type.options; + else if (isDeno()) { + globalEnv = "deno"; } - else if (type instanceof ZodNativeEnum) { - // eslint-disable-next-line ban/ban - return util.objectValues(type.enum); + else { + globalEnv = "other"; } - else if (type instanceof ZodDefault) { - return getDiscriminator(type._def.innerType); + return globalEnv; +}; +let runtimeEnvironment; +function getRuntimeEnvironment() { + if (runtimeEnvironment === undefined) { + const env = getEnv(); + const releaseEnv = getShas(); + runtimeEnvironment = { + library: "langsmith", + runtime: env, + sdk: "langsmith-js", + sdk_version: __version__, + ...releaseEnv, + }; } - else if (type instanceof ZodUndefined) { - return [undefined]; + return runtimeEnvironment; +} +/** + * Retrieves the LangChain-specific environment variables from the current runtime environment. + * Sensitive keys (containing the word "key", "token", or "secret") have their values redacted for security. + * + * @returns {Record} + * - A record of LangChain-specific environment variables. + */ +function getLangChainEnvVars() { + const allEnvVars = getEnvironmentVariables() || {}; + const envVars = {}; + for (const [key, value] of Object.entries(allEnvVars)) { + if (key.startsWith("LANGCHAIN_") && typeof value === "string") { + envVars[key] = value; + } } - else if (type instanceof ZodNull) { - return [null]; + for (const key in envVars) { + if ((key.toLowerCase().includes("key") || + key.toLowerCase().includes("secret") || + key.toLowerCase().includes("token")) && + typeof envVars[key] === "string") { + const value = envVars[key]; + envVars[key] = + value.slice(0, 2) + "*".repeat(value.length - 4) + value.slice(-2); + } } - else if (type instanceof ZodOptional) { - return [undefined, ...getDiscriminator(type.unwrap())]; + return envVars; +} +/** + * Retrieves the LangChain-specific metadata from the current runtime environment. + * + * @returns {Record} + * - A record of LangChain-specific metadata environment variables. + */ +function getLangChainEnvVarsMetadata() { + const allEnvVars = getEnvironmentVariables() || {}; + const envVars = {}; + const excluded = [ + "LANGCHAIN_API_KEY", + "LANGCHAIN_ENDPOINT", + "LANGCHAIN_TRACING_V2", + "LANGCHAIN_PROJECT", + "LANGCHAIN_SESSION", + "LANGSMITH_API_KEY", + "LANGSMITH_ENDPOINT", + "LANGSMITH_TRACING_V2", + "LANGSMITH_PROJECT", + "LANGSMITH_SESSION", + ]; + for (const [key, value] of Object.entries(allEnvVars)) { + if ((key.startsWith("LANGCHAIN_") || key.startsWith("LANGSMITH_")) && + typeof value === "string" && + !excluded.includes(key) && + !key.toLowerCase().includes("key") && + !key.toLowerCase().includes("secret") && + !key.toLowerCase().includes("token")) { + if (key === "LANGCHAIN_REVISION_ID") { + envVars["revision_id"] = value; + } + else { + envVars[key] = value; + } + } } - else if (type instanceof ZodNullable) { - return [null, ...getDiscriminator(type.unwrap())]; + return envVars; +} +/** + * Retrieves the environment variables from the current runtime environment. + * + * This function is designed to operate in a variety of JS environments, + * including Node.js, Deno, browsers, etc. + * + * @returns {Record | undefined} + * - A record of environment variables if available. + * - `undefined` if the environment does not support or allows access to environment variables. + */ +function getEnvironmentVariables() { + try { + // Check for Node.js environment + // eslint-disable-next-line no-process-env + if (typeof process !== "undefined" && process.env) { + // eslint-disable-next-line no-process-env + return Object.entries(process.env).reduce((acc, [key, value]) => { + acc[key] = String(value); + return acc; + }, {}); + } + // For browsers and other environments, we may not have direct access to env variables + // Return undefined or any other fallback as required. + return undefined; } - else if (type instanceof ZodBranded) { - return getDiscriminator(type.unwrap()); + catch (e) { + // Catch any errors that might occur while trying to access environment variables + return undefined; } - else if (type instanceof ZodReadonly) { - return getDiscriminator(type.unwrap()); +} +function getEnvironmentVariable(name) { + // Certain Deno setups will throw an error if you try to access environment variables + // https://github.com/hwchase17/langchainjs/issues/1412 + try { + return typeof process !== "undefined" + ? // eslint-disable-next-line no-process-env + process.env?.[name] + : undefined; } - else if (type instanceof ZodCatch) { - return getDiscriminator(type._def.innerType); + catch (e) { + return undefined; } - else { - return []; +} +function getLangSmithEnvironmentVariable(name) { + return (getEnvironmentVariable(`LANGSMITH_${name}`) || + getEnvironmentVariable(`LANGCHAIN_${name}`)); +} +function setEnvironmentVariable(name, value) { + if (typeof process !== "undefined") { + // eslint-disable-next-line no-process-env + process.env[name] = value; } -}; -class ZodDiscriminatedUnion extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.object) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.object, - received: ctx.parsedType, - }); - return INVALID; +} +let cachedCommitSHAs; +/** + * Get the Git commit SHA from common environment variables + * used by different CI/CD platforms. + * @returns {string | undefined} The Git commit SHA or undefined if not found. + */ +function getShas() { + if (cachedCommitSHAs !== undefined) { + return cachedCommitSHAs; + } + const common_release_envs = [ + "VERCEL_GIT_COMMIT_SHA", + "NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA", + "COMMIT_REF", + "RENDER_GIT_COMMIT", + "CI_COMMIT_SHA", + "CIRCLE_SHA1", + "CF_PAGES_COMMIT_SHA", + "REACT_APP_GIT_SHA", + "SOURCE_VERSION", + "GITHUB_SHA", + "TRAVIS_COMMIT", + "GIT_COMMIT", + "BUILD_VCS_NUMBER", + "bamboo_planRepository_revision", + "Build.SourceVersion", + "BITBUCKET_COMMIT", + "DRONE_COMMIT_SHA", + "SEMAPHORE_GIT_SHA", + "BUILDKITE_COMMIT", + ]; + const shas = {}; + for (const env of common_release_envs) { + const envVar = getEnvironmentVariable(env); + if (envVar !== undefined) { + shas[env] = envVar; } - const discriminator = this.discriminator; - const discriminatorValue = ctx.data[discriminator]; - const option = this.optionsMap.get(discriminatorValue); - if (!option) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_union_discriminator, - options: Array.from(this.optionsMap.keys()), - path: [discriminator], - }); - return INVALID; + } + cachedCommitSHAs = shas; + return shas; +} +function getOtelEnabled() { + return (getEnvironmentVariable("OTEL_ENABLED") === "true" || + getLangSmithEnvironmentVariable("OTEL_ENABLED") === "true"); +} + +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/singletons/otel.js +// Should not import any OTEL packages to avoid pulling in optional deps. + +class MockTracer { + constructor() { + Object.defineProperty(this, "hasWarned", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + } + startActiveSpan(_name, ...args) { + if (!this.hasWarned && getOtelEnabled()) { + console.warn("You have enabled OTEL export via the `OTEL_ENABLED` or `LANGSMITH_OTEL_ENABLED` environment variable, but have not initialized the required OTEL instances. " + + 'Please add:\n```\nimport { initializeOTEL } from "langsmith/experimental/otel/setup";\ninitializeOTEL();\n```\nat the beginning of your code.'); + this.hasWarned = true; } - if (ctx.common.async) { - return option._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }); + // Handle different overloads: + // startActiveSpan(name, fn) + // startActiveSpan(name, options, fn) + // startActiveSpan(name, options, context, fn) + let fn; + if (args.length === 1 && typeof args[0] === "function") { + fn = args[0]; } - else { - return option._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }); + else if (args.length === 2 && typeof args[1] === "function") { + fn = args[1]; } + else if (args.length === 3 && typeof args[2] === "function") { + fn = args[2]; + } + if (typeof fn === "function") { + return fn(); + } + return undefined; } - get discriminator() { - return this._def.discriminator; - } - get options() { - return this._def.options; +} +class MockOTELTrace { + constructor() { + Object.defineProperty(this, "mockTracer", { + enumerable: true, + configurable: true, + writable: true, + value: new MockTracer() + }); } - get optionsMap() { - return this._def.optionsMap; + getTracer(_name, _version) { + return this.mockTracer; } - /** - * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor. - * However, it only allows a union of objects, all of which need to share a discriminator property. This property must - * have a different value for each object in the union. - * @param discriminator the name of the discriminator property - * @param types an array of object schemas - * @param params - */ - static create(discriminator, options, params) { - // Get all the valid discriminator values - const optionsMap = new Map(); - // try { - for (const type of options) { - const discriminatorValues = getDiscriminator(type.shape[discriminator]); - if (!discriminatorValues.length) { - throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); - } - for (const value of discriminatorValues) { - if (optionsMap.has(value)) { - throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); - } - optionsMap.set(value, type); - } - } - return new ZodDiscriminatedUnion({ - typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion, - discriminator, - options, - optionsMap, - ...processCreateParams(params), - }); + getActiveSpan() { + return undefined; } -} -function mergeValues(a, b) { - const aType = getParsedType(a); - const bType = getParsedType(b); - if (a === b) { - return { valid: true, data: a }; + setSpan(context, _span) { + return context; } - else if (aType === ZodParsedType.object && bType === ZodParsedType.object) { - const bKeys = util.objectKeys(b); - const sharedKeys = util - .objectKeys(a) - .filter((key) => bKeys.indexOf(key) !== -1); - const newObj = { ...a, ...b }; - for (const key of sharedKeys) { - const sharedValue = mergeValues(a[key], b[key]); - if (!sharedValue.valid) { - return { valid: false }; - } - newObj[key] = sharedValue.data; - } - return { valid: true, data: newObj }; + getSpan(_context) { + return undefined; } - else if (aType === ZodParsedType.array && bType === ZodParsedType.array) { - if (a.length !== b.length) { - return { valid: false }; - } - const newArray = []; - for (let index = 0; index < a.length; index++) { - const itemA = a[index]; - const itemB = b[index]; - const sharedValue = mergeValues(itemA, itemB); - if (!sharedValue.valid) { - return { valid: false }; - } - newArray.push(sharedValue.data); - } - return { valid: true, data: newArray }; + setSpanContext(context, _spanContext) { + return context; } - else if (aType === ZodParsedType.date && - bType === ZodParsedType.date && - +a === +b) { - return { valid: true, data: a }; + getTracerProvider() { + return undefined; } - else { - return { valid: false }; + setGlobalTracerProvider(_tracerProvider) { + return false; } } -class ZodIntersection extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - const handleParsed = (parsedLeft, parsedRight) => { - if (isAborted(parsedLeft) || isAborted(parsedRight)) { - return INVALID; - } - const merged = mergeValues(parsedLeft.value, parsedRight.value); - if (!merged.valid) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_intersection_types, - }); - return INVALID; - } - if (isDirty(parsedLeft) || isDirty(parsedRight)) { - status.dirty(); - } - return { status: status.value, value: merged.data }; - }; - if (ctx.common.async) { - return Promise.all([ - this._def.left._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }), - this._def.right._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }), - ]).then(([left, right]) => handleParsed(left, right)); - } - else { - return handleParsed(this._def.left._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }), this._def.right._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - })); - } +class MockOTELContext { + active() { + return {}; + } + with(_context, fn) { + return fn(); } } -ZodIntersection.create = (left, right, params) => { - return new ZodIntersection({ - left: left, - right: right, - typeName: ZodFirstPartyTypeKind.ZodIntersection, - ...processCreateParams(params), - }); -}; -class ZodTuple extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.array) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.array, - received: ctx.parsedType, - }); - return INVALID; - } - if (ctx.data.length < this._def.items.length) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: this._def.items.length, - inclusive: true, - exact: false, - type: "array", - }); - return INVALID; - } - const rest = this._def.rest; - if (!rest && ctx.data.length > this._def.items.length) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: this._def.items.length, - inclusive: true, - exact: false, - type: "array", - }); - status.dirty(); - } - const items = [...ctx.data] - .map((item, itemIndex) => { - const schema = this._def.items[itemIndex] || this._def.rest; - if (!schema) - return null; - return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)); - }) - .filter((x) => !!x); // filter nulls - if (ctx.common.async) { - return Promise.all(items).then((results) => { - return ParseStatus.mergeArray(status, results); - }); +const OTEL_TRACE_KEY = Symbol.for("ls:otel_trace"); +const OTEL_CONTEXT_KEY = Symbol.for("ls:otel_context"); +const OTEL_GET_DEFAULT_OTLP_TRACER_PROVIDER_KEY = Symbol.for("ls:otel_get_default_otlp_tracer_provider"); +const mockOTELTrace = new MockOTELTrace(); +const mockOTELContext = new MockOTELContext(); +class OTELProvider { + getTraceInstance() { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return globalThis[OTEL_TRACE_KEY] ?? mockOTELTrace; + } + getContextInstance() { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return globalThis[OTEL_CONTEXT_KEY] ?? mockOTELContext; + } + initializeGlobalInstances(otel) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + if (globalThis[OTEL_TRACE_KEY] === undefined) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + globalThis[OTEL_TRACE_KEY] = otel.trace; } - else { - return ParseStatus.mergeArray(status, items); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + if (globalThis[OTEL_CONTEXT_KEY] === undefined) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + globalThis[OTEL_CONTEXT_KEY] = otel.context; } } - get items() { - return this._def.items; + setDefaultOTLPTracerComponents(components) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + globalThis[OTEL_GET_DEFAULT_OTLP_TRACER_PROVIDER_KEY] = components; } - rest(rest) { - return new ZodTuple({ - ...this._def, - rest, - }); + getDefaultOTLPTracerComponents() { + return (globalThis[OTEL_GET_DEFAULT_OTLP_TRACER_PROVIDER_KEY] ?? + undefined); } } -ZodTuple.create = (schemas, params) => { - if (!Array.isArray(schemas)) { - throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); - } - return new ZodTuple({ - items: schemas, - typeName: ZodFirstPartyTypeKind.ZodTuple, - rest: null, - ...processCreateParams(params), - }); +const OTELProviderSingleton = new OTELProvider(); +/** + * Get the current OTEL trace instance. + * Returns a mock implementation if OTEL is not available. + */ +function getOTELTrace() { + return OTELProviderSingleton.getTraceInstance(); +} +/** + * Get the current OTEL context instance. + * Returns a mock implementation if OTEL is not available. + */ +function getOTELContext() { + return OTELProviderSingleton.getContextInstance(); +} +/** + * Initialize the global OTEL instances. + * Should be called once when OTEL packages are available. + */ +function setOTELInstances(otel) { + OTELProviderSingleton.initializeGlobalInstances(otel); +} +/** + * Set a getter function for the default OTLP tracer provider. + * This allows lazy initialization of the tracer provider. + */ +function setDefaultOTLPTracerComponents(components) { + OTELProviderSingleton.setDefaultOTLPTracerComponents(components); +} +/** + * Get the default OTLP tracer provider instance. + * Returns undefined if not set. + */ +function getDefaultOTLPTracerComponents() { + return OTELProviderSingleton.getDefaultOTLPTracerComponents(); +} + +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/experimental/otel/translator.js + + +const WELL_KNOWN_OPERATION_NAMES = { + llm: "chat", + tool: "execute_tool", + retriever: "embeddings", + embedding: "embeddings", + prompt: "chat", }; -class ZodRecord extends ZodType { - get keySchema() { - return this._def.keyType; +function getOperationName(runType) { + return WELL_KNOWN_OPERATION_NAMES[runType] || runType; +} +class LangSmithToOTELTranslator { + constructor() { + Object.defineProperty(this, "spans", { + enumerable: true, + configurable: true, + writable: true, + value: new Map() + }); } - get valueSchema() { - return this._def.valueType; + exportBatch(operations, otelContextMap) { + for (const op of operations) { + try { + if (!op.run) { + continue; + } + if (op.operation === "post") { + const span = this.createSpanForRun(op, op.run, otelContextMap.get(op.id)); + if (span && !op.run.end_time) { + this.spans.set(op.id, span); + } + } + else { + this.updateSpanForRun(op, op.run); + } + } + catch (e) { + console.error(`Error processing operation ${op.id}:`, e); + } + } } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.object) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.object, - received: ctx.parsedType, - }); - return INVALID; + createSpanForRun(op, runInfo, otelContext) { + const activeSpan = otelContext && getOTELTrace().getSpan(otelContext); + if (!activeSpan) { + return; } - const pairs = []; - const keyType = this._def.keyType; - const valueType = this._def.valueType; - for (const key in ctx.data) { - pairs.push({ - key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)), - value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)), - alwaysSet: key in ctx.data, - }); + try { + return this.finishSpanSetup(activeSpan, runInfo, op); } - if (ctx.common.async) { - return ParseStatus.mergeObjectAsync(status, pairs); + catch (e) { + console.error(`Failed to create span for run ${op.id}:`, e); + return undefined; + } + } + finishSpanSetup(span, runInfo, op) { + // Set all attributes + this.setSpanAttributes(span, runInfo, op); + // Set status based on error + if (runInfo.error) { + span.setStatus({ code: 2 }); // ERROR status + span.recordException(new Error(runInfo.error)); } else { - return ParseStatus.mergeObjectSync(status, pairs); + span.setStatus({ code: 1 }); // OK status + } + // End the span if end_time is present + if (runInfo.end_time) { + span.end(new Date(runInfo.end_time)); } + return span; } - get element() { - return this._def.valueType; + updateSpanForRun(op, runInfo) { + try { + const span = this.spans.get(op.id); + if (!span) { + console.debug(`No span found for run ${op.id} during update`); + return; + } + // Update attributes + this.setSpanAttributes(span, runInfo, op); + // Update status based on error + if (runInfo.error) { + span.setStatus({ code: 2 }); // ERROR status + span.recordException(new Error(runInfo.error)); + } + else { + span.setStatus({ code: 1 }); // OK status + } + // End the span if end_time is present + const endTime = runInfo.end_time; + if (endTime) { + span.end(new Date(endTime)); + this.spans.delete(op.id); + } + } + catch (e) { + console.error(`Failed to update span for run ${op.id}:`, e); + } } - static create(first, second, third) { - if (second instanceof ZodType) { - return new ZodRecord({ - keyType: first, - valueType: second, - typeName: ZodFirstPartyTypeKind.ZodRecord, - ...processCreateParams(third), - }); + extractModelName(runInfo) { + // Try to get model name from metadata + if (runInfo.extra?.metadata) { + const metadata = runInfo.extra.metadata; + // First check for ls_model_name in metadata + if (metadata.ls_model_name) { + return metadata.ls_model_name; + } + // Then check invocation_params for model info + if (metadata.invocation_params) { + const invocationParams = metadata.invocation_params; + if (invocationParams.model) { + return invocationParams.model; + } + else if (invocationParams.model_name) { + return invocationParams.model_name; + } + } } - return new ZodRecord({ - keyType: ZodString.create(), - valueType: first, - typeName: ZodFirstPartyTypeKind.ZodRecord, - ...processCreateParams(second), - }); + return; } -} -class ZodMap extends ZodType { - get keySchema() { - return this._def.keyType; + setSpanAttributes(span, runInfo, op) { + if ("run_type" in runInfo && runInfo.run_type) { + span.setAttribute(LANGSMITH_RUN_TYPE, runInfo.run_type); + // Set GenAI attributes according to OTEL semantic conventions + const operationName = getOperationName(runInfo.run_type || "chain"); + span.setAttribute(GEN_AI_OPERATION_NAME, operationName); + } + if ("name" in runInfo && runInfo.name) { + span.setAttribute(LANGSMITH_NAME, runInfo.name); + } + if ("session_id" in runInfo && runInfo.session_id) { + span.setAttribute(LANGSMITH_SESSION_ID, runInfo.session_id); + } + if ("session_name" in runInfo && runInfo.session_name) { + span.setAttribute(LANGSMITH_SESSION_NAME, runInfo.session_name); + } + // Set gen_ai.system + this.setGenAiSystem(span, runInfo); + // Set model name if available + const modelName = this.extractModelName(runInfo); + if (modelName) { + span.setAttribute(GEN_AI_REQUEST_MODEL, modelName); + } + // Set token usage information + if ("prompt_tokens" in runInfo && + typeof runInfo.prompt_tokens === "number") { + span.setAttribute(GEN_AI_USAGE_INPUT_TOKENS, runInfo.prompt_tokens); + } + if ("completion_tokens" in runInfo && + typeof runInfo.completion_tokens === "number") { + span.setAttribute(GEN_AI_USAGE_OUTPUT_TOKENS, runInfo.completion_tokens); + } + if ("total_tokens" in runInfo && typeof runInfo.total_tokens === "number") { + span.setAttribute(GEN_AI_USAGE_TOTAL_TOKENS, runInfo.total_tokens); + } + // Set other parameters from invocation_params + this.setInvocationParameters(span, runInfo); + // Set metadata and tags if available + const metadata = runInfo.extra?.metadata || {}; + for (const [key, value] of Object.entries(metadata)) { + if (value !== null && value !== undefined) { + span.setAttribute(`${LANGSMITH_METADATA}.${key}`, String(value)); + } + } + const tags = runInfo.tags; + if (tags && Array.isArray(tags)) { + span.setAttribute(LANGSMITH_TAGS, tags.join(", ")); + } + else if (tags) { + span.setAttribute(LANGSMITH_TAGS, String(tags)); + } + // Support additional serialized attributes, if present + if ("serialized" in runInfo && typeof runInfo.serialized === "object") { + const serialized = runInfo.serialized; + if (serialized.name) { + span.setAttribute(GEN_AI_SERIALIZED_NAME, String(serialized.name)); + } + if (serialized.signature) { + span.setAttribute(GEN_AI_SERIALIZED_SIGNATURE, String(serialized.signature)); + } + if (serialized.doc) { + span.setAttribute(GEN_AI_SERIALIZED_DOC, String(serialized.doc)); + } + } + // Set inputs/outputs if available + this.setIOAttributes(span, op); } - get valueSchema() { - return this._def.valueType; + setGenAiSystem(span, runInfo) { + // Default to "langchain" if we can't determine the system + let system = "langchain"; + // Extract model name to determine the system + const modelName = this.extractModelName(runInfo); + if (modelName) { + const modelLower = modelName.toLowerCase(); + if (modelLower.includes("anthropic") || modelLower.startsWith("claude")) { + system = "anthropic"; + } + else if (modelLower.includes("bedrock")) { + system = "aws.bedrock"; + } + else if (modelLower.includes("azure") && + modelLower.includes("openai")) { + system = "az.ai.openai"; + } + else if (modelLower.includes("azure") && + modelLower.includes("inference")) { + system = "az.ai.inference"; + } + else if (modelLower.includes("cohere")) { + system = "cohere"; + } + else if (modelLower.includes("deepseek")) { + system = "deepseek"; + } + else if (modelLower.includes("gemini")) { + system = "gemini"; + } + else if (modelLower.includes("groq")) { + system = "groq"; + } + else if (modelLower.includes("watson") || modelLower.includes("ibm")) { + system = "ibm.watsonx.ai"; + } + else if (modelLower.includes("mistral")) { + system = "mistral_ai"; + } + else if (modelLower.includes("gpt") || modelLower.includes("openai")) { + system = "openai"; + } + else if (modelLower.includes("perplexity") || + modelLower.includes("sonar")) { + system = "perplexity"; + } + else if (modelLower.includes("vertex")) { + system = "vertex_ai"; + } + else if (modelLower.includes("xai") || modelLower.includes("grok")) { + system = "xai"; + } + } + span.setAttribute(GEN_AI_SYSTEM, system); } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.map) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.map, - received: ctx.parsedType, - }); - return INVALID; + setInvocationParameters(span, runInfo) { + if (!runInfo.extra?.metadata?.invocation_params) { + return; } - const keyType = this._def.keyType; - const valueType = this._def.valueType; - const pairs = [...ctx.data.entries()].map(([key, value], index) => { - return { - key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])), - value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])), - }; - }); - if (ctx.common.async) { - const finalMap = new Map(); - return Promise.resolve().then(async () => { - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - if (key.status === "aborted" || value.status === "aborted") { - return INVALID; + const invocationParams = runInfo.extra.metadata.invocation_params; + // Set relevant invocation parameters + if (invocationParams.max_tokens !== undefined) { + span.setAttribute(GEN_AI_REQUEST_MAX_TOKENS, invocationParams.max_tokens); + } + if (invocationParams.temperature !== undefined) { + span.setAttribute(GEN_AI_REQUEST_TEMPERATURE, invocationParams.temperature); + } + if (invocationParams.top_p !== undefined) { + span.setAttribute(GEN_AI_REQUEST_TOP_P, invocationParams.top_p); + } + if (invocationParams.frequency_penalty !== undefined) { + span.setAttribute(GEN_AI_REQUEST_FREQUENCY_PENALTY, invocationParams.frequency_penalty); + } + if (invocationParams.presence_penalty !== undefined) { + span.setAttribute(GEN_AI_REQUEST_PRESENCE_PENALTY, invocationParams.presence_penalty); + } + } + setIOAttributes(span, op) { + if (op.run.inputs) { + try { + const inputs = op.run.inputs; + if (typeof inputs === "object" && inputs !== null) { + if (inputs.model && Array.isArray(inputs.messages)) { + span.setAttribute(GEN_AI_REQUEST_MODEL, inputs.model); } - if (key.status === "dirty" || value.status === "dirty") { - status.dirty(); + // Set additional request attributes if available + if (inputs.stream !== undefined) { + span.setAttribute(LANGSMITH_REQUEST_STREAMING, inputs.stream); + } + if (inputs.extra_headers) { + span.setAttribute(LANGSMITH_REQUEST_HEADERS, JSON.stringify(inputs.extra_headers)); + } + if (inputs.extra_query) { + span.setAttribute(GEN_AI_REQUEST_EXTRA_QUERY, JSON.stringify(inputs.extra_query)); + } + if (inputs.extra_body) { + span.setAttribute(GEN_AI_REQUEST_EXTRA_BODY, JSON.stringify(inputs.extra_body)); } - finalMap.set(key.value, value.value); } - return { status: status.value, value: finalMap }; - }); + span.setAttribute(GENAI_PROMPT, JSON.stringify(inputs)); + } + catch (e) { + console.debug(`Failed to process inputs for run ${op.id}`, e); + } } - else { - const finalMap = new Map(); - for (const pair of pairs) { - const key = pair.key; - const value = pair.value; - if (key.status === "aborted" || value.status === "aborted") { - return INVALID; - } - if (key.status === "dirty" || value.status === "dirty") { - status.dirty(); + if (op.run.outputs) { + try { + const outputs = op.run.outputs; + // Extract token usage from outputs (for LLM runs) + const tokenUsage = this.getUnifiedRunTokens(outputs); + if (tokenUsage) { + span.setAttribute(GEN_AI_USAGE_INPUT_TOKENS, tokenUsage[0]); + span.setAttribute(GEN_AI_USAGE_OUTPUT_TOKENS, tokenUsage[1]); + span.setAttribute(GEN_AI_USAGE_TOTAL_TOKENS, tokenUsage[0] + tokenUsage[1]); + } + if (outputs && typeof outputs === "object") { + if (outputs.model) { + span.setAttribute(GEN_AI_RESPONSE_MODEL, String(outputs.model)); + } + // Extract additional response attributes + if (outputs.id) { + span.setAttribute(GEN_AI_RESPONSE_ID, outputs.id); + } + if (outputs.choices && Array.isArray(outputs.choices)) { + const finishReasons = outputs.choices + // eslint-disable-next-line @typescript-eslint/no-explicit-any + .map((choice) => choice.finish_reason) + // eslint-disable-next-line @typescript-eslint/no-explicit-any + .filter((reason) => reason) + .map(String); + if (finishReasons.length > 0) { + span.setAttribute(GEN_AI_RESPONSE_FINISH_REASONS, finishReasons.join(", ")); + } + } + if (outputs.service_tier) { + span.setAttribute(GEN_AI_RESPONSE_SERVICE_TIER, outputs.service_tier); + } + if (outputs.system_fingerprint) { + span.setAttribute(GEN_AI_RESPONSE_SYSTEM_FINGERPRINT, outputs.system_fingerprint); + } + if (outputs.usage_metadata && + typeof outputs.usage_metadata === "object") { + const usageMetadata = outputs.usage_metadata; + if (usageMetadata.input_token_details) { + span.setAttribute(GEN_AI_USAGE_INPUT_TOKEN_DETAILS, JSON.stringify(usageMetadata.input_token_details)); + } + if (usageMetadata.output_token_details) { + span.setAttribute(GEN_AI_USAGE_OUTPUT_TOKEN_DETAILS, JSON.stringify(usageMetadata.output_token_details)); + } + } } - finalMap.set(key.value, value.value); + span.setAttribute(GENAI_COMPLETION, JSON.stringify(outputs)); + } + catch (e) { + console.debug(`Failed to process outputs for run ${op.id}`, e); } - return { status: status.value, value: finalMap }; } } -} -ZodMap.create = (keyType, valueType, params) => { - return new ZodMap({ - valueType, - keyType, - typeName: ZodFirstPartyTypeKind.ZodMap, - ...processCreateParams(params), - }); -}; -class ZodSet extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.set) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.set, - received: ctx.parsedType, - }); - return INVALID; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + getUnifiedRunTokens(outputs) { + if (!outputs) { + return null; } - const def = this._def; - if (def.minSize !== null) { - if (ctx.data.size < def.minSize.value) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: def.minSize.value, - type: "set", - inclusive: true, - exact: false, - message: def.minSize.message, - }); - status.dirty(); - } + // Search in non-generations lists + let tokenUsage = this.extractUnifiedRunTokens(outputs.usage_metadata); + if (tokenUsage) { + return tokenUsage; } - if (def.maxSize !== null) { - if (ctx.data.size > def.maxSize.value) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: def.maxSize.value, - type: "set", - inclusive: true, - exact: false, - message: def.maxSize.message, - }); - status.dirty(); + // Find if direct kwarg in outputs + const keys = Object.keys(outputs); + for (const key of keys) { + const haystack = outputs[key]; + if (!haystack || typeof haystack !== "object") { + continue; + } + tokenUsage = this.extractUnifiedRunTokens(haystack.usage_metadata); + if (tokenUsage) { + return tokenUsage; + } + if (haystack.lc === 1 && + haystack.kwargs && + typeof haystack.kwargs === "object") { + tokenUsage = this.extractUnifiedRunTokens(haystack.kwargs.usage_metadata); + if (tokenUsage) { + return tokenUsage; + } } } - const valueType = this._def.valueType; - function finalizeSet(elements) { - const parsedSet = new Set(); - for (const element of elements) { - if (element.status === "aborted") - return INVALID; - if (element.status === "dirty") - status.dirty(); - parsedSet.add(element.value); + // Find in generations + const generations = outputs.generations || []; + if (!Array.isArray(generations)) { + return null; + } + const flatGenerations = Array.isArray(generations[0]) + ? generations.flat() + : generations; + for (const generation of flatGenerations) { + if (typeof generation === "object" && + generation.message && + typeof generation.message === "object" && + generation.message.kwargs && + typeof generation.message.kwargs === "object") { + tokenUsage = this.extractUnifiedRunTokens(generation.message.kwargs.usage_metadata); + if (tokenUsage) { + return tokenUsage; + } } - return { status: status.value, value: parsedSet }; } - const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i))); - if (ctx.common.async) { - return Promise.all(elements).then((elements) => finalizeSet(elements)); + return null; + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + extractUnifiedRunTokens(outputs) { + if (!outputs || typeof outputs !== "object") { + return null; } - else { - return finalizeSet(elements); + if (typeof outputs.input_tokens !== "number" || + typeof outputs.output_tokens !== "number") { + return null; } + return [outputs.input_tokens, outputs.output_tokens]; } - min(minSize, message) { - return new ZodSet({ - ...this._def, - minSize: { value: minSize, message: errorUtil.toString(message) }, +} + +// EXTERNAL MODULE: ./node_modules/p-queue/dist/index.js +var p_queue_dist = __nccwpck_require__(6459); +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/async_caller.js + + + +const STATUS_NO_RETRY = [ + 400, // Bad Request + 401, // Unauthorized + 403, // Forbidden + 404, // Not Found + 405, // Method Not Allowed + 406, // Not Acceptable + 407, // Proxy Authentication Required + 408, // Request Timeout +]; +const STATUS_IGNORE = [ + 409, // Conflict +]; +/** + * A class that can be used to make async calls with concurrency and retry logic. + * + * This is useful for making calls to any kind of "expensive" external resource, + * be it because it's rate-limited, subject to network issues, etc. + * + * Concurrent calls are limited by the `maxConcurrency` parameter, which defaults + * to `Infinity`. This means that by default, all calls will be made in parallel. + * + * Retries are limited by the `maxRetries` parameter, which defaults to 6. This + * means that by default, each call will be retried up to 6 times, with an + * exponential backoff between each attempt. + */ +class AsyncCaller { + constructor(params) { + Object.defineProperty(this, "maxConcurrency", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 }); - } - max(maxSize, message) { - return new ZodSet({ - ...this._def, - maxSize: { value: maxSize, message: errorUtil.toString(message) }, + Object.defineProperty(this, "maxRetries", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 }); - } - size(size, message) { - return this.min(size, message).max(size, message); - } - nonempty(message) { - return this.min(1, message); - } -} -ZodSet.create = (valueType, params) => { - return new ZodSet({ - valueType, - minSize: null, - maxSize: null, - typeName: ZodFirstPartyTypeKind.ZodSet, - ...processCreateParams(params), - }); -}; -class ZodFunction extends ZodType { - constructor() { - super(...arguments); - this.validate = this.implement; - } - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.function) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.function, - received: ctx.parsedType, - }); - return INVALID; - } - function makeArgsIssue(args, error) { - return makeIssue({ - data: args, - path: ctx.path, - errorMaps: [ - ctx.common.contextualErrorMap, - ctx.schemaErrorMap, - getErrorMap(), - errorMap, - ].filter((x) => !!x), - issueData: { - code: ZodIssueCode.invalid_arguments, - argumentsError: error, - }, + Object.defineProperty(this, "queue", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "onFailedResponseHook", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "debug", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.maxConcurrency = params.maxConcurrency ?? Infinity; + this.maxRetries = params.maxRetries ?? 6; + this.debug = params.debug; + if ( true) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + this.queue = new p_queue_dist["default"]({ + concurrency: this.maxConcurrency, }); } - function makeReturnsIssue(returns, error) { - return makeIssue({ - data: returns, - path: ctx.path, - errorMaps: [ - ctx.common.contextualErrorMap, - ctx.schemaErrorMap, - getErrorMap(), - errorMap, - ].filter((x) => !!x), - issueData: { - code: ZodIssueCode.invalid_return_type, - returnTypeError: error, - }, - }); + else { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + this.queue = new p_queue_dist({ concurrency: this.maxConcurrency }); } - const params = { errorMap: ctx.common.contextualErrorMap }; - const fn = ctx.data; - if (this._def.returns instanceof ZodPromise) { - // Would love a way to avoid disabling this rule, but we need - // an alias (using an arrow function was what caused 2651). - // eslint-disable-next-line @typescript-eslint/no-this-alias - const me = this; - return OK(async function (...args) { - const error = new ZodError([]); - const parsedArgs = await me._def.args - .parseAsync(args, params) - .catch((e) => { - error.addIssue(makeArgsIssue(args, e)); + this.onFailedResponseHook = params?.onFailedResponseHook; + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + call(callable, ...args) { + const onFailedResponseHook = this.onFailedResponseHook; + return this.queue.add(() => p_retry(() => callable(...args).catch((error) => { + // eslint-disable-next-line no-instanceof/no-instanceof + if (error instanceof Error) { + throw error; + } + else { + throw new Error(error); + } + }), { + async onFailedAttempt(error) { + if (error.message.startsWith("Cancel") || + error.message.startsWith("TimeoutError") || + error.message.startsWith("AbortError")) { throw error; - }); - const result = await Reflect.apply(fn, this, parsedArgs); - const parsedReturns = await me._def.returns._def.type - .parseAsync(result, params) - .catch((e) => { - error.addIssue(makeReturnsIssue(result, e)); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + if (error?.code === "ECONNABORTED") { throw error; - }); - return parsedReturns; - }); - } - else { - // Would love a way to avoid disabling this rule, but we need - // an alias (using an arrow function was what caused 2651). - // eslint-disable-next-line @typescript-eslint/no-this-alias - const me = this; - return OK(function (...args) { - const parsedArgs = me._def.args.safeParse(args, params); - if (!parsedArgs.success) { - throw new ZodError([makeArgsIssue(args, parsedArgs.error)]); } - const result = Reflect.apply(fn, this, parsedArgs.data); - const parsedReturns = me._def.returns.safeParse(result, params); - if (!parsedReturns.success) { - throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const response = error?.response; + const status = response?.status; + if (status) { + if (STATUS_NO_RETRY.includes(+status)) { + throw error; + } + else if (STATUS_IGNORE.includes(+status)) { + return; + } + if (onFailedResponseHook) { + await onFailedResponseHook(response); + } } - return parsedReturns.data; - }); - } - } - parameters() { - return this._def.args; - } - returnType() { - return this._def.returns; - } - args(...items) { - return new ZodFunction({ - ...this._def, - args: ZodTuple.create(items).rest(ZodUnknown.create()), - }); - } - returns(returnType) { - return new ZodFunction({ - ...this._def, - returns: returnType, - }); - } - implement(func) { - const validatedFunc = this.parse(func); - return validatedFunc; + }, + // If needed we can change some of the defaults here, + // but they're quite sensible. + retries: this.maxRetries, + randomize: true, + }), { throwOnTimeout: true }); } - strictImplement(func) { - const validatedFunc = this.parse(func); - return validatedFunc; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + callWithOptions(options, callable, ...args) { + // Note this doesn't cancel the underlying request, + // when available prefer to use the signal option of the underlying call + if (options.signal) { + return Promise.race([ + this.call(callable, ...args), + new Promise((_, reject) => { + options.signal?.addEventListener("abort", () => { + reject(new Error("AbortError")); + }); + }), + ]); + } + return this.call(callable, ...args); } - static create(args, returns, params) { - return new ZodFunction({ - args: (args - ? args - : ZodTuple.create([]).rest(ZodUnknown.create())), - returns: returns || ZodUnknown.create(), - typeName: ZodFirstPartyTypeKind.ZodFunction, - ...processCreateParams(params), - }); + fetch(...args) { + return this.call(() => _getFetchImplementation(this.debug)(...args).then((res) => res.ok ? res : Promise.reject(res))); } } -class ZodLazy extends ZodType { - get schema() { - return this._def.getter(); - } - _parse(input) { - const { ctx } = this._processInputParams(input); - const lazySchema = this._def.getter(); - return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); - } + +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/messages.js +function isLangChainMessage( +// eslint-disable-next-line @typescript-eslint/no-explicit-any +message) { + return typeof message?._getType === "function"; } -ZodLazy.create = (getter, params) => { - return new ZodLazy({ - getter: getter, - typeName: ZodFirstPartyTypeKind.ZodLazy, - ...processCreateParams(params), - }); -}; -class ZodLiteral extends ZodType { - _parse(input) { - if (input.data !== this._def.value) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - received: ctx.data, - code: ZodIssueCode.invalid_literal, - expected: this._def.value, - }); - return INVALID; - } - return { status: "valid", value: input.data }; - } - get value() { - return this._def.value; +function convertLangChainMessageToExample(message) { + const converted = { + type: message._getType(), + data: { content: message.content }, + }; + // Check for presence of keys in additional_kwargs + if (message?.additional_kwargs && + Object.keys(message.additional_kwargs).length > 0) { + converted.data.additional_kwargs = { ...message.additional_kwargs }; } + return converted; } -ZodLiteral.create = (value, params) => { - return new ZodLiteral({ - value: value, - typeName: ZodFirstPartyTypeKind.ZodLiteral, - ...processCreateParams(params), - }); -}; -function createZodEnum(values, params) { - return new ZodEnum({ - values, - typeName: ZodFirstPartyTypeKind.ZodEnum, - ...processCreateParams(params), - }); + +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/_uuid.js +// Relaxed UUID validation regex (allows any valid UUID format including nil UUIDs) +const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; +function assertUuid(str, which) { + // Use relaxed regex validation instead of strict uuid.validate() + // This allows edge cases like nil UUIDs or test UUIDs that might not pass strict validation + if (!UUID_REGEX.test(str)) { + const msg = which !== undefined + ? `Invalid UUID for ${which}: ${str}` + : `Invalid UUID: ${str}`; + throw new Error(msg); + } + return str; } -class ZodEnum extends ZodType { - constructor() { - super(...arguments); - _ZodEnum_cache.set(this, void 0); + +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/warn.js +const warnedMessages = {}; +function warnOnce(message) { + if (!warnedMessages[message]) { + console.warn(message); + warnedMessages[message] = true; } - _parse(input) { - if (typeof input.data !== "string") { - const ctx = this._getOrReturnCtx(input); - const expectedValues = this._def.values; - addIssueToContext(ctx, { - expected: util.joinValues(expectedValues), - received: ctx.parsedType, - code: ZodIssueCode.invalid_type, - }); - return INVALID; - } - if (!lib_classPrivateFieldGet(this, _ZodEnum_cache, "f")) { - lib_classPrivateFieldSet(this, _ZodEnum_cache, new Set(this._def.values), "f"); - } - if (!lib_classPrivateFieldGet(this, _ZodEnum_cache, "f").has(input.data)) { - const ctx = this._getOrReturnCtx(input); - const expectedValues = this._def.values; - addIssueToContext(ctx, { - received: ctx.data, - code: ZodIssueCode.invalid_enum_value, - options: expectedValues, - }); - return INVALID; - } - return OK(input.data); +} + +// EXTERNAL MODULE: ./node_modules/semver/index.js +var semver = __nccwpck_require__(2088); +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/prompts.js + +function isVersionGreaterOrEqual(current_version, target_version) { + const current = parseVersion(current_version); + const target = parseVersion(target_version); + if (!current || !target) { + throw new Error("Invalid version format."); } - get options() { - return this._def.values; + return current.compare(target) >= 0; +} +function parsePromptIdentifier(identifier) { + if (!identifier || + identifier.split("/").length > 2 || + identifier.startsWith("/") || + identifier.endsWith("/") || + identifier.split(":").length > 2) { + throw new Error(`Invalid identifier format: ${identifier}`); } - get enum() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; + const [ownerNamePart, commitPart] = identifier.split(":"); + const commit = commitPart || "latest"; + if (ownerNamePart.includes("/")) { + const [owner, name] = ownerNamePart.split("/", 2); + if (!owner || !name) { + throw new Error(`Invalid identifier format: ${identifier}`); } - return enumValues; + return [owner, name, commit]; } - get Values() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; + else { + if (!ownerNamePart) { + throw new Error(`Invalid identifier format: ${identifier}`); } - return enumValues; + return ["-", ownerNamePart, commit]; } - get Enum() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; +} + +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/error.js +function getErrorStackTrace(e) { + if (typeof e !== "object" || e == null) + return undefined; + if (!("stack" in e) || typeof e.stack !== "string") + return undefined; + let stack = e.stack; + const prevLine = `${e}`; + if (stack.startsWith(prevLine)) { + stack = stack.slice(prevLine.length); } - extract(values, newDef = this._def) { - return ZodEnum.create(values, { - ...this._def, - ...newDef, - }); + if (stack.startsWith("\n")) { + stack = stack.slice(1); } - exclude(values, newDef = this._def) { - return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), { - ...this._def, - ...newDef, + return stack; +} +function printErrorStackTrace(e) { + const stack = getErrorStackTrace(e); + if (stack == null) + return; + console.error(stack); +} +/** + * LangSmithConflictError + * + * Represents an error that occurs when there's a conflict during an operation, + * typically corresponding to HTTP 409 status code responses. + * + * This error is thrown when an attempt to create or modify a resource conflicts + * with the current state of the resource on the server. Common scenarios include: + * - Attempting to create a resource that already exists + * - Trying to update a resource that has been modified by another process + * - Violating a uniqueness constraint in the data + * + * @extends Error + * + * @example + * try { + * await createProject("existingProject"); + * } catch (error) { + * if (error instanceof ConflictError) { + * console.log("A conflict occurred:", error.message); + * // Handle the conflict, e.g., by suggesting a different project name + * } else { + * // Handle other types of errors + * } + * } + * + * @property {string} name - Always set to 'ConflictError' for easy identification + * @property {string} message - Detailed error message including server response + * + * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/409 + */ +class LangSmithConflictError extends Error { + constructor(message) { + super(message); + Object.defineProperty(this, "status", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 }); + this.name = "LangSmithConflictError"; + this.status = 409; } } -_ZodEnum_cache = new WeakMap(); -ZodEnum.create = createZodEnum; -class ZodNativeEnum extends ZodType { - constructor() { - super(...arguments); - _ZodNativeEnum_cache.set(this, void 0); - } - _parse(input) { - const nativeEnumValues = util.getValidEnumValues(this._def.values); - const ctx = this._getOrReturnCtx(input); - if (ctx.parsedType !== ZodParsedType.string && - ctx.parsedType !== ZodParsedType.number) { - const expectedValues = util.objectValues(nativeEnumValues); - addIssueToContext(ctx, { - expected: util.joinValues(expectedValues), - received: ctx.parsedType, - code: ZodIssueCode.invalid_type, - }); - return INVALID; - } - if (!lib_classPrivateFieldGet(this, _ZodNativeEnum_cache, "f")) { - lib_classPrivateFieldSet(this, _ZodNativeEnum_cache, new Set(util.getValidEnumValues(this._def.values)), "f"); - } - if (!lib_classPrivateFieldGet(this, _ZodNativeEnum_cache, "f").has(input.data)) { - const expectedValues = util.objectValues(nativeEnumValues); - addIssueToContext(ctx, { - received: ctx.data, - code: ZodIssueCode.invalid_enum_value, - options: expectedValues, - }); - return INVALID; +/** + * Throws an appropriate error based on the response status and body. + * + * @param response - The fetch Response object + * @param context - Additional context to include in the error message (e.g., operation being performed) + * @throws {LangSmithConflictError} When the response status is 409 + * @throws {Error} For all other non-ok responses + */ +async function raiseForStatus(response, context, consume) { + // consume the response body to release the connection + // https://undici.nodejs.org/#/?id=garbage-collection + let errorBody; + if (response.ok) { + if (consume) { + errorBody = await response.text(); } - return OK(input.data); + return; } - get enum() { - return this._def.values; + errorBody = await response.text(); + const fullMessage = `Failed to ${context}. Received status [${response.status}]: ${response.statusText}. Server response: ${errorBody}`; + if (response.status === 409) { + throw new LangSmithConflictError(fullMessage); } + const err = new Error(fullMessage); + err.status = response.status; + throw err; } -_ZodNativeEnum_cache = new WeakMap(); -ZodNativeEnum.create = (values, params) => { - return new ZodNativeEnum({ - values: values, - typeName: ZodFirstPartyTypeKind.ZodNativeEnum, - ...processCreateParams(params), - }); -}; -class ZodPromise extends ZodType { - unwrap() { - return this._def.type; - } - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.promise && - ctx.common.async === false) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.promise, - received: ctx.parsedType, - }); - return INVALID; - } - const promisified = ctx.parsedType === ZodParsedType.promise - ? ctx.data - : Promise.resolve(ctx.data); - return OK(promisified.then((data) => { - return this._def.type.parseAsync(data, { - path: ctx.path, - errorMap: ctx.common.contextualErrorMap, - }); - })); +const ERR_CONFLICTING_ENDPOINTS = "ERR_CONFLICTING_ENDPOINTS"; +class ConflictingEndpointsError extends Error { + constructor() { + super("You cannot provide both LANGSMITH_ENDPOINT / LANGCHAIN_ENDPOINT " + + "and LANGSMITH_RUNS_ENDPOINTS."); + Object.defineProperty(this, "code", { + enumerable: true, + configurable: true, + writable: true, + value: ERR_CONFLICTING_ENDPOINTS + }); + this.name = "ConflictingEndpointsError"; // helpful in logs } } -ZodPromise.create = (schema, params) => { - return new ZodPromise({ - type: schema, - typeName: ZodFirstPartyTypeKind.ZodPromise, - ...processCreateParams(params), - }); -}; -class ZodEffects extends ZodType { - innerType() { - return this._def.schema; - } - sourceType() { - return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects - ? this._def.schema.sourceType() - : this._def.schema; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - const effect = this._def.effect || null; - const checkCtx = { - addIssue: (arg) => { - addIssueToContext(ctx, arg); - if (arg.fatal) { - status.abort(); - } - else { - status.dirty(); - } - }, - get path() { - return ctx.path; - }, - }; - checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); - if (effect.type === "preprocess") { - const processed = effect.transform(ctx.data, checkCtx); - if (ctx.common.async) { - return Promise.resolve(processed).then(async (processed) => { - if (status.value === "aborted") - return INVALID; - const result = await this._def.schema._parseAsync({ - data: processed, - path: ctx.path, - parent: ctx, - }); - if (result.status === "aborted") - return INVALID; - if (result.status === "dirty") - return DIRTY(result.value); - if (status.value === "dirty") - return DIRTY(result.value); - return result; - }); - } - else { - if (status.value === "aborted") - return INVALID; - const result = this._def.schema._parseSync({ - data: processed, - path: ctx.path, - parent: ctx, - }); - if (result.status === "aborted") - return INVALID; - if (result.status === "dirty") - return DIRTY(result.value); - if (status.value === "dirty") - return DIRTY(result.value); - return result; - } - } - if (effect.type === "refinement") { - const executeRefinement = (acc) => { - const result = effect.refinement(acc, checkCtx); - if (ctx.common.async) { - return Promise.resolve(result); - } - if (result instanceof Promise) { - throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); - } - return acc; - }; - if (ctx.common.async === false) { - const inner = this._def.schema._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }); - if (inner.status === "aborted") - return INVALID; - if (inner.status === "dirty") - status.dirty(); - // return value is ignored - executeRefinement(inner.value); - return { status: status.value, value: inner.value }; - } - else { - return this._def.schema - ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }) - .then((inner) => { - if (inner.status === "aborted") - return INVALID; - if (inner.status === "dirty") - status.dirty(); - return executeRefinement(inner.value).then(() => { - return { status: status.value, value: inner.value }; - }); - }); - } - } - if (effect.type === "transform") { - if (ctx.common.async === false) { - const base = this._def.schema._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }); - if (!isValid(base)) - return base; - const result = effect.transform(base.value, checkCtx); - if (result instanceof Promise) { - throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); - } - return { status: status.value, value: result }; - } - else { - return this._def.schema - ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }) - .then((base) => { - if (!isValid(base)) - return base; - return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ status: status.value, value: result })); - }); - } - } - util.assertNever(effect); - } +function isConflictingEndpointsError(err) { + return (typeof err === "object" && + err !== null && + err.code === ERR_CONFLICTING_ENDPOINTS); } -ZodEffects.create = (schema, effect, params) => { - return new ZodEffects({ - schema, - typeName: ZodFirstPartyTypeKind.ZodEffects, - effect, - ...processCreateParams(params), - }); -}; -ZodEffects.createWithPreprocess = (preprocess, schema, params) => { - return new ZodEffects({ - schema, - effect: { type: "preprocess", transform: preprocess }, - typeName: ZodFirstPartyTypeKind.ZodEffects, - ...processCreateParams(params), - }); -}; -class ZodOptional extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType === ZodParsedType.undefined) { - return OK(undefined); - } - return this._def.innerType._parse(input); - } - unwrap() { - return this._def.innerType; - } + +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/fast-safe-stringify/index.js +/* eslint-disable */ +// @ts-nocheck + +var LIMIT_REPLACE_NODE = "[...]"; +var CIRCULAR_REPLACE_NODE = { result: "[Circular]" }; +var arr = []; +var replacerStack = []; +const encoder = new TextEncoder(); +function defaultOptions() { + return { + depthLimit: Number.MAX_SAFE_INTEGER, + edgesLimit: Number.MAX_SAFE_INTEGER, + }; } -ZodOptional.create = (type, params) => { - return new ZodOptional({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodOptional, - ...processCreateParams(params), - }); -}; -class ZodNullable extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType === ZodParsedType.null) { - return OK(null); +function encodeString(str) { + return encoder.encode(str); +} +// Shared function to handle well-known types +function serializeWellKnownTypes(val) { + if (val && typeof val === "object" && val !== null) { + if (val instanceof Map) { + return Object.fromEntries(val); + } + else if (val instanceof Set) { + return Array.from(val); + } + else if (val instanceof Date) { + return val.toISOString(); + } + else if (val instanceof RegExp) { + return val.toString(); + } + else if (val instanceof Error) { + return { + name: val.name, + message: val.message, + }; } - return this._def.innerType._parse(input); } - unwrap() { - return this._def.innerType; + else if (typeof val === "bigint") { + return val.toString(); } + return val; } -ZodNullable.create = (type, params) => { - return new ZodNullable({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodNullable, - ...processCreateParams(params), - }); -}; -class ZodDefault extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - let data = ctx.data; - if (ctx.parsedType === ZodParsedType.undefined) { - data = this._def.defaultValue(); +// Default replacer function to handle well-known types +function createDefaultReplacer(userReplacer) { + return function (key, val) { + // Apply user replacer first if provided + if (userReplacer) { + const userResult = userReplacer.call(this, key, val); + // If user replacer returned undefined, fall back to our serialization + if (userResult !== undefined) { + return userResult; + } } - return this._def.innerType._parse({ - data, - path: ctx.path, - parent: ctx, - }); + // Fall back to our well-known type handling + return serializeWellKnownTypes(val); + }; +} +// Regular stringify +function serialize(obj, errorContext, replacer, spacer, options) { + try { + const str = JSON.stringify(obj, createDefaultReplacer(replacer), spacer); + return encodeString(str); } - removeDefault() { - return this._def.innerType; + catch (e) { + // Fall back to more complex stringify if circular reference + if (!e.message?.includes("Converting circular structure to JSON")) { + console.warn(`[WARNING]: LangSmith received unserializable value.${errorContext ? `\nContext: ${errorContext}` : ""}`); + return encodeString("[Unserializable]"); + } + getLangSmithEnvironmentVariable("SUPPRESS_CIRCULAR_JSON_WARNINGS") !== + "true" && + console.warn(`[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. ${errorContext ? `\nContext: ${errorContext}` : ""}`); + if (typeof options === "undefined") { + options = defaultOptions(); + } + decirc(obj, "", 0, [], undefined, 0, options); + let res; + try { + if (replacerStack.length === 0) { + res = JSON.stringify(obj, replacer, spacer); + } + else { + res = JSON.stringify(obj, replaceGetterValues(replacer), spacer); + } + } + catch (_) { + return encodeString("[unable to serialize, circular reference is too complex to analyze]"); + } + finally { + while (arr.length !== 0) { + const part = arr.pop(); + if (part.length === 4) { + Object.defineProperty(part[0], part[1], part[3]); + } + else { + part[0][part[1]] = part[2]; + } + } + } + return encodeString(res); } } -ZodDefault.create = (type, params) => { - return new ZodDefault({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodDefault, - defaultValue: typeof params.default === "function" - ? params.default - : () => params.default, - ...processCreateParams(params), - }); -}; -class ZodCatch extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - // newCtx is used to not collect issues from inner types in ctx - const newCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [], - }, - }; - const result = this._def.innerType._parse({ - data: newCtx.data, - path: newCtx.path, - parent: { - ...newCtx, - }, - }); - if (isAsync(result)) { - return result.then((result) => { - return { - status: "valid", - value: result.status === "valid" - ? result.value - : this._def.catchValue({ - get error() { - return new ZodError(newCtx.common.issues); - }, - input: newCtx.data, - }), - }; - }); +function setReplace(replace, val, k, parent) { + var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k); + if (propertyDescriptor.get !== undefined) { + if (propertyDescriptor.configurable) { + Object.defineProperty(parent, k, { value: replace }); + arr.push([parent, k, val, propertyDescriptor]); } else { - return { - status: "valid", - value: result.status === "valid" - ? result.value - : this._def.catchValue({ - get error() { - return new ZodError(newCtx.common.issues); - }, - input: newCtx.data, - }), - }; + replacerStack.push([val, k, replace]); } } - removeCatch() { - return this._def.innerType; + else { + parent[k] = replace; + arr.push([parent, k, val]); } } -ZodCatch.create = (type, params) => { - return new ZodCatch({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodCatch, - catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, - ...processCreateParams(params), - }); -}; -class ZodNaN extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.nan) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.nan, - received: ctx.parsedType, - }); - return INVALID; +function decirc(val, k, edgeIndex, stack, parent, depth, options) { + depth += 1; + var i; + if (typeof val === "object" && val !== null) { + for (i = 0; i < stack.length; i++) { + if (stack[i] === val) { + setReplace(CIRCULAR_REPLACE_NODE, val, k, parent); + return; + } } - return { status: "valid", value: input.data }; + if (typeof options.depthLimit !== "undefined" && + depth > options.depthLimit) { + setReplace(LIMIT_REPLACE_NODE, val, k, parent); + return; + } + if (typeof options.edgesLimit !== "undefined" && + edgeIndex + 1 > options.edgesLimit) { + setReplace(LIMIT_REPLACE_NODE, val, k, parent); + return; + } + stack.push(val); + // Optimize for Arrays. Big arrays could kill the performance otherwise! + if (Array.isArray(val)) { + for (i = 0; i < val.length; i++) { + decirc(val[i], i, i, stack, val, depth, options); + } + } + else { + // Handle well-known types before Object.keys iteration + val = serializeWellKnownTypes(val); + var keys = Object.keys(val); + for (i = 0; i < keys.length; i++) { + var key = keys[i]; + decirc(val[key], key, i, stack, val, depth, options); + } + } + stack.pop(); } } -ZodNaN.create = (params) => { - return new ZodNaN({ - typeName: ZodFirstPartyTypeKind.ZodNaN, - ...processCreateParams(params), - }); -}; -const BRAND = Symbol("zod_brand"); -class ZodBranded extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - const data = ctx.data; - return this._def.type._parse({ - data, - path: ctx.path, - parent: ctx, - }); +// Stable-stringify +function compareFunction(a, b) { + if (a < b) { + return -1; } - unwrap() { - return this._def.type; + if (a > b) { + return 1; } + return 0; } -class ZodPipeline extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.common.async) { - const handleAsync = async () => { - const inResult = await this._def.in._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }); - if (inResult.status === "aborted") - return INVALID; - if (inResult.status === "dirty") { - status.dirty(); - return DIRTY(inResult.value); - } - else { - return this._def.out._parseAsync({ - data: inResult.value, - path: ctx.path, - parent: ctx, - }); - } - }; - return handleAsync(); +function deterministicStringify(obj, replacer, spacer, options) { + if (typeof options === "undefined") { + options = defaultOptions(); + } + var tmp = deterministicDecirc(obj, "", 0, [], undefined, 0, options) || obj; + var res; + try { + if (replacerStack.length === 0) { + res = JSON.stringify(tmp, replacer, spacer); } else { - const inResult = this._def.in._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }); - if (inResult.status === "aborted") - return INVALID; - if (inResult.status === "dirty") { - status.dirty(); - return { - status: "dirty", - value: inResult.value, - }; + res = JSON.stringify(tmp, replaceGetterValues(replacer), spacer); + } + } + catch (_) { + return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]"); + } + finally { + // Ensure that we restore the object as it was. + while (arr.length !== 0) { + var part = arr.pop(); + if (part.length === 4) { + Object.defineProperty(part[0], part[1], part[3]); } else { - return this._def.out._parseSync({ - data: inResult.value, - path: ctx.path, - parent: ctx, - }); + part[0][part[1]] = part[2]; } } } - static create(a, b) { - return new ZodPipeline({ - in: a, - out: b, - typeName: ZodFirstPartyTypeKind.ZodPipeline, - }); - } + return res; } -class ZodReadonly extends ZodType { - _parse(input) { - const result = this._def.innerType._parse(input); - const freeze = (data) => { - if (isValid(data)) { - data.value = Object.freeze(data.value); +function deterministicDecirc(val, k, edgeIndex, stack, parent, depth, options) { + depth += 1; + var i; + if (typeof val === "object" && val !== null) { + for (i = 0; i < stack.length; i++) { + if (stack[i] === val) { + setReplace(CIRCULAR_REPLACE_NODE, val, k, parent); + return; } - return data; - }; - return isAsync(result) - ? result.then((data) => freeze(data)) - : freeze(result); - } - unwrap() { - return this._def.innerType; + } + try { + if (typeof val.toJSON === "function") { + return; + } + } + catch (_) { + return; + } + if (typeof options.depthLimit !== "undefined" && + depth > options.depthLimit) { + setReplace(LIMIT_REPLACE_NODE, val, k, parent); + return; + } + if (typeof options.edgesLimit !== "undefined" && + edgeIndex + 1 > options.edgesLimit) { + setReplace(LIMIT_REPLACE_NODE, val, k, parent); + return; + } + stack.push(val); + // Optimize for Arrays. Big arrays could kill the performance otherwise! + if (Array.isArray(val)) { + for (i = 0; i < val.length; i++) { + deterministicDecirc(val[i], i, i, stack, val, depth, options); + } + } + else { + // Handle well-known types before Object.keys iteration + val = serializeWellKnownTypes(val); + // Create a temporary object in the required way + var tmp = {}; + var keys = Object.keys(val).sort(compareFunction); + for (i = 0; i < keys.length; i++) { + var key = keys[i]; + deterministicDecirc(val[key], key, i, stack, val, depth, options); + tmp[key] = val[key]; + } + if (typeof parent !== "undefined") { + arr.push([parent, k, val]); + parent[k] = tmp; + } + else { + return tmp; + } + } + stack.pop(); } } -ZodReadonly.create = (type, params) => { - return new ZodReadonly({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodReadonly, - ...processCreateParams(params), - }); -}; -//////////////////////////////////////// -//////////////////////////////////////// -////////// ////////// -////////// z.custom ////////// -////////// ////////// -//////////////////////////////////////// -//////////////////////////////////////// -function cleanParams(params, data) { - const p = typeof params === "function" - ? params(data) - : typeof params === "string" - ? { message: params } - : params; - const p2 = typeof p === "string" ? { message: p } : p; - return p2; -} -function custom(check, _params = {}, -/** - * @deprecated - * - * Pass `fatal` into the params object instead: - * - * ```ts - * z.string().custom((val) => val.length > 5, { fatal: false }) - * ``` - * - */ -fatal) { - if (check) - return ZodAny.create().superRefine((data, ctx) => { - var _a, _b; - const r = check(data); - if (r instanceof Promise) { - return r.then((r) => { - var _a, _b; - if (!r) { - const params = cleanParams(_params, data); - const _fatal = (_b = (_a = params.fatal) !== null && _a !== void 0 ? _a : fatal) !== null && _b !== void 0 ? _b : true; - ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); - } - }); - } - if (!r) { - const params = cleanParams(_params, data); - const _fatal = (_b = (_a = params.fatal) !== null && _a !== void 0 ? _a : fatal) !== null && _b !== void 0 ? _b : true; - ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); +// wraps replacer function to handle values we couldn't replace +// and mark them as replaced value +function replaceGetterValues(replacer) { + replacer = + typeof replacer !== "undefined" + ? replacer + : function (k, v) { + return v; + }; + return function (key, val) { + if (replacerStack.length > 0) { + for (var i = 0; i < replacerStack.length; i++) { + var part = replacerStack[i]; + if (part[1] === key && part[0] === val) { + val = part[2]; + replacerStack.splice(i, 1); + break; + } } - return; - }); - return ZodAny.create(); + } + return replacer.call(this, key, val); + }; } -const late = { - object: ZodObject.lazycreate, -}; -var ZodFirstPartyTypeKind; -(function (ZodFirstPartyTypeKind) { - ZodFirstPartyTypeKind["ZodString"] = "ZodString"; - ZodFirstPartyTypeKind["ZodNumber"] = "ZodNumber"; - ZodFirstPartyTypeKind["ZodNaN"] = "ZodNaN"; - ZodFirstPartyTypeKind["ZodBigInt"] = "ZodBigInt"; - ZodFirstPartyTypeKind["ZodBoolean"] = "ZodBoolean"; - ZodFirstPartyTypeKind["ZodDate"] = "ZodDate"; - ZodFirstPartyTypeKind["ZodSymbol"] = "ZodSymbol"; - ZodFirstPartyTypeKind["ZodUndefined"] = "ZodUndefined"; - ZodFirstPartyTypeKind["ZodNull"] = "ZodNull"; - ZodFirstPartyTypeKind["ZodAny"] = "ZodAny"; - ZodFirstPartyTypeKind["ZodUnknown"] = "ZodUnknown"; - ZodFirstPartyTypeKind["ZodNever"] = "ZodNever"; - ZodFirstPartyTypeKind["ZodVoid"] = "ZodVoid"; - ZodFirstPartyTypeKind["ZodArray"] = "ZodArray"; - ZodFirstPartyTypeKind["ZodObject"] = "ZodObject"; - ZodFirstPartyTypeKind["ZodUnion"] = "ZodUnion"; - ZodFirstPartyTypeKind["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; - ZodFirstPartyTypeKind["ZodIntersection"] = "ZodIntersection"; - ZodFirstPartyTypeKind["ZodTuple"] = "ZodTuple"; - ZodFirstPartyTypeKind["ZodRecord"] = "ZodRecord"; - ZodFirstPartyTypeKind["ZodMap"] = "ZodMap"; - ZodFirstPartyTypeKind["ZodSet"] = "ZodSet"; - ZodFirstPartyTypeKind["ZodFunction"] = "ZodFunction"; - ZodFirstPartyTypeKind["ZodLazy"] = "ZodLazy"; - ZodFirstPartyTypeKind["ZodLiteral"] = "ZodLiteral"; - ZodFirstPartyTypeKind["ZodEnum"] = "ZodEnum"; - ZodFirstPartyTypeKind["ZodEffects"] = "ZodEffects"; - ZodFirstPartyTypeKind["ZodNativeEnum"] = "ZodNativeEnum"; - ZodFirstPartyTypeKind["ZodOptional"] = "ZodOptional"; - ZodFirstPartyTypeKind["ZodNullable"] = "ZodNullable"; - ZodFirstPartyTypeKind["ZodDefault"] = "ZodDefault"; - ZodFirstPartyTypeKind["ZodCatch"] = "ZodCatch"; - ZodFirstPartyTypeKind["ZodPromise"] = "ZodPromise"; - ZodFirstPartyTypeKind["ZodBranded"] = "ZodBranded"; - ZodFirstPartyTypeKind["ZodPipeline"] = "ZodPipeline"; - ZodFirstPartyTypeKind["ZodReadonly"] = "ZodReadonly"; -})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {})); -const instanceOfType = ( -// const instanceOfType = any>( -cls, params = { - message: `Input not instance of ${cls.name}`, -}) => custom((data) => data instanceof cls, params); -const stringType = ZodString.create; -const numberType = ZodNumber.create; -const nanType = ZodNaN.create; -const bigIntType = ZodBigInt.create; -const booleanType = ZodBoolean.create; -const dateType = ZodDate.create; -const symbolType = ZodSymbol.create; -const undefinedType = ZodUndefined.create; -const nullType = ZodNull.create; -const anyType = ZodAny.create; -const unknownType = ZodUnknown.create; -const neverType = ZodNever.create; -const voidType = ZodVoid.create; -const arrayType = ZodArray.create; -const objectType = ZodObject.create; -const strictObjectType = ZodObject.strictCreate; -const unionType = ZodUnion.create; -const discriminatedUnionType = ZodDiscriminatedUnion.create; -const intersectionType = ZodIntersection.create; -const tupleType = ZodTuple.create; -const recordType = ZodRecord.create; -const mapType = ZodMap.create; -const setType = ZodSet.create; -const functionType = ZodFunction.create; -const lazyType = ZodLazy.create; -const literalType = ZodLiteral.create; -const enumType = ZodEnum.create; -const nativeEnumType = ZodNativeEnum.create; -const promiseType = ZodPromise.create; -const effectsType = ZodEffects.create; -const optionalType = ZodOptional.create; -const nullableType = ZodNullable.create; -const preprocessType = ZodEffects.createWithPreprocess; -const pipelineType = ZodPipeline.create; -const ostring = () => stringType().optional(); -const onumber = () => numberType().optional(); -const oboolean = () => booleanType().optional(); -const coerce = { - string: ((arg) => ZodString.create({ ...arg, coerce: true })), - number: ((arg) => ZodNumber.create({ ...arg, coerce: true })), - boolean: ((arg) => ZodBoolean.create({ - ...arg, - coerce: true, - })), - bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })), - date: ((arg) => ZodDate.create({ ...arg, coerce: true })), -}; -const NEVER = INVALID; -var z = /*#__PURE__*/Object.freeze({ - __proto__: null, - defaultErrorMap: errorMap, - setErrorMap: setErrorMap, - getErrorMap: getErrorMap, - makeIssue: makeIssue, - EMPTY_PATH: EMPTY_PATH, - addIssueToContext: addIssueToContext, - ParseStatus: ParseStatus, - INVALID: INVALID, - DIRTY: DIRTY, - OK: OK, - isAborted: isAborted, - isDirty: isDirty, - isValid: isValid, - isAsync: isAsync, - get util () { return util; }, - get objectUtil () { return objectUtil; }, - ZodParsedType: ZodParsedType, - getParsedType: getParsedType, - ZodType: ZodType, - datetimeRegex: datetimeRegex, - ZodString: ZodString, - ZodNumber: ZodNumber, - ZodBigInt: ZodBigInt, - ZodBoolean: ZodBoolean, - ZodDate: ZodDate, - ZodSymbol: ZodSymbol, - ZodUndefined: ZodUndefined, - ZodNull: ZodNull, - ZodAny: ZodAny, - ZodUnknown: ZodUnknown, - ZodNever: ZodNever, - ZodVoid: ZodVoid, - ZodArray: ZodArray, - ZodObject: ZodObject, - ZodUnion: ZodUnion, - ZodDiscriminatedUnion: ZodDiscriminatedUnion, - ZodIntersection: ZodIntersection, - ZodTuple: ZodTuple, - ZodRecord: ZodRecord, - ZodMap: ZodMap, - ZodSet: ZodSet, - ZodFunction: ZodFunction, - ZodLazy: ZodLazy, - ZodLiteral: ZodLiteral, - ZodEnum: ZodEnum, - ZodNativeEnum: ZodNativeEnum, - ZodPromise: ZodPromise, - ZodEffects: ZodEffects, - ZodTransformer: ZodEffects, - ZodOptional: ZodOptional, - ZodNullable: ZodNullable, - ZodDefault: ZodDefault, - ZodCatch: ZodCatch, - ZodNaN: ZodNaN, - BRAND: BRAND, - ZodBranded: ZodBranded, - ZodPipeline: ZodPipeline, - ZodReadonly: ZodReadonly, - custom: custom, - Schema: ZodType, - ZodSchema: ZodType, - late: late, - get ZodFirstPartyTypeKind () { return ZodFirstPartyTypeKind; }, - coerce: coerce, - any: anyType, - array: arrayType, - bigint: bigIntType, - boolean: booleanType, - date: dateType, - discriminatedUnion: discriminatedUnionType, - effect: effectsType, - 'enum': enumType, - 'function': functionType, - 'instanceof': instanceOfType, - intersection: intersectionType, - lazy: lazyType, - literal: literalType, - map: mapType, - nan: nanType, - nativeEnum: nativeEnumType, - never: neverType, - 'null': nullType, - nullable: nullableType, - number: numberType, - object: objectType, - oboolean: oboolean, - onumber: onumber, - optional: optionalType, - ostring: ostring, - pipeline: pipelineType, - preprocess: preprocessType, - promise: promiseType, - record: recordType, - set: setType, - strictObject: strictObjectType, - string: stringType, - symbol: symbolType, - transformer: effectsType, - tuple: tupleType, - 'undefined': undefinedType, - union: unionType, - unknown: unknownType, - 'void': voidType, - NEVER: NEVER, - ZodIssueCode: ZodIssueCode, - quotelessJson: quotelessJson, - ZodError: ZodError -}); +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/client.js + + + + -// EXTERNAL MODULE: ./node_modules/p-retry/index.js -var p_retry = __nccwpck_require__(2103); -// EXTERNAL MODULE: ./node_modules/p-queue/dist/index.js -var p_queue_dist = __nccwpck_require__(6459); -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/singletons/fetch.js -// Wrap the default fetch call due to issues with illegal invocations -// in some environments: -// https://stackoverflow.com/questions/69876859/why-does-bind-fix-failed-to-execute-fetch-on-window-illegal-invocation-err -// @ts-expect-error Broad typing to support a range of fetch implementations -const DEFAULT_FETCH_IMPLEMENTATION = (...args) => fetch(...args); -const LANGSMITH_FETCH_IMPLEMENTATION_KEY = Symbol.for("ls:fetch_implementation"); -/** - * Overrides the fetch implementation used for LangSmith calls. - * You should use this if you need to use an implementation of fetch - * other than the default global (e.g. for dealing with proxies). - * @param fetch The new fetch functino to use. - */ -const overrideFetchImplementation = (fetch) => { - globalThis[LANGSMITH_FETCH_IMPLEMENTATION_KEY] = fetch; -}; -/** - * @internal - */ -const _getFetchImplementation = (debug) => { - return async (...args) => { - if (debug || getLangSmithEnvironmentVariable("DEBUG") === "true") { - const [url, options] = args; - console.log(`→ ${options?.method || "GET"} ${url}`); - } - const res = await (globalThis[LANGSMITH_FETCH_IMPLEMENTATION_KEY] ?? - DEFAULT_FETCH_IMPLEMENTATION)(...args); - if (debug || getLangSmithEnvironmentVariable("DEBUG") === "true") { - console.log(`← ${res.status} ${res.statusText} ${res.url}`); - } - return res; - }; -}; -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/async_caller.js -const STATUS_NO_RETRY = [ - 400, // Bad Request - 401, // Unauthorized - 403, // Forbidden - 404, // Not Found - 405, // Method Not Allowed - 406, // Not Acceptable - 407, // Proxy Authentication Required - 408, // Request Timeout -]; -const STATUS_IGNORE = [ - 409, // Conflict -]; -/** - * A class that can be used to make async calls with concurrency and retry logic. - * - * This is useful for making calls to any kind of "expensive" external resource, - * be it because it's rate-limited, subject to network issues, etc. - * - * Concurrent calls are limited by the `maxConcurrency` parameter, which defaults - * to `Infinity`. This means that by default, all calls will be made in parallel. - * - * Retries are limited by the `maxRetries` parameter, which defaults to 6. This - * means that by default, each call will be retried up to 6 times, with an - * exponential backoff between each attempt. - */ -class AsyncCaller { - constructor(params) { - Object.defineProperty(this, "maxConcurrency", { + +function mergeRuntimeEnvIntoRun(run) { + const runtimeEnv = getRuntimeEnvironment(); + const envVars = getLangChainEnvVarsMetadata(); + const extra = run.extra ?? {}; + const metadata = extra.metadata; + run.extra = { + ...extra, + runtime: { + ...runtimeEnv, + ...extra?.runtime, + }, + metadata: { + ...envVars, + ...(envVars.revision_id || ("revision_id" in run && run.revision_id) + ? { + revision_id: ("revision_id" in run ? run.revision_id : undefined) ?? + envVars.revision_id, + } + : {}), + ...metadata, + }, + }; + return run; +} +const getTracingSamplingRate = (configRate) => { + const samplingRateStr = configRate?.toString() ?? + getLangSmithEnvironmentVariable("TRACING_SAMPLING_RATE"); + if (samplingRateStr === undefined) { + return undefined; + } + const samplingRate = parseFloat(samplingRateStr); + if (samplingRate < 0 || samplingRate > 1) { + throw new Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${samplingRate}`); + } + return samplingRate; +}; +// utility functions +const isLocalhost = (url) => { + const strippedUrl = url.replace("http://", "").replace("https://", ""); + const hostname = strippedUrl.split("/")[0].split(":")[0]; + return (hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1"); +}; +async function toArray(iterable) { + const result = []; + for await (const item of iterable) { + result.push(item); + } + return result; +} +function trimQuotes(str) { + if (str === undefined) { + return undefined; + } + return str + .trim() + .replace(/^"(.*)"$/, "$1") + .replace(/^'(.*)'$/, "$1"); +} +const handle429 = async (response) => { + if (response?.status === 429) { + const retryAfter = parseInt(response.headers.get("retry-after") ?? "30", 10) * 1000; + if (retryAfter > 0) { + await new Promise((resolve) => setTimeout(resolve, retryAfter)); + // Return directly after calling this check + return true; + } + } + // Fall back to existing status checks + return false; +}; +function _formatFeedbackScore(score) { + if (typeof score === "number") { + // Truncate at 4 decimal places + return Number(score.toFixed(4)); + } + return score; +} +class AutoBatchQueue { + constructor() { + Object.defineProperty(this, "items", { + enumerable: true, + configurable: true, + writable: true, + value: [] + }); + Object.defineProperty(this, "sizeBytes", { + enumerable: true, + configurable: true, + writable: true, + value: 0 + }); + } + peek() { + return this.items[0]; + } + push(item) { + let itemPromiseResolve; + const itemPromise = new Promise((resolve) => { + // Setting itemPromiseResolve is synchronous with promise creation: + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise + itemPromiseResolve = resolve; + }); + const size = serialize(item.item, `Serializing run with id: ${item.item.id}`).length; + this.items.push({ + action: item.action, + payload: item.item, + otelContext: item.otelContext, + apiKey: item.apiKey, + apiUrl: item.apiUrl, + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + itemPromiseResolve: itemPromiseResolve, + itemPromise, + size, + }); + this.sizeBytes += size; + return itemPromise; + } + pop(upToSizeBytes) { + if (upToSizeBytes < 1) { + throw new Error("Number of bytes to pop off may not be less than 1."); + } + const popped = []; + let poppedSizeBytes = 0; + // Pop items until we reach or exceed the size limit + while (poppedSizeBytes + (this.peek()?.size ?? 0) < upToSizeBytes && + this.items.length > 0) { + const item = this.items.shift(); + if (item) { + popped.push(item); + poppedSizeBytes += item.size; + this.sizeBytes -= item.size; + } + } + // If there is an item on the queue we were unable to pop, + // just return it as a single batch. + if (popped.length === 0 && this.items.length > 0) { + const item = this.items.shift(); + popped.push(item); + poppedSizeBytes += item.size; + this.sizeBytes -= item.size; + } + return [ + popped.map((it) => ({ + action: it.action, + item: it.payload, + otelContext: it.otelContext, + apiKey: it.apiKey, + apiUrl: it.apiUrl, + })), + () => popped.forEach((it) => it.itemPromiseResolve()), + ]; + } +} +// 20 MB +const DEFAULT_BATCH_SIZE_LIMIT_BYTES = 20_971_520; +const SERVER_INFO_REQUEST_TIMEOUT = 2500; +const DEFAULT_API_URL = "https://api.smith.langchain.com"; +class Client { + constructor(config = {}) { + Object.defineProperty(this, "apiKey", { enumerable: true, configurable: true, writable: true, value: void 0 }); - Object.defineProperty(this, "maxRetries", { + Object.defineProperty(this, "apiUrl", { enumerable: true, configurable: true, writable: true, value: void 0 }); - Object.defineProperty(this, "queue", { + Object.defineProperty(this, "webUrl", { enumerable: true, configurable: true, writable: true, value: void 0 }); - Object.defineProperty(this, "onFailedResponseHook", { + Object.defineProperty(this, "caller", { enumerable: true, configurable: true, writable: true, value: void 0 }); - Object.defineProperty(this, "debug", { + Object.defineProperty(this, "batchIngestCaller", { enumerable: true, configurable: true, writable: true, value: void 0 }); - this.maxConcurrency = params.maxConcurrency ?? Infinity; - this.maxRetries = params.maxRetries ?? 6; - this.debug = params.debug; - if ( true) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - this.queue = new p_queue_dist["default"]({ - concurrency: this.maxConcurrency, + Object.defineProperty(this, "timeout_ms", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "_tenantId", { + enumerable: true, + configurable: true, + writable: true, + value: null + }); + Object.defineProperty(this, "hideInputs", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "hideOutputs", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "tracingSampleRate", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "filteredPostUuids", { + enumerable: true, + configurable: true, + writable: true, + value: new Set() + }); + Object.defineProperty(this, "autoBatchTracing", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "autoBatchQueue", { + enumerable: true, + configurable: true, + writable: true, + value: new AutoBatchQueue() + }); + Object.defineProperty(this, "autoBatchTimeout", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "autoBatchAggregationDelayMs", { + enumerable: true, + configurable: true, + writable: true, + value: 250 + }); + Object.defineProperty(this, "batchSizeBytesLimit", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "fetchOptions", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "settings", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "blockOnRootRunFinalization", { + enumerable: true, + configurable: true, + writable: true, + value: getEnvironmentVariable("LANGSMITH_TRACING_BACKGROUND") === "false" + }); + Object.defineProperty(this, "traceBatchConcurrency", { + enumerable: true, + configurable: true, + writable: true, + value: 5 + }); + Object.defineProperty(this, "_serverInfo", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + Object.defineProperty(this, "_getServerInfoPromise", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "manualFlushMode", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "langSmithToOTELTranslator", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "multipartStreamingDisabled", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "debug", { + enumerable: true, + configurable: true, + writable: true, + value: getEnvironmentVariable("LANGSMITH_DEBUG") === "true" + }); + const defaultConfig = Client.getDefaultClientConfig(); + this.tracingSampleRate = getTracingSamplingRate(config.tracingSamplingRate); + this.apiUrl = trimQuotes(config.apiUrl ?? defaultConfig.apiUrl) ?? ""; + if (this.apiUrl.endsWith("/")) { + this.apiUrl = this.apiUrl.slice(0, -1); + } + this.apiKey = trimQuotes(config.apiKey ?? defaultConfig.apiKey); + this.webUrl = trimQuotes(config.webUrl ?? defaultConfig.webUrl); + if (this.webUrl?.endsWith("/")) { + this.webUrl = this.webUrl.slice(0, -1); + } + this.timeout_ms = config.timeout_ms ?? 90_000; + this.caller = new AsyncCaller({ + ...(config.callerOptions ?? {}), + debug: config.debug ?? this.debug, + }); + this.traceBatchConcurrency = + config.traceBatchConcurrency ?? this.traceBatchConcurrency; + if (this.traceBatchConcurrency < 1) { + throw new Error("Trace batch concurrency must be positive."); + } + this.debug = config.debug ?? this.debug; + this.batchIngestCaller = new AsyncCaller({ + maxRetries: 2, + maxConcurrency: this.traceBatchConcurrency, + ...(config.callerOptions ?? {}), + onFailedResponseHook: handle429, + debug: config.debug ?? this.debug, + }); + this.hideInputs = + config.hideInputs ?? config.anonymizer ?? defaultConfig.hideInputs; + this.hideOutputs = + config.hideOutputs ?? config.anonymizer ?? defaultConfig.hideOutputs; + this.autoBatchTracing = config.autoBatchTracing ?? this.autoBatchTracing; + this.blockOnRootRunFinalization = + config.blockOnRootRunFinalization ?? this.blockOnRootRunFinalization; + this.batchSizeBytesLimit = config.batchSizeBytesLimit; + this.fetchOptions = config.fetchOptions || {}; + this.manualFlushMode = config.manualFlushMode ?? this.manualFlushMode; + if (getOtelEnabled()) { + this.langSmithToOTELTranslator = new LangSmithToOTELTranslator(); + } + } + static getDefaultClientConfig() { + const apiKey = getLangSmithEnvironmentVariable("API_KEY"); + const apiUrl = getLangSmithEnvironmentVariable("ENDPOINT") ?? DEFAULT_API_URL; + const hideInputs = getLangSmithEnvironmentVariable("HIDE_INPUTS") === "true"; + const hideOutputs = getLangSmithEnvironmentVariable("HIDE_OUTPUTS") === "true"; + return { + apiUrl: apiUrl, + apiKey: apiKey, + webUrl: undefined, + hideInputs: hideInputs, + hideOutputs: hideOutputs, + }; + } + getHostUrl() { + if (this.webUrl) { + return this.webUrl; + } + else if (isLocalhost(this.apiUrl)) { + this.webUrl = "http://localhost:3000"; + return this.webUrl; + } + else if (this.apiUrl.endsWith("/api/v1")) { + this.webUrl = this.apiUrl.replace("/api/v1", ""); + return this.webUrl; + } + else if (this.apiUrl.includes("/api") && + !this.apiUrl.split(".", 1)[0].endsWith("api")) { + this.webUrl = this.apiUrl.replace("/api", ""); + return this.webUrl; + } + else if (this.apiUrl.split(".", 1)[0].includes("dev")) { + this.webUrl = "https://dev.smith.langchain.com"; + return this.webUrl; + } + else if (this.apiUrl.split(".", 1)[0].includes("eu")) { + this.webUrl = "https://eu.smith.langchain.com"; + return this.webUrl; + } + else if (this.apiUrl.split(".", 1)[0].includes("beta")) { + this.webUrl = "https://beta.smith.langchain.com"; + return this.webUrl; + } + else { + this.webUrl = "https://smith.langchain.com"; + return this.webUrl; + } + } + get headers() { + const headers = { + "User-Agent": `langsmith-js/${__version__}`, + }; + if (this.apiKey) { + headers["x-api-key"] = `${this.apiKey}`; + } + return headers; + } + _getPlatformEndpointPath(path) { + // Check if apiUrl already ends with /v1 or /v1/ to avoid double /v1/v1/ paths + const needsV1Prefix = this.apiUrl.slice(-3) !== "/v1" && this.apiUrl.slice(-4) !== "/v1/"; + return needsV1Prefix ? `/v1/platform/${path}` : `/platform/${path}`; + } + async processInputs(inputs) { + if (this.hideInputs === false) { + return inputs; + } + if (this.hideInputs === true) { + return {}; + } + if (typeof this.hideInputs === "function") { + return this.hideInputs(inputs); + } + return inputs; + } + async processOutputs(outputs) { + if (this.hideOutputs === false) { + return outputs; + } + if (this.hideOutputs === true) { + return {}; + } + if (typeof this.hideOutputs === "function") { + return this.hideOutputs(outputs); + } + return outputs; + } + async prepareRunCreateOrUpdateInputs(run) { + const runParams = { ...run }; + if (runParams.inputs !== undefined) { + runParams.inputs = await this.processInputs(runParams.inputs); + } + if (runParams.outputs !== undefined) { + runParams.outputs = await this.processOutputs(runParams.outputs); + } + return runParams; + } + async _getResponse(path, queryParams) { + const paramsString = queryParams?.toString() ?? ""; + const url = `${this.apiUrl}${path}?${paramsString}`; + const response = await this.caller.call(_getFetchImplementation(this.debug), url, { + method: "GET", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(response, `Failed to fetch ${path}`); + return response; + } + async _get(path, queryParams) { + const response = await this._getResponse(path, queryParams); + return response.json(); + } + async *_getPaginated(path, queryParams = new URLSearchParams(), transform) { + let offset = Number(queryParams.get("offset")) || 0; + const limit = Number(queryParams.get("limit")) || 100; + while (true) { + queryParams.set("offset", String(offset)); + queryParams.set("limit", String(limit)); + const url = `${this.apiUrl}${path}?${queryParams}`; + const response = await this.caller.call(_getFetchImplementation(this.debug), url, { + method: "GET", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, }); + await raiseForStatus(response, `Failed to fetch ${path}`); + const items = transform + ? transform(await response.json()) + : await response.json(); + if (items.length === 0) { + break; + } + yield items; + if (items.length < limit) { + break; + } + offset += items.length; } - else { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - this.queue = new p_queue_dist({ concurrency: this.maxConcurrency }); - } - this.onFailedResponseHook = params?.onFailedResponseHook; } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - call(callable, ...args) { - const onFailedResponseHook = this.onFailedResponseHook; - return this.queue.add(() => p_retry(() => callable(...args).catch((error) => { - // eslint-disable-next-line no-instanceof/no-instanceof - if (error instanceof Error) { - throw error; + async *_getCursorPaginatedList(path, body = null, requestMethod = "POST", dataKey = "runs") { + const bodyParams = body ? { ...body } : {}; + while (true) { + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}${path}`, { + method: requestMethod, + headers: { ...this.headers, "Content-Type": "application/json" }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + body: JSON.stringify(bodyParams), + }); + const responseBody = await response.json(); + if (!responseBody) { + break; } - else { - throw new Error(error); + if (!responseBody[dataKey]) { + break; } - }), { - async onFailedAttempt(error) { - if (error.message.startsWith("Cancel") || - error.message.startsWith("TimeoutError") || - error.message.startsWith("AbortError")) { - throw error; + yield responseBody[dataKey]; + const cursors = responseBody.cursors; + if (!cursors) { + break; + } + if (!cursors.next) { + break; + } + bodyParams.cursor = cursors.next; + } + } + // Allows mocking for tests + _shouldSample() { + if (this.tracingSampleRate === undefined) { + return true; + } + return Math.random() < this.tracingSampleRate; + } + _filterForSampling(runs, patch = false) { + if (this.tracingSampleRate === undefined) { + return runs; + } + if (patch) { + const sampled = []; + for (const run of runs) { + if (!this.filteredPostUuids.has(run.trace_id)) { + sampled.push(run); } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - if (error?.code === "ECONNABORTED") { - throw error; + else if (run.id === run.trace_id) { + this.filteredPostUuids.delete(run.trace_id); } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const response = error?.response; - const status = response?.status; - if (status) { - if (STATUS_NO_RETRY.includes(+status)) { - throw error; - } - else if (STATUS_IGNORE.includes(+status)) { - return; + } + return sampled; + } + else { + // For new runs, sample at trace level to maintain consistency + const sampled = []; + for (const run of runs) { + const traceId = run.trace_id ?? run.id; + // If we've already made a decision about this trace, follow it + if (this.filteredPostUuids.has(traceId)) { + continue; + } + // For new traces, apply sampling + if (run.id === traceId) { + if (this._shouldSample()) { + sampled.push(run); } - if (onFailedResponseHook) { - await onFailedResponseHook(response); + else { + this.filteredPostUuids.add(traceId); } } - }, - // If needed we can change some of the defaults here, - // but they're quite sensible. - retries: this.maxRetries, - randomize: true, - }), { throwOnTimeout: true }); - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - callWithOptions(options, callable, ...args) { - // Note this doesn't cancel the underlying request, - // when available prefer to use the signal option of the underlying call - if (options.signal) { - return Promise.race([ - this.call(callable, ...args), - new Promise((_, reject) => { - options.signal?.addEventListener("abort", () => { - reject(new Error("AbortError")); - }); - }), - ]); + else { + // Child runs follow their trace's sampling decision + sampled.push(run); + } + } + return sampled; } - return this.call(callable, ...args); } - fetch(...args) { - return this.call(() => _getFetchImplementation(this.debug)(...args).then((res) => res.ok ? res : Promise.reject(res))); + async _getBatchSizeLimitBytes() { + const serverInfo = await this._ensureServerInfo(); + return (this.batchSizeBytesLimit ?? + serverInfo.batch_ingest_config?.size_limit_bytes ?? + DEFAULT_BATCH_SIZE_LIMIT_BYTES); } -} - -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/messages.js -function isLangChainMessage( -// eslint-disable-next-line @typescript-eslint/no-explicit-any -message) { - return typeof message?._getType === "function"; -} -function convertLangChainMessageToExample(message) { - const converted = { - type: message._getType(), - data: { content: message.content }, - }; - // Check for presence of keys in additional_kwargs - if (message?.additional_kwargs && - Object.keys(message.additional_kwargs).length > 0) { - converted.data.additional_kwargs = { ...message.additional_kwargs }; + async _getMultiPartSupport() { + const serverInfo = await this._ensureServerInfo(); + return (serverInfo.instance_flags?.dataset_examples_multipart_enabled ?? false); } - return converted; -} - -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/_uuid.js - -function assertUuid(str, which) { - if (!wrapper_validate(str)) { - const msg = which !== undefined - ? `Invalid UUID for ${which}: ${str}` - : `Invalid UUID: ${str}`; - throw new Error(msg); + drainAutoBatchQueue(batchSizeLimit) { + const promises = []; + while (this.autoBatchQueue.items.length > 0) { + const [batch, done] = this.autoBatchQueue.pop(batchSizeLimit); + if (!batch.length) { + done(); + break; + } + const batchesByDestination = batch.reduce((acc, item) => { + const apiUrl = item.apiUrl ?? this.apiUrl; + const apiKey = item.apiKey ?? this.apiKey; + const isDefault = item.apiKey === this.apiKey && item.apiUrl === this.apiUrl; + const batchKey = isDefault ? "default" : `${apiUrl}|${apiKey}`; + if (!acc[batchKey]) { + acc[batchKey] = []; + } + acc[batchKey].push(item); + return acc; + }, {}); + const batchPromises = []; + for (const [batchKey, batch] of Object.entries(batchesByDestination)) { + const batchPromise = this._processBatch(batch, { + apiUrl: batchKey === "default" ? undefined : batchKey.split("|")[0], + apiKey: batchKey === "default" ? undefined : batchKey.split("|")[1], + }); + batchPromises.push(batchPromise); + } + // Wait for all batches to complete, then call the overall done callback + const allBatchesPromise = Promise.all(batchPromises).finally(done); + promises.push(allBatchesPromise); + } + return Promise.all(promises); } - return str; -} - -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/warn.js -const warnedMessages = {}; -function warnOnce(message) { - if (!warnedMessages[message]) { - console.warn(message); - warnedMessages[message] = true; + async _processBatch(batch, options) { + if (!batch.length) { + return; + } + try { + if (this.langSmithToOTELTranslator !== undefined) { + this._sendBatchToOTELTranslator(batch); + } + else { + const ingestParams = { + runCreates: batch + .filter((item) => item.action === "create") + .map((item) => item.item), + runUpdates: batch + .filter((item) => item.action === "update") + .map((item) => item.item), + }; + const serverInfo = await this._ensureServerInfo(); + if (serverInfo?.batch_ingest_config?.use_multipart_endpoint) { + await this.multipartIngestRuns(ingestParams, options); + } + else { + await this.batchIngestRuns(ingestParams, options); + } + } + } + catch (e) { + console.error("Error exporting batch:", e); + } + } + _sendBatchToOTELTranslator(batch) { + if (this.langSmithToOTELTranslator !== undefined) { + const otelContextMap = new Map(); + const operations = []; + for (const item of batch) { + if (item.item.id && item.otelContext) { + otelContextMap.set(item.item.id, item.otelContext); + if (item.action === "create") { + operations.push({ + operation: "post", + id: item.item.id, + trace_id: item.item.trace_id ?? item.item.id, + run: item.item, + }); + } + else { + operations.push({ + operation: "patch", + id: item.item.id, + trace_id: item.item.trace_id ?? item.item.id, + run: item.item, + }); + } + } + } + this.langSmithToOTELTranslator.exportBatch(operations, otelContextMap); + } } -} - -// EXTERNAL MODULE: ./node_modules/semver/index.js -var semver = __nccwpck_require__(2088); -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/prompts.js - -function isVersionGreaterOrEqual(current_version, target_version) { - const current = parseVersion(current_version); - const target = parseVersion(target_version); - if (!current || !target) { - throw new Error("Invalid version format."); + async processRunOperation(item) { + clearTimeout(this.autoBatchTimeout); + this.autoBatchTimeout = undefined; + item.item = mergeRuntimeEnvIntoRun(item.item); + const itemPromise = this.autoBatchQueue.push(item); + if (this.manualFlushMode) { + // Rely on manual flushing in serverless environments + return itemPromise; + } + const sizeLimitBytes = await this._getBatchSizeLimitBytes(); + if (this.autoBatchQueue.sizeBytes > sizeLimitBytes) { + void this.drainAutoBatchQueue(sizeLimitBytes); + } + if (this.autoBatchQueue.items.length > 0) { + this.autoBatchTimeout = setTimeout(() => { + this.autoBatchTimeout = undefined; + void this.drainAutoBatchQueue(sizeLimitBytes); + }, this.autoBatchAggregationDelayMs); + } + return itemPromise; } - return current.compare(target) >= 0; -} -function parsePromptIdentifier(identifier) { - if (!identifier || - identifier.split("/").length > 2 || - identifier.startsWith("/") || - identifier.endsWith("/") || - identifier.split(":").length > 2) { - throw new Error(`Invalid identifier format: ${identifier}`); + async _getServerInfo() { + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/info`, { + method: "GET", + headers: { Accept: "application/json" }, + signal: AbortSignal.timeout(SERVER_INFO_REQUEST_TIMEOUT), + ...this.fetchOptions, + }); + await raiseForStatus(response, "get server info"); + const json = await response.json(); + if (this.debug) { + console.log("\n=== LangSmith Server Configuration ===\n" + + JSON.stringify(json, null, 2) + + "\n"); + } + return json; } - const [ownerNamePart, commitPart] = identifier.split(":"); - const commit = commitPart || "latest"; - if (ownerNamePart.includes("/")) { - const [owner, name] = ownerNamePart.split("/", 2); - if (!owner || !name) { - throw new Error(`Invalid identifier format: ${identifier}`); + async _ensureServerInfo() { + if (this._getServerInfoPromise === undefined) { + this._getServerInfoPromise = (async () => { + if (this._serverInfo === undefined) { + try { + this._serverInfo = await this._getServerInfo(); + } + catch (e) { + console.warn(`[WARNING]: LangSmith failed to fetch info on supported operations with status code ${e.status}. Falling back to batch operations and default limits.`); + } + } + return this._serverInfo ?? {}; + })(); } - return [owner, name, commit]; + return this._getServerInfoPromise.then((serverInfo) => { + if (this._serverInfo === undefined) { + this._getServerInfoPromise = undefined; + } + return serverInfo; + }); } - else { - if (!ownerNamePart) { - throw new Error(`Invalid identifier format: ${identifier}`); + async _getSettings() { + if (!this.settings) { + this.settings = this._get("/settings"); } - return ["-", ownerNamePart, commit]; + return await this.settings; } -} - -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/error.js -function getErrorStackTrace(e) { - if (typeof e !== "object" || e == null) - return undefined; - if (!("stack" in e) || typeof e.stack !== "string") - return undefined; - let stack = e.stack; - const prevLine = `${e}`; - if (stack.startsWith(prevLine)) { - stack = stack.slice(prevLine.length); + /** + * Flushes current queued traces. + */ + async flush() { + const sizeLimitBytes = await this._getBatchSizeLimitBytes(); + await this.drainAutoBatchQueue(sizeLimitBytes); } - if (stack.startsWith("\n")) { - stack = stack.slice(1); + _cloneCurrentOTELContext() { + const otel_trace = getOTELTrace(); + const otel_context = getOTELContext(); + if (this.langSmithToOTELTranslator !== undefined) { + const currentSpan = otel_trace.getActiveSpan(); + if (currentSpan) { + return otel_trace.setSpan(otel_context.active(), currentSpan); + } + } + return undefined; } - return stack; -} -function printErrorStackTrace(e) { - const stack = getErrorStackTrace(e); - if (stack == null) - return; - console.error(stack); -} -/** - * LangSmithConflictError - * - * Represents an error that occurs when there's a conflict during an operation, - * typically corresponding to HTTP 409 status code responses. - * - * This error is thrown when an attempt to create or modify a resource conflicts - * with the current state of the resource on the server. Common scenarios include: - * - Attempting to create a resource that already exists - * - Trying to update a resource that has been modified by another process - * - Violating a uniqueness constraint in the data - * - * @extends Error - * - * @example - * try { - * await createProject("existingProject"); - * } catch (error) { - * if (error instanceof ConflictError) { - * console.log("A conflict occurred:", error.message); - * // Handle the conflict, e.g., by suggesting a different project name - * } else { - * // Handle other types of errors - * } - * } - * - * @property {string} name - Always set to 'ConflictError' for easy identification - * @property {string} message - Detailed error message including server response - * - * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/409 - */ -class LangSmithConflictError extends Error { - constructor(message) { - super(message); - Object.defineProperty(this, "status", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 + async createRun(run, options) { + if (!this._filterForSampling([run]).length) { + return; + } + const headers = { + ...this.headers, + "Content-Type": "application/json", + }; + const session_name = run.project_name; + delete run.project_name; + const runCreate = await this.prepareRunCreateOrUpdateInputs({ + session_name, + ...run, + start_time: run.start_time ?? Date.now(), }); - this.name = "LangSmithConflictError"; - this.status = 409; - } -} -/** - * Throws an appropriate error based on the response status and body. - * - * @param response - The fetch Response object - * @param context - Additional context to include in the error message (e.g., operation being performed) - * @throws {LangSmithConflictError} When the response status is 409 - * @throws {Error} For all other non-ok responses - */ -async function raiseForStatus(response, context, consume) { - // consume the response body to release the connection - // https://undici.nodejs.org/#/?id=garbage-collection - let errorBody; - if (response.ok) { - if (consume) { - errorBody = await response.text(); + if (this.autoBatchTracing && + runCreate.trace_id !== undefined && + runCreate.dotted_order !== undefined) { + const otelContext = this._cloneCurrentOTELContext(); + void this.processRunOperation({ + action: "create", + item: runCreate, + otelContext, + apiKey: options?.apiKey, + apiUrl: options?.apiUrl, + }).catch(console.error); + return; } - return; - } - errorBody = await response.text(); - const fullMessage = `Failed to ${context}. Received status [${response.status}]: ${response.statusText}. Server response: ${errorBody}`; - if (response.status === 409) { - throw new LangSmithConflictError(fullMessage); + const mergedRunCreateParam = mergeRuntimeEnvIntoRun(runCreate); + if (options?.apiKey !== undefined) { + headers["x-api-key"] = options.apiKey; + } + const response = await this.caller.call(_getFetchImplementation(this.debug), `${options?.apiUrl ?? this.apiUrl}/runs`, { + method: "POST", + headers, + body: serialize(mergedRunCreateParam, `Creating run with id: ${mergedRunCreateParam.id}`), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(response, "create run", true); } - const err = new Error(fullMessage); - err.status = response.status; - throw err; -} - -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/fast-safe-stringify/index.js -/* eslint-disable */ -// @ts-nocheck -var LIMIT_REPLACE_NODE = "[...]"; -var CIRCULAR_REPLACE_NODE = { result: "[Circular]" }; -var arr = []; -var replacerStack = []; -const encoder = new TextEncoder(); -function fast_safe_stringify_defaultOptions() { - return { - depthLimit: Number.MAX_SAFE_INTEGER, - edgesLimit: Number.MAX_SAFE_INTEGER, - }; -} -function encodeString(str) { - return encoder.encode(str); -} -// Regular stringify -function serialize(obj, replacer, spacer, options) { - try { - const str = JSON.stringify(obj, replacer, spacer); - return encodeString(str); + /** + * Batch ingest/upsert multiple runs in the Langsmith system. + * @param runs + */ + async batchIngestRuns({ runCreates, runUpdates, }, options) { + if (runCreates === undefined && runUpdates === undefined) { + return; + } + let preparedCreateParams = await Promise.all(runCreates?.map((create) => this.prepareRunCreateOrUpdateInputs(create)) ?? []); + let preparedUpdateParams = await Promise.all(runUpdates?.map((update) => this.prepareRunCreateOrUpdateInputs(update)) ?? []); + if (preparedCreateParams.length > 0 && preparedUpdateParams.length > 0) { + const createById = preparedCreateParams.reduce((params, run) => { + if (!run.id) { + return params; + } + params[run.id] = run; + return params; + }, {}); + const standaloneUpdates = []; + for (const updateParam of preparedUpdateParams) { + if (updateParam.id !== undefined && createById[updateParam.id]) { + createById[updateParam.id] = { + ...createById[updateParam.id], + ...updateParam, + }; + } + else { + standaloneUpdates.push(updateParam); + } + } + preparedCreateParams = Object.values(createById); + preparedUpdateParams = standaloneUpdates; + } + const rawBatch = { + post: preparedCreateParams, + patch: preparedUpdateParams, + }; + if (!rawBatch.post.length && !rawBatch.patch.length) { + return; + } + const batchChunks = { + post: [], + patch: [], + }; + for (const k of ["post", "patch"]) { + const key = k; + const batchItems = rawBatch[key].reverse(); + let batchItem = batchItems.pop(); + while (batchItem !== undefined) { + // Type is wrong but this is a deprecated code path anyway + batchChunks[key].push(batchItem); + batchItem = batchItems.pop(); + } + } + if (batchChunks.post.length > 0 || batchChunks.patch.length > 0) { + const runIds = batchChunks.post + .map((item) => item.id) + .concat(batchChunks.patch.map((item) => item.id)) + .join(","); + await this._postBatchIngestRuns(serialize(batchChunks, `Ingesting runs with ids: ${runIds}`), options); + } } - catch (e) { - // Fall back to more complex stringify if circular reference - if (!e.message?.includes("Converting circular structure to JSON")) { - console.warn("[WARNING]: LangSmith received unserializable value."); - return encodeString("[Unserializable]"); + async _postBatchIngestRuns(body, options) { + const headers = { + ...this.headers, + "Content-Type": "application/json", + Accept: "application/json", + }; + if (options?.apiKey !== undefined) { + headers["x-api-key"] = options.apiKey; } - console.warn("[WARNING]: LangSmith received circular JSON. This will decrease tracer performance."); - if (typeof options === "undefined") { - options = fast_safe_stringify_defaultOptions(); + const response = await this.batchIngestCaller.call(_getFetchImplementation(this.debug), `${options?.apiUrl ?? this.apiUrl}/runs/batch`, { + method: "POST", + headers, + body: body, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(response, "batch create run", true); + } + /** + * Batch ingest/upsert multiple runs in the Langsmith system. + * @param runs + */ + async multipartIngestRuns({ runCreates, runUpdates, }, options) { + if (runCreates === undefined && runUpdates === undefined) { + return; } - decirc(obj, "", 0, [], undefined, 0, options); - let res; - try { - if (replacerStack.length === 0) { - res = JSON.stringify(obj, replacer, spacer); - } - else { - res = JSON.stringify(obj, replaceGetterValues(replacer), spacer); + // transform and convert to dicts + const allAttachments = {}; + let preparedCreateParams = []; + for (const create of runCreates ?? []) { + const preparedCreate = await this.prepareRunCreateOrUpdateInputs(create); + if (preparedCreate.id !== undefined && + preparedCreate.attachments !== undefined) { + allAttachments[preparedCreate.id] = preparedCreate.attachments; } + delete preparedCreate.attachments; + preparedCreateParams.push(preparedCreate); } - catch (_) { - return encodeString("[unable to serialize, circular reference is too complex to analyze]"); + let preparedUpdateParams = []; + for (const update of runUpdates ?? []) { + preparedUpdateParams.push(await this.prepareRunCreateOrUpdateInputs(update)); } - finally { - while (arr.length !== 0) { - const part = arr.pop(); - if (part.length === 4) { - Object.defineProperty(part[0], part[1], part[3]); + // require trace_id and dotted_order + const invalidRunCreate = preparedCreateParams.find((runCreate) => { + return (runCreate.trace_id === undefined || runCreate.dotted_order === undefined); + }); + if (invalidRunCreate !== undefined) { + throw new Error(`Multipart ingest requires "trace_id" and "dotted_order" to be set when creating a run`); + } + const invalidRunUpdate = preparedUpdateParams.find((runUpdate) => { + return (runUpdate.trace_id === undefined || runUpdate.dotted_order === undefined); + }); + if (invalidRunUpdate !== undefined) { + throw new Error(`Multipart ingest requires "trace_id" and "dotted_order" to be set when updating a run`); + } + // combine post and patch dicts where possible + if (preparedCreateParams.length > 0 && preparedUpdateParams.length > 0) { + const createById = preparedCreateParams.reduce((params, run) => { + if (!run.id) { + return params; + } + params[run.id] = run; + return params; + }, {}); + const standaloneUpdates = []; + for (const updateParam of preparedUpdateParams) { + if (updateParam.id !== undefined && createById[updateParam.id]) { + createById[updateParam.id] = { + ...createById[updateParam.id], + ...updateParam, + }; } else { - part[0][part[1]] = part[2]; + standaloneUpdates.push(updateParam); } } + preparedCreateParams = Object.values(createById); + preparedUpdateParams = standaloneUpdates; } - return encodeString(res); - } -} -function setReplace(replace, val, k, parent) { - var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k); - if (propertyDescriptor.get !== undefined) { - if (propertyDescriptor.configurable) { - Object.defineProperty(parent, k, { value: replace }); - arr.push([parent, k, val, propertyDescriptor]); + if (preparedCreateParams.length === 0 && + preparedUpdateParams.length === 0) { + return; } - else { - replacerStack.push([val, k, replace]); + // send the runs in multipart requests + const accumulatedContext = []; + const accumulatedParts = []; + for (const [method, payloads] of [ + ["post", preparedCreateParams], + ["patch", preparedUpdateParams], + ]) { + for (const originalPayload of payloads) { + // collect fields to be sent as separate parts + const { inputs, outputs, events, attachments, ...payload } = originalPayload; + const fields = { inputs, outputs, events }; + // encode the main run payload + const stringifiedPayload = serialize(payload, `Serializing for multipart ingestion of run with id: ${payload.id}`); + accumulatedParts.push({ + name: `${method}.${payload.id}`, + payload: new Blob([stringifiedPayload], { + type: `application/json; length=${stringifiedPayload.length}`, // encoding=gzip + }), + }); + // encode the fields we collected + for (const [key, value] of Object.entries(fields)) { + if (value === undefined) { + continue; + } + const stringifiedValue = serialize(value, `Serializing ${key} for multipart ingestion of run with id: ${payload.id}`); + accumulatedParts.push({ + name: `${method}.${payload.id}.${key}`, + payload: new Blob([stringifiedValue], { + type: `application/json; length=${stringifiedValue.length}`, + }), + }); + } + // encode the attachments + if (payload.id !== undefined) { + const attachments = allAttachments[payload.id]; + if (attachments) { + delete allAttachments[payload.id]; + for (const [name, attachment] of Object.entries(attachments)) { + let contentType; + let content; + if (Array.isArray(attachment)) { + [contentType, content] = attachment; + } + else { + contentType = attachment.mimeType; + content = attachment.data; + } + // Validate that the attachment name doesn't contain a '.' + if (name.includes(".")) { + console.warn(`Skipping attachment '${name}' for run ${payload.id}: Invalid attachment name. ` + + `Attachment names must not contain periods ('.'). Please rename the attachment and try again.`); + continue; + } + accumulatedParts.push({ + name: `attachment.${payload.id}.${name}`, + payload: new Blob([content], { + type: `${contentType}; length=${content.byteLength}`, + }), + }); + } + } + } + // compute context + accumulatedContext.push(`trace=${payload.trace_id},id=${payload.id}`); + } } + await this._sendMultipartRequest(accumulatedParts, accumulatedContext.join("; "), options); + } + async _createNodeFetchBody(parts, boundary) { + // Create multipart form data manually using Blobs + const chunks = []; + for (const part of parts) { + // Add field boundary + chunks.push(new Blob([`--${boundary}\r\n`])); + chunks.push(new Blob([ + `Content-Disposition: form-data; name="${part.name}"\r\n`, + `Content-Type: ${part.payload.type}\r\n\r\n`, + ])); + chunks.push(part.payload); + chunks.push(new Blob(["\r\n"])); + } + // Add final boundary + chunks.push(new Blob([`--${boundary}--\r\n`])); + // Combine all chunks into a single Blob + const body = new Blob(chunks); + // Convert Blob to ArrayBuffer for compatibility + const arrayBuffer = await body.arrayBuffer(); + return arrayBuffer; + } + async _createMultipartStream(parts, boundary) { + const encoder = new TextEncoder(); + // Create a ReadableStream for streaming the multipart data + // Only do special handling if we're using node-fetch + const stream = new ReadableStream({ + async start(controller) { + // Helper function to write a chunk to the stream + const writeChunk = async (chunk) => { + if (typeof chunk === "string") { + controller.enqueue(encoder.encode(chunk)); + } + else { + controller.enqueue(chunk); + } + }; + // Write each part to the stream + for (const part of parts) { + // Write boundary and headers + await writeChunk(`--${boundary}\r\n`); + await writeChunk(`Content-Disposition: form-data; name="${part.name}"\r\n`); + await writeChunk(`Content-Type: ${part.payload.type}\r\n\r\n`); + // Write the payload + const payloadStream = part.payload.stream(); + const reader = payloadStream.getReader(); + try { + let result; + while (!(result = await reader.read()).done) { + controller.enqueue(result.value); + } + } + finally { + reader.releaseLock(); + } + await writeChunk("\r\n"); + } + // Write final boundary + await writeChunk(`--${boundary}--\r\n`); + controller.close(); + }, + }); + return stream; } - else { - parent[k] = replace; - arr.push([parent, k, val]); - } -} -function decirc(val, k, edgeIndex, stack, parent, depth, options) { - depth += 1; - var i; - if (typeof val === "object" && val !== null) { - for (i = 0; i < stack.length; i++) { - if (stack[i] === val) { - setReplace(CIRCULAR_REPLACE_NODE, val, k, parent); - return; + async _sendMultipartRequest(parts, context, options) { + // Create multipart form data boundary + const boundary = "----LangSmithFormBoundary" + Math.random().toString(36).slice(2); + const isNodeFetch = _globalFetchImplementationIsNodeFetch(); + const buildBuffered = () => this._createNodeFetchBody(parts, boundary); + const buildStream = () => this._createMultipartStream(parts, boundary); + const send = async (body) => { + const headers = { + ...this.headers, + "Content-Type": `multipart/form-data; boundary=${boundary}`, + }; + if (options?.apiKey !== undefined) { + headers["x-api-key"] = options.apiKey; + } + return this.batchIngestCaller.call(_getFetchImplementation(this.debug), `${options?.apiUrl ?? this.apiUrl}/runs/multipart`, { + method: "POST", + headers, + body, + duplex: "half", + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + }; + try { + let res; + let streamedAttempt = false; + // attempt stream only if not disabled and not using node-fetch + if (!isNodeFetch && !this.multipartStreamingDisabled) { + streamedAttempt = true; + res = await send(await buildStream()); } + else { + res = await send(await buildBuffered()); + } + // if stream fails, fallback to buffered body + if ((!this.multipartStreamingDisabled || streamedAttempt) && + res.status === 422 && + (options?.apiUrl ?? this.apiUrl) !== DEFAULT_API_URL) { + console.warn(`Streaming multipart upload to ${options?.apiUrl ?? this.apiUrl}/runs/multipart failed. ` + + `This usually means the host does not support chunked uploads. ` + + `Retrying with a buffered upload for operation "${context}".`); + // Disable streaming for future requests + this.multipartStreamingDisabled = true; + // retry with fully-buffered body + res = await send(await buildBuffered()); + } + // raise if still failing + await raiseForStatus(res, "ingest multipart runs", true); + // eslint-disable-next-line @typescript-eslint/no-explicit-any } - if (typeof options.depthLimit !== "undefined" && - depth > options.depthLimit) { - setReplace(LIMIT_REPLACE_NODE, val, k, parent); - return; + catch (e) { + console.warn(`${e.message.trim()}\n\nContext: ${context}`); } - if (typeof options.edgesLimit !== "undefined" && - edgeIndex + 1 > options.edgesLimit) { - setReplace(LIMIT_REPLACE_NODE, val, k, parent); + } + async updateRun(runId, run, options) { + assertUuid(runId); + if (run.inputs) { + run.inputs = await this.processInputs(run.inputs); + } + if (run.outputs) { + run.outputs = await this.processOutputs(run.outputs); + } + // TODO: Untangle types + const data = { ...run, id: runId }; + if (!this._filterForSampling([data], true).length) { return; } - stack.push(val); - // Optimize for Arrays. Big arrays could kill the performance otherwise! - if (Array.isArray(val)) { - for (i = 0; i < val.length; i++) { - decirc(val[i], i, i, stack, val, depth, options); + if (this.autoBatchTracing && + data.trace_id !== undefined && + data.dotted_order !== undefined) { + const otelContext = this._cloneCurrentOTELContext(); + if (run.end_time !== undefined && + data.parent_run_id === undefined && + this.blockOnRootRunFinalization && + !this.manualFlushMode) { + // Trigger batches as soon as a root trace ends and wait to ensure trace finishes + // in serverless environments. + await this.processRunOperation({ + action: "update", + item: data, + otelContext, + apiKey: options?.apiKey, + apiUrl: options?.apiUrl, + }).catch(console.error); + return; } - } - else { - var keys = Object.keys(val); - for (i = 0; i < keys.length; i++) { - var key = keys[i]; - decirc(val[key], key, i, stack, val, depth, options); + else { + void this.processRunOperation({ + action: "update", + item: data, + otelContext, + apiKey: options?.apiKey, + apiUrl: options?.apiUrl, + }).catch(console.error); } + return; } - stack.pop(); - } -} -// Stable-stringify -function compareFunction(a, b) { - if (a < b) { - return -1; - } - if (a > b) { - return 1; - } - return 0; -} -function deterministicStringify(obj, replacer, spacer, options) { - if (typeof options === "undefined") { - options = fast_safe_stringify_defaultOptions(); - } - var tmp = deterministicDecirc(obj, "", 0, [], undefined, 0, options) || obj; - var res; - try { - if (replacerStack.length === 0) { - res = JSON.stringify(tmp, replacer, spacer); - } - else { - res = JSON.stringify(tmp, replaceGetterValues(replacer), spacer); + const headers = { + ...this.headers, + "Content-Type": "application/json", + }; + if (options?.apiKey !== undefined) { + headers["x-api-key"] = options.apiKey; } + const response = await this.caller.call(_getFetchImplementation(this.debug), `${options?.apiUrl ?? this.apiUrl}/runs/${runId}`, { + method: "PATCH", + headers, + body: serialize(run, `Serializing payload to update run with id: ${runId}`), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(response, "update run", true); } - catch (_) { - return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]"); + async readRun(runId, { loadChildRuns } = { loadChildRuns: false }) { + assertUuid(runId); + let run = await this._get(`/runs/${runId}`); + if (loadChildRuns) { + run = await this._loadChildRuns(run); + } + return run; } - finally { - // Ensure that we restore the object as it was. - while (arr.length !== 0) { - var part = arr.pop(); - if (part.length === 4) { - Object.defineProperty(part[0], part[1], part[3]); + async getRunUrl({ runId, run, projectOpts, }) { + if (run !== undefined) { + let sessionId; + if (run.session_id) { + sessionId = run.session_id; + } + else if (projectOpts?.projectName) { + sessionId = (await this.readProject({ projectName: projectOpts?.projectName })).id; + } + else if (projectOpts?.projectId) { + sessionId = projectOpts?.projectId; } else { - part[0][part[1]] = part[2]; + const project = await this.readProject({ + projectName: getLangSmithEnvironmentVariable("PROJECT") || "default", + }); + sessionId = project.id; } + const tenantId = await this._getTenantId(); + return `${this.getHostUrl()}/o/${tenantId}/projects/p/${sessionId}/r/${run.id}?poll=true`; } - } - return res; -} -function deterministicDecirc(val, k, edgeIndex, stack, parent, depth, options) { - depth += 1; - var i; - if (typeof val === "object" && val !== null) { - for (i = 0; i < stack.length; i++) { - if (stack[i] === val) { - setReplace(CIRCULAR_REPLACE_NODE, val, k, parent); - return; + else if (runId !== undefined) { + const run_ = await this.readRun(runId); + if (!run_.app_path) { + throw new Error(`Run ${runId} has no app_path`); } + const baseUrl = this.getHostUrl(); + return `${baseUrl}${run_.app_path}`; } - try { - if (typeof val.toJSON === "function") { - return; - } + else { + throw new Error("Must provide either runId or run"); } - catch (_) { - return; + } + async _loadChildRuns(run) { + const childRuns = await toArray(this.listRuns({ + isRoot: false, + projectId: run.session_id, + traceId: run.trace_id, + })); + const treemap = {}; + const runs = {}; + // TODO: make dotted order required when the migration finishes + childRuns.sort((a, b) => (a?.dotted_order ?? "").localeCompare(b?.dotted_order ?? "")); + for (const childRun of childRuns) { + if (childRun.parent_run_id === null || + childRun.parent_run_id === undefined) { + throw new Error(`Child run ${childRun.id} has no parent`); + } + if (childRun.dotted_order?.startsWith(run.dotted_order ?? "") && + childRun.id !== run.id) { + if (!(childRun.parent_run_id in treemap)) { + treemap[childRun.parent_run_id] = []; + } + treemap[childRun.parent_run_id].push(childRun); + runs[childRun.id] = childRun; + } } - if (typeof options.depthLimit !== "undefined" && - depth > options.depthLimit) { - setReplace(LIMIT_REPLACE_NODE, val, k, parent); - return; + run.child_runs = treemap[run.id] || []; + for (const runId in treemap) { + if (runId !== run.id) { + runs[runId].child_runs = treemap[runId]; + } } - if (typeof options.edgesLimit !== "undefined" && - edgeIndex + 1 > options.edgesLimit) { - setReplace(LIMIT_REPLACE_NODE, val, k, parent); - return; + return run; + } + /** + * List runs from the LangSmith server. + * @param projectId - The ID of the project to filter by. + * @param projectName - The name of the project to filter by. + * @param parentRunId - The ID of the parent run to filter by. + * @param traceId - The ID of the trace to filter by. + * @param referenceExampleId - The ID of the reference example to filter by. + * @param startTime - The start time to filter by. + * @param isRoot - Indicates whether to only return root runs. + * @param runType - The run type to filter by. + * @param error - Indicates whether to filter by error runs. + * @param id - The ID of the run to filter by. + * @param query - The query string to filter by. + * @param filter - The filter string to apply to the run spans. + * @param traceFilter - The filter string to apply on the root run of the trace. + * @param treeFilter - The filter string to apply on other runs in the trace. + * @param limit - The maximum number of runs to retrieve. + * @returns {AsyncIterable} - The runs. + * + * @example + * // List all runs in a project + * const projectRuns = client.listRuns({ projectName: "" }); + * + * @example + * // List LLM and Chat runs in the last 24 hours + * const todaysLLMRuns = client.listRuns({ + * projectName: "", + * start_time: new Date(Date.now() - 24 * 60 * 60 * 1000), + * run_type: "llm", + * }); + * + * @example + * // List traces in a project + * const rootRuns = client.listRuns({ + * projectName: "", + * execution_order: 1, + * }); + * + * @example + * // List runs without errors + * const correctRuns = client.listRuns({ + * projectName: "", + * error: false, + * }); + * + * @example + * // List runs by run ID + * const runIds = [ + * "a36092d2-4ad5-4fb4-9c0d-0dba9a2ed836", + * "9398e6be-964f-4aa4-8ae9-ad78cd4b7074", + * ]; + * const selectedRuns = client.listRuns({ run_ids: runIds }); + * + * @example + * // List all "chain" type runs that took more than 10 seconds and had `total_tokens` greater than 5000 + * const chainRuns = client.listRuns({ + * projectName: "", + * filter: 'and(eq(run_type, "chain"), gt(latency, 10), gt(total_tokens, 5000))', + * }); + * + * @example + * // List all runs called "extractor" whose root of the trace was assigned feedback "user_score" score of 1 + * const goodExtractorRuns = client.listRuns({ + * projectName: "", + * filter: 'eq(name, "extractor")', + * traceFilter: 'and(eq(feedback_key, "user_score"), eq(feedback_score, 1))', + * }); + * + * @example + * // List all runs that started after a specific timestamp and either have "error" not equal to null or a "Correctness" feedback score equal to 0 + * const complexRuns = client.listRuns({ + * projectName: "", + * filter: 'and(gt(start_time, "2023-07-15T12:34:56Z"), or(neq(error, null), and(eq(feedback_key, "Correctness"), eq(feedback_score, 0.0))))', + * }); + * + * @example + * // List all runs where `tags` include "experimental" or "beta" and `latency` is greater than 2 seconds + * const taggedRuns = client.listRuns({ + * projectName: "", + * filter: 'and(or(has(tags, "experimental"), has(tags, "beta")), gt(latency, 2))', + * }); + */ + async *listRuns(props) { + const { projectId, projectName, parentRunId, traceId, referenceExampleId, startTime, executionOrder, isRoot, runType, error, id, query, filter, traceFilter, treeFilter, limit, select, order, } = props; + let projectIds = []; + if (projectId) { + projectIds = Array.isArray(projectId) ? projectId : [projectId]; } - stack.push(val); - // Optimize for Arrays. Big arrays could kill the performance otherwise! - if (Array.isArray(val)) { - for (i = 0; i < val.length; i++) { - deterministicDecirc(val[i], i, i, stack, val, depth, options); - } + if (projectName) { + const projectNames = Array.isArray(projectName) + ? projectName + : [projectName]; + const projectIds_ = await Promise.all(projectNames.map((name) => this.readProject({ projectName: name }).then((project) => project.id))); + projectIds.push(...projectIds_); } - else { - // Create a temporary object in the required way - var tmp = {}; - var keys = Object.keys(val).sort(compareFunction); - for (i = 0; i < keys.length; i++) { - var key = keys[i]; - deterministicDecirc(val[key], key, i, stack, val, depth, options); - tmp[key] = val[key]; - } - if (typeof parent !== "undefined") { - arr.push([parent, k, val]); - parent[k] = tmp; + const default_select = [ + "app_path", + "completion_cost", + "completion_tokens", + "dotted_order", + "end_time", + "error", + "events", + "extra", + "feedback_stats", + "first_token_time", + "id", + "inputs", + "name", + "outputs", + "parent_run_id", + "parent_run_ids", + "prompt_cost", + "prompt_tokens", + "reference_example_id", + "run_type", + "session_id", + "start_time", + "status", + "tags", + "total_cost", + "total_tokens", + "trace_id", + ]; + const body = { + session: projectIds.length ? projectIds : null, + run_type: runType, + reference_example: referenceExampleId, + query, + filter, + trace_filter: traceFilter, + tree_filter: treeFilter, + execution_order: executionOrder, + parent_run: parentRunId, + start_time: startTime ? startTime.toISOString() : null, + error, + id, + limit, + trace: traceId, + select: select ? select : default_select, + is_root: isRoot, + order, + }; + let runsYielded = 0; + for await (const runs of this._getCursorPaginatedList("/runs/query", body)) { + if (limit) { + if (runsYielded >= limit) { + break; + } + if (runs.length + runsYielded > limit) { + const newRuns = runs.slice(0, limit - runsYielded); + yield* newRuns; + break; + } + runsYielded += runs.length; + yield* runs; } else { - return tmp; + yield* runs; } } - stack.pop(); } -} -// wraps replacer function to handle values we couldn't replace -// and mark them as replaced value -function replaceGetterValues(replacer) { - replacer = - typeof replacer !== "undefined" - ? replacer - : function (k, v) { - return v; + async *listGroupRuns(props) { + const { projectId, projectName, groupBy, filter, startTime, endTime, limit, offset, } = props; + const sessionId = projectId || (await this.readProject({ projectName })).id; + const baseBody = { + session_id: sessionId, + group_by: groupBy, + filter, + start_time: startTime ? startTime.toISOString() : null, + end_time: endTime ? endTime.toISOString() : null, + limit: Number(limit) || 100, + }; + let currentOffset = Number(offset) || 0; + const path = "/runs/group"; + const url = `${this.apiUrl}${path}`; + while (true) { + const currentBody = { + ...baseBody, + offset: currentOffset, }; - return function (key, val) { - if (replacerStack.length > 0) { - for (var i = 0; i < replacerStack.length; i++) { - var part = replacerStack[i]; - if (part[1] === key && part[0] === val) { - val = part[2]; - replacerStack.splice(i, 1); - break; - } + // Remove undefined values from the payload + const filteredPayload = Object.fromEntries(Object.entries(currentBody).filter(([_, value]) => value !== undefined)); + const response = await this.caller.call(_getFetchImplementation(), url, { + method: "POST", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(filteredPayload), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(response, `Failed to fetch ${path}`); + const items = await response.json(); + const { groups, total } = items; + if (groups.length === 0) { + break; + } + for (const thread of groups) { + yield thread; + } + currentOffset += groups.length; + if (currentOffset >= total) { + break; } } - return replacer.call(this, key, val); - }; -} - -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/client.js - - - - - - - - - - - -function mergeRuntimeEnvIntoRunCreate(run) { - const runtimeEnv = getRuntimeEnvironment(); - const envVars = getLangChainEnvVarsMetadata(); - const extra = run.extra ?? {}; - const metadata = extra.metadata; - run.extra = { - ...extra, - runtime: { - ...runtimeEnv, - ...extra?.runtime, - }, - metadata: { - ...envVars, - ...(envVars.revision_id || run.revision_id - ? { revision_id: run.revision_id ?? envVars.revision_id } - : {}), - ...metadata, - }, - }; - return run; -} -const getTracingSamplingRate = (configRate) => { - const samplingRateStr = configRate?.toString() ?? - getLangSmithEnvironmentVariable("TRACING_SAMPLING_RATE"); - if (samplingRateStr === undefined) { - return undefined; - } - const samplingRate = parseFloat(samplingRateStr); - if (samplingRate < 0 || samplingRate > 1) { - throw new Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${samplingRate}`); - } - return samplingRate; -}; -// utility functions -const isLocalhost = (url) => { - const strippedUrl = url.replace("http://", "").replace("https://", ""); - const hostname = strippedUrl.split("/")[0].split(":")[0]; - return (hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1"); -}; -async function toArray(iterable) { - const result = []; - for await (const item of iterable) { - result.push(item); - } - return result; -} -function trimQuotes(str) { - if (str === undefined) { - return undefined; } - return str - .trim() - .replace(/^"(.*)"$/, "$1") - .replace(/^'(.*)'$/, "$1"); -} -const handle429 = async (response) => { - if (response?.status === 429) { - const retryAfter = parseInt(response.headers.get("retry-after") ?? "30", 10) * 1000; - if (retryAfter > 0) { - await new Promise((resolve) => setTimeout(resolve, retryAfter)); - // Return directly after calling this check - return true; + async getRunStats({ id, trace, parentRun, runType, projectNames, projectIds, referenceExampleIds, startTime, endTime, error, query, filter, traceFilter, treeFilter, isRoot, dataSourceType, }) { + let projectIds_ = projectIds || []; + if (projectNames) { + projectIds_ = [ + ...(projectIds || []), + ...(await Promise.all(projectNames.map((name) => this.readProject({ projectName: name }).then((project) => project.id)))), + ]; } + const payload = { + id, + trace, + parent_run: parentRun, + run_type: runType, + session: projectIds_, + reference_example: referenceExampleIds, + start_time: startTime, + end_time: endTime, + error, + query, + filter, + trace_filter: traceFilter, + tree_filter: treeFilter, + is_root: isRoot, + data_source_type: dataSourceType, + }; + // Remove undefined values from the payload + const filteredPayload = Object.fromEntries(Object.entries(payload).filter(([_, value]) => value !== undefined)); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/runs/stats`, { + method: "POST", + headers: this.headers, + body: JSON.stringify(filteredPayload), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + const result = await response.json(); + return result; } - // Fall back to existing status checks - return false; -}; -function _formatFeedbackScore(score) { - if (typeof score === "number") { - // Truncate at 4 decimal places - return Number(score.toFixed(4)); - } - return score; -} -class AutoBatchQueue { - constructor() { - Object.defineProperty(this, "items", { - enumerable: true, - configurable: true, - writable: true, - value: [] + async shareRun(runId, { shareId } = {}) { + const data = { + run_id: runId, + share_token: shareId || v4(), + }; + assertUuid(runId); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/runs/${runId}/share`, { + method: "PUT", + headers: this.headers, + body: JSON.stringify(data), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, }); - Object.defineProperty(this, "sizeBytes", { - enumerable: true, - configurable: true, - writable: true, - value: 0 + const result = await response.json(); + if (result === null || !("share_token" in result)) { + throw new Error("Invalid response from server"); + } + return `${this.getHostUrl()}/public/${result["share_token"]}/r`; + } + async unshareRun(runId) { + assertUuid(runId); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/runs/${runId}/share`, { + method: "DELETE", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, }); + await raiseForStatus(response, "unshare run", true); } - peek() { - return this.items[0]; + async readRunSharedLink(runId) { + assertUuid(runId); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/runs/${runId}/share`, { + method: "GET", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + const result = await response.json(); + if (result === null || !("share_token" in result)) { + return undefined; + } + return `${this.getHostUrl()}/public/${result["share_token"]}/r`; } - push(item) { - let itemPromiseResolve; - const itemPromise = new Promise((resolve) => { - // Setting itemPromiseResolve is synchronous with promise creation: - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise - itemPromiseResolve = resolve; + async listSharedRuns(shareToken, { runIds, } = {}) { + const queryParams = new URLSearchParams({ + share_token: shareToken, }); - const size = serialize(item.item).length; - this.items.push({ - action: item.action, - payload: item.item, - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - itemPromiseResolve: itemPromiseResolve, - itemPromise, - size, + if (runIds !== undefined) { + for (const runId of runIds) { + queryParams.append("id", runId); + } + } + assertUuid(shareToken); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/public/${shareToken}/runs${queryParams}`, { + method: "GET", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, }); - this.sizeBytes += size; - return itemPromise; + const runs = await response.json(); + return runs; } - pop(upToSizeBytes) { - if (upToSizeBytes < 1) { - throw new Error("Number of bytes to pop off may not be less than 1."); - } - const popped = []; - let poppedSizeBytes = 0; - // Pop items until we reach or exceed the size limit - while (poppedSizeBytes + (this.peek()?.size ?? 0) < upToSizeBytes && - this.items.length > 0) { - const item = this.items.shift(); - if (item) { - popped.push(item); - poppedSizeBytes += item.size; - this.sizeBytes -= item.size; - } + async readDatasetSharedSchema(datasetId, datasetName) { + if (!datasetId && !datasetName) { + throw new Error("Either datasetId or datasetName must be given"); } - // If there is an item on the queue we were unable to pop, - // just return it as a single batch. - if (popped.length === 0 && this.items.length > 0) { - const item = this.items.shift(); - popped.push(item); - poppedSizeBytes += item.size; - this.sizeBytes -= item.size; + if (!datasetId) { + const dataset = await this.readDataset({ datasetName }); + datasetId = dataset.id; } - return [ - popped.map((it) => ({ action: it.action, item: it.payload })), - () => popped.forEach((it) => it.itemPromiseResolve()), - ]; - } -} -// 20 MB -const DEFAULT_BATCH_SIZE_LIMIT_BYTES = 20_971_520; -const SERVER_INFO_REQUEST_TIMEOUT = 2500; -class Client { - constructor(config = {}) { - Object.defineProperty(this, "apiKey", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "apiUrl", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "webUrl", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "caller", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "batchIngestCaller", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "timeout_ms", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "_tenantId", { - enumerable: true, - configurable: true, - writable: true, - value: null - }); - Object.defineProperty(this, "hideInputs", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "hideOutputs", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "tracingSampleRate", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "filteredPostUuids", { - enumerable: true, - configurable: true, - writable: true, - value: new Set() - }); - Object.defineProperty(this, "autoBatchTracing", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - Object.defineProperty(this, "autoBatchQueue", { - enumerable: true, - configurable: true, - writable: true, - value: new AutoBatchQueue() - }); - Object.defineProperty(this, "autoBatchTimeout", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "autoBatchAggregationDelayMs", { - enumerable: true, - configurable: true, - writable: true, - value: 250 - }); - Object.defineProperty(this, "batchSizeBytesLimit", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "fetchOptions", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "settings", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "blockOnRootRunFinalization", { - enumerable: true, - configurable: true, - writable: true, - value: getEnvironmentVariable("LANGSMITH_TRACING_BACKGROUND") === "false" + assertUuid(datasetId); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/${datasetId}/share`, { + method: "GET", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, }); - Object.defineProperty(this, "traceBatchConcurrency", { - enumerable: true, - configurable: true, - writable: true, - value: 5 + const shareSchema = await response.json(); + shareSchema.url = `${this.getHostUrl()}/public/${shareSchema.share_token}/d`; + return shareSchema; + } + async shareDataset(datasetId, datasetName) { + if (!datasetId && !datasetName) { + throw new Error("Either datasetId or datasetName must be given"); + } + if (!datasetId) { + const dataset = await this.readDataset({ datasetName }); + datasetId = dataset.id; + } + const data = { + dataset_id: datasetId, + }; + assertUuid(datasetId); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/${datasetId}/share`, { + method: "PUT", + headers: this.headers, + body: JSON.stringify(data), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, }); - Object.defineProperty(this, "_serverInfo", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 + const shareSchema = await response.json(); + shareSchema.url = `${this.getHostUrl()}/public/${shareSchema.share_token}/d`; + return shareSchema; + } + async unshareDataset(datasetId) { + assertUuid(datasetId); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/${datasetId}/share`, { + method: "DELETE", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, }); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - Object.defineProperty(this, "_getServerInfoPromise", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 + await raiseForStatus(response, "unshare dataset", true); + } + async readSharedDataset(shareToken) { + assertUuid(shareToken); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/public/${shareToken}/datasets`, { + method: "GET", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, }); - Object.defineProperty(this, "manualFlushMode", { - enumerable: true, - configurable: true, - writable: true, - value: false + const dataset = await response.json(); + return dataset; + } + /** + * Get shared examples. + * + * @param {string} shareToken The share token to get examples for. A share token is the UUID (or LangSmith URL, including UUID) generated when explicitly marking an example as public. + * @param {Object} [options] Additional options for listing the examples. + * @param {string[] | undefined} [options.exampleIds] A list of example IDs to filter by. + * @returns {Promise} The shared examples. + */ + async listSharedExamples(shareToken, options) { + const params = {}; + if (options?.exampleIds) { + params.id = options.exampleIds; + } + const urlParams = new URLSearchParams(); + Object.entries(params).forEach(([key, value]) => { + if (Array.isArray(value)) { + value.forEach((v) => urlParams.append(key, v)); + } + else { + urlParams.append(key, value); + } }); - Object.defineProperty(this, "debug", { - enumerable: true, - configurable: true, - writable: true, - value: getEnvironmentVariable("LANGSMITH_DEBUG") === "true" + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/public/${shareToken}/examples?${urlParams.toString()}`, { + method: "GET", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, }); - const defaultConfig = Client.getDefaultClientConfig(); - this.tracingSampleRate = getTracingSamplingRate(config.tracingSamplingRate); - this.apiUrl = trimQuotes(config.apiUrl ?? defaultConfig.apiUrl) ?? ""; - if (this.apiUrl.endsWith("/")) { - this.apiUrl = this.apiUrl.slice(0, -1); + const result = await response.json(); + if (!response.ok) { + if ("detail" in result) { + throw new Error(`Failed to list shared examples.\nStatus: ${response.status}\nMessage: ${Array.isArray(result.detail) + ? result.detail.join("\n") + : "Unspecified error"}`); + } + throw new Error(`Failed to list shared examples: ${response.status} ${response.statusText}`); } - this.apiKey = trimQuotes(config.apiKey ?? defaultConfig.apiKey); - this.webUrl = trimQuotes(config.webUrl ?? defaultConfig.webUrl); - if (this.webUrl?.endsWith("/")) { - this.webUrl = this.webUrl.slice(0, -1); + return result.map((example) => ({ + ...example, + _hostUrl: this.getHostUrl(), + })); + } + async createProject({ projectName, description = null, metadata = null, upsert = false, projectExtra = null, referenceDatasetId = null, }) { + const upsert_ = upsert ? `?upsert=true` : ""; + const endpoint = `${this.apiUrl}/sessions${upsert_}`; + const extra = projectExtra || {}; + if (metadata) { + extra["metadata"] = metadata; } - this.timeout_ms = config.timeout_ms ?? 90_000; - this.caller = new AsyncCaller({ - ...(config.callerOptions ?? {}), - debug: config.debug ?? this.debug, - }); - this.traceBatchConcurrency = - config.traceBatchConcurrency ?? this.traceBatchConcurrency; - if (this.traceBatchConcurrency < 1) { - throw new Error("Trace batch concurrency must be positive."); + const body = { + name: projectName, + extra, + description, + }; + if (referenceDatasetId !== null) { + body["reference_dataset_id"] = referenceDatasetId; } - this.debug = config.debug ?? this.debug; - this.batchIngestCaller = new AsyncCaller({ - maxRetries: 2, - maxConcurrency: this.traceBatchConcurrency, - ...(config.callerOptions ?? {}), - onFailedResponseHook: handle429, - debug: config.debug ?? this.debug, + const response = await this.caller.call(_getFetchImplementation(this.debug), endpoint, { + method: "POST", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(body), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, }); - this.hideInputs = - config.hideInputs ?? config.anonymizer ?? defaultConfig.hideInputs; - this.hideOutputs = - config.hideOutputs ?? config.anonymizer ?? defaultConfig.hideOutputs; - this.autoBatchTracing = config.autoBatchTracing ?? this.autoBatchTracing; - this.blockOnRootRunFinalization = - config.blockOnRootRunFinalization ?? this.blockOnRootRunFinalization; - this.batchSizeBytesLimit = config.batchSizeBytesLimit; - this.fetchOptions = config.fetchOptions || {}; - this.manualFlushMode = config.manualFlushMode ?? this.manualFlushMode; + await raiseForStatus(response, "create project"); + const result = await response.json(); + return result; } - static getDefaultClientConfig() { - const apiKey = getLangSmithEnvironmentVariable("API_KEY"); - const apiUrl = getLangSmithEnvironmentVariable("ENDPOINT") ?? - "https://api.smith.langchain.com"; - const hideInputs = getLangSmithEnvironmentVariable("HIDE_INPUTS") === "true"; - const hideOutputs = getLangSmithEnvironmentVariable("HIDE_OUTPUTS") === "true"; - return { - apiUrl: apiUrl, - apiKey: apiKey, - webUrl: undefined, - hideInputs: hideInputs, - hideOutputs: hideOutputs, + async updateProject(projectId, { name = null, description = null, metadata = null, projectExtra = null, endTime = null, }) { + const endpoint = `${this.apiUrl}/sessions/${projectId}`; + let extra = projectExtra; + if (metadata) { + extra = { ...(extra || {}), metadata }; + } + const body = { + name, + extra, + description, + end_time: endTime ? new Date(endTime).toISOString() : null, }; + const response = await this.caller.call(_getFetchImplementation(this.debug), endpoint, { + method: "PATCH", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(body), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(response, "update project"); + const result = await response.json(); + return result; } - getHostUrl() { - if (this.webUrl) { - return this.webUrl; + async hasProject({ projectId, projectName, }) { + // TODO: Add a head request + let path = "/sessions"; + const params = new URLSearchParams(); + if (projectId !== undefined && projectName !== undefined) { + throw new Error("Must provide either projectName or projectId, not both"); } - else if (isLocalhost(this.apiUrl)) { - this.webUrl = "http://localhost:3000"; - return this.webUrl; + else if (projectId !== undefined) { + assertUuid(projectId); + path += `/${projectId}`; } - else if (this.apiUrl.endsWith("/api/v1")) { - this.webUrl = this.apiUrl.replace("/api/v1", ""); - return this.webUrl; + else if (projectName !== undefined) { + params.append("name", projectName); } - else if (this.apiUrl.includes("/api") && - !this.apiUrl.split(".", 1)[0].endsWith("api")) { - this.webUrl = this.apiUrl.replace("/api", ""); - return this.webUrl; + else { + throw new Error("Must provide projectName or projectId"); } - else if (this.apiUrl.split(".", 1)[0].includes("dev")) { - this.webUrl = "https://dev.smith.langchain.com"; - return this.webUrl; + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}${path}?${params}`, { + method: "GET", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + // consume the response body to release the connection + // https://undici.nodejs.org/#/?id=garbage-collection + try { + const result = await response.json(); + if (!response.ok) { + return false; + } + // If it's OK and we're querying by name, need to check the list is not empty + if (Array.isArray(result)) { + return result.length > 0; + } + // projectId querying + return true; } - else if (this.apiUrl.split(".", 1)[0].includes("eu")) { - this.webUrl = "https://eu.smith.langchain.com"; - return this.webUrl; + catch (e) { + return false; } - else if (this.apiUrl.split(".", 1)[0].includes("beta")) { - this.webUrl = "https://beta.smith.langchain.com"; - return this.webUrl; + } + async readProject({ projectId, projectName, includeStats, }) { + let path = "/sessions"; + const params = new URLSearchParams(); + if (projectId !== undefined && projectName !== undefined) { + throw new Error("Must provide either projectName or projectId, not both"); + } + else if (projectId !== undefined) { + assertUuid(projectId); + path += `/${projectId}`; + } + else if (projectName !== undefined) { + params.append("name", projectName); } else { - this.webUrl = "https://smith.langchain.com"; - return this.webUrl; + throw new Error("Must provide projectName or projectId"); + } + if (includeStats !== undefined) { + params.append("include_stats", includeStats.toString()); + } + const response = await this._get(path, params); + let result; + if (Array.isArray(response)) { + if (response.length === 0) { + throw new Error(`Project[id=${projectId}, name=${projectName}] not found`); + } + result = response[0]; } + else { + result = response; + } + return result; } - get headers() { - const headers = { - "User-Agent": `langsmith-js/${__version__}`, - }; - if (this.apiKey) { - headers["x-api-key"] = `${this.apiKey}`; + async getProjectUrl({ projectId, projectName, }) { + if (projectId === undefined && projectName === undefined) { + throw new Error("Must provide either projectName or projectId"); } - return headers; + const project = await this.readProject({ projectId, projectName }); + const tenantId = await this._getTenantId(); + return `${this.getHostUrl()}/o/${tenantId}/projects/p/${project.id}`; } - async processInputs(inputs) { - if (this.hideInputs === false) { - return inputs; + async getDatasetUrl({ datasetId, datasetName, }) { + if (datasetId === undefined && datasetName === undefined) { + throw new Error("Must provide either datasetName or datasetId"); } - if (this.hideInputs === true) { - return {}; + const dataset = await this.readDataset({ datasetId, datasetName }); + const tenantId = await this._getTenantId(); + return `${this.getHostUrl()}/o/${tenantId}/datasets/${dataset.id}`; + } + async _getTenantId() { + if (this._tenantId !== null) { + return this._tenantId; } - if (typeof this.hideInputs === "function") { - return this.hideInputs(inputs); + const queryParams = new URLSearchParams({ limit: "1" }); + for await (const projects of this._getPaginated("/sessions", queryParams)) { + this._tenantId = projects[0].tenant_id; + return projects[0].tenant_id; } - return inputs; + throw new Error("No projects found to resolve tenant."); } - async processOutputs(outputs) { - if (this.hideOutputs === false) { - return outputs; + async *listProjects({ projectIds, name, nameContains, referenceDatasetId, referenceDatasetName, referenceFree, metadata, } = {}) { + const params = new URLSearchParams(); + if (projectIds !== undefined) { + for (const projectId of projectIds) { + params.append("id", projectId); + } } - if (this.hideOutputs === true) { - return {}; + if (name !== undefined) { + params.append("name", name); } - if (typeof this.hideOutputs === "function") { - return this.hideOutputs(outputs); + if (nameContains !== undefined) { + params.append("name_contains", nameContains); + } + if (referenceDatasetId !== undefined) { + params.append("reference_dataset", referenceDatasetId); + } + else if (referenceDatasetName !== undefined) { + const dataset = await this.readDataset({ + datasetName: referenceDatasetName, + }); + params.append("reference_dataset", dataset.id); + } + if (referenceFree !== undefined) { + params.append("reference_free", referenceFree.toString()); + } + if (metadata !== undefined) { + params.append("metadata", JSON.stringify(metadata)); + } + for await (const projects of this._getPaginated("/sessions", params)) { + yield* projects; } - return outputs; } - async prepareRunCreateOrUpdateInputs(run) { - const runParams = { ...run }; - if (runParams.inputs !== undefined) { - runParams.inputs = await this.processInputs(runParams.inputs); + async deleteProject({ projectId, projectName, }) { + let projectId_; + if (projectId === undefined && projectName === undefined) { + throw new Error("Must provide projectName or projectId"); } - if (runParams.outputs !== undefined) { - runParams.outputs = await this.processOutputs(runParams.outputs); + else if (projectId !== undefined && projectName !== undefined) { + throw new Error("Must provide either projectName or projectId, not both"); } - return runParams; + else if (projectId === undefined) { + projectId_ = (await this.readProject({ projectName })).id; + } + else { + projectId_ = projectId; + } + assertUuid(projectId_); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/sessions/${projectId_}`, { + method: "DELETE", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(response, `delete session ${projectId_} (${projectName})`, true); } - async _getResponse(path, queryParams) { - const paramsString = queryParams?.toString() ?? ""; - const url = `${this.apiUrl}${path}?${paramsString}`; + async uploadCsv({ csvFile, fileName, inputKeys, outputKeys, description, dataType, name, }) { + const url = `${this.apiUrl}/datasets/upload`; + const formData = new FormData(); + formData.append("file", csvFile, fileName); + inputKeys.forEach((key) => { + formData.append("input_keys", key); + }); + outputKeys.forEach((key) => { + formData.append("output_keys", key); + }); + if (description) { + formData.append("description", description); + } + if (dataType) { + formData.append("data_type", dataType); + } + if (name) { + formData.append("name", name); + } const response = await this.caller.call(_getFetchImplementation(this.debug), url, { - method: "GET", + method: "POST", headers: this.headers, + body: formData, signal: AbortSignal.timeout(this.timeout_ms), ...this.fetchOptions, }); - await raiseForStatus(response, `Failed to fetch ${path}`); - return response; - } - async _get(path, queryParams) { - const response = await this._getResponse(path, queryParams); - return response.json(); + await raiseForStatus(response, "upload CSV"); + const result = await response.json(); + return result; } - async *_getPaginated(path, queryParams = new URLSearchParams(), transform) { - let offset = Number(queryParams.get("offset")) || 0; - const limit = Number(queryParams.get("limit")) || 100; - while (true) { - queryParams.set("offset", String(offset)); - queryParams.set("limit", String(limit)); - const url = `${this.apiUrl}${path}?${queryParams}`; - const response = await this.caller.call(_getFetchImplementation(this.debug), url, { - method: "GET", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(response, `Failed to fetch ${path}`); - const items = transform - ? transform(await response.json()) - : await response.json(); - if (items.length === 0) { - break; - } - yield items; - if (items.length < limit) { - break; - } - offset += items.length; + async createDataset(name, { description, dataType, inputsSchema, outputsSchema, metadata, } = {}) { + const body = { + name, + description, + extra: metadata ? { metadata } : undefined, + }; + if (dataType) { + body.data_type = dataType; } - } - async *_getCursorPaginatedList(path, body = null, requestMethod = "POST", dataKey = "runs") { - const bodyParams = body ? { ...body } : {}; - while (true) { - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}${path}`, { - method: requestMethod, - headers: { ...this.headers, "Content-Type": "application/json" }, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - body: JSON.stringify(bodyParams), - }); - const responseBody = await response.json(); - if (!responseBody) { - break; - } - if (!responseBody[dataKey]) { - break; - } - yield responseBody[dataKey]; - const cursors = responseBody.cursors; - if (!cursors) { - break; - } - if (!cursors.next) { - break; - } - bodyParams.cursor = cursors.next; + if (inputsSchema) { + body.inputs_schema_definition = inputsSchema; } - } - // Allows mocking for tests - _shouldSample() { - if (this.tracingSampleRate === undefined) { - return true; + if (outputsSchema) { + body.outputs_schema_definition = outputsSchema; } - return Math.random() < this.tracingSampleRate; + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets`, { + method: "POST", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(body), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(response, "create dataset"); + const result = await response.json(); + return result; } - _filterForSampling(runs, patch = false) { - if (this.tracingSampleRate === undefined) { - return runs; + async readDataset({ datasetId, datasetName, }) { + let path = "/datasets"; + // limit to 1 result + const params = new URLSearchParams({ limit: "1" }); + if (datasetId && datasetName) { + throw new Error("Must provide either datasetName or datasetId, not both"); } - if (patch) { - const sampled = []; - for (const run of runs) { - if (!this.filteredPostUuids.has(run.id)) { - sampled.push(run); - } - else { - this.filteredPostUuids.delete(run.id); - } - } - return sampled; + else if (datasetId) { + assertUuid(datasetId); + path += `/${datasetId}`; + } + else if (datasetName) { + params.append("name", datasetName); } else { - // For new runs, sample at trace level to maintain consistency - const sampled = []; - for (const run of runs) { - const traceId = run.trace_id ?? run.id; - // If we've already made a decision about this trace, follow it - if (this.filteredPostUuids.has(traceId)) { - continue; - } - // For new traces, apply sampling - if (run.id === traceId) { - if (this._shouldSample()) { - sampled.push(run); - } - else { - this.filteredPostUuids.add(traceId); - } - } - else { - // Child runs follow their trace's sampling decision - sampled.push(run); - } + throw new Error("Must provide datasetName or datasetId"); + } + const response = await this._get(path, params); + let result; + if (Array.isArray(response)) { + if (response.length === 0) { + throw new Error(`Dataset[id=${datasetId}, name=${datasetName}] not found`); } - return sampled; + result = response[0]; } + else { + result = response; + } + return result; } - async _getBatchSizeLimitBytes() { - const serverInfo = await this._ensureServerInfo(); - return (this.batchSizeBytesLimit ?? - serverInfo.batch_ingest_config?.size_limit_bytes ?? - DEFAULT_BATCH_SIZE_LIMIT_BYTES); - } - async _getMultiPartSupport() { - const serverInfo = await this._ensureServerInfo(); - return (serverInfo.instance_flags?.dataset_examples_multipart_enabled ?? false); - } - drainAutoBatchQueue(batchSizeLimit) { - const promises = []; - while (this.autoBatchQueue.items.length > 0) { - const [batch, done] = this.autoBatchQueue.pop(batchSizeLimit); - if (!batch.length) { - done(); - break; + async hasDataset({ datasetId, datasetName, }) { + try { + await this.readDataset({ datasetId, datasetName }); + return true; + } + catch (e) { + if ( + // eslint-disable-next-line no-instanceof/no-instanceof + e instanceof Error && + e.message.toLocaleLowerCase().includes("not found")) { + return false; } - const batchPromise = this._processBatch(batch, done).catch(console.error); - promises.push(batchPromise); + throw e; } - return Promise.all(promises); } - async _processBatch(batch, done) { - if (!batch.length) { - done(); - return; + async diffDatasetVersions({ datasetId, datasetName, fromVersion, toVersion, }) { + let datasetId_ = datasetId; + if (datasetId_ === undefined && datasetName === undefined) { + throw new Error("Must provide either datasetName or datasetId"); } - try { - const ingestParams = { - runCreates: batch - .filter((item) => item.action === "create") - .map((item) => item.item), - runUpdates: batch - .filter((item) => item.action === "update") - .map((item) => item.item), - }; - const serverInfo = await this._ensureServerInfo(); - if (serverInfo?.batch_ingest_config?.use_multipart_endpoint) { - await this.multipartIngestRuns(ingestParams); - } - else { - await this.batchIngestRuns(ingestParams); - } + else if (datasetId_ !== undefined && datasetName !== undefined) { + throw new Error("Must provide either datasetName or datasetId, not both"); } - finally { - done(); + else if (datasetId_ === undefined) { + const dataset = await this.readDataset({ datasetName }); + datasetId_ = dataset.id; } + const urlParams = new URLSearchParams({ + from_version: typeof fromVersion === "string" + ? fromVersion + : fromVersion.toISOString(), + to_version: typeof toVersion === "string" ? toVersion : toVersion.toISOString(), + }); + const response = await this._get(`/datasets/${datasetId_}/versions/diff`, urlParams); + return response; } - async processRunOperation(item) { - clearTimeout(this.autoBatchTimeout); - this.autoBatchTimeout = undefined; - if (item.action === "create") { - item.item = mergeRuntimeEnvIntoRunCreate(item.item); - } - const itemPromise = this.autoBatchQueue.push(item); - if (this.manualFlushMode) { - // Rely on manual flushing in serverless environments - return itemPromise; + async readDatasetOpenaiFinetuning({ datasetId, datasetName, }) { + const path = "/datasets"; + if (datasetId !== undefined) { + // do nothing } - const sizeLimitBytes = await this._getBatchSizeLimitBytes(); - if (this.autoBatchQueue.sizeBytes > sizeLimitBytes) { - void this.drainAutoBatchQueue(sizeLimitBytes); + else if (datasetName !== undefined) { + datasetId = (await this.readDataset({ datasetName })).id; } - if (this.autoBatchQueue.items.length > 0) { - this.autoBatchTimeout = setTimeout(() => { - this.autoBatchTimeout = undefined; - void this.drainAutoBatchQueue(sizeLimitBytes); - }, this.autoBatchAggregationDelayMs); + else { + throw new Error("Must provide either datasetName or datasetId"); } - return itemPromise; + const response = await this._getResponse(`${path}/${datasetId}/openai_ft`); + const datasetText = await response.text(); + const dataset = datasetText + .trim() + .split("\n") + .map((line) => JSON.parse(line)); + return dataset; } - async _getServerInfo() { - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/info`, { - method: "GET", - headers: { Accept: "application/json" }, - signal: AbortSignal.timeout(SERVER_INFO_REQUEST_TIMEOUT), - ...this.fetchOptions, + async *listDatasets({ limit = 100, offset = 0, datasetIds, datasetName, datasetNameContains, metadata, } = {}) { + const path = "/datasets"; + const params = new URLSearchParams({ + limit: limit.toString(), + offset: offset.toString(), }); - await raiseForStatus(response, "get server info"); - const json = await response.json(); - if (this.debug) { - console.log("\n=== LangSmith Server Configuration ===\n" + - JSON.stringify(json, null, 2) + - "\n"); + if (datasetIds !== undefined) { + for (const id_ of datasetIds) { + params.append("id", id_); + } } - return json; - } - async _ensureServerInfo() { - if (this._getServerInfoPromise === undefined) { - this._getServerInfoPromise = (async () => { - if (this._serverInfo === undefined) { - try { - this._serverInfo = await this._getServerInfo(); - } - catch (e) { - console.warn(`[WARNING]: LangSmith failed to fetch info on supported operations with status code ${e.status}. Falling back to batch operations and default limits.`); - } - } - return this._serverInfo ?? {}; - })(); + if (datasetName !== undefined) { + params.append("name", datasetName); } - return this._getServerInfoPromise.then((serverInfo) => { - if (this._serverInfo === undefined) { - this._getServerInfoPromise = undefined; - } - return serverInfo; - }); - } - async _getSettings() { - if (!this.settings) { - this.settings = this._get("/settings"); + if (datasetNameContains !== undefined) { + params.append("name_contains", datasetNameContains); + } + if (metadata !== undefined) { + params.append("metadata", JSON.stringify(metadata)); + } + for await (const datasets of this._getPaginated(path, params)) { + yield* datasets; } - return await this.settings; } /** - * Flushes current queued traces. + * Update a dataset + * @param props The dataset details to update + * @returns The updated dataset */ - async flush() { - const sizeLimitBytes = await this._getBatchSizeLimitBytes(); - await this.drainAutoBatchQueue(sizeLimitBytes); - } - async createRun(run) { - if (!this._filterForSampling([run]).length) { - return; - } - const headers = { ...this.headers, "Content-Type": "application/json" }; - const session_name = run.project_name; - delete run.project_name; - const runCreate = await this.prepareRunCreateOrUpdateInputs({ - session_name, - ...run, - start_time: run.start_time ?? Date.now(), - }); - if (this.autoBatchTracing && - runCreate.trace_id !== undefined && - runCreate.dotted_order !== undefined) { - void this.processRunOperation({ - action: "create", - item: runCreate, - }).catch(console.error); - return; + async updateDataset(props) { + const { datasetId, datasetName, ...update } = props; + if (!datasetId && !datasetName) { + throw new Error("Must provide either datasetName or datasetId"); } - const mergedRunCreateParam = mergeRuntimeEnvIntoRunCreate(runCreate); - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/runs`, { - method: "POST", - headers, - body: serialize(mergedRunCreateParam), + const _datasetId = datasetId ?? (await this.readDataset({ datasetName })).id; + assertUuid(_datasetId); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/${_datasetId}`, { + method: "PATCH", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(update), signal: AbortSignal.timeout(this.timeout_ms), ...this.fetchOptions, }); - await raiseForStatus(response, "create run", true); + await raiseForStatus(response, "update dataset"); + return (await response.json()); } /** - * Batch ingest/upsert multiple runs in the Langsmith system. - * @param runs + * Updates a tag on a dataset. + * + * If the tag is already assigned to a different version of this dataset, + * the tag will be moved to the new version. The as_of parameter is used to + * determine which version of the dataset to apply the new tags to. + * + * It must be an exact version of the dataset to succeed. You can + * use the "readDatasetVersion" method to find the exact version + * to apply the tags to. + * @param params.datasetId The ID of the dataset to update. Must be provided if "datasetName" is not provided. + * @param params.datasetName The name of the dataset to update. Must be provided if "datasetId" is not provided. + * @param params.asOf The timestamp of the dataset to apply the new tags to. + * @param params.tag The new tag to apply to the dataset. */ - async batchIngestRuns({ runCreates, runUpdates, }) { - if (runCreates === undefined && runUpdates === undefined) { - return; + async updateDatasetTag(props) { + const { datasetId, datasetName, asOf, tag } = props; + if (!datasetId && !datasetName) { + throw new Error("Must provide either datasetName or datasetId"); } - let preparedCreateParams = await Promise.all(runCreates?.map((create) => this.prepareRunCreateOrUpdateInputs(create)) ?? []); - let preparedUpdateParams = await Promise.all(runUpdates?.map((update) => this.prepareRunCreateOrUpdateInputs(update)) ?? []); - if (preparedCreateParams.length > 0 && preparedUpdateParams.length > 0) { - const createById = preparedCreateParams.reduce((params, run) => { - if (!run.id) { - return params; - } - params[run.id] = run; - return params; - }, {}); - const standaloneUpdates = []; - for (const updateParam of preparedUpdateParams) { - if (updateParam.id !== undefined && createById[updateParam.id]) { - createById[updateParam.id] = { - ...createById[updateParam.id], - ...updateParam, - }; - } - else { - standaloneUpdates.push(updateParam); - } - } - preparedCreateParams = Object.values(createById); - preparedUpdateParams = standaloneUpdates; + const _datasetId = datasetId ?? (await this.readDataset({ datasetName })).id; + assertUuid(_datasetId); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/${_datasetId}/tags`, { + method: "PUT", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify({ + as_of: typeof asOf === "string" ? asOf : asOf.toISOString(), + tag, + }), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(response, "update dataset tags"); + } + async deleteDataset({ datasetId, datasetName, }) { + let path = "/datasets"; + let datasetId_ = datasetId; + if (datasetId !== undefined && datasetName !== undefined) { + throw new Error("Must provide either datasetName or datasetId, not both"); } - const rawBatch = { - post: preparedCreateParams, - patch: preparedUpdateParams, - }; - if (!rawBatch.post.length && !rawBatch.patch.length) { - return; + else if (datasetName !== undefined) { + const dataset = await this.readDataset({ datasetName }); + datasetId_ = dataset.id; } - const batchChunks = { - post: [], - patch: [], - }; - for (const k of ["post", "patch"]) { - const key = k; - const batchItems = rawBatch[key].reverse(); - let batchItem = batchItems.pop(); - while (batchItem !== undefined) { - // Type is wrong but this is a deprecated code path anyway - batchChunks[key].push(batchItem); - batchItem = batchItems.pop(); - } + if (datasetId_ !== undefined) { + assertUuid(datasetId_); + path += `/${datasetId_}`; } - if (batchChunks.post.length > 0 || batchChunks.patch.length > 0) { - await this._postBatchIngestRuns(serialize(batchChunks)); + else { + throw new Error("Must provide datasetName or datasetId"); } + const response = await this.caller.call(_getFetchImplementation(this.debug), this.apiUrl + path, { + method: "DELETE", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(response, `delete ${path}`); + await response.json(); } - async _postBatchIngestRuns(body) { - const headers = { - ...this.headers, - "Content-Type": "application/json", - Accept: "application/json", + async indexDataset({ datasetId, datasetName, tag, }) { + let datasetId_ = datasetId; + if (!datasetId_ && !datasetName) { + throw new Error("Must provide either datasetName or datasetId"); + } + else if (datasetId_ && datasetName) { + throw new Error("Must provide either datasetName or datasetId, not both"); + } + else if (!datasetId_) { + const dataset = await this.readDataset({ datasetName }); + datasetId_ = dataset.id; + } + assertUuid(datasetId_); + const data = { + tag: tag, }; - const response = await this.batchIngestCaller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/runs/batch`, { + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/${datasetId_}/index`, { method: "POST", - headers, - body: body, + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(data), signal: AbortSignal.timeout(this.timeout_ms), ...this.fetchOptions, }); - await raiseForStatus(response, "batch create run", true); + await raiseForStatus(response, "index dataset"); + await response.json(); } /** - * Batch ingest/upsert multiple runs in the Langsmith system. - * @param runs + * Lets you run a similarity search query on a dataset. + * + * Requires the dataset to be indexed. Please see the `indexDataset` method to set up indexing. + * + * @param inputs The input on which to run the similarity search. Must have the + * same schema as the dataset. + * + * @param datasetId The dataset to search for similar examples. + * + * @param limit The maximum number of examples to return. Will return the top `limit` most + * similar examples in order of most similar to least similar. If no similar + * examples are found, random examples will be returned. + * + * @param filter A filter string to apply to the search. Only examples will be returned that + * match the filter string. Some examples of filters + * + * - eq(metadata.mykey, "value") + * - and(neq(metadata.my.nested.key, "value"), neq(metadata.mykey, "value")) + * - or(eq(metadata.mykey, "value"), eq(metadata.mykey, "othervalue")) + * + * @returns A list of similar examples. + * + * + * @example + * dataset_id = "123e4567-e89b-12d3-a456-426614174000" + * inputs = {"text": "How many people live in Berlin?"} + * limit = 5 + * examples = await client.similarExamples(inputs, dataset_id, limit) */ - async multipartIngestRuns({ runCreates, runUpdates, }) { - if (runCreates === undefined && runUpdates === undefined) { - return; + async similarExamples(inputs, datasetId, limit, { filter, } = {}) { + const data = { + limit: limit, + inputs: inputs, + }; + if (filter !== undefined) { + data["filter"] = filter; } - // transform and convert to dicts - const allAttachments = {}; - let preparedCreateParams = []; - for (const create of runCreates ?? []) { - const preparedCreate = await this.prepareRunCreateOrUpdateInputs(create); - if (preparedCreate.id !== undefined && - preparedCreate.attachments !== undefined) { - allAttachments[preparedCreate.id] = preparedCreate.attachments; + assertUuid(datasetId); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/${datasetId}/search`, { + method: "POST", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(data), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(response, "fetch similar examples"); + const result = await response.json(); + return result["examples"]; + } + async createExample(inputsOrUpdate, outputs, options) { + if (isExampleCreate(inputsOrUpdate)) { + if (outputs !== undefined || options !== undefined) { + throw new Error("Cannot provide outputs or options when using ExampleCreate object"); } - delete preparedCreate.attachments; - preparedCreateParams.push(preparedCreate); } - let preparedUpdateParams = []; - for (const update of runUpdates ?? []) { - preparedUpdateParams.push(await this.prepareRunCreateOrUpdateInputs(update)); + let datasetId_ = outputs ? options?.datasetId : inputsOrUpdate.dataset_id; + const datasetName_ = outputs + ? options?.datasetName + : inputsOrUpdate.dataset_name; + if (datasetId_ === undefined && datasetName_ === undefined) { + throw new Error("Must provide either datasetName or datasetId"); } - // require trace_id and dotted_order - const invalidRunCreate = preparedCreateParams.find((runCreate) => { - return (runCreate.trace_id === undefined || runCreate.dotted_order === undefined); - }); - if (invalidRunCreate !== undefined) { - throw new Error(`Multipart ingest requires "trace_id" and "dotted_order" to be set when creating a run`); + else if (datasetId_ !== undefined && datasetName_ !== undefined) { + throw new Error("Must provide either datasetName or datasetId, not both"); } - const invalidRunUpdate = preparedUpdateParams.find((runUpdate) => { - return (runUpdate.trace_id === undefined || runUpdate.dotted_order === undefined); - }); - if (invalidRunUpdate !== undefined) { - throw new Error(`Multipart ingest requires "trace_id" and "dotted_order" to be set when updating a run`); + else if (datasetId_ === undefined) { + const dataset = await this.readDataset({ datasetName: datasetName_ }); + datasetId_ = dataset.id; } - // combine post and patch dicts where possible - if (preparedCreateParams.length > 0 && preparedUpdateParams.length > 0) { - const createById = preparedCreateParams.reduce((params, run) => { - if (!run.id) { - return params; - } - params[run.id] = run; - return params; - }, {}); - const standaloneUpdates = []; - for (const updateParam of preparedUpdateParams) { - if (updateParam.id !== undefined && createById[updateParam.id]) { - createById[updateParam.id] = { - ...createById[updateParam.id], - ...updateParam, - }; - } - else { - standaloneUpdates.push(updateParam); - } + const createdAt_ = (outputs ? options?.createdAt : inputsOrUpdate.created_at) || new Date(); + let data; + if (!isExampleCreate(inputsOrUpdate)) { + data = { + inputs: inputsOrUpdate, + outputs, + created_at: createdAt_?.toISOString(), + id: options?.exampleId, + metadata: options?.metadata, + split: options?.split, + source_run_id: options?.sourceRunId, + use_source_run_io: options?.useSourceRunIO, + use_source_run_attachments: options?.useSourceRunAttachments, + attachments: options?.attachments, + }; + } + else { + data = inputsOrUpdate; + } + const response = await this._uploadExamplesMultipart(datasetId_, [data]); + const example = await this.readExample(response.example_ids?.[0] ?? v4()); + return example; + } + async createExamples(propsOrUploads) { + if (Array.isArray(propsOrUploads)) { + if (propsOrUploads.length === 0) { + return []; } - preparedCreateParams = Object.values(createById); - preparedUpdateParams = standaloneUpdates; + const uploads = propsOrUploads; + let datasetId_ = uploads[0].dataset_id; + const datasetName_ = uploads[0].dataset_name; + if (datasetId_ === undefined && datasetName_ === undefined) { + throw new Error("Must provide either datasetName or datasetId"); + } + else if (datasetId_ !== undefined && datasetName_ !== undefined) { + throw new Error("Must provide either datasetName or datasetId, not both"); + } + else if (datasetId_ === undefined) { + const dataset = await this.readDataset({ datasetName: datasetName_ }); + datasetId_ = dataset.id; + } + const response = await this._uploadExamplesMultipart(datasetId_, uploads); + const examples = await Promise.all(response.example_ids.map((id) => this.readExample(id))); + return examples; + } + const { inputs, outputs, metadata, splits, sourceRunIds, useSourceRunIOs, useSourceRunAttachments, attachments, exampleIds, datasetId, datasetName, } = propsOrUploads; + if (inputs === undefined) { + throw new Error("Must provide inputs when using legacy parameters"); + } + let datasetId_ = datasetId; + const datasetName_ = datasetName; + if (datasetId_ === undefined && datasetName_ === undefined) { + throw new Error("Must provide either datasetName or datasetId"); + } + else if (datasetId_ !== undefined && datasetName_ !== undefined) { + throw new Error("Must provide either datasetName or datasetId, not both"); + } + else if (datasetId_ === undefined) { + const dataset = await this.readDataset({ datasetName: datasetName_ }); + datasetId_ = dataset.id; + } + const formattedExamples = inputs.map((input, idx) => { + return { + dataset_id: datasetId_, + inputs: input, + outputs: outputs?.[idx], + metadata: metadata?.[idx], + split: splits?.[idx], + id: exampleIds?.[idx], + attachments: attachments?.[idx], + source_run_id: sourceRunIds?.[idx], + use_source_run_io: useSourceRunIOs?.[idx], + use_source_run_attachments: useSourceRunAttachments?.[idx], + }; + }); + const response = await this._uploadExamplesMultipart(datasetId_, formattedExamples); + const examples = await Promise.all(response.example_ids.map((id) => this.readExample(id))); + return examples; + } + async createLLMExample(input, generation, options) { + return this.createExample({ input }, { output: generation }, options); + } + async createChatExample(input, generations, options) { + const finalInput = input.map((message) => { + if (isLangChainMessage(message)) { + return convertLangChainMessageToExample(message); + } + return message; + }); + const finalOutput = isLangChainMessage(generations) + ? convertLangChainMessageToExample(generations) + : generations; + return this.createExample({ input: finalInput }, { output: finalOutput }, options); + } + async readExample(exampleId) { + assertUuid(exampleId); + const path = `/examples/${exampleId}`; + const rawExample = await this._get(path); + const { attachment_urls, ...rest } = rawExample; + const example = rest; + if (attachment_urls) { + example.attachments = Object.entries(attachment_urls).reduce((acc, [key, value]) => { + acc[key.slice("attachment.".length)] = { + presigned_url: value.presigned_url, + mime_type: value.mime_type, + }; + return acc; + }, {}); + } + return example; + } + async *listExamples({ datasetId, datasetName, exampleIds, asOf, splits, inlineS3Urls, metadata, limit, offset, filter, includeAttachments, } = {}) { + let datasetId_; + if (datasetId !== undefined && datasetName !== undefined) { + throw new Error("Must provide either datasetName or datasetId, not both"); + } + else if (datasetId !== undefined) { + datasetId_ = datasetId; + } + else if (datasetName !== undefined) { + const dataset = await this.readDataset({ datasetName }); + datasetId_ = dataset.id; + } + else { + throw new Error("Must provide a datasetName or datasetId"); } - if (preparedCreateParams.length === 0 && - preparedUpdateParams.length === 0) { - return; + const params = new URLSearchParams({ dataset: datasetId_ }); + const dataset_version = asOf + ? typeof asOf === "string" + ? asOf + : asOf?.toISOString() + : undefined; + if (dataset_version) { + params.append("as_of", dataset_version); } - // send the runs in multipart requests - const accumulatedContext = []; - const accumulatedParts = []; - for (const [method, payloads] of [ - ["post", preparedCreateParams], - ["patch", preparedUpdateParams], - ]) { - for (const originalPayload of payloads) { - // collect fields to be sent as separate parts - const { inputs, outputs, events, attachments, ...payload } = originalPayload; - const fields = { inputs, outputs, events }; - // encode the main run payload - const stringifiedPayload = serialize(payload); - accumulatedParts.push({ - name: `${method}.${payload.id}`, - payload: new Blob([stringifiedPayload], { - type: `application/json; length=${stringifiedPayload.length}`, // encoding=gzip - }), - }); - // encode the fields we collected - for (const [key, value] of Object.entries(fields)) { - if (value === undefined) { - continue; - } - const stringifiedValue = serialize(value); - accumulatedParts.push({ - name: `${method}.${payload.id}.${key}`, - payload: new Blob([stringifiedValue], { - type: `application/json; length=${stringifiedValue.length}`, - }), - }); - } - // encode the attachments - if (payload.id !== undefined) { - const attachments = allAttachments[payload.id]; - if (attachments) { - delete allAttachments[payload.id]; - for (const [name, attachment] of Object.entries(attachments)) { - let contentType; - let content; - if (Array.isArray(attachment)) { - [contentType, content] = attachment; - } - else { - contentType = attachment.mimeType; - content = attachment.data; - } - // Validate that the attachment name doesn't contain a '.' - if (name.includes(".")) { - console.warn(`Skipping attachment '${name}' for run ${payload.id}: Invalid attachment name. ` + - `Attachment names must not contain periods ('.'). Please rename the attachment and try again.`); - continue; - } - accumulatedParts.push({ - name: `attachment.${payload.id}.${name}`, - payload: new Blob([content], { - type: `${contentType}; length=${content.byteLength}`, - }), - }); - } - } - } - // compute context - accumulatedContext.push(`trace=${payload.trace_id},id=${payload.id}`); + const inlineS3Urls_ = inlineS3Urls ?? true; + params.append("inline_s3_urls", inlineS3Urls_.toString()); + if (exampleIds !== undefined) { + for (const id_ of exampleIds) { + params.append("id", id_); } } - await this._sendMultipartRequest(accumulatedParts, accumulatedContext.join("; ")); - } - async _sendMultipartRequest(parts, context) { - try { - // Create multipart form data manually using Blobs - const boundary = "----LangSmithFormBoundary" + Math.random().toString(36).slice(2); - const chunks = []; - for (const part of parts) { - // Add field boundary - chunks.push(new Blob([`--${boundary}\r\n`])); - chunks.push(new Blob([ - `Content-Disposition: form-data; name="${part.name}"\r\n`, - `Content-Type: ${part.payload.type}\r\n\r\n`, - ])); - chunks.push(part.payload); - chunks.push(new Blob(["\r\n"])); - } - // Add final boundary - chunks.push(new Blob([`--${boundary}--\r\n`])); - // Combine all chunks into a single Blob - const body = new Blob(chunks); - // Convert Blob to ArrayBuffer for compatibility - const arrayBuffer = await body.arrayBuffer(); - const res = await this.batchIngestCaller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/runs/multipart`, { - method: "POST", - headers: { - ...this.headers, - "Content-Type": `multipart/form-data; boundary=${boundary}`, - }, - body: arrayBuffer, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(res, "ingest multipart runs", true); - // eslint-disable-next-line @typescript-eslint/no-explicit-any + if (splits !== undefined) { + for (const split of splits) { + params.append("splits", split); + } } - catch (e) { - console.warn(`${e.message.trim()}\n\nContext: ${context}`); + if (metadata !== undefined) { + const serializedMetadata = JSON.stringify(metadata); + params.append("metadata", serializedMetadata); } - } - async updateRun(runId, run) { - assertUuid(runId); - if (run.inputs) { - run.inputs = await this.processInputs(run.inputs); + if (limit !== undefined) { + params.append("limit", limit.toString()); } - if (run.outputs) { - run.outputs = await this.processOutputs(run.outputs); + if (offset !== undefined) { + params.append("offset", offset.toString()); } - // TODO: Untangle types - const data = { ...run, id: runId }; - if (!this._filterForSampling([data], true).length) { - return; + if (filter !== undefined) { + params.append("filter", filter); } - if (this.autoBatchTracing && - data.trace_id !== undefined && - data.dotted_order !== undefined) { - if (run.end_time !== undefined && - data.parent_run_id === undefined && - this.blockOnRootRunFinalization && - !this.manualFlushMode) { - // Trigger batches as soon as a root trace ends and wait to ensure trace finishes - // in serverless environments. - await this.processRunOperation({ action: "update", item: data }).catch(console.error); - return; + if (includeAttachments === true) { + ["attachment_urls", "outputs", "metadata"].forEach((field) => params.append("select", field)); + } + let i = 0; + for await (const rawExamples of this._getPaginated("/examples", params)) { + for (const rawExample of rawExamples) { + const { attachment_urls, ...rest } = rawExample; + const example = rest; + if (attachment_urls) { + example.attachments = Object.entries(attachment_urls).reduce((acc, [key, value]) => { + acc[key.slice("attachment.".length)] = { + presigned_url: value.presigned_url, + mime_type: value.mime_type || undefined, + }; + return acc; + }, {}); + } + yield example; + i++; } - else { - void this.processRunOperation({ action: "update", item: data }).catch(console.error); + if (limit !== undefined && i >= limit) { + break; } - return; } - const headers = { ...this.headers, "Content-Type": "application/json" }; - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/runs/${runId}`, { - method: "PATCH", - headers, - body: serialize(run), + } + async deleteExample(exampleId) { + assertUuid(exampleId); + const path = `/examples/${exampleId}`; + const response = await this.caller.call(_getFetchImplementation(this.debug), this.apiUrl + path, { + method: "DELETE", + headers: this.headers, signal: AbortSignal.timeout(this.timeout_ms), ...this.fetchOptions, }); - await raiseForStatus(response, "update run", true); + await raiseForStatus(response, `delete ${path}`); + await response.json(); } - async readRun(runId, { loadChildRuns } = { loadChildRuns: false }) { - assertUuid(runId); - let run = await this._get(`/runs/${runId}`); - if (loadChildRuns && run.child_run_ids) { - run = await this._loadChildRuns(run); + async updateExample(exampleIdOrUpdate, update) { + let exampleId; + if (update) { + exampleId = exampleIdOrUpdate; } - return run; - } - async getRunUrl({ runId, run, projectOpts, }) { - if (run !== undefined) { - let sessionId; - if (run.session_id) { - sessionId = run.session_id; - } - else if (projectOpts?.projectName) { - sessionId = (await this.readProject({ projectName: projectOpts?.projectName })).id; - } - else if (projectOpts?.projectId) { - sessionId = projectOpts?.projectId; - } - else { - const project = await this.readProject({ - projectName: getLangSmithEnvironmentVariable("PROJECT") || "default", - }); - sessionId = project.id; - } - const tenantId = await this._getTenantId(); - return `${this.getHostUrl()}/o/${tenantId}/projects/p/${sessionId}/r/${run.id}?poll=true`; + else { + exampleId = exampleIdOrUpdate.id; } - else if (runId !== undefined) { - const run_ = await this.readRun(runId); - if (!run_.app_path) { - throw new Error(`Run ${runId} has no app_path`); - } - const baseUrl = this.getHostUrl(); - return `${baseUrl}${run_.app_path}`; + assertUuid(exampleId); + let updateToUse; + if (update) { + updateToUse = { id: exampleId, ...update }; } else { - throw new Error("Must provide either runId or run"); + updateToUse = exampleIdOrUpdate; + } + let datasetId; + if (updateToUse.dataset_id !== undefined) { + datasetId = updateToUse.dataset_id; + } + else { + const example = await this.readExample(exampleId); + datasetId = example.dataset_id; } + return this._updateExamplesMultipart(datasetId, [updateToUse]); } - async _loadChildRuns(run) { - const childRuns = await toArray(this.listRuns({ id: run.child_run_ids })); - const treemap = {}; - const runs = {}; - // TODO: make dotted order required when the migration finishes - childRuns.sort((a, b) => (a?.dotted_order ?? "").localeCompare(b?.dotted_order ?? "")); - for (const childRun of childRuns) { - if (childRun.parent_run_id === null || - childRun.parent_run_id === undefined) { - throw new Error(`Child run ${childRun.id} has no parent`); - } - if (!(childRun.parent_run_id in treemap)) { - treemap[childRun.parent_run_id] = []; - } - treemap[childRun.parent_run_id].push(childRun); - runs[childRun.id] = childRun; + async updateExamples(update) { + // We will naively get dataset id from first example and assume it works for all + let datasetId; + if (update[0].dataset_id === undefined) { + const example = await this.readExample(update[0].id); + datasetId = example.dataset_id; } - run.child_runs = treemap[run.id] || []; - for (const runId in treemap) { - if (runId !== run.id) { - runs[runId].child_runs = treemap[runId]; - } + else { + datasetId = update[0].dataset_id; } - return run; + return this._updateExamplesMultipart(datasetId, update); } /** - * List runs from the LangSmith server. - * @param projectId - The ID of the project to filter by. - * @param projectName - The name of the project to filter by. - * @param parentRunId - The ID of the parent run to filter by. - * @param traceId - The ID of the trace to filter by. - * @param referenceExampleId - The ID of the reference example to filter by. - * @param startTime - The start time to filter by. - * @param isRoot - Indicates whether to only return root runs. - * @param runType - The run type to filter by. - * @param error - Indicates whether to filter by error runs. - * @param id - The ID of the run to filter by. - * @param query - The query string to filter by. - * @param filter - The filter string to apply to the run spans. - * @param traceFilter - The filter string to apply on the root run of the trace. - * @param treeFilter - The filter string to apply on other runs in the trace. - * @param limit - The maximum number of runs to retrieve. - * @returns {AsyncIterable} - The runs. - * - * @example - * // List all runs in a project - * const projectRuns = client.listRuns({ projectName: "" }); - * - * @example - * // List LLM and Chat runs in the last 24 hours - * const todaysLLMRuns = client.listRuns({ - * projectName: "", - * start_time: new Date(Date.now() - 24 * 60 * 60 * 1000), - * run_type: "llm", - * }); - * - * @example - * // List traces in a project - * const rootRuns = client.listRuns({ - * projectName: "", - * execution_order: 1, - * }); - * - * @example - * // List runs without errors - * const correctRuns = client.listRuns({ - * projectName: "", - * error: false, - * }); - * - * @example - * // List runs by run ID - * const runIds = [ - * "a36092d2-4ad5-4fb4-9c0d-0dba9a2ed836", - * "9398e6be-964f-4aa4-8ae9-ad78cd4b7074", - * ]; - * const selectedRuns = client.listRuns({ run_ids: runIds }); - * - * @example - * // List all "chain" type runs that took more than 10 seconds and had `total_tokens` greater than 5000 - * const chainRuns = client.listRuns({ - * projectName: "", - * filter: 'and(eq(run_type, "chain"), gt(latency, 10), gt(total_tokens, 5000))', - * }); - * - * @example - * // List all runs called "extractor" whose root of the trace was assigned feedback "user_score" score of 1 - * const goodExtractorRuns = client.listRuns({ - * projectName: "", - * filter: 'eq(name, "extractor")', - * traceFilter: 'and(eq(feedback_key, "user_score"), eq(feedback_score, 1))', - * }); + * Get dataset version by closest date or exact tag. * - * @example - * // List all runs that started after a specific timestamp and either have "error" not equal to null or a "Correctness" feedback score equal to 0 - * const complexRuns = client.listRuns({ - * projectName: "", - * filter: 'and(gt(start_time, "2023-07-15T12:34:56Z"), or(neq(error, null), and(eq(feedback_key, "Correctness"), eq(feedback_score, 0.0))))', - * }); + * Use this to resolve the nearest version to a given timestamp or for a given tag. * - * @example - * // List all runs where `tags` include "experimental" or "beta" and `latency` is greater than 2 seconds - * const taggedRuns = client.listRuns({ - * projectName: "", - * filter: 'and(or(has(tags, "experimental"), has(tags, "beta")), gt(latency, 2))', - * }); + * @param options The options for getting the dataset version + * @param options.datasetId The ID of the dataset + * @param options.datasetName The name of the dataset + * @param options.asOf The timestamp of the dataset to retrieve + * @param options.tag The tag of the dataset to retrieve + * @returns The dataset version */ - async *listRuns(props) { - const { projectId, projectName, parentRunId, traceId, referenceExampleId, startTime, executionOrder, isRoot, runType, error, id, query, filter, traceFilter, treeFilter, limit, select, order, } = props; - let projectIds = []; - if (projectId) { - projectIds = Array.isArray(projectId) ? projectId : [projectId]; + async readDatasetVersion({ datasetId, datasetName, asOf, tag, }) { + let resolvedDatasetId; + if (!datasetId) { + const dataset = await this.readDataset({ datasetName }); + resolvedDatasetId = dataset.id; } - if (projectName) { - const projectNames = Array.isArray(projectName) - ? projectName - : [projectName]; - const projectIds_ = await Promise.all(projectNames.map((name) => this.readProject({ projectName: name }).then((project) => project.id))); - projectIds.push(...projectIds_); + else { + resolvedDatasetId = datasetId; } - const default_select = [ - "app_path", - "child_run_ids", - "completion_cost", - "completion_tokens", - "dotted_order", - "end_time", - "error", - "events", - "extra", - "feedback_stats", - "first_token_time", - "id", - "inputs", - "name", - "outputs", - "parent_run_id", - "parent_run_ids", - "prompt_cost", - "prompt_tokens", - "reference_example_id", - "run_type", - "session_id", - "start_time", - "status", - "tags", - "total_cost", - "total_tokens", - "trace_id", - ]; - const body = { - session: projectIds.length ? projectIds : null, - run_type: runType, - reference_example: referenceExampleId, - query, - filter, - trace_filter: traceFilter, - tree_filter: treeFilter, - execution_order: executionOrder, - parent_run: parentRunId, - start_time: startTime ? startTime.toISOString() : null, - error, - id, - limit, - trace: traceId, - select: select ? select : default_select, - is_root: isRoot, - order, - }; - let runsYielded = 0; - for await (const runs of this._getCursorPaginatedList("/runs/query", body)) { - if (limit) { - if (runsYielded >= limit) { - break; - } - if (runs.length + runsYielded > limit) { - const newRuns = runs.slice(0, limit - runsYielded); - yield* newRuns; - break; - } - runsYielded += runs.length; - yield* runs; - } - else { - yield* runs; - } + assertUuid(resolvedDatasetId); + if ((asOf && tag) || (!asOf && !tag)) { + throw new Error("Exactly one of asOf and tag must be specified."); + } + const params = new URLSearchParams(); + if (asOf !== undefined) { + params.append("as_of", typeof asOf === "string" ? asOf : asOf.toISOString()); + } + if (tag !== undefined) { + params.append("tag", tag); } + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/${resolvedDatasetId}/version?${params.toString()}`, { + method: "GET", + headers: { ...this.headers }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(response, "read dataset version"); + return await response.json(); } - async *listGroupRuns(props) { - const { projectId, projectName, groupBy, filter, startTime, endTime, limit, offset, } = props; - const sessionId = projectId || (await this.readProject({ projectName })).id; - const baseBody = { - session_id: sessionId, - group_by: groupBy, - filter, - start_time: startTime ? startTime.toISOString() : null, - end_time: endTime ? endTime.toISOString() : null, - limit: Number(limit) || 100, - }; - let currentOffset = Number(offset) || 0; - const path = "/runs/group"; - const url = `${this.apiUrl}${path}`; - while (true) { - const currentBody = { - ...baseBody, - offset: currentOffset, - }; - // Remove undefined values from the payload - const filteredPayload = Object.fromEntries(Object.entries(currentBody).filter(([_, value]) => value !== undefined)); - const response = await this.caller.call(_getFetchImplementation(), url, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(filteredPayload), - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(response, `Failed to fetch ${path}`); - const items = await response.json(); - const { groups, total } = items; - if (groups.length === 0) { - break; - } - for (const thread of groups) { - yield thread; - } - currentOffset += groups.length; - if (currentOffset >= total) { - break; - } + async listDatasetSplits({ datasetId, datasetName, asOf, }) { + let datasetId_; + if (datasetId === undefined && datasetName === undefined) { + throw new Error("Must provide dataset name or ID"); + } + else if (datasetId !== undefined && datasetName !== undefined) { + throw new Error("Must provide either datasetName or datasetId, not both"); + } + else if (datasetId === undefined) { + const dataset = await this.readDataset({ datasetName }); + datasetId_ = dataset.id; + } + else { + datasetId_ = datasetId; + } + assertUuid(datasetId_); + const params = new URLSearchParams(); + const dataset_version = asOf + ? typeof asOf === "string" + ? asOf + : asOf?.toISOString() + : undefined; + if (dataset_version) { + params.append("as_of", dataset_version); } + const response = await this._get(`/datasets/${datasetId_}/splits`, params); + return response; } - async getRunStats({ id, trace, parentRun, runType, projectNames, projectIds, referenceExampleIds, startTime, endTime, error, query, filter, traceFilter, treeFilter, isRoot, dataSourceType, }) { - let projectIds_ = projectIds || []; - if (projectNames) { - projectIds_ = [ - ...(projectIds || []), - ...(await Promise.all(projectNames.map((name) => this.readProject({ projectName: name }).then((project) => project.id)))), - ]; + async updateDatasetSplits({ datasetId, datasetName, splitName, exampleIds, remove = false, }) { + let datasetId_; + if (datasetId === undefined && datasetName === undefined) { + throw new Error("Must provide dataset name or ID"); + } + else if (datasetId !== undefined && datasetName !== undefined) { + throw new Error("Must provide either datasetName or datasetId, not both"); + } + else if (datasetId === undefined) { + const dataset = await this.readDataset({ datasetName }); + datasetId_ = dataset.id; + } + else { + datasetId_ = datasetId; } - const payload = { - id, - trace, - parent_run: parentRun, - run_type: runType, - session: projectIds_, - reference_example: referenceExampleIds, - start_time: startTime, - end_time: endTime, - error, - query, - filter, - trace_filter: traceFilter, - tree_filter: treeFilter, - is_root: isRoot, - data_source_type: dataSourceType, + assertUuid(datasetId_); + const data = { + split_name: splitName, + examples: exampleIds.map((id) => { + assertUuid(id); + return id; + }), + remove, }; - // Remove undefined values from the payload - const filteredPayload = Object.fromEntries(Object.entries(payload).filter(([_, value]) => value !== undefined)); - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/runs/stats`, { - method: "POST", - headers: this.headers, - body: JSON.stringify(filteredPayload), + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/${datasetId_}/splits`, { + method: "PUT", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(data), signal: AbortSignal.timeout(this.timeout_ms), ...this.fetchOptions, }); - const result = await response.json(); - return result; + await raiseForStatus(response, "update dataset splits", true); } - async shareRun(runId, { shareId } = {}) { - const data = { + /** + * @deprecated This method is deprecated and will be removed in future LangSmith versions, use `evaluate` from `langsmith/evaluation` instead. + */ + async evaluateRun(run, evaluator, { sourceInfo, loadChildRuns, referenceExample, } = { loadChildRuns: false }) { + warnOnce("This method is deprecated and will be removed in future LangSmith versions, use `evaluate` from `langsmith/evaluation` instead."); + let run_; + if (typeof run === "string") { + run_ = await this.readRun(run, { loadChildRuns }); + } + else if (typeof run === "object" && "id" in run) { + run_ = run; + } + else { + throw new Error(`Invalid run type: ${typeof run}`); + } + if (run_.reference_example_id !== null && + run_.reference_example_id !== undefined) { + referenceExample = await this.readExample(run_.reference_example_id); + } + const feedbackResult = await evaluator.evaluateRun(run_, referenceExample); + const [_, feedbacks] = await this._logEvaluationFeedback(feedbackResult, run_, sourceInfo); + return feedbacks[0]; + } + async createFeedback(runId, key, { score, value, correction, comment, sourceInfo, feedbackSourceType = "api", sourceRunId, feedbackId, feedbackConfig, projectId, comparativeExperimentId, }) { + if (!runId && !projectId) { + throw new Error("One of runId or projectId must be provided"); + } + if (runId && projectId) { + throw new Error("Only one of runId or projectId can be provided"); + } + const feedback_source = { + type: feedbackSourceType ?? "api", + metadata: sourceInfo ?? {}, + }; + if (sourceRunId !== undefined && + feedback_source?.metadata !== undefined && + !feedback_source.metadata["__run"]) { + feedback_source.metadata["__run"] = { run_id: sourceRunId }; + } + if (feedback_source?.metadata !== undefined && + feedback_source.metadata["__run"]?.run_id !== undefined) { + assertUuid(feedback_source.metadata["__run"].run_id); + } + const feedback = { + id: feedbackId ?? v4(), run_id: runId, - share_token: shareId || v4(), + key, + score: _formatFeedbackScore(score), + value, + correction, + comment, + feedback_source: feedback_source, + comparative_experiment_id: comparativeExperimentId, + feedbackConfig, + session_id: projectId, }; - assertUuid(runId); - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/runs/${runId}/share`, { - method: "PUT", - headers: this.headers, - body: JSON.stringify(data), + const url = `${this.apiUrl}/feedback`; + const response = await this.caller.call(_getFetchImplementation(this.debug), url, { + method: "POST", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(feedback), signal: AbortSignal.timeout(this.timeout_ms), ...this.fetchOptions, }); - const result = await response.json(); - if (result === null || !("share_token" in result)) { - throw new Error("Invalid response from server"); - } - return `${this.getHostUrl()}/public/${result["share_token"]}/r`; + await raiseForStatus(response, "create feedback", true); + return feedback; } - async unshareRun(runId) { - assertUuid(runId); - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/runs/${runId}/share`, { - method: "DELETE", - headers: this.headers, + async updateFeedback(feedbackId, { score, value, correction, comment, }) { + const feedbackUpdate = {}; + if (score !== undefined && score !== null) { + feedbackUpdate["score"] = _formatFeedbackScore(score); + } + if (value !== undefined && value !== null) { + feedbackUpdate["value"] = value; + } + if (correction !== undefined && correction !== null) { + feedbackUpdate["correction"] = correction; + } + if (comment !== undefined && comment !== null) { + feedbackUpdate["comment"] = comment; + } + assertUuid(feedbackId); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/feedback/${feedbackId}`, { + method: "PATCH", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(feedbackUpdate), signal: AbortSignal.timeout(this.timeout_ms), ...this.fetchOptions, }); - await raiseForStatus(response, "unshare run", true); + await raiseForStatus(response, "update feedback", true); } - async readRunSharedLink(runId) { - assertUuid(runId); - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/runs/${runId}/share`, { - method: "GET", + async readFeedback(feedbackId) { + assertUuid(feedbackId); + const path = `/feedback/${feedbackId}`; + const response = await this._get(path); + return response; + } + async deleteFeedback(feedbackId) { + assertUuid(feedbackId); + const path = `/feedback/${feedbackId}`; + const response = await this.caller.call(_getFetchImplementation(this.debug), this.apiUrl + path, { + method: "DELETE", headers: this.headers, signal: AbortSignal.timeout(this.timeout_ms), ...this.fetchOptions, }); - const result = await response.json(); - if (result === null || !("share_token" in result)) { - return undefined; + await raiseForStatus(response, `delete ${path}`); + await response.json(); + } + async *listFeedback({ runIds, feedbackKeys, feedbackSourceTypes, } = {}) { + const queryParams = new URLSearchParams(); + if (runIds) { + queryParams.append("run", runIds.join(",")); + } + if (feedbackKeys) { + for (const key of feedbackKeys) { + queryParams.append("key", key); + } + } + if (feedbackSourceTypes) { + for (const type of feedbackSourceTypes) { + queryParams.append("source", type); + } + } + for await (const feedbacks of this._getPaginated("/feedback", queryParams)) { + yield* feedbacks; } - return `${this.getHostUrl()}/public/${result["share_token"]}/r`; } - async listSharedRuns(shareToken, { runIds, } = {}) { - const queryParams = new URLSearchParams({ - share_token: shareToken, - }); - if (runIds !== undefined) { - for (const runId of runIds) { - queryParams.append("id", runId); + /** + * Creates a presigned feedback token and URL. + * + * The token can be used to authorize feedback metrics without + * needing an API key. This is useful for giving browser-based + * applications the ability to submit feedback without needing + * to expose an API key. + * + * @param runId The ID of the run. + * @param feedbackKey The feedback key. + * @param options Additional options for the token. + * @param options.expiration The expiration time for the token. + * + * @returns A promise that resolves to a FeedbackIngestToken. + */ + async createPresignedFeedbackToken(runId, feedbackKey, { expiration, feedbackConfig, } = {}) { + const body = { + run_id: runId, + feedback_key: feedbackKey, + feedback_config: feedbackConfig, + }; + if (expiration) { + if (typeof expiration === "string") { + body["expires_at"] = expiration; + } + else if (expiration?.hours || expiration?.minutes || expiration?.days) { + body["expires_in"] = expiration; } } - assertUuid(shareToken); - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/public/${shareToken}/runs${queryParams}`, { - method: "GET", - headers: this.headers, + else { + body["expires_in"] = { + hours: 3, + }; + } + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/feedback/tokens`, { + method: "POST", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(body), signal: AbortSignal.timeout(this.timeout_ms), ...this.fetchOptions, }); - const runs = await response.json(); - return runs; + const result = await response.json(); + return result; } - async readDatasetSharedSchema(datasetId, datasetName) { - if (!datasetId && !datasetName) { - throw new Error("Either datasetId or datasetName must be given"); + async createComparativeExperiment({ name, experimentIds, referenceDatasetId, createdAt, description, metadata, id, }) { + if (experimentIds.length === 0) { + throw new Error("At least one experiment is required"); } - if (!datasetId) { - const dataset = await this.readDataset({ datasetName }); - datasetId = dataset.id; + if (!referenceDatasetId) { + referenceDatasetId = (await this.readProject({ + projectId: experimentIds[0], + })).reference_dataset_id; } - assertUuid(datasetId); - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/${datasetId}/share`, { - method: "GET", - headers: this.headers, + if (!referenceDatasetId == null) { + throw new Error("A reference dataset is required"); + } + const body = { + id, + name, + experiment_ids: experimentIds, + reference_dataset_id: referenceDatasetId, + description, + created_at: (createdAt ?? new Date())?.toISOString(), + extra: {}, + }; + if (metadata) + body.extra["metadata"] = metadata; + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/comparative`, { + method: "POST", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(body), signal: AbortSignal.timeout(this.timeout_ms), ...this.fetchOptions, }); - const shareSchema = await response.json(); - shareSchema.url = `${this.getHostUrl()}/public/${shareSchema.share_token}/d`; - return shareSchema; + return await response.json(); } - async shareDataset(datasetId, datasetName) { - if (!datasetId && !datasetName) { - throw new Error("Either datasetId or datasetName must be given"); + /** + * Retrieves a list of presigned feedback tokens for a given run ID. + * @param runId The ID of the run. + * @returns An async iterable of FeedbackIngestToken objects. + */ + async *listPresignedFeedbackTokens(runId) { + assertUuid(runId); + const params = new URLSearchParams({ run_id: runId }); + for await (const tokens of this._getPaginated("/feedback/tokens", params)) { + yield* tokens; } - if (!datasetId) { - const dataset = await this.readDataset({ datasetName }); - datasetId = dataset.id; + } + _selectEvalResults(results) { + let results_; + if ("results" in results) { + results_ = results.results; } - const data = { - dataset_id: datasetId, + else if (Array.isArray(results)) { + results_ = results; + } + else { + results_ = [results]; + } + return results_; + } + async _logEvaluationFeedback(evaluatorResponse, run, sourceInfo) { + const evalResults = this._selectEvalResults(evaluatorResponse); + const feedbacks = []; + for (const res of evalResults) { + let sourceInfo_ = sourceInfo || {}; + if (res.evaluatorInfo) { + sourceInfo_ = { ...res.evaluatorInfo, ...sourceInfo_ }; + } + let runId_ = null; + if (res.targetRunId) { + runId_ = res.targetRunId; + } + else if (run) { + runId_ = run.id; + } + feedbacks.push(await this.createFeedback(runId_, res.key, { + score: res.score, + value: res.value, + comment: res.comment, + correction: res.correction, + sourceInfo: sourceInfo_, + sourceRunId: res.sourceRunId, + feedbackConfig: res.feedbackConfig, + feedbackSourceType: "model", + })); + } + return [evalResults, feedbacks]; + } + async logEvaluationFeedback(evaluatorResponse, run, sourceInfo) { + const [results] = await this._logEvaluationFeedback(evaluatorResponse, run, sourceInfo); + return results; + } + /** + * API for managing annotation queues + */ + /** + * List the annotation queues on the LangSmith API. + * @param options - The options for listing annotation queues + * @param options.queueIds - The IDs of the queues to filter by + * @param options.name - The name of the queue to filter by + * @param options.nameContains - The substring that the queue name should contain + * @param options.limit - The maximum number of queues to return + * @returns An iterator of AnnotationQueue objects + */ + async *listAnnotationQueues(options = {}) { + const { queueIds, name, nameContains, limit } = options; + const params = new URLSearchParams(); + if (queueIds) { + queueIds.forEach((id, i) => { + assertUuid(id, `queueIds[${i}]`); + params.append("ids", id); + }); + } + if (name) + params.append("name", name); + if (nameContains) + params.append("name_contains", nameContains); + params.append("limit", (limit !== undefined ? Math.min(limit, 100) : 100).toString()); + let count = 0; + for await (const queues of this._getPaginated("/annotation-queues", params)) { + yield* queues; + count++; + if (limit !== undefined && count >= limit) + break; + } + } + /** + * Create an annotation queue on the LangSmith API. + * @param options - The options for creating an annotation queue + * @param options.name - The name of the annotation queue + * @param options.description - The description of the annotation queue + * @param options.queueId - The ID of the annotation queue + * @returns The created AnnotationQueue object + */ + async createAnnotationQueue(options) { + const { name, description, queueId, rubricInstructions } = options; + const body = { + name, + description, + id: queueId || v4(), + rubric_instructions: rubricInstructions, }; - assertUuid(datasetId); - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/${datasetId}/share`, { - method: "PUT", - headers: this.headers, - body: JSON.stringify(data), + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/annotation-queues`, { + method: "POST", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(Object.fromEntries(Object.entries(body).filter(([_, v]) => v !== undefined))), signal: AbortSignal.timeout(this.timeout_ms), ...this.fetchOptions, }); - const shareSchema = await response.json(); - shareSchema.url = `${this.getHostUrl()}/public/${shareSchema.share_token}/d`; - return shareSchema; + await raiseForStatus(response, "create annotation queue"); + const data = await response.json(); + return data; } - async unshareDataset(datasetId) { - assertUuid(datasetId); - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/${datasetId}/share`, { - method: "DELETE", + /** + * Read an annotation queue with the specified queue ID. + * @param queueId - The ID of the annotation queue to read + * @returns The AnnotationQueueWithDetails object + */ + async readAnnotationQueue(queueId) { + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}`, { + method: "GET", headers: this.headers, signal: AbortSignal.timeout(this.timeout_ms), ...this.fetchOptions, }); - await raiseForStatus(response, "unshare dataset", true); + await raiseForStatus(response, "read annotation queue"); + const data = await response.json(); + return data; } - async readSharedDataset(shareToken) { - assertUuid(shareToken); - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/public/${shareToken}/datasets`, { - method: "GET", - headers: this.headers, + /** + * Update an annotation queue with the specified queue ID. + * @param queueId - The ID of the annotation queue to update + * @param options - The options for updating the annotation queue + * @param options.name - The new name for the annotation queue + * @param options.description - The new description for the annotation queue + */ + async updateAnnotationQueue(queueId, options) { + const { name, description, rubricInstructions } = options; + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}`, { + method: "PATCH", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify({ + name, + description, + rubric_instructions: rubricInstructions, + }), signal: AbortSignal.timeout(this.timeout_ms), ...this.fetchOptions, }); - const dataset = await response.json(); - return dataset; + await raiseForStatus(response, "update annotation queue"); } /** - * Get shared examples. - * - * @param {string} shareToken The share token to get examples for. A share token is the UUID (or LangSmith URL, including UUID) generated when explicitly marking an example as public. - * @param {Object} [options] Additional options for listing the examples. - * @param {string[] | undefined} [options.exampleIds] A list of example IDs to filter by. - * @returns {Promise} The shared examples. + * Delete an annotation queue with the specified queue ID. + * @param queueId - The ID of the annotation queue to delete */ - async listSharedExamples(shareToken, options) { - const params = {}; - if (options?.exampleIds) { - params.id = options.exampleIds; - } - const urlParams = new URLSearchParams(); - Object.entries(params).forEach(([key, value]) => { - if (Array.isArray(value)) { - value.forEach((v) => urlParams.append(key, v)); - } - else { - urlParams.append(key, value); - } - }); - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/public/${shareToken}/examples?${urlParams.toString()}`, { - method: "GET", - headers: this.headers, + async deleteAnnotationQueue(queueId) { + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}`, { + method: "DELETE", + headers: { ...this.headers, Accept: "application/json" }, signal: AbortSignal.timeout(this.timeout_ms), ...this.fetchOptions, }); - const result = await response.json(); - if (!response.ok) { - if ("detail" in result) { - throw new Error(`Failed to list shared examples.\nStatus: ${response.status}\nMessage: ${result.detail.join("\n")}`); - } - throw new Error(`Failed to list shared examples: ${response.status} ${response.statusText}`); - } - return result.map((example) => ({ - ...example, - _hostUrl: this.getHostUrl(), - })); + await raiseForStatus(response, "delete annotation queue"); } - async createProject({ projectName, description = null, metadata = null, upsert = false, projectExtra = null, referenceDatasetId = null, }) { - const upsert_ = upsert ? `?upsert=true` : ""; - const endpoint = `${this.apiUrl}/sessions${upsert_}`; - const extra = projectExtra || {}; - if (metadata) { - extra["metadata"] = metadata; - } - const body = { - name: projectName, - extra, - description, - }; - if (referenceDatasetId !== null) { - body["reference_dataset_id"] = referenceDatasetId; - } - const response = await this.caller.call(_getFetchImplementation(this.debug), endpoint, { + /** + * Add runs to an annotation queue with the specified queue ID. + * @param queueId - The ID of the annotation queue + * @param runIds - The IDs of the runs to be added to the annotation queue + */ + async addRunsToAnnotationQueue(queueId, runIds) { + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}/runs`, { method: "POST", headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(body), + body: JSON.stringify(runIds.map((id, i) => assertUuid(id, `runIds[${i}]`).toString())), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(response, "add runs to annotation queue"); + } + /** + * Get a run from an annotation queue at the specified index. + * @param queueId - The ID of the annotation queue + * @param index - The index of the run to retrieve + * @returns A Promise that resolves to a RunWithAnnotationQueueInfo object + * @throws {Error} If the run is not found at the given index or for other API-related errors + */ + async getRunFromAnnotationQueue(queueId, index) { + const baseUrl = `/annotation-queues/${assertUuid(queueId, "queueId")}/run`; + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}${baseUrl}/${index}`, { + method: "GET", + headers: this.headers, signal: AbortSignal.timeout(this.timeout_ms), ...this.fetchOptions, }); - await raiseForStatus(response, "create project"); - const result = await response.json(); - return result; + await raiseForStatus(response, "get run from annotation queue"); + return await response.json(); } - async updateProject(projectId, { name = null, description = null, metadata = null, projectExtra = null, endTime = null, }) { - const endpoint = `${this.apiUrl}/sessions/${projectId}`; - let extra = projectExtra; - if (metadata) { - extra = { ...(extra || {}), metadata }; - } - const body = { - name, - extra, - description, - end_time: endTime ? new Date(endTime).toISOString() : null, - }; - const response = await this.caller.call(_getFetchImplementation(this.debug), endpoint, { - method: "PATCH", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(body), + /** + * Delete a run from an an annotation queue. + * @param queueId - The ID of the annotation queue to delete the run from + * @param queueRunId - The ID of the run to delete from the annotation queue + */ + async deleteRunFromAnnotationQueue(queueId, queueRunId) { + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}/runs/${assertUuid(queueRunId, "queueRunId")}`, { + method: "DELETE", + headers: { ...this.headers, Accept: "application/json" }, signal: AbortSignal.timeout(this.timeout_ms), ...this.fetchOptions, }); - await raiseForStatus(response, "update project"); - const result = await response.json(); - return result; + await raiseForStatus(response, "delete run from annotation queue"); } - async hasProject({ projectId, projectName, }) { - // TODO: Add a head request - let path = "/sessions"; - const params = new URLSearchParams(); - if (projectId !== undefined && projectName !== undefined) { - throw new Error("Must provide either projectName or projectId, not both"); - } - else if (projectId !== undefined) { - assertUuid(projectId); - path += `/${projectId}`; - } - else if (projectName !== undefined) { - params.append("name", projectName); - } - else { - throw new Error("Must provide projectName or projectId"); - } - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}${path}?${params}`, { + /** + * Get the size of an annotation queue. + * @param queueId - The ID of the annotation queue + */ + async getSizeFromAnnotationQueue(queueId) { + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}/size`, { method: "GET", headers: this.headers, signal: AbortSignal.timeout(this.timeout_ms), ...this.fetchOptions, }); - // consume the response body to release the connection - // https://undici.nodejs.org/#/?id=garbage-collection - try { - const result = await response.json(); - if (!response.ok) { - return false; - } - // If it's OK and we're querying by name, need to check the list is not empty - if (Array.isArray(result)) { - return result.length > 0; - } - // projectId querying - return true; - } - catch (e) { - return false; - } + await raiseForStatus(response, "get size from annotation queue"); + return await response.json(); } - async readProject({ projectId, projectName, includeStats, }) { - let path = "/sessions"; - const params = new URLSearchParams(); - if (projectId !== undefined && projectName !== undefined) { - throw new Error("Must provide either projectName or projectId, not both"); - } - else if (projectId !== undefined) { - assertUuid(projectId); - path += `/${projectId}`; - } - else if (projectName !== undefined) { - params.append("name", projectName); - } - else { - throw new Error("Must provide projectName or projectId"); + async _currentTenantIsOwner(owner) { + const settings = await this._getSettings(); + return owner == "-" || settings.tenant_handle === owner; + } + async _ownerConflictError(action, owner) { + const settings = await this._getSettings(); + return new Error(`Cannot ${action} for another tenant.\n + Current tenant: ${settings.tenant_handle}\n + Requested tenant: ${owner}`); + } + async _getLatestCommitHash(promptOwnerAndName) { + const res = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/commits/${promptOwnerAndName}/?limit=${1}&offset=${0}`, { + method: "GET", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + const json = await res.json(); + if (!res.ok) { + const detail = typeof json.detail === "string" + ? json.detail + : JSON.stringify(json.detail); + const error = new Error(`Error ${res.status}: ${res.statusText}\n${detail}`); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + error.statusCode = res.status; + throw error; } - if (includeStats !== undefined) { - params.append("include_stats", includeStats.toString()); + if (json.commits.length === 0) { + return undefined; } - const response = await this._get(path, params); - let result; - if (Array.isArray(response)) { - if (response.length === 0) { - throw new Error(`Project[id=${projectId}, name=${projectName}] not found`); + return json.commits[0].commit_hash; + } + async _likeOrUnlikePrompt(promptIdentifier, like) { + const [owner, promptName, _] = parsePromptIdentifier(promptIdentifier); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/likes/${owner}/${promptName}`, { + method: "POST", + body: JSON.stringify({ like: like }), + headers: { ...this.headers, "Content-Type": "application/json" }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(response, `${like ? "like" : "unlike"} prompt`); + return await response.json(); + } + async _getPromptUrl(promptIdentifier) { + const [owner, promptName, commitHash] = parsePromptIdentifier(promptIdentifier); + if (!(await this._currentTenantIsOwner(owner))) { + if (commitHash !== "latest") { + return `${this.getHostUrl()}/hub/${owner}/${promptName}/${commitHash.substring(0, 8)}`; + } + else { + return `${this.getHostUrl()}/hub/${owner}/${promptName}`; } - result = response[0]; } else { - result = response; + const settings = await this._getSettings(); + if (commitHash !== "latest") { + return `${this.getHostUrl()}/prompts/${promptName}/${commitHash.substring(0, 8)}?organizationId=${settings.id}`; + } + else { + return `${this.getHostUrl()}/prompts/${promptName}?organizationId=${settings.id}`; + } } - return result; } - async getProjectUrl({ projectId, projectName, }) { - if (projectId === undefined && projectName === undefined) { - throw new Error("Must provide either projectName or projectId"); - } - const project = await this.readProject({ projectId, projectName }); - const tenantId = await this._getTenantId(); - return `${this.getHostUrl()}/o/${tenantId}/projects/p/${project.id}`; + async promptExists(promptIdentifier) { + const prompt = await this.getPrompt(promptIdentifier); + return !!prompt; } - async getDatasetUrl({ datasetId, datasetName, }) { - if (datasetId === undefined && datasetName === undefined) { - throw new Error("Must provide either datasetName or datasetId"); - } - const dataset = await this.readDataset({ datasetId, datasetName }); - const tenantId = await this._getTenantId(); - return `${this.getHostUrl()}/o/${tenantId}/datasets/${dataset.id}`; + async likePrompt(promptIdentifier) { + return this._likeOrUnlikePrompt(promptIdentifier, true); } - async _getTenantId() { - if (this._tenantId !== null) { - return this._tenantId; - } - const queryParams = new URLSearchParams({ limit: "1" }); - for await (const projects of this._getPaginated("/sessions", queryParams)) { - this._tenantId = projects[0].tenant_id; - return projects[0].tenant_id; + async unlikePrompt(promptIdentifier) { + return this._likeOrUnlikePrompt(promptIdentifier, false); + } + async *listCommits(promptOwnerAndName) { + for await (const commits of this._getPaginated(`/commits/${promptOwnerAndName}/`, new URLSearchParams(), (res) => res.commits)) { + yield* commits; } - throw new Error("No projects found to resolve tenant."); } - async *listProjects({ projectIds, name, nameContains, referenceDatasetId, referenceDatasetName, referenceFree, metadata, } = {}) { + async *listPrompts(options) { const params = new URLSearchParams(); - if (projectIds !== undefined) { - for (const projectId of projectIds) { - params.append("id", projectId); - } - } - if (name !== undefined) { - params.append("name", name); - } - if (nameContains !== undefined) { - params.append("name_contains", nameContains); - } - if (referenceDatasetId !== undefined) { - params.append("reference_dataset", referenceDatasetId); - } - else if (referenceDatasetName !== undefined) { - const dataset = await this.readDataset({ - datasetName: referenceDatasetName, - }); - params.append("reference_dataset", dataset.id); - } - if (referenceFree !== undefined) { - params.append("reference_free", referenceFree.toString()); + params.append("sort_field", options?.sortField ?? "updated_at"); + params.append("sort_direction", "desc"); + params.append("is_archived", (!!options?.isArchived).toString()); + if (options?.isPublic !== undefined) { + params.append("is_public", options.isPublic.toString()); } - if (metadata !== undefined) { - params.append("metadata", JSON.stringify(metadata)); + if (options?.query) { + params.append("query", options.query); } - for await (const projects of this._getPaginated("/sessions", params)) { - yield* projects; + for await (const prompts of this._getPaginated("/repos", params, (res) => res.repos)) { + yield* prompts; } } - async deleteProject({ projectId, projectName, }) { - let projectId_; - if (projectId === undefined && projectName === undefined) { - throw new Error("Must provide projectName or projectId"); - } - else if (projectId !== undefined && projectName !== undefined) { - throw new Error("Must provide either projectName or projectId, not both"); - } - else if (projectId === undefined) { - projectId_ = (await this.readProject({ projectName })).id; - } - else { - projectId_ = projectId; - } - assertUuid(projectId_); - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/sessions/${projectId_}`, { - method: "DELETE", + async getPrompt(promptIdentifier) { + const [owner, promptName, _] = parsePromptIdentifier(promptIdentifier); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/repos/${owner}/${promptName}`, { + method: "GET", headers: this.headers, signal: AbortSignal.timeout(this.timeout_ms), ...this.fetchOptions, }); - await raiseForStatus(response, `delete session ${projectId_} (${projectName})`, true); - } - async uploadCsv({ csvFile, fileName, inputKeys, outputKeys, description, dataType, name, }) { - const url = `${this.apiUrl}/datasets/upload`; - const formData = new FormData(); - formData.append("file", csvFile, fileName); - inputKeys.forEach((key) => { - formData.append("input_keys", key); - }); - outputKeys.forEach((key) => { - formData.append("output_keys", key); - }); - if (description) { - formData.append("description", description); + if (response.status === 404) { + return null; } - if (dataType) { - formData.append("data_type", dataType); + await raiseForStatus(response, "get prompt"); + const result = await response.json(); + if (result.repo) { + return result.repo; } - if (name) { - formData.append("name", name); + else { + return null; } - const response = await this.caller.call(_getFetchImplementation(this.debug), url, { + } + async createPrompt(promptIdentifier, options) { + const settings = await this._getSettings(); + if (options?.isPublic && !settings.tenant_handle) { + throw new Error(`Cannot create a public prompt without first\n + creating a LangChain Hub handle. + You can add a handle by creating a public prompt at:\n + https://smith.langchain.com/prompts`); + } + const [owner, promptName, _] = parsePromptIdentifier(promptIdentifier); + if (!(await this._currentTenantIsOwner(owner))) { + throw await this._ownerConflictError("create a prompt", owner); + } + const data = { + repo_handle: promptName, + ...(options?.description && { description: options.description }), + ...(options?.readme && { readme: options.readme }), + ...(options?.tags && { tags: options.tags }), + is_public: !!options?.isPublic, + }; + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/repos/`, { method: "POST", - headers: this.headers, - body: formData, + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(data), signal: AbortSignal.timeout(this.timeout_ms), ...this.fetchOptions, }); - await raiseForStatus(response, "upload CSV"); - const result = await response.json(); - return result; + await raiseForStatus(response, "create prompt"); + const { repo } = await response.json(); + return repo; } - async createDataset(name, { description, dataType, inputsSchema, outputsSchema, metadata, } = {}) { - const body = { - name, - description, - extra: metadata ? { metadata } : undefined, - }; - if (dataType) { - body.data_type = dataType; - } - if (inputsSchema) { - body.inputs_schema_definition = inputsSchema; - } - if (outputsSchema) { - body.outputs_schema_definition = outputsSchema; + async createCommit(promptIdentifier, object, options) { + if (!(await this.promptExists(promptIdentifier))) { + throw new Error("Prompt does not exist, you must create it first."); } - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets`, { + const [owner, promptName, _] = parsePromptIdentifier(promptIdentifier); + const resolvedParentCommitHash = options?.parentCommitHash === "latest" || !options?.parentCommitHash + ? await this._getLatestCommitHash(`${owner}/${promptName}`) + : options?.parentCommitHash; + const payload = { + manifest: JSON.parse(JSON.stringify(object)), + parent_commit: resolvedParentCommitHash, + }; + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/commits/${owner}/${promptName}`, { method: "POST", headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(body), + body: JSON.stringify(payload), signal: AbortSignal.timeout(this.timeout_ms), ...this.fetchOptions, }); - await raiseForStatus(response, "create dataset"); + await raiseForStatus(response, "create commit"); const result = await response.json(); - return result; + return this._getPromptUrl(`${owner}/${promptName}${result.commit_hash ? `:${result.commit_hash}` : ""}`); } - async readDataset({ datasetId, datasetName, }) { - let path = "/datasets"; - // limit to 1 result - const params = new URLSearchParams({ limit: "1" }); - if (datasetId !== undefined && datasetName !== undefined) { - throw new Error("Must provide either datasetName or datasetId, not both"); - } - else if (datasetId !== undefined) { - assertUuid(datasetId); - path += `/${datasetId}`; - } - else if (datasetName !== undefined) { - params.append("name", datasetName); - } - else { - throw new Error("Must provide datasetName or datasetId"); + /** + * Update examples with attachments using multipart form data. + * @param updates List of ExampleUpdateWithAttachments objects to upsert + * @returns Promise with the update response + */ + async updateExamplesMultipart(datasetId, updates = []) { + return this._updateExamplesMultipart(datasetId, updates); + } + async _updateExamplesMultipart(datasetId, updates = []) { + if (!(await this._getMultiPartSupport())) { + throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version."); } - const response = await this._get(path, params); - let result; - if (Array.isArray(response)) { - if (response.length === 0) { - throw new Error(`Dataset[id=${datasetId}, name=${datasetName}] not found`); + const formData = new FormData(); + for (const example of updates) { + const exampleId = example.id; + // Prepare the main example body + const exampleBody = { + ...(example.metadata && { metadata: example.metadata }), + ...(example.split && { split: example.split }), + }; + // Add main example data + const stringifiedExample = serialize(exampleBody, `Serializing body for example with id: ${exampleId}`); + const exampleBlob = new Blob([stringifiedExample], { + type: "application/json", + }); + formData.append(exampleId, exampleBlob); + // Add inputs if present + if (example.inputs) { + const stringifiedInputs = serialize(example.inputs, `Serializing inputs for example with id: ${exampleId}`); + const inputsBlob = new Blob([stringifiedInputs], { + type: "application/json", + }); + formData.append(`${exampleId}.inputs`, inputsBlob); + } + // Add outputs if present + if (example.outputs) { + const stringifiedOutputs = serialize(example.outputs, `Serializing outputs whle updating example with id: ${exampleId}`); + const outputsBlob = new Blob([stringifiedOutputs], { + type: "application/json", + }); + formData.append(`${exampleId}.outputs`, outputsBlob); + } + // Add attachments if present + if (example.attachments) { + for (const [name, attachment] of Object.entries(example.attachments)) { + let mimeType; + let data; + if (Array.isArray(attachment)) { + [mimeType, data] = attachment; + } + else { + mimeType = attachment.mimeType; + data = attachment.data; + } + const attachmentBlob = new Blob([data], { + type: `${mimeType}; length=${data.byteLength}`, + }); + formData.append(`${exampleId}.attachment.${name}`, attachmentBlob); + } + } + if (example.attachments_operations) { + const stringifiedAttachmentsOperations = serialize(example.attachments_operations, `Serializing attachments while updating example with id: ${exampleId}`); + const attachmentsOperationsBlob = new Blob([stringifiedAttachmentsOperations], { + type: "application/json", + }); + formData.append(`${exampleId}.attachments_operations`, attachmentsOperationsBlob); } - result = response[0]; - } - else { - result = response; } + const datasetIdToUse = datasetId ?? updates[0]?.dataset_id; + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${datasetIdToUse}/examples`)}`, { + method: "PATCH", + headers: this.headers, + body: formData, + }); + const result = await response.json(); return result; } - async hasDataset({ datasetId, datasetName, }) { - try { - await this.readDataset({ datasetId, datasetName }); - return true; - } - catch (e) { - if ( - // eslint-disable-next-line no-instanceof/no-instanceof - e instanceof Error && - e.message.toLocaleLowerCase().includes("not found")) { - return false; - } - throw e; - } + /** + * Upload examples with attachments using multipart form data. + * @param uploads List of ExampleUploadWithAttachments objects to upload + * @returns Promise with the upload response + * @deprecated This method is deprecated and will be removed in future LangSmith versions, please use `createExamples` instead + */ + async uploadExamplesMultipart(datasetId, uploads = []) { + return this._uploadExamplesMultipart(datasetId, uploads); } - async diffDatasetVersions({ datasetId, datasetName, fromVersion, toVersion, }) { - let datasetId_ = datasetId; - if (datasetId_ === undefined && datasetName === undefined) { - throw new Error("Must provide either datasetName or datasetId"); - } - else if (datasetId_ !== undefined && datasetName !== undefined) { - throw new Error("Must provide either datasetName or datasetId, not both"); + async _uploadExamplesMultipart(datasetId, uploads = []) { + if (!(await this._getMultiPartSupport())) { + throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version."); } - else if (datasetId_ === undefined) { - const dataset = await this.readDataset({ datasetName }); - datasetId_ = dataset.id; + const formData = new FormData(); + for (const example of uploads) { + const exampleId = (example.id ?? v4()).toString(); + // Prepare the main example body + const exampleBody = { + created_at: example.created_at, + ...(example.metadata && { metadata: example.metadata }), + ...(example.split && { split: example.split }), + ...(example.source_run_id && { source_run_id: example.source_run_id }), + ...(example.use_source_run_io && { + use_source_run_io: example.use_source_run_io, + }), + ...(example.use_source_run_attachments && { + use_source_run_attachments: example.use_source_run_attachments, + }), + }; + // Add main example data + const stringifiedExample = serialize(exampleBody, `Serializing body for uploaded example with id: ${exampleId}`); + const exampleBlob = new Blob([stringifiedExample], { + type: "application/json", + }); + formData.append(exampleId, exampleBlob); + // Add inputs if present + if (example.inputs) { + const stringifiedInputs = serialize(example.inputs, `Serializing inputs for uploaded example with id: ${exampleId}`); + const inputsBlob = new Blob([stringifiedInputs], { + type: "application/json", + }); + formData.append(`${exampleId}.inputs`, inputsBlob); + } + // Add outputs if present + if (example.outputs) { + const stringifiedOutputs = serialize(example.outputs, `Serializing outputs for uploaded example with id: ${exampleId}`); + const outputsBlob = new Blob([stringifiedOutputs], { + type: "application/json", + }); + formData.append(`${exampleId}.outputs`, outputsBlob); + } + // Add attachments if present + if (example.attachments) { + for (const [name, attachment] of Object.entries(example.attachments)) { + let mimeType; + let data; + if (Array.isArray(attachment)) { + [mimeType, data] = attachment; + } + else { + mimeType = attachment.mimeType; + data = attachment.data; + } + const attachmentBlob = new Blob([data], { + type: `${mimeType}; length=${data.byteLength}`, + }); + formData.append(`${exampleId}.attachment.${name}`, attachmentBlob); + } + } } - const urlParams = new URLSearchParams({ - from_version: typeof fromVersion === "string" - ? fromVersion - : fromVersion.toISOString(), - to_version: typeof toVersion === "string" ? toVersion : toVersion.toISOString(), + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${datasetId}/examples`)}`, { + method: "POST", + headers: this.headers, + body: formData, }); - const response = await this._get(`/datasets/${datasetId_}/versions/diff`, urlParams); - return response; - } - async readDatasetOpenaiFinetuning({ datasetId, datasetName, }) { - const path = "/datasets"; - if (datasetId !== undefined) { - // do nothing - } - else if (datasetName !== undefined) { - datasetId = (await this.readDataset({ datasetName })).id; - } - else { - throw new Error("Must provide either datasetName or datasetId"); - } - const response = await this._getResponse(`${path}/${datasetId}/openai_ft`); - const datasetText = await response.text(); - const dataset = datasetText - .trim() - .split("\n") - .map((line) => JSON.parse(line)); - return dataset; + await raiseForStatus(response, "upload examples"); + const result = await response.json(); + return result; } - async *listDatasets({ limit = 100, offset = 0, datasetIds, datasetName, datasetNameContains, metadata, } = {}) { - const path = "/datasets"; - const params = new URLSearchParams({ - limit: limit.toString(), - offset: offset.toString(), - }); - if (datasetIds !== undefined) { - for (const id_ of datasetIds) { - params.append("id", id_); - } - } - if (datasetName !== undefined) { - params.append("name", datasetName); - } - if (datasetNameContains !== undefined) { - params.append("name_contains", datasetNameContains); - } - if (metadata !== undefined) { - params.append("metadata", JSON.stringify(metadata)); + async updatePrompt(promptIdentifier, options) { + if (!(await this.promptExists(promptIdentifier))) { + throw new Error("Prompt does not exist, you must create it first."); } - for await (const datasets of this._getPaginated(path, params)) { - yield* datasets; + const [owner, promptName] = parsePromptIdentifier(promptIdentifier); + if (!(await this._currentTenantIsOwner(owner))) { + throw await this._ownerConflictError("update a prompt", owner); } - } - /** - * Update a dataset - * @param props The dataset details to update - * @returns The updated dataset - */ - async updateDataset(props) { - const { datasetId, datasetName, ...update } = props; - if (!datasetId && !datasetName) { - throw new Error("Must provide either datasetName or datasetId"); + const payload = {}; + if (options?.description !== undefined) + payload.description = options.description; + if (options?.readme !== undefined) + payload.readme = options.readme; + if (options?.tags !== undefined) + payload.tags = options.tags; + if (options?.isPublic !== undefined) + payload.is_public = options.isPublic; + if (options?.isArchived !== undefined) + payload.is_archived = options.isArchived; + // Check if payload is empty + if (Object.keys(payload).length === 0) { + throw new Error("No valid update options provided"); } - const _datasetId = datasetId ?? (await this.readDataset({ datasetName })).id; - assertUuid(_datasetId); - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/${_datasetId}`, { + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/repos/${owner}/${promptName}`, { method: "PATCH", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(update), + body: JSON.stringify(payload), + headers: { + ...this.headers, + "Content-Type": "application/json", + }, signal: AbortSignal.timeout(this.timeout_ms), ...this.fetchOptions, }); - await raiseForStatus(response, "update dataset"); - return (await response.json()); + await raiseForStatus(response, "update prompt"); + return response.json(); } - /** - * Updates a tag on a dataset. - * - * If the tag is already assigned to a different version of this dataset, - * the tag will be moved to the new version. The as_of parameter is used to - * determine which version of the dataset to apply the new tags to. - * - * It must be an exact version of the dataset to succeed. You can - * use the "readDatasetVersion" method to find the exact version - * to apply the tags to. - * @param params.datasetId The ID of the dataset to update. Must be provided if "datasetName" is not provided. - * @param params.datasetName The name of the dataset to update. Must be provided if "datasetId" is not provided. - * @param params.asOf The timestamp of the dataset to apply the new tags to. - * @param params.tag The new tag to apply to the dataset. - */ - async updateDatasetTag(props) { - const { datasetId, datasetName, asOf, tag } = props; - if (!datasetId && !datasetName) { - throw new Error("Must provide either datasetName or datasetId"); + async deletePrompt(promptIdentifier) { + if (!(await this.promptExists(promptIdentifier))) { + throw new Error("Prompt does not exist, you must create it first."); } - const _datasetId = datasetId ?? (await this.readDataset({ datasetName })).id; - assertUuid(_datasetId); - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/${_datasetId}/tags`, { - method: "PUT", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify({ - as_of: typeof asOf === "string" ? asOf : asOf.toISOString(), - tag, - }), + const [owner, promptName, _] = parsePromptIdentifier(promptIdentifier); + if (!(await this._currentTenantIsOwner(owner))) { + throw await this._ownerConflictError("delete a prompt", owner); + } + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/repos/${owner}/${promptName}`, { + method: "DELETE", + headers: this.headers, signal: AbortSignal.timeout(this.timeout_ms), ...this.fetchOptions, }); - await raiseForStatus(response, "update dataset tags"); + return await response.json(); } - async deleteDataset({ datasetId, datasetName, }) { - let path = "/datasets"; - let datasetId_ = datasetId; - if (datasetId !== undefined && datasetName !== undefined) { - throw new Error("Must provide either datasetName or datasetId, not both"); - } - else if (datasetName !== undefined) { - const dataset = await this.readDataset({ datasetName }); - datasetId_ = dataset.id; - } - if (datasetId_ !== undefined) { - assertUuid(datasetId_); - path += `/${datasetId_}`; - } - else { - throw new Error("Must provide datasetName or datasetId"); - } - const response = await this.caller.call(_getFetchImplementation(this.debug), this.apiUrl + path, { - method: "DELETE", + async pullPromptCommit(promptIdentifier, options) { + const [owner, promptName, commitHash] = parsePromptIdentifier(promptIdentifier); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/commits/${owner}/${promptName}/${commitHash}${options?.includeModel ? "?include_model=true" : ""}`, { + method: "GET", headers: this.headers, signal: AbortSignal.timeout(this.timeout_ms), ...this.fetchOptions, }); - await raiseForStatus(response, `delete ${path}`); - await response.json(); + await raiseForStatus(response, "pull prompt commit"); + const result = await response.json(); + return { + owner, + repo: promptName, + commit_hash: result.commit_hash, + manifest: result.manifest, + examples: result.examples, + }; } - async indexDataset({ datasetId, datasetName, tag, }) { - let datasetId_ = datasetId; - if (!datasetId_ && !datasetName) { - throw new Error("Must provide either datasetName or datasetId"); + /** + * This method should not be used directly, use `import { pull } from "langchain/hub"` instead. + * Using this method directly returns the JSON string of the prompt rather than a LangChain object. + * @private + */ + async _pullPrompt(promptIdentifier, options) { + const promptObject = await this.pullPromptCommit(promptIdentifier, { + includeModel: options?.includeModel, + }); + const prompt = JSON.stringify(promptObject.manifest); + return prompt; + } + async pushPrompt(promptIdentifier, options) { + // Create or update prompt metadata + if (await this.promptExists(promptIdentifier)) { + if (options && Object.keys(options).some((key) => key !== "object")) { + await this.updatePrompt(promptIdentifier, { + description: options?.description, + readme: options?.readme, + tags: options?.tags, + isPublic: options?.isPublic, + }); + } } - else if (datasetId_ && datasetName) { - throw new Error("Must provide either datasetName or datasetId, not both"); + else { + await this.createPrompt(promptIdentifier, { + description: options?.description, + readme: options?.readme, + tags: options?.tags, + isPublic: options?.isPublic, + }); } - else if (!datasetId_) { - const dataset = await this.readDataset({ datasetName }); - datasetId_ = dataset.id; + if (!options?.object) { + return await this._getPromptUrl(promptIdentifier); } - assertUuid(datasetId_); - const data = { - tag: tag, - }; - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/${datasetId_}/index`, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(data), - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, + // Create a commit with the new manifest + const url = await this.createCommit(promptIdentifier, options?.object, { + parentCommitHash: options?.parentCommitHash, }); - await raiseForStatus(response, "index dataset"); - await response.json(); + return url; } /** - * Lets you run a similarity search query on a dataset. - * - * Requires the dataset to be indexed. Please see the `indexDataset` method to set up indexing. - * - * @param inputs The input on which to run the similarity search. Must have the - * same schema as the dataset. - * - * @param datasetId The dataset to search for similar examples. - * - * @param limit The maximum number of examples to return. Will return the top `limit` most - * similar examples in order of most similar to least similar. If no similar - * examples are found, random examples will be returned. - * - * @param filter A filter string to apply to the search. Only examples will be returned that - * match the filter string. Some examples of filters - * - * - eq(metadata.mykey, "value") - * - and(neq(metadata.my.nested.key, "value"), neq(metadata.mykey, "value")) - * - or(eq(metadata.mykey, "value"), eq(metadata.mykey, "othervalue")) - * - * @returns A list of similar examples. - * - * - * @example - * dataset_id = "123e4567-e89b-12d3-a456-426614174000" - * inputs = {"text": "How many people live in Berlin?"} - * limit = 5 - * examples = await client.similarExamples(inputs, dataset_id, limit) + * Clone a public dataset to your own langsmith tenant. + * This operation is idempotent. If you already have a dataset with the given name, + * this function will do nothing. + + * @param {string} tokenOrUrl The token of the public dataset to clone. + * @param {Object} [options] Additional options for cloning the dataset. + * @param {string} [options.sourceApiUrl] The URL of the langsmith server where the data is hosted. Defaults to the API URL of your current client. + * @param {string} [options.datasetName] The name of the dataset to create in your tenant. Defaults to the name of the public dataset. + * @returns {Promise} */ - async similarExamples(inputs, datasetId, limit, { filter, } = {}) { - const data = { - limit: limit, - inputs: inputs, - }; - if (filter !== undefined) { - data["filter"] = filter; - } - assertUuid(datasetId); - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/${datasetId}/search`, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(data), - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, + async clonePublicDataset(tokenOrUrl, options = {}) { + const { sourceApiUrl = this.apiUrl, datasetName } = options; + const [parsedApiUrl, tokenUuid] = this.parseTokenOrUrl(tokenOrUrl, sourceApiUrl); + const sourceClient = new Client({ + apiUrl: parsedApiUrl, + // Placeholder API key not needed anymore in most cases, but + // some private deployments may have API key-based rate limiting + // that would cause this to fail if we provide no value. + apiKey: "placeholder", }); - await raiseForStatus(response, "fetch similar examples"); - const result = await response.json(); - return result["examples"]; - } - async createExample(inputsOrUpdate, outputs, options) { - if (isExampleCreate(inputsOrUpdate)) { - if (outputs !== undefined || options !== undefined) { - throw new Error("Cannot provide outputs or options when using ExampleCreate object"); + const ds = await sourceClient.readSharedDataset(tokenUuid); + const finalDatasetName = datasetName || ds.name; + try { + if (await this.hasDataset({ datasetId: finalDatasetName })) { + console.log(`Dataset ${finalDatasetName} already exists in your tenant. Skipping.`); + return; } } - let datasetId_ = outputs ? options?.datasetId : inputsOrUpdate.dataset_id; - const datasetName_ = outputs - ? options?.datasetName - : inputsOrUpdate.dataset_name; - if (datasetId_ === undefined && datasetName_ === undefined) { - throw new Error("Must provide either datasetName or datasetId"); + catch (_) { + // `.hasDataset` will throw an error if the dataset does not exist. + // no-op in that case } - else if (datasetId_ !== undefined && datasetName_ !== undefined) { - throw new Error("Must provide either datasetName or datasetId, not both"); + // Fetch examples first, then create the dataset + const examples = await sourceClient.listSharedExamples(tokenUuid); + const dataset = await this.createDataset(finalDatasetName, { + description: ds.description, + dataType: ds.data_type || "kv", + inputsSchema: ds.inputs_schema_definition ?? undefined, + outputsSchema: ds.outputs_schema_definition ?? undefined, + }); + try { + await this.createExamples({ + inputs: examples.map((e) => e.inputs), + outputs: examples.flatMap((e) => (e.outputs ? [e.outputs] : [])), + datasetId: dataset.id, + }); } - else if (datasetId_ === undefined) { - const dataset = await this.readDataset({ datasetName: datasetName_ }); - datasetId_ = dataset.id; + catch (e) { + console.error(`An error occurred while creating dataset ${finalDatasetName}. ` + + "You should delete it manually."); + throw e; } - const createdAt_ = (outputs ? options?.createdAt : inputsOrUpdate.created_at) || new Date(); - let data; - if (!isExampleCreate(inputsOrUpdate)) { - data = { - inputs: inputsOrUpdate, - outputs, - created_at: createdAt_?.toISOString(), - id: options?.exampleId, - metadata: options?.metadata, - split: options?.split, - source_run_id: options?.sourceRunId, - use_source_run_io: options?.useSourceRunIO, - use_source_run_attachments: options?.useSourceRunAttachments, - attachments: options?.attachments, - }; + } + parseTokenOrUrl(urlOrToken, apiUrl, numParts = 2, kind = "dataset") { + // Try parsing as UUID + try { + assertUuid(urlOrToken); // Will throw if it's not a UUID. + return [apiUrl, urlOrToken]; } - else { - data = inputsOrUpdate; + catch (_) { + // no-op if it's not a uuid } - const response = await this._uploadExamplesMultipart(datasetId_, [data]); - const example = await this.readExample(response.example_ids?.[0] ?? v4()); - return example; - } - async createExamples(propsOrUploads) { - if (Array.isArray(propsOrUploads)) { - if (propsOrUploads.length === 0) { - return []; - } - const uploads = propsOrUploads; - let datasetId_ = uploads[0].dataset_id; - const datasetName_ = uploads[0].dataset_name; - if (datasetId_ === undefined && datasetName_ === undefined) { - throw new Error("Must provide either datasetName or datasetId"); - } - else if (datasetId_ !== undefined && datasetName_ !== undefined) { - throw new Error("Must provide either datasetName or datasetId, not both"); + // Parse as URL + try { + const parsedUrl = new URL(urlOrToken); + const pathParts = parsedUrl.pathname + .split("/") + .filter((part) => part !== ""); + if (pathParts.length >= numParts) { + const tokenUuid = pathParts[pathParts.length - numParts]; + return [apiUrl, tokenUuid]; } - else if (datasetId_ === undefined) { - const dataset = await this.readDataset({ datasetName: datasetName_ }); - datasetId_ = dataset.id; + else { + throw new Error(`Invalid public ${kind} URL: ${urlOrToken}`); } - const response = await this._uploadExamplesMultipart(datasetId_, uploads); - const examples = await Promise.all(response.example_ids.map((id) => this.readExample(id))); - return examples; } - const { inputs, outputs, metadata, splits, sourceRunIds, useSourceRunIOs, useSourceRunAttachments, attachments, exampleIds, datasetId, datasetName, } = propsOrUploads; - if (inputs === undefined) { - throw new Error("Must provide inputs when using legacy parameters"); - } - let datasetId_ = datasetId; - const datasetName_ = datasetName; - if (datasetId_ === undefined && datasetName_ === undefined) { - throw new Error("Must provide either datasetName or datasetId"); + catch (error) { + throw new Error(`Invalid public ${kind} URL or token: ${urlOrToken}`); } - else if (datasetId_ !== undefined && datasetName_ !== undefined) { - throw new Error("Must provide either datasetName or datasetId, not both"); + } + /** + * Awaits all pending trace batches. Useful for environments where + * you need to be sure that all tracing requests finish before execution ends, + * such as serverless environments. + * + * @example + * ``` + * import { Client } from "langsmith"; + * + * const client = new Client(); + * + * try { + * // Tracing happens here + * ... + * } finally { + * await client.awaitPendingTraceBatches(); + * } + * ``` + * + * @returns A promise that resolves once all currently pending traces have sent. + */ + async awaitPendingTraceBatches() { + if (this.manualFlushMode) { + console.warn("[WARNING]: When tracing in manual flush mode, you must call `await client.flush()` manually to submit trace batches."); + return Promise.resolve(); } - else if (datasetId_ === undefined) { - const dataset = await this.readDataset({ datasetName: datasetName_ }); - datasetId_ = dataset.id; + await Promise.all([ + ...this.autoBatchQueue.items.map(({ itemPromise }) => itemPromise), + this.batchIngestCaller.queue.onIdle(), + ]); + if (this.langSmithToOTELTranslator !== undefined) { + await getDefaultOTLPTracerComponents()?.DEFAULT_LANGSMITH_SPAN_PROCESSOR?.forceFlush(); } - const formattedExamples = inputs.map((input, idx) => { - return { - dataset_id: datasetId_, - inputs: input, - outputs: outputs?.[idx], - metadata: metadata?.[idx], - split: splits?.[idx], - id: exampleIds?.[idx], - attachments: attachments?.[idx], - source_run_id: sourceRunIds?.[idx], - use_source_run_io: useSourceRunIOs?.[idx], - use_source_run_attachments: useSourceRunAttachments?.[idx], - }; + } +} +function isExampleCreate(input) { + return "dataset_id" in input || "dataset_name" in input; +} + +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/env.js + +const isTracingEnabled = (tracingEnabled) => { + if (tracingEnabled !== undefined) { + return tracingEnabled; + } + const envVars = ["TRACING_V2", "TRACING"]; + return !!envVars.find((envVar) => getLangSmithEnvironmentVariable(envVar) === "true"); +}; + +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/singletons/constants.js +const _LC_CONTEXT_VARIABLES_KEY = Symbol.for("lc:context_variables"); + +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/run_trees.js + + + + + + + + + +function stripNonAlphanumeric(input) { + return input.replace(/[-:.]/g, ""); +} +function convertToDottedOrderFormat(epoch, runId, executionOrder = 1) { + // Date only has millisecond precision, so we use the microseconds to break + // possible ties, avoiding incorrect run order + const paddedOrder = executionOrder.toFixed(0).slice(0, 3).padStart(3, "0"); + const microsecondPrecisionDatestring = `${new Date(epoch) + .toISOString() + .slice(0, -1)}${paddedOrder}Z`; + return { + dottedOrder: stripNonAlphanumeric(microsecondPrecisionDatestring) + runId, + microsecondPrecisionDatestring, + }; +} +/** + * Baggage header information + */ +class Baggage { + constructor(metadata, tags, project_name, replicas) { + Object.defineProperty(this, "metadata", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 }); - const response = await this._uploadExamplesMultipart(datasetId_, formattedExamples); - const examples = await Promise.all(response.example_ids.map((id) => this.readExample(id))); - return examples; - } - async createLLMExample(input, generation, options) { - return this.createExample({ input }, { output: generation }, options); - } - async createChatExample(input, generations, options) { - const finalInput = input.map((message) => { - if (isLangChainMessage(message)) { - return convertLangChainMessageToExample(message); - } - return message; + Object.defineProperty(this, "tags", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 }); - const finalOutput = isLangChainMessage(generations) - ? convertLangChainMessageToExample(generations) - : generations; - return this.createExample({ input: finalInput }, { output: finalOutput }, options); + Object.defineProperty(this, "project_name", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "replicas", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.metadata = metadata; + this.tags = tags; + this.project_name = project_name; + this.replicas = replicas; } - async readExample(exampleId) { - assertUuid(exampleId); - const path = `/examples/${exampleId}`; - const rawExample = await this._get(path); - const { attachment_urls, ...rest } = rawExample; - const example = rest; - if (attachment_urls) { - example.attachments = Object.entries(attachment_urls).reduce((acc, [key, value]) => { - acc[key.slice("attachment.".length)] = { - presigned_url: value.presigned_url, - mime_type: value.mime_type, - }; - return acc; - }, {}); + static fromHeader(value) { + const items = value.split(","); + let metadata = {}; + let tags = []; + let project_name; + let replicas; + for (const item of items) { + const [key, uriValue] = item.split("="); + const value = decodeURIComponent(uriValue); + if (key === "langsmith-metadata") { + metadata = JSON.parse(value); + } + else if (key === "langsmith-tags") { + tags = value.split(","); + } + else if (key === "langsmith-project") { + project_name = value; + } + else if (key === "langsmith-replicas") { + replicas = JSON.parse(value); + } } - return example; + return new Baggage(metadata, tags, project_name, replicas); } - async *listExamples({ datasetId, datasetName, exampleIds, asOf, splits, inlineS3Urls, metadata, limit, offset, filter, includeAttachments, } = {}) { - let datasetId_; - if (datasetId !== undefined && datasetName !== undefined) { - throw new Error("Must provide either datasetName or datasetId, not both"); - } - else if (datasetId !== undefined) { - datasetId_ = datasetId; + toHeader() { + const items = []; + if (this.metadata && Object.keys(this.metadata).length > 0) { + items.push(`langsmith-metadata=${encodeURIComponent(JSON.stringify(this.metadata))}`); } - else if (datasetName !== undefined) { - const dataset = await this.readDataset({ datasetName }); - datasetId_ = dataset.id; + if (this.tags && this.tags.length > 0) { + items.push(`langsmith-tags=${encodeURIComponent(this.tags.join(","))}`); } - else { - throw new Error("Must provide a datasetName or datasetId"); + if (this.project_name) { + items.push(`langsmith-project=${encodeURIComponent(this.project_name)}`); } - const params = new URLSearchParams({ dataset: datasetId_ }); - const dataset_version = asOf - ? typeof asOf === "string" - ? asOf - : asOf?.toISOString() - : undefined; - if (dataset_version) { - params.append("as_of", dataset_version); + return items.join(","); + } +} +class run_trees_RunTree { + constructor(originalConfig) { + Object.defineProperty(this, "id", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "run_type", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "project_name", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "parent_run", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "parent_run_id", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "child_runs", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "start_time", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "end_time", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "extra", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "tags", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "error", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "serialized", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "inputs", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "outputs", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "reference_example_id", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "client", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "events", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "trace_id", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "dotted_order", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "tracingEnabled", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "execution_order", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "child_execution_order", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + /** + * Attachments associated with the run. + * Each entry is a tuple of [mime_type, bytes] + */ + Object.defineProperty(this, "attachments", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + /** + * Projects to replicate this run to with optional updates. + */ + Object.defineProperty(this, "replicas", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "_serialized_start_time", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + // If you pass in a run tree directly, return a shallow clone + if (run_trees_isRunTree(originalConfig)) { + Object.assign(this, { ...originalConfig }); + return; } - const inlineS3Urls_ = inlineS3Urls ?? true; - params.append("inline_s3_urls", inlineS3Urls_.toString()); - if (exampleIds !== undefined) { - for (const id_ of exampleIds) { - params.append("id", id_); + const defaultConfig = run_trees_RunTree.getDefaultConfig(); + const { metadata, ...config } = originalConfig; + const client = config.client ?? run_trees_RunTree.getSharedClient(); + const dedupedMetadata = { + ...metadata, + ...config?.extra?.metadata, + }; + config.extra = { ...config.extra, metadata: dedupedMetadata }; + Object.assign(this, { ...defaultConfig, ...config, client }); + if (!this.trace_id) { + if (this.parent_run) { + this.trace_id = this.parent_run.trace_id ?? this.id; } - } - if (splits !== undefined) { - for (const split of splits) { - params.append("splits", split); + else { + this.trace_id = this.id; } } - if (metadata !== undefined) { - const serializedMetadata = JSON.stringify(metadata); - params.append("metadata", serializedMetadata); - } - if (limit !== undefined) { - params.append("limit", limit.toString()); - } - if (offset !== undefined) { - params.append("offset", offset.toString()); - } - if (filter !== undefined) { - params.append("filter", filter); - } - if (includeAttachments === true) { - ["attachment_urls", "outputs", "metadata"].forEach((field) => params.append("select", field)); - } - let i = 0; - for await (const rawExamples of this._getPaginated("/examples", params)) { - for (const rawExample of rawExamples) { - const { attachment_urls, ...rest } = rawExample; - const example = rest; - if (attachment_urls) { - example.attachments = Object.entries(attachment_urls).reduce((acc, [key, value]) => { - acc[key.slice("attachment.".length)] = { - presigned_url: value.presigned_url, - mime_type: value.mime_type || undefined, - }; - return acc; - }, {}); - } - yield example; - i++; + this.replicas = _ensureWriteReplicas(this.replicas); + this.execution_order ??= 1; + this.child_execution_order ??= 1; + if (!this.dotted_order) { + const { dottedOrder, microsecondPrecisionDatestring } = convertToDottedOrderFormat(this.start_time, this.id, this.execution_order); + if (this.parent_run) { + this.dotted_order = this.parent_run.dotted_order + "." + dottedOrder; } - if (limit !== undefined && i >= limit) { - break; + else { + this.dotted_order = dottedOrder; } + this._serialized_start_time = microsecondPrecisionDatestring; } } - async deleteExample(exampleId) { - assertUuid(exampleId); - const path = `/examples/${exampleId}`; - const response = await this.caller.call(_getFetchImplementation(this.debug), this.apiUrl + path, { - method: "DELETE", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(response, `delete ${path}`); - await response.json(); + set metadata(metadata) { + this.extra = { + ...this.extra, + metadata: { + ...this.extra?.metadata, + ...metadata, + }, + }; } - async updateExample(exampleIdOrUpdate, update) { - let exampleId; - if (update) { - exampleId = exampleIdOrUpdate; - } - else { - exampleId = exampleIdOrUpdate.id; - } - assertUuid(exampleId); - let updateToUse; - if (update) { - updateToUse = { id: exampleId, ...update }; + get metadata() { + return this.extra?.metadata; + } + static getDefaultConfig() { + return { + id: v4(), + run_type: "chain", + project_name: getDefaultProjectName(), + child_runs: [], + api_url: getEnvironmentVariable("LANGCHAIN_ENDPOINT") ?? "http://localhost:1984", + api_key: getEnvironmentVariable("LANGCHAIN_API_KEY"), + caller_options: {}, + start_time: Date.now(), + serialized: {}, + inputs: {}, + extra: {}, + }; + } + static getSharedClient() { + if (!run_trees_RunTree.sharedClient) { + run_trees_RunTree.sharedClient = new Client(); } - else { - updateToUse = exampleIdOrUpdate; + return run_trees_RunTree.sharedClient; + } + createChild(config) { + const child_execution_order = this.child_execution_order + 1; + const child = new run_trees_RunTree({ + ...config, + parent_run: this, + project_name: this.project_name, + replicas: this.replicas, + client: this.client, + tracingEnabled: this.tracingEnabled, + execution_order: child_execution_order, + child_execution_order: child_execution_order, + }); + // Copy context vars over into the new run tree. + if (_LC_CONTEXT_VARIABLES_KEY in this) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + child[_LC_CONTEXT_VARIABLES_KEY] = + this[_LC_CONTEXT_VARIABLES_KEY]; } - let datasetId; - if (updateToUse.dataset_id !== undefined) { - datasetId = updateToUse.dataset_id; + const LC_CHILD = Symbol.for("lc:child_config"); + const presentConfig = config.extra?.[LC_CHILD] ?? + this.extra[LC_CHILD]; + // tracing for LangChain is defined by the _parentRunId and runMap of the tracer + if (isRunnableConfigLike(presentConfig)) { + const newConfig = { ...presentConfig }; + const callbacks = isCallbackManagerLike(newConfig.callbacks) + ? newConfig.callbacks.copy?.() + : undefined; + if (callbacks) { + // update the parent run id + Object.assign(callbacks, { _parentRunId: child.id }); + // only populate if we're in a newer LC.JS version + callbacks.handlers + ?.find(isLangChainTracerLike) + ?.updateFromRunTree?.(child); + newConfig.callbacks = callbacks; + } + child.extra[LC_CHILD] = newConfig; } - else { - const example = await this.readExample(exampleId); - datasetId = example.dataset_id; + // propagate child_execution_order upwards + const visited = new Set(); + let current = this; + while (current != null && !visited.has(current.id)) { + visited.add(current.id); + current.child_execution_order = Math.max(current.child_execution_order, child_execution_order); + current = current.parent_run; } - return this._updateExamplesMultipart(datasetId, [updateToUse]); + this.child_runs.push(child); + return child; } - async updateExamples(update) { - // We will naively get dataset id from first example and assume it works for all - let datasetId; - if (update[0].dataset_id === undefined) { - const example = await this.readExample(update[0].id); - datasetId = example.dataset_id; - } - else { - datasetId = update[0].dataset_id; + async end(outputs, error, endTime = Date.now(), metadata) { + this.outputs = this.outputs ?? outputs; + this.error = this.error ?? error; + this.end_time = this.end_time ?? endTime; + if (metadata && Object.keys(metadata).length > 0) { + this.extra = this.extra + ? { ...this.extra, metadata: { ...this.extra.metadata, ...metadata } } + : { metadata }; } - return this._updateExamplesMultipart(datasetId, update); } - /** - * Get dataset version by closest date or exact tag. - * - * Use this to resolve the nearest version to a given timestamp or for a given tag. - * - * @param options The options for getting the dataset version - * @param options.datasetId The ID of the dataset - * @param options.datasetName The name of the dataset - * @param options.asOf The timestamp of the dataset to retrieve - * @param options.tag The tag of the dataset to retrieve - * @returns The dataset version - */ - async readDatasetVersion({ datasetId, datasetName, asOf, tag, }) { - let resolvedDatasetId; - if (!datasetId) { - const dataset = await this.readDataset({ datasetName }); - resolvedDatasetId = dataset.id; - } - else { - resolvedDatasetId = datasetId; - } - assertUuid(resolvedDatasetId); - if ((asOf && tag) || (!asOf && !tag)) { - throw new Error("Exactly one of asOf and tag must be specified."); + _convertToCreate(run, runtimeEnv, excludeChildRuns = true) { + const runExtra = run.extra ?? {}; + // Avoid overwriting the runtime environment if it's already set + if (runExtra?.runtime?.library === undefined) { + if (!runExtra.runtime) { + runExtra.runtime = {}; + } + if (runtimeEnv) { + for (const [k, v] of Object.entries(runtimeEnv)) { + if (!runExtra.runtime[k]) { + runExtra.runtime[k] = v; + } + } + } } - const params = new URLSearchParams(); - if (asOf !== undefined) { - params.append("as_of", typeof asOf === "string" ? asOf : asOf.toISOString()); + let child_runs; + let parent_run_id; + if (!excludeChildRuns) { + child_runs = run.child_runs.map((child_run) => this._convertToCreate(child_run, runtimeEnv, excludeChildRuns)); + parent_run_id = undefined; } - if (tag !== undefined) { - params.append("tag", tag); + else { + parent_run_id = run.parent_run?.id ?? run.parent_run_id; + child_runs = []; } - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/${resolvedDatasetId}/version?${params.toString()}`, { - method: "GET", - headers: { ...this.headers }, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(response, "read dataset version"); - return await response.json(); + return { + id: run.id, + name: run.name, + start_time: run._serialized_start_time ?? run.start_time, + end_time: run.end_time, + run_type: run.run_type, + reference_example_id: run.reference_example_id, + extra: runExtra, + serialized: run.serialized, + error: run.error, + inputs: run.inputs, + outputs: run.outputs, + session_name: run.project_name, + child_runs: child_runs, + parent_run_id: parent_run_id, + trace_id: run.trace_id, + dotted_order: run.dotted_order, + tags: run.tags, + attachments: run.attachments, + events: run.events, + }; } - async listDatasetSplits({ datasetId, datasetName, asOf, }) { - let datasetId_; - if (datasetId === undefined && datasetName === undefined) { - throw new Error("Must provide dataset name or ID"); - } - else if (datasetId !== undefined && datasetName !== undefined) { - throw new Error("Must provide either datasetName or datasetId, not both"); - } - else if (datasetId === undefined) { - const dataset = await this.readDataset({ datasetName }); - datasetId_ = dataset.id; - } - else { - datasetId_ = datasetId; + _remapForProject(projectName, runtimeEnv, excludeChildRuns = true) { + const baseRun = this._convertToCreate(this, runtimeEnv, excludeChildRuns); + if (projectName === this.project_name) { + return baseRun; } - assertUuid(datasetId_); - const params = new URLSearchParams(); - const dataset_version = asOf - ? typeof asOf === "string" - ? asOf - : asOf?.toISOString() + // Create a deterministic UUID mapping for this project + const createRemappedId = (originalId) => { + return v5(`${originalId}:${projectName}`, v5.DNS); + }; + // Remap the current run's ID + const newId = createRemappedId(baseRun.id); + const newTraceId = baseRun.trace_id + ? createRemappedId(baseRun.trace_id) : undefined; - if (dataset_version) { - params.append("as_of", dataset_version); + const newParentRunId = baseRun.parent_run_id + ? createRemappedId(baseRun.parent_run_id) + : undefined; + let newDottedOrder; + if (baseRun.dotted_order) { + const segments = _parseDottedOrder(baseRun.dotted_order); + const rebuilt = []; + // Process all segments except the last one + for (let i = 0; i < segments.length - 1; i++) { + const [timestamp, segmentId] = segments[i]; + const remappedId = createRemappedId(segmentId); + rebuilt.push(timestamp.toISOString().replace(/[-:]/g, "").replace(".", "") + + remappedId); + } + // Process the last segment with the new run ID + const [lastTimestamp] = segments[segments.length - 1]; + rebuilt.push(lastTimestamp.toISOString().replace(/[-:]/g, "").replace(".", "") + + newId); + newDottedOrder = rebuilt.join("."); } - const response = await this._get(`/datasets/${datasetId_}/splits`, params); - return response; + else { + newDottedOrder = undefined; + } + const remappedRun = { + ...baseRun, + id: newId, + trace_id: newTraceId, + parent_run_id: newParentRunId, + dotted_order: newDottedOrder, + session_name: projectName, + }; + return remappedRun; } - async updateDatasetSplits({ datasetId, datasetName, splitName, exampleIds, remove = false, }) { - let datasetId_; - if (datasetId === undefined && datasetName === undefined) { - throw new Error("Must provide dataset name or ID"); + async postRun(excludeChildRuns = true) { + try { + const runtimeEnv = getRuntimeEnvironment(); + if (this.replicas && this.replicas.length > 0) { + for (const { projectName, apiKey, apiUrl } of this.replicas) { + const runCreate = this._remapForProject(projectName ?? this.project_name, runtimeEnv, true); + await this.client.createRun(runCreate, { + apiKey, + apiUrl, + }); + } + } + else { + const runCreate = this._convertToCreate(this, runtimeEnv, excludeChildRuns); + await this.client.createRun(runCreate); + } + if (!excludeChildRuns) { + warnOnce("Posting with excludeChildRuns=false is deprecated and will be removed in a future version."); + for (const childRun of this.child_runs) { + await childRun.postRun(false); + } + } } - else if (datasetId !== undefined && datasetName !== undefined) { - throw new Error("Must provide either datasetName or datasetId, not both"); + catch (error) { + console.error(`Error in postRun for run ${this.id}:`, error); } - else if (datasetId === undefined) { - const dataset = await this.readDataset({ datasetName }); - datasetId_ = dataset.id; + } + async patchRun() { + if (this.replicas && this.replicas.length > 0) { + for (const { projectName, apiKey, apiUrl, updates } of this.replicas) { + const runData = this._remapForProject(projectName ?? this.project_name); + await this.client.updateRun(runData.id, { + inputs: runData.inputs, + outputs: runData.outputs, + error: runData.error, + parent_run_id: runData.parent_run_id, + session_name: runData.session_name, + reference_example_id: runData.reference_example_id, + end_time: runData.end_time, + dotted_order: runData.dotted_order, + trace_id: runData.trace_id, + events: runData.events, + tags: runData.tags, + extra: runData.extra, + attachments: this.attachments, + ...updates, + }, { + apiKey, + apiUrl, + }); + } } else { - datasetId_ = datasetId; + try { + const runUpdate = { + end_time: this.end_time, + error: this.error, + inputs: this.inputs, + outputs: this.outputs, + parent_run_id: this.parent_run?.id ?? this.parent_run_id, + reference_example_id: this.reference_example_id, + extra: this.extra, + events: this.events, + dotted_order: this.dotted_order, + trace_id: this.trace_id, + tags: this.tags, + attachments: this.attachments, + session_name: this.project_name, + }; + await this.client.updateRun(this.id, runUpdate); + } + catch (error) { + console.error(`Error in patchRun for run ${this.id}`, error); + } } - assertUuid(datasetId_); - const data = { - split_name: splitName, - examples: exampleIds.map((id) => { - assertUuid(id); - return id; - }), - remove, - }; - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/${datasetId_}/splits`, { - method: "PUT", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(data), - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(response, "update dataset splits", true); + } + toJSON() { + return this._convertToCreate(this, undefined, false); } /** - * @deprecated This method is deprecated and will be removed in future LangSmith versions, use `evaluate` from `langsmith/evaluation` instead. + * Add an event to the run tree. + * @param event - A single event or string to add */ - async evaluateRun(run, evaluator, { sourceInfo, loadChildRuns, referenceExample, } = { loadChildRuns: false }) { - warnOnce("This method is deprecated and will be removed in future LangSmith versions, use `evaluate` from `langsmith/evaluation` instead."); - let run_; - if (typeof run === "string") { - run_ = await this.readRun(run, { loadChildRuns }); + addEvent(event) { + if (!this.events) { + this.events = []; } - else if (typeof run === "object" && "id" in run) { - run_ = run; + if (typeof event === "string") { + this.events.push({ + name: "event", + time: new Date().toISOString(), + message: event, + }); } else { - throw new Error(`Invalid run type: ${typeof run}`); - } - if (run_.reference_example_id !== null && - run_.reference_example_id !== undefined) { - referenceExample = await this.readExample(run_.reference_example_id); + this.events.push({ + ...event, + time: event.time ?? new Date().toISOString(), + }); } - const feedbackResult = await evaluator.evaluateRun(run_, referenceExample); - const [_, feedbacks] = await this._logEvaluationFeedback(feedbackResult, run_, sourceInfo); - return feedbacks[0]; } - async createFeedback(runId, key, { score, value, correction, comment, sourceInfo, feedbackSourceType = "api", sourceRunId, feedbackId, feedbackConfig, projectId, comparativeExperimentId, }) { - if (!runId && !projectId) { - throw new Error("One of runId or projectId must be provided"); + static fromRunnableConfig(parentConfig, props) { + // We only handle the callback manager case for now + const callbackManager = parentConfig?.callbacks; + let parentRun; + let projectName; + let client; + let tracingEnabled = isTracingEnabled(); + if (callbackManager) { + const parentRunId = callbackManager?.getParentRunId?.() ?? ""; + const langChainTracer = callbackManager?.handlers?.find((handler) => handler?.name == "langchain_tracer"); + parentRun = langChainTracer?.getRun?.(parentRunId); + projectName = langChainTracer?.projectName; + client = langChainTracer?.client; + tracingEnabled = tracingEnabled || !!langChainTracer; } - if (runId && projectId) { - throw new Error("Only one of runId or projectId can be provided"); + if (!parentRun) { + return new run_trees_RunTree({ + ...props, + client, + tracingEnabled, + project_name: projectName, + }); } - const feedback_source = { - type: feedbackSourceType ?? "api", - metadata: sourceInfo ?? {}, + const parentRunTree = new run_trees_RunTree({ + name: parentRun.name, + id: parentRun.id, + trace_id: parentRun.trace_id, + dotted_order: parentRun.dotted_order, + client, + tracingEnabled, + project_name: projectName, + tags: [ + ...new Set((parentRun?.tags ?? []).concat(parentConfig?.tags ?? [])), + ], + extra: { + metadata: { + ...parentRun?.extra?.metadata, + ...parentConfig?.metadata, + }, + }, + }); + return parentRunTree.createChild(props); + } + static fromDottedOrder(dottedOrder) { + return this.fromHeaders({ "langsmith-trace": dottedOrder }); + } + static fromHeaders(headers, inheritArgs) { + const rawHeaders = "get" in headers && typeof headers.get === "function" + ? { + "langsmith-trace": headers.get("langsmith-trace"), + baggage: headers.get("baggage"), + } + : headers; + const headerTrace = rawHeaders["langsmith-trace"]; + if (!headerTrace || typeof headerTrace !== "string") + return undefined; + const parentDottedOrder = headerTrace.trim(); + const parsedDottedOrder = parentDottedOrder.split(".").map((part) => { + const [strTime, uuid] = part.split("Z"); + return { strTime, time: Date.parse(strTime + "Z"), uuid }; + }); + const traceId = parsedDottedOrder[0].uuid; + const config = { + ...inheritArgs, + name: inheritArgs?.["name"] ?? "parent", + run_type: inheritArgs?.["run_type"] ?? "chain", + start_time: inheritArgs?.["start_time"] ?? Date.now(), + id: parsedDottedOrder.at(-1)?.uuid, + trace_id: traceId, + dotted_order: parentDottedOrder, }; - if (sourceRunId !== undefined && - feedback_source?.metadata !== undefined && - !feedback_source.metadata["__run"]) { - feedback_source.metadata["__run"] = { run_id: sourceRunId }; - } - if (feedback_source?.metadata !== undefined && - feedback_source.metadata["__run"]?.run_id !== undefined) { - assertUuid(feedback_source.metadata["__run"].run_id); + if (rawHeaders["baggage"] && typeof rawHeaders["baggage"] === "string") { + const baggage = Baggage.fromHeader(rawHeaders["baggage"]); + config.metadata = baggage.metadata; + config.tags = baggage.tags; + config.project_name = baggage.project_name; + config.replicas = baggage.replicas; } - const feedback = { - id: feedbackId ?? v4(), - run_id: runId, - key, - score: _formatFeedbackScore(score), - value, - correction, - comment, - feedback_source: feedback_source, - comparative_experiment_id: comparativeExperimentId, - feedbackConfig, - session_id: projectId, + return new run_trees_RunTree(config); + } + toHeaders(headers) { + const result = { + "langsmith-trace": this.dotted_order, + baggage: new Baggage(this.extra?.metadata, this.tags, this.project_name, this.replicas).toHeader(), }; - const url = `${this.apiUrl}/feedback`; - const response = await this.caller.call(_getFetchImplementation(this.debug), url, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(feedback), - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, + if (headers) { + for (const [key, value] of Object.entries(result)) { + headers.set(key, value); + } + } + return result; + } +} +Object.defineProperty(run_trees_RunTree, "sharedClient", { + enumerable: true, + configurable: true, + writable: true, + value: null +}); +function run_trees_isRunTree(x) { + return (x !== undefined && + typeof x.createChild === "function" && + typeof x.postRun === "function"); +} +function isLangChainTracerLike(x) { + return (typeof x === "object" && + x != null && + typeof x.name === "string" && + x.name === "langchain_tracer"); +} +function containsLangChainTracerLike(x) { + return (Array.isArray(x) && x.some((callback) => isLangChainTracerLike(callback))); +} +function isCallbackManagerLike(x) { + return (typeof x === "object" && + x != null && + Array.isArray(x.handlers)); +} +function isRunnableConfigLike(x) { + // Check that it's an object with a callbacks arg + // that has either a CallbackManagerLike object with a langchain tracer within it + // or an array with a LangChainTracerLike object within it + return (x !== undefined && + typeof x.callbacks === "object" && + // Callback manager with a langchain tracer + (containsLangChainTracerLike(x.callbacks?.handlers) || + // Or it's an array with a LangChainTracerLike object within it + containsLangChainTracerLike(x.callbacks))); +} +function _parseDottedOrder(dottedOrder) { + const parts = dottedOrder.split("."); + return parts.map((part) => { + const timestampStr = part.slice(0, -36); + const uuidStr = part.slice(-36); + // Parse timestamp: "%Y%m%dT%H%M%S%fZ" format + // Example: "20231215T143045123456Z" + const year = parseInt(timestampStr.slice(0, 4)); + const month = parseInt(timestampStr.slice(4, 6)) - 1; // JS months are 0-indexed + const day = parseInt(timestampStr.slice(6, 8)); + const hour = parseInt(timestampStr.slice(9, 11)); + const minute = parseInt(timestampStr.slice(11, 13)); + const second = parseInt(timestampStr.slice(13, 15)); + const microsecond = parseInt(timestampStr.slice(15, 21)); + const timestamp = new Date(year, month, day, hour, minute, second, microsecond / 1000); + return [timestamp, uuidStr]; + }); +} +function _getWriteReplicasFromEnv() { + const envVar = getEnvironmentVariable("LANGSMITH_RUNS_ENDPOINTS"); + if (!envVar) + return []; + try { + const parsed = JSON.parse(envVar); + if (Array.isArray(parsed)) { + const replicas = []; + for (const item of parsed) { + if (typeof item !== "object" || item === null) { + console.warn(`Invalid item type in LANGSMITH_RUNS_ENDPOINTS: ` + + `expected object, got ${typeof item}`); + continue; + } + if (typeof item.api_url !== "string") { + console.warn(`Invalid api_url type in LANGSMITH_RUNS_ENDPOINTS: ` + + `expected string, got ${typeof item.api_url}`); + continue; + } + if (typeof item.api_key !== "string") { + console.warn(`Invalid api_key type in LANGSMITH_RUNS_ENDPOINTS: ` + + `expected string, got ${typeof item.api_key}`); + continue; + } + replicas.push({ + apiUrl: item.api_url.replace(/\/$/, ""), + apiKey: item.api_key, + }); + } + return replicas; + } + else if (typeof parsed === "object" && parsed !== null) { + _checkEndpointEnvUnset(parsed); + const replicas = []; + for (const [url, key] of Object.entries(parsed)) { + const cleanUrl = url.replace(/\/$/, ""); + if (typeof key === "string") { + replicas.push({ + apiUrl: cleanUrl, + apiKey: key, + }); + } + else { + console.warn(`Invalid value type in LANGSMITH_RUNS_ENDPOINTS for URL ${url}: ` + + `expected string, got ${typeof key}`); + continue; + } + } + return replicas; + } + else { + console.warn("Invalid LANGSMITH_RUNS_ENDPOINTS – must be valid JSON array of " + + `objects with api_url and api_key properties, or object mapping url->apiKey, got ${typeof parsed}`); + return []; + } + } + catch (e) { + if (isConflictingEndpointsError(e)) { + throw e; + } + console.warn("Invalid LANGSMITH_RUNS_ENDPOINTS – must be valid JSON array of " + + "objects with api_url and api_key properties, or object mapping url->apiKey"); + return []; + } +} +function _ensureWriteReplicas(replicas) { + // If null -> fetch from env + if (replicas) { + return replicas.map((replica) => { + if (Array.isArray(replica)) { + return { + projectName: replica[0], + updates: replica[1], + }; + } + return replica; }); - await raiseForStatus(response, "create feedback", true); - return feedback; } - async updateFeedback(feedbackId, { score, value, correction, comment, }) { - const feedbackUpdate = {}; - if (score !== undefined && score !== null) { - feedbackUpdate["score"] = _formatFeedbackScore(score); + return _getWriteReplicasFromEnv(); +} +function _checkEndpointEnvUnset(parsed) { + if (Object.keys(parsed).length > 0 && + getLangSmithEnvironmentVariable("ENDPOINT")) { + throw new ConflictingEndpointsError(); + } +} + +;// CONCATENATED MODULE: ./node_modules/langsmith/run_trees.js + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/env.js +const env_isBrowser = () => typeof window !== "undefined" && typeof window.document !== "undefined"; +const env_isWebWorker = () => typeof globalThis === "object" && + globalThis.constructor && + globalThis.constructor.name === "DedicatedWorkerGlobalScope"; +const env_isJsDom = () => (typeof window !== "undefined" && window.name === "nodejs") || + (typeof navigator !== "undefined" && navigator.userAgent.includes("jsdom")); +// Supabase Edge Function provides a `Deno` global object +// without `version` property +const env_isDeno = () => typeof Deno !== "undefined"; +// Mark not-as-node if in Supabase Edge Function +const env_isNode = () => typeof process !== "undefined" && + typeof process.versions !== "undefined" && + typeof process.versions.node !== "undefined" && + !env_isDeno(); +const env_getEnv = () => { + let env; + if (env_isBrowser()) { + env = "browser"; + } + else if (env_isNode()) { + env = "node"; + } + else if (env_isWebWorker()) { + env = "webworker"; + } + else if (env_isJsDom()) { + env = "jsdom"; + } + else if (env_isDeno()) { + env = "deno"; + } + else { + env = "other"; + } + return env; +}; +let env_runtimeEnvironment; +/** + * @deprecated Use getRuntimeEnvironmentSync instead + */ +async function env_getRuntimeEnvironment() { + return getRuntimeEnvironmentSync(); +} +function getRuntimeEnvironmentSync() { + if (env_runtimeEnvironment === undefined) { + const env = env_getEnv(); + env_runtimeEnvironment = { + library: "langchain-js", + runtime: env, + }; + } + return env_runtimeEnvironment; +} +function env_getEnvironmentVariable(name) { + // Certain Deno setups will throw an error if you try to access environment variables + // https://github.com/langchain-ai/langchainjs/issues/1412 + try { + if (typeof process !== "undefined") { + // eslint-disable-next-line no-process-env + return process.env?.[name]; } - if (value !== undefined && value !== null) { - feedbackUpdate["value"] = value; + else if (env_isDeno()) { + return Deno?.env.get(name); } - if (correction !== undefined && correction !== null) { - feedbackUpdate["correction"] = correction; + else { + return undefined; } - if (comment !== undefined && comment !== null) { - feedbackUpdate["comment"] = comment; + } + catch (e) { + return undefined; + } +} + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/callbacks/base.js + + + +/** + * Abstract class that provides a set of optional methods that can be + * overridden in derived classes to handle various events during the + * execution of a LangChain application. + */ +class BaseCallbackHandlerMethodsClass { +} +function callbackHandlerPrefersStreaming(x) { + return "lc_prefer_streaming" in x && x.lc_prefer_streaming; +} +/** + * Abstract base class for creating callback handlers in the LangChain + * framework. It provides a set of optional methods that can be overridden + * in derived classes to handle various events during the execution of a + * LangChain application. + */ +class BaseCallbackHandler extends BaseCallbackHandlerMethodsClass { + get lc_namespace() { + return ["langchain_core", "callbacks", this.name]; + } + get lc_secrets() { + return undefined; + } + get lc_attributes() { + return undefined; + } + get lc_aliases() { + return undefined; + } + get lc_serializable_keys() { + return undefined; + } + /** + * The name of the serializable. Override to provide an alias or + * to preserve the serialized module name in minified environments. + * + * Implemented as a static method to support loading logic. + */ + static lc_name() { + return this.name; + } + /** + * The final serialized identifier for the module. + */ + get lc_id() { + return [ + ...this.lc_namespace, + get_lc_unique_name(this.constructor), + ]; + } + constructor(input) { + super(); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "lc_kwargs", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "ignoreLLM", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "ignoreChain", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "ignoreAgent", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "ignoreRetriever", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "ignoreCustomEvent", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "raiseError", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "awaitHandlers", { + enumerable: true, + configurable: true, + writable: true, + value: env_getEnvironmentVariable("LANGCHAIN_CALLBACKS_BACKGROUND") === "false" + }); + this.lc_kwargs = input || {}; + if (input) { + this.ignoreLLM = input.ignoreLLM ?? this.ignoreLLM; + this.ignoreChain = input.ignoreChain ?? this.ignoreChain; + this.ignoreAgent = input.ignoreAgent ?? this.ignoreAgent; + this.ignoreRetriever = input.ignoreRetriever ?? this.ignoreRetriever; + this.ignoreCustomEvent = + input.ignoreCustomEvent ?? this.ignoreCustomEvent; + this.raiseError = input.raiseError ?? this.raiseError; + this.awaitHandlers = + this.raiseError || (input._awaitHandler ?? this.awaitHandlers); + } + } + copy() { + return new this.constructor(this); + } + toJSON() { + return Serializable.prototype.toJSON.call(this); + } + toJSONNotImplemented() { + return Serializable.prototype.toJSONNotImplemented.call(this); + } + static fromMethods(methods) { + class Handler extends BaseCallbackHandler { + constructor() { + super(); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: v4() + }); + Object.assign(this, methods); + } } - assertUuid(feedbackId); - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/feedback/${feedbackId}`, { - method: "PATCH", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(feedbackUpdate), - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(response, "update feedback", true); + return new Handler(); } - async readFeedback(feedbackId) { - assertUuid(feedbackId); - const path = `/feedback/${feedbackId}`; - const response = await this._get(path); - return response; +} +const isBaseCallbackHandler = (x) => { + const callbackHandler = x; + return (callbackHandler !== undefined && + typeof callbackHandler.copy === "function" && + typeof callbackHandler.name === "string" && + typeof callbackHandler.awaitHandlers === "boolean"); +}; + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/tracers/base.js + + + +// TODO: Remove and just use base LangSmith Run type +const convertRunTreeToRun = (runTree) => { + if (!runTree) { + return undefined; } - async deleteFeedback(feedbackId) { - assertUuid(feedbackId); - const path = `/feedback/${feedbackId}`; - const response = await this.caller.call(_getFetchImplementation(this.debug), this.apiUrl + path, { - method: "DELETE", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, + // Important that we return the raw run tree object since the reference + // is mutated in other places. + // TODO: Remove places where this is being done. + // eslint-disable-next-line no-param-reassign + runTree.events = runTree.events ?? []; + // eslint-disable-next-line no-param-reassign + runTree.child_runs = runTree.child_runs ?? []; + // TODO: Remove this cast and just use the LangSmith RunTree type. + return runTree; +}; +function convertRunToRunTree(run, parentRun) { + if (!run) { + return undefined; + } + return new run_trees_RunTree({ + ...run, + start_time: run._serialized_start_time ?? run.start_time, + parent_run: convertRunToRunTree(parentRun), + child_runs: run.child_runs + .map((r) => convertRunToRunTree(r)) + .filter((r) => r !== undefined), + extra: { + ...run.extra, + runtime: getRuntimeEnvironmentSync(), + }, + tracingEnabled: false, + }); +} +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function _coerceToDict(value, defaultKey) { + return value && !Array.isArray(value) && typeof value === "object" + ? value + : { [defaultKey]: value }; +} +function isBaseTracer(x) { + return typeof x._addRunToRunMap === "function"; +} +class BaseTracer extends BaseCallbackHandler { + constructor(_fields) { + super(...arguments); + /** @deprecated Use `runTreeMap` instead. */ + Object.defineProperty(this, "runMap", { + enumerable: true, + configurable: true, + writable: true, + value: new Map() + }); + Object.defineProperty(this, "runTreeMap", { + enumerable: true, + configurable: true, + writable: true, + value: new Map() + }); + Object.defineProperty(this, "usesRunTreeMap", { + enumerable: true, + configurable: true, + writable: true, + value: false }); - await raiseForStatus(response, `delete ${path}`); - await response.json(); } - async *listFeedback({ runIds, feedbackKeys, feedbackSourceTypes, } = {}) { - const queryParams = new URLSearchParams(); - if (runIds) { - queryParams.append("run", runIds.join(",")); - } - if (feedbackKeys) { - for (const key of feedbackKeys) { - queryParams.append("key", key); - } + copy() { + return this; + } + getRunById(runId) { + if (runId === undefined) { + return undefined; } - if (feedbackSourceTypes) { - for (const type of feedbackSourceTypes) { - queryParams.append("source", type); - } + return this.usesRunTreeMap + ? convertRunTreeToRun(this.runTreeMap.get(runId)) + : this.runMap.get(runId); + } + stringifyError(error) { + // eslint-disable-next-line no-instanceof/no-instanceof + if (error instanceof Error) { + return error.message + (error?.stack ? `\n\n${error.stack}` : ""); } - for await (const feedbacks of this._getPaginated("/feedback", queryParams)) { - yield* feedbacks; + if (typeof error === "string") { + return error; } + return `${error}`; } - /** - * Creates a presigned feedback token and URL. - * - * The token can be used to authorize feedback metrics without - * needing an API key. This is useful for giving browser-based - * applications the ability to submit feedback without needing - * to expose an API key. - * - * @param runId The ID of the run. - * @param feedbackKey The feedback key. - * @param options Additional options for the token. - * @param options.expiration The expiration time for the token. - * - * @returns A promise that resolves to a FeedbackIngestToken. - */ - async createPresignedFeedbackToken(runId, feedbackKey, { expiration, feedbackConfig, } = {}) { - const body = { - run_id: runId, - feedback_key: feedbackKey, - feedback_config: feedbackConfig, - }; - if (expiration) { - if (typeof expiration === "string") { - body["expires_at"] = expiration; + _addChildRun(parentRun, childRun) { + parentRun.child_runs.push(childRun); + } + _addRunToRunMap(run) { + const { dottedOrder: currentDottedOrder, microsecondPrecisionDatestring } = convertToDottedOrderFormat(new Date(run.start_time).getTime(), run.id, run.execution_order); + const storedRun = { ...run }; + const parentRun = this.getRunById(storedRun.parent_run_id); + if (storedRun.parent_run_id !== undefined) { + if (parentRun) { + this._addChildRun(parentRun, storedRun); + parentRun.child_execution_order = Math.max(parentRun.child_execution_order, storedRun.child_execution_order); + storedRun.trace_id = parentRun.trace_id; + if (parentRun.dotted_order !== undefined) { + storedRun.dotted_order = [ + parentRun.dotted_order, + currentDottedOrder, + ].join("."); + storedRun._serialized_start_time = microsecondPrecisionDatestring; + } + else { + // This can happen naturally for callbacks added within a run + // console.debug(`Parent run with UUID ${storedRun.parent_run_id} has no dotted order.`); + } } - else if (expiration?.hours || expiration?.minutes || expiration?.days) { - body["expires_in"] = expiration; + else { + // This can happen naturally for callbacks added within a run + // console.debug( + // `Parent run with UUID ${storedRun.parent_run_id} not found.` + // ); } } else { - body["expires_in"] = { - hours: 3, - }; - } - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/feedback/tokens`, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(body), - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - const result = await response.json(); - return result; - } - async createComparativeExperiment({ name, experimentIds, referenceDatasetId, createdAt, description, metadata, id, }) { - if (experimentIds.length === 0) { - throw new Error("At least one experiment is required"); + storedRun.trace_id = storedRun.id; + storedRun.dotted_order = currentDottedOrder; + storedRun._serialized_start_time = microsecondPrecisionDatestring; } - if (!referenceDatasetId) { - referenceDatasetId = (await this.readProject({ - projectId: experimentIds[0], - })).reference_dataset_id; + if (this.usesRunTreeMap) { + const runTree = convertRunToRunTree(storedRun, parentRun); + if (runTree !== undefined) { + this.runTreeMap.set(storedRun.id, runTree); + } } - if (!referenceDatasetId == null) { - throw new Error("A reference dataset is required"); + else { + this.runMap.set(storedRun.id, storedRun); } - const body = { - id, - name, - experiment_ids: experimentIds, - reference_dataset_id: referenceDatasetId, - description, - created_at: (createdAt ?? new Date())?.toISOString(), - extra: {}, - }; - if (metadata) - body.extra["metadata"] = metadata; - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/comparative`, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(body), - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - return await response.json(); + return storedRun; } - /** - * Retrieves a list of presigned feedback tokens for a given run ID. - * @param runId The ID of the run. - * @returns An async iterable of FeedbackIngestToken objects. - */ - async *listPresignedFeedbackTokens(runId) { - assertUuid(runId); - const params = new URLSearchParams({ run_id: runId }); - for await (const tokens of this._getPaginated("/feedback/tokens", params)) { - yield* tokens; + async _endTrace(run) { + const parentRun = run.parent_run_id !== undefined && this.getRunById(run.parent_run_id); + if (parentRun) { + parentRun.child_execution_order = Math.max(parentRun.child_execution_order, run.child_execution_order); } - } - _selectEvalResults(results) { - let results_; - if ("results" in results) { - results_ = results.results; + else { + await this.persistRun(run); } - else if (Array.isArray(results)) { - results_ = results; + await this.onRunUpdate?.(run); + if (this.usesRunTreeMap) { + this.runTreeMap.delete(run.id); } else { - results_ = [results]; + this.runMap.delete(run.id); } - return results_; } - async _logEvaluationFeedback(evaluatorResponse, run, sourceInfo) { - const evalResults = this._selectEvalResults(evaluatorResponse); - const feedbacks = []; - for (const res of evalResults) { - let sourceInfo_ = sourceInfo || {}; - if (res.evaluatorInfo) { - sourceInfo_ = { ...res.evaluatorInfo, ...sourceInfo_ }; - } - let runId_ = null; - if (res.targetRunId) { - runId_ = res.targetRunId; - } - else if (run) { - runId_ = run.id; - } - feedbacks.push(await this.createFeedback(runId_, res.key, { - score: res.score, - value: res.value, - comment: res.comment, - correction: res.correction, - sourceInfo: sourceInfo_, - sourceRunId: res.sourceRunId, - feedbackConfig: res.feedbackConfig, - feedbackSourceType: "model", - })); + _getExecutionOrder(parentRunId) { + const parentRun = parentRunId !== undefined && this.getRunById(parentRunId); + // If a run has no parent then execution order is 1 + if (!parentRun) { + return 1; } - return [evalResults, feedbacks]; - } - async logEvaluationFeedback(evaluatorResponse, run, sourceInfo) { - const [results] = await this._logEvaluationFeedback(evaluatorResponse, run, sourceInfo); - return results; + return parentRun.child_execution_order + 1; } /** - * API for managing annotation queues - */ - /** - * List the annotation queues on the LangSmith API. - * @param options - The options for listing annotation queues - * @param options.queueIds - The IDs of the queues to filter by - * @param options.name - The name of the queue to filter by - * @param options.nameContains - The substring that the queue name should contain - * @param options.limit - The maximum number of queues to return - * @returns An iterator of AnnotationQueue objects + * Create and add a run to the run map for LLM start events. + * This must sometimes be done synchronously to avoid race conditions + * when callbacks are backgrounded, so we expose it as a separate method here. */ - async *listAnnotationQueues(options = {}) { - const { queueIds, name, nameContains, limit } = options; - const params = new URLSearchParams(); - if (queueIds) { - queueIds.forEach((id, i) => { - assertUuid(id, `queueIds[${i}]`); - params.append("ids", id); - }); - } - if (name) - params.append("name", name); - if (nameContains) - params.append("name_contains", nameContains); - params.append("limit", (limit !== undefined ? Math.min(limit, 100) : 100).toString()); - let count = 0; - for await (const queues of this._getPaginated("/annotation-queues", params)) { - yield* queues; - count++; - if (limit !== undefined && count >= limit) - break; - } + _createRunForLLMStart(llm, prompts, runId, parentRunId, extraParams, tags, metadata, name) { + const execution_order = this._getExecutionOrder(parentRunId); + const start_time = Date.now(); + const finalExtraParams = metadata + ? { ...extraParams, metadata } + : extraParams; + const run = { + id: runId, + name: name ?? llm.id[llm.id.length - 1], + parent_run_id: parentRunId, + start_time, + serialized: llm, + events: [ + { + name: "start", + time: new Date(start_time).toISOString(), + }, + ], + inputs: { prompts }, + execution_order, + child_runs: [], + child_execution_order: execution_order, + run_type: "llm", + extra: finalExtraParams ?? {}, + tags: tags || [], + }; + return this._addRunToRunMap(run); + } + async handleLLMStart(llm, prompts, runId, parentRunId, extraParams, tags, metadata, name) { + const run = this.getRunById(runId) ?? + this._createRunForLLMStart(llm, prompts, runId, parentRunId, extraParams, tags, metadata, name); + await this.onRunCreate?.(run); + await this.onLLMStart?.(run); + return run; } /** - * Create an annotation queue on the LangSmith API. - * @param options - The options for creating an annotation queue - * @param options.name - The name of the annotation queue - * @param options.description - The description of the annotation queue - * @param options.queueId - The ID of the annotation queue - * @returns The created AnnotationQueue object + * Create and add a run to the run map for chat model start events. + * This must sometimes be done synchronously to avoid race conditions + * when callbacks are backgrounded, so we expose it as a separate method here. */ - async createAnnotationQueue(options) { - const { name, description, queueId, rubricInstructions } = options; - const body = { - name, - description, - id: queueId || v4(), - rubric_instructions: rubricInstructions, + _createRunForChatModelStart(llm, messages, runId, parentRunId, extraParams, tags, metadata, name) { + const execution_order = this._getExecutionOrder(parentRunId); + const start_time = Date.now(); + const finalExtraParams = metadata + ? { ...extraParams, metadata } + : extraParams; + const run = { + id: runId, + name: name ?? llm.id[llm.id.length - 1], + parent_run_id: parentRunId, + start_time, + serialized: llm, + events: [ + { + name: "start", + time: new Date(start_time).toISOString(), + }, + ], + inputs: { messages }, + execution_order, + child_runs: [], + child_execution_order: execution_order, + run_type: "llm", + extra: finalExtraParams ?? {}, + tags: tags || [], }; - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/annotation-queues`, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(Object.fromEntries(Object.entries(body).filter(([_, v]) => v !== undefined))), - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, + return this._addRunToRunMap(run); + } + async handleChatModelStart(llm, messages, runId, parentRunId, extraParams, tags, metadata, name) { + const run = this.getRunById(runId) ?? + this._createRunForChatModelStart(llm, messages, runId, parentRunId, extraParams, tags, metadata, name); + await this.onRunCreate?.(run); + await this.onLLMStart?.(run); + return run; + } + async handleLLMEnd(output, runId, _parentRunId, _tags, extraParams) { + const run = this.getRunById(runId); + if (!run || run?.run_type !== "llm") { + throw new Error("No LLM run to end."); + } + run.end_time = Date.now(); + run.outputs = output; + run.events.push({ + name: "end", + time: new Date(run.end_time).toISOString(), }); - await raiseForStatus(response, "create annotation queue"); - const data = await response.json(); - return data; + run.extra = { ...run.extra, ...extraParams }; + await this.onLLMEnd?.(run); + await this._endTrace(run); + return run; } - /** - * Read an annotation queue with the specified queue ID. - * @param queueId - The ID of the annotation queue to read - * @returns The AnnotationQueueWithDetails object - */ - async readAnnotationQueue(queueId) { - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}`, { - method: "GET", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, + async handleLLMError(error, runId, _parentRunId, _tags, extraParams) { + const run = this.getRunById(runId); + if (!run || run?.run_type !== "llm") { + throw new Error("No LLM run to end."); + } + run.end_time = Date.now(); + run.error = this.stringifyError(error); + run.events.push({ + name: "error", + time: new Date(run.end_time).toISOString(), }); - await raiseForStatus(response, "read annotation queue"); - const data = await response.json(); - return data; + run.extra = { ...run.extra, ...extraParams }; + await this.onLLMError?.(run); + await this._endTrace(run); + return run; } /** - * Update an annotation queue with the specified queue ID. - * @param queueId - The ID of the annotation queue to update - * @param options - The options for updating the annotation queue - * @param options.name - The new name for the annotation queue - * @param options.description - The new description for the annotation queue + * Create and add a run to the run map for chain start events. + * This must sometimes be done synchronously to avoid race conditions + * when callbacks are backgrounded, so we expose it as a separate method here. */ - async updateAnnotationQueue(queueId, options) { - const { name, description, rubricInstructions } = options; - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}`, { - method: "PATCH", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify({ - name, - description, - rubric_instructions: rubricInstructions, - }), - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, + _createRunForChainStart(chain, inputs, runId, parentRunId, tags, metadata, runType, name) { + const execution_order = this._getExecutionOrder(parentRunId); + const start_time = Date.now(); + const run = { + id: runId, + name: name ?? chain.id[chain.id.length - 1], + parent_run_id: parentRunId, + start_time, + serialized: chain, + events: [ + { + name: "start", + time: new Date(start_time).toISOString(), + }, + ], + inputs, + execution_order, + child_execution_order: execution_order, + run_type: runType ?? "chain", + child_runs: [], + extra: metadata ? { metadata } : {}, + tags: tags || [], + }; + return this._addRunToRunMap(run); + } + async handleChainStart(chain, inputs, runId, parentRunId, tags, metadata, runType, name) { + const run = this.getRunById(runId) ?? + this._createRunForChainStart(chain, inputs, runId, parentRunId, tags, metadata, runType, name); + await this.onRunCreate?.(run); + await this.onChainStart?.(run); + return run; + } + async handleChainEnd(outputs, runId, _parentRunId, _tags, kwargs) { + const run = this.getRunById(runId); + if (!run) { + throw new Error("No chain run to end."); + } + run.end_time = Date.now(); + run.outputs = _coerceToDict(outputs, "output"); + run.events.push({ + name: "end", + time: new Date(run.end_time).toISOString(), + }); + if (kwargs?.inputs !== undefined) { + run.inputs = _coerceToDict(kwargs.inputs, "input"); + } + await this.onChainEnd?.(run); + await this._endTrace(run); + return run; + } + async handleChainError(error, runId, _parentRunId, _tags, kwargs) { + const run = this.getRunById(runId); + if (!run) { + throw new Error("No chain run to end."); + } + run.end_time = Date.now(); + run.error = this.stringifyError(error); + run.events.push({ + name: "error", + time: new Date(run.end_time).toISOString(), }); - await raiseForStatus(response, "update annotation queue"); + if (kwargs?.inputs !== undefined) { + run.inputs = _coerceToDict(kwargs.inputs, "input"); + } + await this.onChainError?.(run); + await this._endTrace(run); + return run; } /** - * Delete an annotation queue with the specified queue ID. - * @param queueId - The ID of the annotation queue to delete + * Create and add a run to the run map for tool start events. + * This must sometimes be done synchronously to avoid race conditions + * when callbacks are backgrounded, so we expose it as a separate method here. */ - async deleteAnnotationQueue(queueId) { - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}`, { - method: "DELETE", - headers: { ...this.headers, Accept: "application/json" }, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, + _createRunForToolStart(tool, input, runId, parentRunId, tags, metadata, name) { + const execution_order = this._getExecutionOrder(parentRunId); + const start_time = Date.now(); + const run = { + id: runId, + name: name ?? tool.id[tool.id.length - 1], + parent_run_id: parentRunId, + start_time, + serialized: tool, + events: [ + { + name: "start", + time: new Date(start_time).toISOString(), + }, + ], + inputs: { input }, + execution_order, + child_execution_order: execution_order, + run_type: "tool", + child_runs: [], + extra: metadata ? { metadata } : {}, + tags: tags || [], + }; + return this._addRunToRunMap(run); + } + async handleToolStart(tool, input, runId, parentRunId, tags, metadata, name) { + const run = this.getRunById(runId) ?? + this._createRunForToolStart(tool, input, runId, parentRunId, tags, metadata, name); + await this.onRunCreate?.(run); + await this.onToolStart?.(run); + return run; + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + async handleToolEnd(output, runId) { + const run = this.getRunById(runId); + if (!run || run?.run_type !== "tool") { + throw new Error("No tool run to end"); + } + run.end_time = Date.now(); + run.outputs = { output }; + run.events.push({ + name: "end", + time: new Date(run.end_time).toISOString(), }); - await raiseForStatus(response, "delete annotation queue"); + await this.onToolEnd?.(run); + await this._endTrace(run); + return run; } - /** - * Add runs to an annotation queue with the specified queue ID. - * @param queueId - The ID of the annotation queue - * @param runIds - The IDs of the runs to be added to the annotation queue - */ - async addRunsToAnnotationQueue(queueId, runIds) { - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}/runs`, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(runIds.map((id, i) => assertUuid(id, `runIds[${i}]`).toString())), - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, + async handleToolError(error, runId) { + const run = this.getRunById(runId); + if (!run || run?.run_type !== "tool") { + throw new Error("No tool run to end"); + } + run.end_time = Date.now(); + run.error = this.stringifyError(error); + run.events.push({ + name: "error", + time: new Date(run.end_time).toISOString(), }); - await raiseForStatus(response, "add runs to annotation queue"); + await this.onToolError?.(run); + await this._endTrace(run); + return run; } - /** - * Get a run from an annotation queue at the specified index. - * @param queueId - The ID of the annotation queue - * @param index - The index of the run to retrieve - * @returns A Promise that resolves to a RunWithAnnotationQueueInfo object - * @throws {Error} If the run is not found at the given index or for other API-related errors - */ - async getRunFromAnnotationQueue(queueId, index) { - const baseUrl = `/annotation-queues/${assertUuid(queueId, "queueId")}/run`; - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}${baseUrl}/${index}`, { - method: "GET", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, + async handleAgentAction(action, runId) { + const run = this.getRunById(runId); + if (!run || run?.run_type !== "chain") { + return; + } + const agentRun = run; + agentRun.actions = agentRun.actions || []; + agentRun.actions.push(action); + agentRun.events.push({ + name: "agent_action", + time: new Date().toISOString(), + kwargs: { action }, }); - await raiseForStatus(response, "get run from annotation queue"); - return await response.json(); + await this.onAgentAction?.(run); } - /** - * Delete a run from an an annotation queue. - * @param queueId - The ID of the annotation queue to delete the run from - * @param queueRunId - The ID of the run to delete from the annotation queue - */ - async deleteRunFromAnnotationQueue(queueId, queueRunId) { - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}/runs/${assertUuid(queueRunId, "queueRunId")}`, { - method: "DELETE", - headers: { ...this.headers, Accept: "application/json" }, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, + async handleAgentEnd(action, runId) { + const run = this.getRunById(runId); + if (!run || run?.run_type !== "chain") { + return; + } + run.events.push({ + name: "agent_end", + time: new Date().toISOString(), + kwargs: { action }, }); - await raiseForStatus(response, "delete run from annotation queue"); + await this.onAgentEnd?.(run); } /** - * Get the size of an annotation queue. - * @param queueId - The ID of the annotation queue + * Create and add a run to the run map for retriever start events. + * This must sometimes be done synchronously to avoid race conditions + * when callbacks are backgrounded, so we expose it as a separate method here. */ - async getSizeFromAnnotationQueue(queueId) { - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}/size`, { - method: "GET", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(response, "get size from annotation queue"); - return await response.json(); - } - async _currentTenantIsOwner(owner) { - const settings = await this._getSettings(); - return owner == "-" || settings.tenant_handle === owner; + _createRunForRetrieverStart(retriever, query, runId, parentRunId, tags, metadata, name) { + const execution_order = this._getExecutionOrder(parentRunId); + const start_time = Date.now(); + const run = { + id: runId, + name: name ?? retriever.id[retriever.id.length - 1], + parent_run_id: parentRunId, + start_time, + serialized: retriever, + events: [ + { + name: "start", + time: new Date(start_time).toISOString(), + }, + ], + inputs: { query }, + execution_order, + child_execution_order: execution_order, + run_type: "retriever", + child_runs: [], + extra: metadata ? { metadata } : {}, + tags: tags || [], + }; + return this._addRunToRunMap(run); } - async _ownerConflictError(action, owner) { - const settings = await this._getSettings(); - return new Error(`Cannot ${action} for another tenant.\n - Current tenant: ${settings.tenant_handle}\n - Requested tenant: ${owner}`); + async handleRetrieverStart(retriever, query, runId, parentRunId, tags, metadata, name) { + const run = this.getRunById(runId) ?? + this._createRunForRetrieverStart(retriever, query, runId, parentRunId, tags, metadata, name); + await this.onRunCreate?.(run); + await this.onRetrieverStart?.(run); + return run; } - async _getLatestCommitHash(promptOwnerAndName) { - const res = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/commits/${promptOwnerAndName}/?limit=${1}&offset=${0}`, { - method: "GET", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - const json = await res.json(); - if (!res.ok) { - const detail = typeof json.detail === "string" - ? json.detail - : JSON.stringify(json.detail); - const error = new Error(`Error ${res.status}: ${res.statusText}\n${detail}`); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - error.statusCode = res.status; - throw error; - } - if (json.commits.length === 0) { - return undefined; + async handleRetrieverEnd(documents, runId) { + const run = this.getRunById(runId); + if (!run || run?.run_type !== "retriever") { + throw new Error("No retriever run to end"); } - return json.commits[0].commit_hash; - } - async _likeOrUnlikePrompt(promptIdentifier, like) { - const [owner, promptName, _] = parsePromptIdentifier(promptIdentifier); - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/likes/${owner}/${promptName}`, { - method: "POST", - body: JSON.stringify({ like: like }), - headers: { ...this.headers, "Content-Type": "application/json" }, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, + run.end_time = Date.now(); + run.outputs = { documents }; + run.events.push({ + name: "end", + time: new Date(run.end_time).toISOString(), }); - await raiseForStatus(response, `${like ? "like" : "unlike"} prompt`); - return await response.json(); + await this.onRetrieverEnd?.(run); + await this._endTrace(run); + return run; } - async _getPromptUrl(promptIdentifier) { - const [owner, promptName, commitHash] = parsePromptIdentifier(promptIdentifier); - if (!(await this._currentTenantIsOwner(owner))) { - if (commitHash !== "latest") { - return `${this.getHostUrl()}/hub/${owner}/${promptName}/${commitHash.substring(0, 8)}`; - } - else { - return `${this.getHostUrl()}/hub/${owner}/${promptName}`; - } - } - else { - const settings = await this._getSettings(); - if (commitHash !== "latest") { - return `${this.getHostUrl()}/prompts/${promptName}/${commitHash.substring(0, 8)}?organizationId=${settings.id}`; - } - else { - return `${this.getHostUrl()}/prompts/${promptName}?organizationId=${settings.id}`; - } + async handleRetrieverError(error, runId) { + const run = this.getRunById(runId); + if (!run || run?.run_type !== "retriever") { + throw new Error("No retriever run to end"); } + run.end_time = Date.now(); + run.error = this.stringifyError(error); + run.events.push({ + name: "error", + time: new Date(run.end_time).toISOString(), + }); + await this.onRetrieverError?.(run); + await this._endTrace(run); + return run; } - async promptExists(promptIdentifier) { - const prompt = await this.getPrompt(promptIdentifier); - return !!prompt; + async handleText(text, runId) { + const run = this.getRunById(runId); + if (!run || run?.run_type !== "chain") { + return; + } + run.events.push({ + name: "text", + time: new Date().toISOString(), + kwargs: { text }, + }); + await this.onText?.(run); } - async likePrompt(promptIdentifier) { - return this._likeOrUnlikePrompt(promptIdentifier, true); + async handleLLMNewToken(token, idx, runId, _parentRunId, _tags, fields) { + const run = this.getRunById(runId); + if (!run || run?.run_type !== "llm") { + throw new Error(`Invalid "runId" provided to "handleLLMNewToken" callback.`); + } + run.events.push({ + name: "new_token", + time: new Date().toISOString(), + kwargs: { token, idx, chunk: fields?.chunk }, + }); + await this.onLLMNewToken?.(run, token, { chunk: fields?.chunk }); + return run; } - async unlikePrompt(promptIdentifier) { - return this._likeOrUnlikePrompt(promptIdentifier, false); +} + +// EXTERNAL MODULE: ./node_modules/@langchain/core/node_modules/ansi-styles/index.js +var ansi_styles = __nccwpck_require__(2227); +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/tracers/console.js + + +function wrap(style, text) { + return `${style.open}${text}${style.close}`; +} +function tryJsonStringify(obj, fallback) { + try { + return JSON.stringify(obj, null, 2); } - async *listCommits(promptOwnerAndName) { - for await (const commits of this._getPaginated(`/commits/${promptOwnerAndName}/`, new URLSearchParams(), (res) => res.commits)) { - yield* commits; - } + catch (err) { + return fallback; } - async *listPrompts(options) { - const params = new URLSearchParams(); - params.append("sort_field", options?.sortField ?? "updated_at"); - params.append("sort_direction", "desc"); - params.append("is_archived", (!!options?.isArchived).toString()); - if (options?.isPublic !== undefined) { - params.append("is_public", options.isPublic.toString()); - } - if (options?.query) { - params.append("query", options.query); - } - for await (const prompts of this._getPaginated("/repos", params, (res) => res.repos)) { - yield* prompts; - } +} +function formatKVMapItem(value) { + if (typeof value === "string") { + return value.trim(); } - async getPrompt(promptIdentifier) { - const [owner, promptName, _] = parsePromptIdentifier(promptIdentifier); - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/repos/${owner}/${promptName}`, { - method: "GET", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - if (response.status === 404) { - return null; - } - await raiseForStatus(response, "get prompt"); - const result = await response.json(); - if (result.repo) { - return result.repo; - } - else { - return null; - } + if (value === null || value === undefined) { + return value; } - async createPrompt(promptIdentifier, options) { - const settings = await this._getSettings(); - if (options?.isPublic && !settings.tenant_handle) { - throw new Error(`Cannot create a public prompt without first\n - creating a LangChain Hub handle. - You can add a handle by creating a public prompt at:\n - https://smith.langchain.com/prompts`); - } - const [owner, promptName, _] = parsePromptIdentifier(promptIdentifier); - if (!(await this._currentTenantIsOwner(owner))) { - throw await this._ownerConflictError("create a prompt", owner); - } - const data = { - repo_handle: promptName, - ...(options?.description && { description: options.description }), - ...(options?.readme && { readme: options.readme }), - ...(options?.tags && { tags: options.tags }), - is_public: !!options?.isPublic, - }; - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/repos/`, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(data), - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(response, "create prompt"); - const { repo } = await response.json(); - return repo; + return tryJsonStringify(value, value.toString()); +} +function elapsed(run) { + if (!run.end_time) + return ""; + const elapsed = run.end_time - run.start_time; + if (elapsed < 1000) { + return `${elapsed}ms`; } - async createCommit(promptIdentifier, object, options) { - if (!(await this.promptExists(promptIdentifier))) { - throw new Error("Prompt does not exist, you must create it first."); - } - const [owner, promptName, _] = parsePromptIdentifier(promptIdentifier); - const resolvedParentCommitHash = options?.parentCommitHash === "latest" || !options?.parentCommitHash - ? await this._getLatestCommitHash(`${owner}/${promptName}`) - : options?.parentCommitHash; - const payload = { - manifest: JSON.parse(JSON.stringify(object)), - parent_commit: resolvedParentCommitHash, - }; - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/commits/${owner}/${promptName}`, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(payload), - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, + return `${(elapsed / 1000).toFixed(2)}s`; +} +const { color } = ansi_styles; +/** + * A tracer that logs all events to the console. It extends from the + * `BaseTracer` class and overrides its methods to provide custom logging + * functionality. + * @example + * ```typescript + * + * const llm = new ChatAnthropic({ + * temperature: 0, + * tags: ["example", "callbacks", "constructor"], + * callbacks: [new ConsoleCallbackHandler()], + * }); + * + * ``` + */ +class ConsoleCallbackHandler extends BaseTracer { + constructor() { + super(...arguments); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "console_callback_handler" }); - await raiseForStatus(response, "create commit"); - const result = await response.json(); - return this._getPromptUrl(`${owner}/${promptName}${result.commit_hash ? `:${result.commit_hash}` : ""}`); } /** - * Update examples with attachments using multipart form data. - * @param updates List of ExampleUpdateWithAttachments objects to upsert - * @returns Promise with the update response + * Method used to persist the run. In this case, it simply returns a + * resolved promise as there's no persistence logic. + * @param _run The run to persist. + * @returns A resolved promise. */ - async updateExamplesMultipart(datasetId, updates = []) { - return this._updateExamplesMultipart(datasetId, updates); + persistRun(_run) { + return Promise.resolve(); } - async _updateExamplesMultipart(datasetId, updates = []) { - if (!(await this._getMultiPartSupport())) { - throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version."); - } - const formData = new FormData(); - for (const example of updates) { - const exampleId = example.id; - // Prepare the main example body - const exampleBody = { - ...(example.metadata && { metadata: example.metadata }), - ...(example.split && { split: example.split }), - }; - // Add main example data - const stringifiedExample = serialize(exampleBody); - const exampleBlob = new Blob([stringifiedExample], { - type: "application/json", - }); - formData.append(exampleId, exampleBlob); - // Add inputs if present - if (example.inputs) { - const stringifiedInputs = serialize(example.inputs); - const inputsBlob = new Blob([stringifiedInputs], { - type: "application/json", - }); - formData.append(`${exampleId}.inputs`, inputsBlob); - } - // Add outputs if present - if (example.outputs) { - const stringifiedOutputs = serialize(example.outputs); - const outputsBlob = new Blob([stringifiedOutputs], { - type: "application/json", - }); - formData.append(`${exampleId}.outputs`, outputsBlob); - } - // Add attachments if present - if (example.attachments) { - for (const [name, attachment] of Object.entries(example.attachments)) { - let mimeType; - let data; - if (Array.isArray(attachment)) { - [mimeType, data] = attachment; - } - else { - mimeType = attachment.mimeType; - data = attachment.data; - } - const attachmentBlob = new Blob([data], { - type: `${mimeType}; length=${data.byteLength}`, - }); - formData.append(`${exampleId}.attachment.${name}`, attachmentBlob); - } + // utility methods + /** + * Method used to get all the parent runs of a given run. + * @param run The run whose parents are to be retrieved. + * @returns An array of parent runs. + */ + getParents(run) { + const parents = []; + let currentRun = run; + while (currentRun.parent_run_id) { + const parent = this.runMap.get(currentRun.parent_run_id); + if (parent) { + parents.push(parent); + currentRun = parent; } - if (example.attachments_operations) { - const stringifiedAttachmentsOperations = serialize(example.attachments_operations); - const attachmentsOperationsBlob = new Blob([stringifiedAttachmentsOperations], { - type: "application/json", - }); - formData.append(`${exampleId}.attachments_operations`, attachmentsOperationsBlob); + else { + break; } } - const datasetIdToUse = datasetId ?? updates[0]?.dataset_id; - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/v1/platform/datasets/${datasetIdToUse}/examples`, { - method: "PATCH", - headers: this.headers, - body: formData, - }); - const result = await response.json(); - return result; + return parents; } /** - * Upload examples with attachments using multipart form data. - * @param uploads List of ExampleUploadWithAttachments objects to upload - * @returns Promise with the upload response - * @deprecated This method is deprecated and will be removed in future LangSmith versions, please use `createExamples` instead + * Method used to get a string representation of the run's lineage, which + * is used in logging. + * @param run The run whose lineage is to be retrieved. + * @returns A string representation of the run's lineage. */ - async uploadExamplesMultipart(datasetId, uploads = []) { - return this._uploadExamplesMultipart(datasetId, uploads); + getBreadcrumbs(run) { + const parents = this.getParents(run).reverse(); + const string = [...parents, run] + .map((parent, i, arr) => { + const name = `${parent.execution_order}:${parent.run_type}:${parent.name}`; + return i === arr.length - 1 ? wrap(ansi_styles.bold, name) : name; + }) + .join(" > "); + return wrap(color.grey, string); } - async _uploadExamplesMultipart(datasetId, uploads = []) { - if (!(await this._getMultiPartSupport())) { - throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version."); - } - const formData = new FormData(); - for (const example of uploads) { - const exampleId = (example.id ?? v4()).toString(); - // Prepare the main example body - const exampleBody = { - created_at: example.created_at, - ...(example.metadata && { metadata: example.metadata }), - ...(example.split && { split: example.split }), - ...(example.source_run_id && { source_run_id: example.source_run_id }), - ...(example.use_source_run_io && { - use_source_run_io: example.use_source_run_io, - }), - ...(example.use_source_run_attachments && { - use_source_run_attachments: example.use_source_run_attachments, - }), - }; - // Add main example data - const stringifiedExample = serialize(exampleBody); - const exampleBlob = new Blob([stringifiedExample], { - type: "application/json", - }); - formData.append(exampleId, exampleBlob); - // Add inputs if present - if (example.inputs) { - const stringifiedInputs = serialize(example.inputs); - const inputsBlob = new Blob([stringifiedInputs], { - type: "application/json", - }); - formData.append(`${exampleId}.inputs`, inputsBlob); - } - // Add outputs if present - if (example.outputs) { - const stringifiedOutputs = serialize(example.outputs); - const outputsBlob = new Blob([stringifiedOutputs], { - type: "application/json", - }); - formData.append(`${exampleId}.outputs`, outputsBlob); - } - // Add attachments if present - if (example.attachments) { - for (const [name, attachment] of Object.entries(example.attachments)) { - let mimeType; - let data; - if (Array.isArray(attachment)) { - [mimeType, data] = attachment; - } - else { - mimeType = attachment.mimeType; - data = attachment.data; - } - const attachmentBlob = new Blob([data], { - type: `${mimeType}; length=${data.byteLength}`, - }); - formData.append(`${exampleId}.attachment.${name}`, attachmentBlob); - } - } - } - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/v1/platform/datasets/${datasetId}/examples`, { - method: "POST", - headers: this.headers, - body: formData, - }); - await raiseForStatus(response, "upload examples"); - const result = await response.json(); - return result; + // logging methods + /** + * Method used to log the start of a chain run. + * @param run The chain run that has started. + * @returns void + */ + onChainStart(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.green, "[chain/start]")} [${crumbs}] Entering Chain run with input: ${tryJsonStringify(run.inputs, "[inputs]")}`); } - async updatePrompt(promptIdentifier, options) { - if (!(await this.promptExists(promptIdentifier))) { - throw new Error("Prompt does not exist, you must create it first."); - } - const [owner, promptName] = parsePromptIdentifier(promptIdentifier); - if (!(await this._currentTenantIsOwner(owner))) { - throw await this._ownerConflictError("update a prompt", owner); - } - const payload = {}; - if (options?.description !== undefined) - payload.description = options.description; - if (options?.readme !== undefined) - payload.readme = options.readme; - if (options?.tags !== undefined) - payload.tags = options.tags; - if (options?.isPublic !== undefined) - payload.is_public = options.isPublic; - if (options?.isArchived !== undefined) - payload.is_archived = options.isArchived; - // Check if payload is empty - if (Object.keys(payload).length === 0) { - throw new Error("No valid update options provided"); - } - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/repos/${owner}/${promptName}`, { - method: "PATCH", - body: JSON.stringify(payload), - headers: { - ...this.headers, - "Content-Type": "application/json", - }, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(response, "update prompt"); - return response.json(); + /** + * Method used to log the end of a chain run. + * @param run The chain run that has ended. + * @returns void + */ + onChainEnd(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.cyan, "[chain/end]")} [${crumbs}] [${elapsed(run)}] Exiting Chain run with output: ${tryJsonStringify(run.outputs, "[outputs]")}`); } - async deletePrompt(promptIdentifier) { - if (!(await this.promptExists(promptIdentifier))) { - throw new Error("Prompt does not exist, you must create it first."); - } - const [owner, promptName, _] = parsePromptIdentifier(promptIdentifier); - if (!(await this._currentTenantIsOwner(owner))) { - throw await this._ownerConflictError("delete a prompt", owner); - } - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/repos/${owner}/${promptName}`, { - method: "DELETE", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - return await response.json(); + /** + * Method used to log any errors of a chain run. + * @param run The chain run that has errored. + * @returns void + */ + onChainError(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.red, "[chain/error]")} [${crumbs}] [${elapsed(run)}] Chain run errored with error: ${tryJsonStringify(run.error, "[error]")}`); } - async pullPromptCommit(promptIdentifier, options) { - const [owner, promptName, commitHash] = parsePromptIdentifier(promptIdentifier); - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/commits/${owner}/${promptName}/${commitHash}${options?.includeModel ? "?include_model=true" : ""}`, { - method: "GET", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(response, "pull prompt commit"); - const result = await response.json(); - return { - owner, - repo: promptName, - commit_hash: result.commit_hash, - manifest: result.manifest, - examples: result.examples, - }; + /** + * Method used to log the start of an LLM run. + * @param run The LLM run that has started. + * @returns void + */ + onLLMStart(run) { + const crumbs = this.getBreadcrumbs(run); + const inputs = "prompts" in run.inputs + ? { prompts: run.inputs.prompts.map((p) => p.trim()) } + : run.inputs; + console.log(`${wrap(color.green, "[llm/start]")} [${crumbs}] Entering LLM run with input: ${tryJsonStringify(inputs, "[inputs]")}`); } /** - * This method should not be used directly, use `import { pull } from "langchain/hub"` instead. - * Using this method directly returns the JSON string of the prompt rather than a LangChain object. - * @private + * Method used to log the end of an LLM run. + * @param run The LLM run that has ended. + * @returns void */ - async _pullPrompt(promptIdentifier, options) { - const promptObject = await this.pullPromptCommit(promptIdentifier, { - includeModel: options?.includeModel, - }); - const prompt = JSON.stringify(promptObject.manifest); - return prompt; + onLLMEnd(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.cyan, "[llm/end]")} [${crumbs}] [${elapsed(run)}] Exiting LLM run with output: ${tryJsonStringify(run.outputs, "[response]")}`); } - async pushPrompt(promptIdentifier, options) { - // Create or update prompt metadata - if (await this.promptExists(promptIdentifier)) { - if (options && Object.keys(options).some((key) => key !== "object")) { - await this.updatePrompt(promptIdentifier, { - description: options?.description, - readme: options?.readme, - tags: options?.tags, - isPublic: options?.isPublic, - }); - } - } - else { - await this.createPrompt(promptIdentifier, { - description: options?.description, - readme: options?.readme, - tags: options?.tags, - isPublic: options?.isPublic, - }); - } - if (!options?.object) { - return await this._getPromptUrl(promptIdentifier); - } - // Create a commit with the new manifest - const url = await this.createCommit(promptIdentifier, options?.object, { - parentCommitHash: options?.parentCommitHash, - }); - return url; + /** + * Method used to log any errors of an LLM run. + * @param run The LLM run that has errored. + * @returns void + */ + onLLMError(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.red, "[llm/error]")} [${crumbs}] [${elapsed(run)}] LLM run errored with error: ${tryJsonStringify(run.error, "[error]")}`); } /** - * Clone a public dataset to your own langsmith tenant. - * This operation is idempotent. If you already have a dataset with the given name, - * this function will do nothing. - - * @param {string} tokenOrUrl The token of the public dataset to clone. - * @param {Object} [options] Additional options for cloning the dataset. - * @param {string} [options.sourceApiUrl] The URL of the langsmith server where the data is hosted. Defaults to the API URL of your current client. - * @param {string} [options.datasetName] The name of the dataset to create in your tenant. Defaults to the name of the public dataset. - * @returns {Promise} + * Method used to log the start of a tool run. + * @param run The tool run that has started. + * @returns void */ - async clonePublicDataset(tokenOrUrl, options = {}) { - const { sourceApiUrl = this.apiUrl, datasetName } = options; - const [parsedApiUrl, tokenUuid] = this.parseTokenOrUrl(tokenOrUrl, sourceApiUrl); - const sourceClient = new Client({ - apiUrl: parsedApiUrl, - // Placeholder API key not needed anymore in most cases, but - // some private deployments may have API key-based rate limiting - // that would cause this to fail if we provide no value. - apiKey: "placeholder", - }); - const ds = await sourceClient.readSharedDataset(tokenUuid); - const finalDatasetName = datasetName || ds.name; - try { - if (await this.hasDataset({ datasetId: finalDatasetName })) { - console.log(`Dataset ${finalDatasetName} already exists in your tenant. Skipping.`); - return; + onToolStart(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.green, "[tool/start]")} [${crumbs}] Entering Tool run with input: "${formatKVMapItem(run.inputs.input)}"`); + } + /** + * Method used to log the end of a tool run. + * @param run The tool run that has ended. + * @returns void + */ + onToolEnd(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.cyan, "[tool/end]")} [${crumbs}] [${elapsed(run)}] Exiting Tool run with output: "${formatKVMapItem(run.outputs?.output)}"`); + } + /** + * Method used to log any errors of a tool run. + * @param run The tool run that has errored. + * @returns void + */ + onToolError(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.red, "[tool/error]")} [${crumbs}] [${elapsed(run)}] Tool run errored with error: ${tryJsonStringify(run.error, "[error]")}`); + } + /** + * Method used to log the start of a retriever run. + * @param run The retriever run that has started. + * @returns void + */ + onRetrieverStart(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.green, "[retriever/start]")} [${crumbs}] Entering Retriever run with input: ${tryJsonStringify(run.inputs, "[inputs]")}`); + } + /** + * Method used to log the end of a retriever run. + * @param run The retriever run that has ended. + * @returns void + */ + onRetrieverEnd(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.cyan, "[retriever/end]")} [${crumbs}] [${elapsed(run)}] Exiting Retriever run with output: ${tryJsonStringify(run.outputs, "[outputs]")}`); + } + /** + * Method used to log any errors of a retriever run. + * @param run The retriever run that has errored. + * @returns void + */ + onRetrieverError(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.red, "[retriever/error]")} [${crumbs}] [${elapsed(run)}] Retriever run errored with error: ${tryJsonStringify(run.error, "[error]")}`); + } + /** + * Method used to log the action selected by the agent. + * @param run The run in which the agent action occurred. + * @returns void + */ + onAgentAction(run) { + const agentRun = run; + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.blue, "[agent/action]")} [${crumbs}] Agent selected action: ${tryJsonStringify(agentRun.actions[agentRun.actions.length - 1], "[action]")}`); + } +} + +;// CONCATENATED MODULE: ./node_modules/langsmith/index.js + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/singletons/tracer.js + + +let client; +const tracer_getDefaultLangChainClientSingleton = () => { + if (client === undefined) { + const clientParams = env_getEnvironmentVariable("LANGCHAIN_CALLBACKS_BACKGROUND") === "false" + ? { + // LangSmith has its own backgrounding system + blockOnRootRunFinalization: true, } - } - catch (_) { - // `.hasDataset` will throw an error if the dataset does not exist. - // no-op in that case - } - // Fetch examples first, then create the dataset - const examples = await sourceClient.listSharedExamples(tokenUuid); - const dataset = await this.createDataset(finalDatasetName, { - description: ds.description, - dataType: ds.data_type || "kv", - inputsSchema: ds.inputs_schema_definition ?? undefined, - outputsSchema: ds.outputs_schema_definition ?? undefined, + : {}; + client = new Client(clientParams); + } + return client; +}; +const setDefaultLangChainClientSingleton = (newClient) => { + client = newClient; +}; + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/tracers/tracer_langchain.js + + + + + +class tracer_langchain_LangChainTracer extends BaseTracer { + constructor(fields = {}) { + super(fields); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "langchain_tracer" }); - try { - await this.createExamples({ - inputs: examples.map((e) => e.inputs), - outputs: examples.flatMap((e) => (e.outputs ? [e.outputs] : [])), - datasetId: dataset.id, - }); - } - catch (e) { - console.error(`An error occurred while creating dataset ${finalDatasetName}. ` + - "You should delete it manually."); - throw e; + Object.defineProperty(this, "projectName", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "exampleId", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "client", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "replicas", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "usesRunTreeMap", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + const { exampleId, projectName, client, replicas } = fields; + this.projectName = projectName ?? getDefaultProjectName(); + this.replicas = replicas; + this.exampleId = exampleId; + this.client = client ?? tracer_getDefaultLangChainClientSingleton(); + const traceableTree = tracer_langchain_LangChainTracer.getTraceableRunTree(); + if (traceableTree) { + this.updateFromRunTree(traceableTree); } } - parseTokenOrUrl(urlOrToken, apiUrl, numParts = 2, kind = "dataset") { - // Try parsing as UUID - try { - assertUuid(urlOrToken); // Will throw if it's not a UUID. - return [apiUrl, urlOrToken]; - } - catch (_) { - // no-op if it's not a uuid + async persistRun(_run) { } + async onRunCreate(run) { + const runTree = this.getRunTreeWithTracingConfig(run.id); + await runTree?.postRun(); + } + async onRunUpdate(run) { + const runTree = this.getRunTreeWithTracingConfig(run.id); + await runTree?.patchRun(); + } + getRun(id) { + return this.runTreeMap.get(id); + } + updateFromRunTree(runTree) { + let rootRun = runTree; + const visited = new Set(); + while (rootRun.parent_run) { + if (visited.has(rootRun.id)) + break; + visited.add(rootRun.id); + if (!rootRun.parent_run) + break; + rootRun = rootRun.parent_run; } - // Parse as URL - try { - const parsedUrl = new URL(urlOrToken); - const pathParts = parsedUrl.pathname - .split("/") - .filter((part) => part !== ""); - if (pathParts.length >= numParts) { - const tokenUuid = pathParts[pathParts.length - numParts]; - return [apiUrl, tokenUuid]; - } - else { - throw new Error(`Invalid public ${kind} URL: ${urlOrToken}`); + visited.clear(); + const queue = [rootRun]; + while (queue.length > 0) { + const current = queue.shift(); + if (!current || visited.has(current.id)) + continue; + visited.add(current.id); + this.runTreeMap.set(current.id, current); + if (current.child_runs) { + queue.push(...current.child_runs); } } - catch (error) { - throw new Error(`Invalid public ${kind} URL or token: ${urlOrToken}`); - } + this.client = runTree.client ?? this.client; + this.replicas = runTree.replicas ?? this.replicas; + this.projectName = runTree.project_name ?? this.projectName; + this.exampleId = runTree.reference_example_id ?? this.exampleId; } - /** - * Awaits all pending trace batches. Useful for environments where - * you need to be sure that all tracing requests finish before execution ends, - * such as serverless environments. - * - * @example - * ``` - * import { Client } from "langsmith"; - * - * const client = new Client(); - * - * try { - * // Tracing happens here - * ... - * } finally { - * await client.awaitPendingTraceBatches(); - * } - * ``` - * - * @returns A promise that resolves once all currently pending traces have sent. - */ - awaitPendingTraceBatches() { - if (this.manualFlushMode) { - console.warn("[WARNING]: When tracing in manual flush mode, you must call `await client.flush()` manually to submit trace batches."); - return Promise.resolve(); + getRunTreeWithTracingConfig(id) { + const runTree = this.runTreeMap.get(id); + if (!runTree) + return undefined; + return new run_trees_RunTree({ + ...runTree, + client: this.client, + project_name: this.projectName, + replicas: this.replicas, + reference_example_id: this.exampleId, + tracingEnabled: true, + }); + } + static getTraceableRunTree() { + try { + return ( + // The type cast here provides forward compatibility. Old versions of LangSmith will just + // ignore the permitAbsentRunTree arg. + getCurrentRunTree(true)); + } + catch { + return undefined; } - return Promise.all([ - ...this.autoBatchQueue.items.map(({ itemPromise }) => itemPromise), - this.batchIngestCaller.queue.onIdle(), - ]); } } -function isExampleCreate(input) { - return "dataset_id" in input || "dataset_name" in input; -} - -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/index.js +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/singletons/async_local_storage/globals.js +const globals_TRACING_ALS_KEY = Symbol.for("ls:tracing_async_local_storage"); +const globals_CONTEXT_VARIABLES_KEY = Symbol.for("lc:context_variables"); +const setGlobalAsyncLocalStorageInstance = (instance) => { + globalThis[globals_TRACING_ALS_KEY] = instance; +}; +const globals_getGlobalAsyncLocalStorageInstance = () => { + return globalThis[globals_TRACING_ALS_KEY]; +}; +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/singletons/callbacks.js +/* eslint-disable @typescript-eslint/no-explicit-any */ -// Update using yarn bump-version -const __version__ = "0.3.28"; -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/env.js -// Inlined from https://github.com/flexdinesh/browser-or-node -let globalEnv; -const isBrowser = () => typeof window !== "undefined" && typeof window.document !== "undefined"; -const isWebWorker = () => typeof globalThis === "object" && - globalThis.constructor && - globalThis.constructor.name === "DedicatedWorkerGlobalScope"; -const isJsDom = () => (typeof window !== "undefined" && window.name === "nodejs") || - (typeof navigator !== "undefined" && - (navigator.userAgent.includes("Node.js") || - navigator.userAgent.includes("jsdom"))); -// Supabase Edge Function provides a `Deno` global object -// without `version` property -const isDeno = () => typeof Deno !== "undefined"; -// Mark not-as-node if in Supabase Edge Function -const isNode = () => typeof process !== "undefined" && - typeof process.versions !== "undefined" && - typeof process.versions.node !== "undefined" && - !isDeno(); -const getEnv = () => { - if (globalEnv) { - return globalEnv; - } - if (isBrowser()) { - globalEnv = "browser"; - } - else if (isNode()) { - globalEnv = "node"; - } - else if (isWebWorker()) { - globalEnv = "webworker"; - } - else if (isJsDom()) { - globalEnv = "jsdom"; - } - else if (isDeno()) { - globalEnv = "deno"; - } - else { - globalEnv = "other"; - } - return globalEnv; -}; -let runtimeEnvironment; -function getRuntimeEnvironment() { - if (runtimeEnvironment === undefined) { - const env = getEnv(); - const releaseEnv = getShas(); - runtimeEnvironment = { - library: "langsmith", - runtime: env, - sdk: "langsmith-js", - sdk_version: __version__, - ...releaseEnv, - }; +let queue; +/** + * Creates a queue using the p-queue library. The queue is configured to + * auto-start and has a concurrency of 1, meaning it will process tasks + * one at a time. + */ +function createQueue() { + const PQueue = true ? p_queue_dist["default"] : p_queue_dist; + return new PQueue({ + autoStart: true, + concurrency: 1, + }); +} +function getQueue() { + if (typeof queue === "undefined") { + queue = createQueue(); } - return runtimeEnvironment; + return queue; } /** - * Retrieves the LangChain-specific environment variables from the current runtime environment. - * Sensitive keys (containing the word "key", "token", or "secret") have their values redacted for security. - * - * @returns {Record} - * - A record of LangChain-specific environment variables. + * Consume a promise, either adding it to the queue or waiting for it to resolve + * @param promiseFn Promise to consume + * @param wait Whether to wait for the promise to resolve or resolve immediately */ -function getLangChainEnvVars() { - const allEnvVars = getEnvironmentVariables() || {}; - const envVars = {}; - for (const [key, value] of Object.entries(allEnvVars)) { - if (key.startsWith("LANGCHAIN_") && typeof value === "string") { - envVars[key] = value; +async function consumeCallback(promiseFn, wait) { + if (wait === true) { + // Clear config since callbacks are not part of the root run + // Avoid using global singleton due to circuluar dependency issues + const asyncLocalStorageInstance = globals_getGlobalAsyncLocalStorageInstance(); + if (asyncLocalStorageInstance !== undefined) { + await asyncLocalStorageInstance.run(undefined, async () => promiseFn()); } - } - for (const key in envVars) { - if ((key.toLowerCase().includes("key") || - key.toLowerCase().includes("secret") || - key.toLowerCase().includes("token")) && - typeof envVars[key] === "string") { - const value = envVars[key]; - envVars[key] = - value.slice(0, 2) + "*".repeat(value.length - 4) + value.slice(-2); + else { + await promiseFn(); } } - return envVars; -} -/** - * Retrieves the LangChain-specific metadata from the current runtime environment. - * - * @returns {Record} - * - A record of LangChain-specific metadata environment variables. - */ -function getLangChainEnvVarsMetadata() { - const allEnvVars = getEnvironmentVariables() || {}; - const envVars = {}; - const excluded = [ - "LANGCHAIN_API_KEY", - "LANGCHAIN_ENDPOINT", - "LANGCHAIN_TRACING_V2", - "LANGCHAIN_PROJECT", - "LANGCHAIN_SESSION", - "LANGSMITH_API_KEY", - "LANGSMITH_ENDPOINT", - "LANGSMITH_TRACING_V2", - "LANGSMITH_PROJECT", - "LANGSMITH_SESSION", - ]; - for (const [key, value] of Object.entries(allEnvVars)) { - if ((key.startsWith("LANGCHAIN_") || key.startsWith("LANGSMITH_")) && - typeof value === "string" && - !excluded.includes(key) && - !key.toLowerCase().includes("key") && - !key.toLowerCase().includes("secret") && - !key.toLowerCase().includes("token")) { - if (key === "LANGCHAIN_REVISION_ID") { - envVars["revision_id"] = value; + else { + queue = getQueue(); + void queue.add(async () => { + const asyncLocalStorageInstance = globals_getGlobalAsyncLocalStorageInstance(); + if (asyncLocalStorageInstance !== undefined) { + await asyncLocalStorageInstance.run(undefined, async () => promiseFn()); } else { - envVars[key] = value; + await promiseFn(); } - } + }); } - return envVars; } /** - * Retrieves the environment variables from the current runtime environment. + * Waits for all promises in the queue to resolve. If the queue is + * undefined, it immediately resolves a promise. + */ +async function awaitAllCallbacks() { + const defaultClient = getDefaultLangChainClientSingleton(); + await Promise.allSettled([ + typeof queue !== "undefined" ? queue.onIdle() : Promise.resolve(), + defaultClient.awaitPendingTraceBatches(), + ]); +} + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/callbacks/promises.js + + + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/callbacks.js + +const callbacks_isTracingEnabled = (tracingEnabled) => { + if (tracingEnabled !== undefined) { + return tracingEnabled; + } + const envVars = [ + "LANGSMITH_TRACING_V2", + "LANGCHAIN_TRACING_V2", + "LANGSMITH_TRACING", + "LANGCHAIN_TRACING", + ]; + return !!envVars.find((envVar) => env_getEnvironmentVariable(envVar) === "true"); +}; + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/singletons/async_local_storage/context.js + + +/** + * Set a context variable. Context variables are scoped to any + * child runnables called by the current runnable, or globally if set outside + * of any runnable. * - * This function is designed to operate in a variety of JS environments, - * including Node.js, Deno, browsers, etc. + * @remarks + * This function is only supported in environments that support AsyncLocalStorage, + * including Node.js, Deno, and Cloudflare Workers. * - * @returns {Record | undefined} - * - A record of environment variables if available. - * - `undefined` if the environment does not support or allows access to environment variables. + * @example + * ```ts + * import { RunnableLambda } from "@langchain/core/runnables"; + * import { + * getContextVariable, + * setContextVariable + * } from "@langchain/core/context"; + * + * const nested = RunnableLambda.from(() => { + * // "bar" because it was set by a parent + * console.log(getContextVariable("foo")); + * + * // Override to "baz", but only for child runnables + * setContextVariable("foo", "baz"); + * + * // Now "baz", but only for child runnables + * return getContextVariable("foo"); + * }); + * + * const runnable = RunnableLambda.from(async () => { + * // Set a context variable named "foo" + * setContextVariable("foo", "bar"); + * + * const res = await nested.invoke({}); + * + * // Still "bar" since child changes do not affect parents + * console.log(getContextVariable("foo")); + * + * return res; + * }); + * + * // undefined, because context variable has not been set yet + * console.log(getContextVariable("foo")); + * + * // Final return value is "baz" + * const result = await runnable.invoke({}); + * ``` + * + * @param name The name of the context variable. + * @param value The value to set. */ -function getEnvironmentVariables() { - try { - // Check for Node.js environment - // eslint-disable-next-line no-process-env - if (typeof process !== "undefined" && process.env) { - // eslint-disable-next-line no-process-env - return Object.entries(process.env).reduce((acc, [key, value]) => { - acc[key] = String(value); - return acc; - }, {}); - } - // For browsers and other environments, we may not have direct access to env variables - // Return undefined or any other fallback as required. - return undefined; +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function setContextVariable(name, value) { + // Avoid using global singleton due to circuluar dependency issues + const asyncLocalStorageInstance = getGlobalAsyncLocalStorageInstance(); + if (asyncLocalStorageInstance === undefined) { + throw new Error(`Internal error: Global shared async local storage instance has not been initialized.`); } - catch (e) { - // Catch any errors that might occur while trying to access environment variables - return undefined; + const runTree = asyncLocalStorageInstance.getStore(); + const contextVars = { ...runTree?.[_CONTEXT_VARIABLES_KEY] }; + contextVars[name] = value; + let newValue = {}; + if (isRunTree(runTree)) { + newValue = new RunTree(runTree); } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + newValue[_CONTEXT_VARIABLES_KEY] = contextVars; + asyncLocalStorageInstance.enterWith(newValue); } -function getEnvironmentVariable(name) { - // Certain Deno setups will throw an error if you try to access environment variables - // https://github.com/hwchase17/langchainjs/issues/1412 - try { - return typeof process !== "undefined" - ? // eslint-disable-next-line no-process-env - process.env?.[name] - : undefined; - } - catch (e) { +/** + * Get the value of a previously set context variable. Context variables + * are scoped to any child runnables called by the current runnable, + * or globally if set outside of any runnable. + * + * @remarks + * This function is only supported in environments that support AsyncLocalStorage, + * including Node.js, Deno, and Cloudflare Workers. + * + * @example + * ```ts + * import { RunnableLambda } from "@langchain/core/runnables"; + * import { + * getContextVariable, + * setContextVariable + * } from "@langchain/core/context"; + * + * const nested = RunnableLambda.from(() => { + * // "bar" because it was set by a parent + * console.log(getContextVariable("foo")); + * + * // Override to "baz", but only for child runnables + * setContextVariable("foo", "baz"); + * + * // Now "baz", but only for child runnables + * return getContextVariable("foo"); + * }); + * + * const runnable = RunnableLambda.from(async () => { + * // Set a context variable named "foo" + * setContextVariable("foo", "bar"); + * + * const res = await nested.invoke({}); + * + * // Still "bar" since child changes do not affect parents + * console.log(getContextVariable("foo")); + * + * return res; + * }); + * + * // undefined, because context variable has not been set yet + * console.log(getContextVariable("foo")); + * + * // Final return value is "baz" + * const result = await runnable.invoke({}); + * ``` + * + * @param name The name of the context variable. + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function getContextVariable(name) { + // Avoid using global singleton due to circuluar dependency issues + const asyncLocalStorageInstance = globals_getGlobalAsyncLocalStorageInstance(); + if (asyncLocalStorageInstance === undefined) { return undefined; } + const runTree = asyncLocalStorageInstance.getStore(); + return runTree?.[globals_CONTEXT_VARIABLES_KEY]?.[name]; } -function getLangSmithEnvironmentVariable(name) { - return (getEnvironmentVariable(`LANGSMITH_${name}`) || - getEnvironmentVariable(`LANGCHAIN_${name}`)); -} -function setEnvironmentVariable(name, value) { - if (typeof process !== "undefined") { - // eslint-disable-next-line no-process-env - process.env[name] = value; - } -} -let cachedCommitSHAs; +const LC_CONFIGURE_HOOKS_KEY = Symbol("lc:configure_hooks"); +const _getConfigureHooks = () => getContextVariable(LC_CONFIGURE_HOOKS_KEY) || []; /** - * Get the Git commit SHA from common environment variables - * used by different CI/CD platforms. - * @returns {string | undefined} The Git commit SHA or undefined if not found. + * Register a callback configure hook to automatically add callback handlers to all runs. + * + * There are two ways to use this: + * + * 1. Using a context variable: + * - Set `contextVar` to specify the variable name + * - Use `setContextVariable()` to store your handler instance + * + * 2. Using an environment variable: + * - Set both `envVar` and `handlerClass` + * - The handler will be instantiated when the env var is set to "true". + * + * @example + * ```typescript + * // Method 1: Using context variable + * import { + * registerConfigureHook, + * setContextVariable + * } from "@langchain/core/context"; + * + * const tracer = new MyCallbackHandler(); + * registerConfigureHook({ + * contextVar: "my_tracer", + * }); + * setContextVariable("my_tracer", tracer); + * + * // ...run code here + * + * // Method 2: Using environment variable + * registerConfigureHook({ + * handlerClass: MyCallbackHandler, + * envVar: "MY_TRACER_ENABLED", + * }); + * process.env.MY_TRACER_ENABLED = "true"; + * + * // ...run code here + * ``` + * + * @param config Configuration object for the hook + * @param config.contextVar Name of the context variable containing the handler instance + * @param config.inheritable Whether child runs should inherit this handler + * @param config.handlerClass Optional callback handler class (required if using envVar) + * @param config.envVar Optional environment variable name to control handler activation */ -function getShas() { - if (cachedCommitSHAs !== undefined) { - return cachedCommitSHAs; - } - const common_release_envs = [ - "VERCEL_GIT_COMMIT_SHA", - "NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA", - "COMMIT_REF", - "RENDER_GIT_COMMIT", - "CI_COMMIT_SHA", - "CIRCLE_SHA1", - "CF_PAGES_COMMIT_SHA", - "REACT_APP_GIT_SHA", - "SOURCE_VERSION", - "GITHUB_SHA", - "TRAVIS_COMMIT", - "GIT_COMMIT", - "BUILD_VCS_NUMBER", - "bamboo_planRepository_revision", - "Build.SourceVersion", - "BITBUCKET_COMMIT", - "DRONE_COMMIT_SHA", - "SEMAPHORE_GIT_SHA", - "BUILDKITE_COMMIT", - ]; - const shas = {}; - for (const env of common_release_envs) { - const envVar = getEnvironmentVariable(env); - if (envVar !== undefined) { - shas[env] = envVar; - } - } - cachedCommitSHAs = shas; - return shas; -} - -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/env.js - -const isTracingEnabled = (tracingEnabled) => { - if (tracingEnabled !== undefined) { - return tracingEnabled; +const registerConfigureHook = (config) => { + if (config.envVar && !config.handlerClass) { + throw new Error("If envVar is set, handlerClass must also be set to a non-None value."); } - const envVars = ["TRACING_V2", "TRACING"]; - return !!envVars.find((envVar) => getLangSmithEnvironmentVariable(envVar) === "true"); + setContextVariable(LC_CONFIGURE_HOOKS_KEY, [..._getConfigureHooks(), config]); }; -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/singletons/constants.js -const _LC_CONTEXT_VARIABLES_KEY = Symbol.for("lc:context_variables"); +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/callbacks/manager.js -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/run_trees.js -function stripNonAlphanumeric(input) { - return input.replace(/[-:.]/g, ""); -} -function convertToDottedOrderFormat(epoch, runId, executionOrder = 1) { - // Date only has millisecond precision, so we use the microseconds to break - // possible ties, avoiding incorrect run order - const paddedOrder = executionOrder.toFixed(0).slice(0, 3).padStart(3, "0"); - return (stripNonAlphanumeric(`${new Date(epoch).toISOString().slice(0, -1)}${paddedOrder}Z`) + runId); -} -/** - * Baggage header information - */ -class Baggage { - constructor(metadata, tags, project_name) { - Object.defineProperty(this, "metadata", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "tags", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "project_name", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.metadata = metadata; - this.tags = tags; - this.project_name = project_name; - } - static fromHeader(value) { - const items = value.split(","); - let metadata = {}; - let tags = []; - let project_name; - for (const item of items) { - const [key, uriValue] = item.split("="); - const value = decodeURIComponent(uriValue); - if (key === "langsmith-metadata") { - metadata = JSON.parse(value); - } - else if (key === "langsmith-tags") { - tags = value.split(","); - } - else if (key === "langsmith-project") { - project_name = value; - } - } - return new Baggage(metadata, tags, project_name); + + + +function parseCallbackConfigArg(arg) { + if (!arg) { + return {}; } - toHeader() { - const items = []; - if (this.metadata && Object.keys(this.metadata).length > 0) { - items.push(`langsmith-metadata=${encodeURIComponent(JSON.stringify(this.metadata))}`); - } - if (this.tags && this.tags.length > 0) { - items.push(`langsmith-tags=${encodeURIComponent(this.tags.join(","))}`); - } - if (this.project_name) { - items.push(`langsmith-project=${encodeURIComponent(this.project_name)}`); - } - return items.join(","); + else if (Array.isArray(arg) || "name" in arg) { + return { callbacks: arg }; + } + else { + return arg; } } -class run_trees_RunTree { - constructor(originalConfig) { - Object.defineProperty(this, "id", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "run_type", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "project_name", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "parent_run", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "child_runs", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "start_time", { +/** + * Manage callbacks from different components of LangChain. + */ +class BaseCallbackManager { + setHandler(handler) { + return this.setHandlers([handler]); + } +} +/** + * Base class for run manager in LangChain. + */ +class BaseRunManager { + constructor(runId, handlers, inheritableHandlers, tags, inheritableTags, metadata, inheritableMetadata, _parentRunId) { + Object.defineProperty(this, "runId", { enumerable: true, configurable: true, writable: true, - value: void 0 + value: runId }); - Object.defineProperty(this, "end_time", { + Object.defineProperty(this, "handlers", { enumerable: true, configurable: true, writable: true, - value: void 0 + value: handlers }); - Object.defineProperty(this, "extra", { + Object.defineProperty(this, "inheritableHandlers", { enumerable: true, configurable: true, writable: true, - value: void 0 + value: inheritableHandlers }); Object.defineProperty(this, "tags", { enumerable: true, configurable: true, writable: true, - value: void 0 - }); - Object.defineProperty(this, "error", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 + value: tags }); - Object.defineProperty(this, "serialized", { + Object.defineProperty(this, "inheritableTags", { enumerable: true, configurable: true, writable: true, - value: void 0 + value: inheritableTags }); - Object.defineProperty(this, "inputs", { + Object.defineProperty(this, "metadata", { enumerable: true, configurable: true, writable: true, - value: void 0 + value: metadata }); - Object.defineProperty(this, "outputs", { + Object.defineProperty(this, "inheritableMetadata", { enumerable: true, configurable: true, writable: true, - value: void 0 + value: inheritableMetadata }); - Object.defineProperty(this, "reference_example_id", { + Object.defineProperty(this, "_parentRunId", { enumerable: true, configurable: true, writable: true, - value: void 0 + value: _parentRunId }); - Object.defineProperty(this, "client", { + } + get parentRunId() { + return this._parentRunId; + } + async handleText(text) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + try { + await handler.handleText?.(text, this.runId, this._parentRunId, this.tags); + } + catch (err) { + const logFunction = handler.raiseError + ? console.error + : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleText: ${err}`); + if (handler.raiseError) { + throw err; + } + } + }, handler.awaitHandlers))); + } + async handleCustomEvent(eventName, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + data, _runId, _tags, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + _metadata) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + try { + await handler.handleCustomEvent?.(eventName, data, this.runId, this.tags, this.metadata); + } + catch (err) { + const logFunction = handler.raiseError + ? console.error + : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleCustomEvent: ${err}`); + if (handler.raiseError) { + throw err; + } + } + }, handler.awaitHandlers))); + } +} +/** + * Manages callbacks for retriever runs. + */ +class CallbackManagerForRetrieverRun extends BaseRunManager { + getChild(tag) { + // eslint-disable-next-line @typescript-eslint/no-use-before-define + const manager = new CallbackManager(this.runId); + manager.setHandlers(this.inheritableHandlers); + manager.addTags(this.inheritableTags); + manager.addMetadata(this.inheritableMetadata); + if (tag) { + manager.addTags([tag], false); + } + return manager; + } + async handleRetrieverEnd(documents) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreRetriever) { + try { + await handler.handleRetrieverEnd?.(documents, this.runId, this._parentRunId, this.tags); + } + catch (err) { + const logFunction = handler.raiseError + ? console.error + : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleRetriever`); + if (handler.raiseError) { + throw err; + } + } + } + }, handler.awaitHandlers))); + } + async handleRetrieverError(err) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreRetriever) { + try { + await handler.handleRetrieverError?.(err, this.runId, this._parentRunId, this.tags); + } + catch (error) { + const logFunction = handler.raiseError + ? console.error + : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleRetrieverError: ${error}`); + if (handler.raiseError) { + throw err; + } + } + } + }, handler.awaitHandlers))); + } +} +class CallbackManagerForLLMRun extends BaseRunManager { + async handleLLMNewToken(token, idx, _runId, _parentRunId, _tags, fields) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreLLM) { + try { + await handler.handleLLMNewToken?.(token, idx ?? { prompt: 0, completion: 0 }, this.runId, this._parentRunId, this.tags, fields); + } + catch (err) { + const logFunction = handler.raiseError + ? console.error + : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleLLMNewToken: ${err}`); + if (handler.raiseError) { + throw err; + } + } + } + }, handler.awaitHandlers))); + } + async handleLLMError(err, _runId, _parentRunId, _tags, extraParams) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreLLM) { + try { + await handler.handleLLMError?.(err, this.runId, this._parentRunId, this.tags, extraParams); + } + catch (err) { + const logFunction = handler.raiseError + ? console.error + : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleLLMError: ${err}`); + if (handler.raiseError) { + throw err; + } + } + } + }, handler.awaitHandlers))); + } + async handleLLMEnd(output, _runId, _parentRunId, _tags, extraParams) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreLLM) { + try { + await handler.handleLLMEnd?.(output, this.runId, this._parentRunId, this.tags, extraParams); + } + catch (err) { + const logFunction = handler.raiseError + ? console.error + : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleLLMEnd: ${err}`); + if (handler.raiseError) { + throw err; + } + } + } + }, handler.awaitHandlers))); + } +} +class CallbackManagerForChainRun extends BaseRunManager { + getChild(tag) { + // eslint-disable-next-line @typescript-eslint/no-use-before-define + const manager = new CallbackManager(this.runId); + manager.setHandlers(this.inheritableHandlers); + manager.addTags(this.inheritableTags); + manager.addMetadata(this.inheritableMetadata); + if (tag) { + manager.addTags([tag], false); + } + return manager; + } + async handleChainError(err, _runId, _parentRunId, _tags, kwargs) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreChain) { + try { + await handler.handleChainError?.(err, this.runId, this._parentRunId, this.tags, kwargs); + } + catch (err) { + const logFunction = handler.raiseError + ? console.error + : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleChainError: ${err}`); + if (handler.raiseError) { + throw err; + } + } + } + }, handler.awaitHandlers))); + } + async handleChainEnd(output, _runId, _parentRunId, _tags, kwargs) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreChain) { + try { + await handler.handleChainEnd?.(output, this.runId, this._parentRunId, this.tags, kwargs); + } + catch (err) { + const logFunction = handler.raiseError + ? console.error + : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleChainEnd: ${err}`); + if (handler.raiseError) { + throw err; + } + } + } + }, handler.awaitHandlers))); + } + async handleAgentAction(action) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreAgent) { + try { + await handler.handleAgentAction?.(action, this.runId, this._parentRunId, this.tags); + } + catch (err) { + const logFunction = handler.raiseError + ? console.error + : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleAgentAction: ${err}`); + if (handler.raiseError) { + throw err; + } + } + } + }, handler.awaitHandlers))); + } + async handleAgentEnd(action) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreAgent) { + try { + await handler.handleAgentEnd?.(action, this.runId, this._parentRunId, this.tags); + } + catch (err) { + const logFunction = handler.raiseError + ? console.error + : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleAgentEnd: ${err}`); + if (handler.raiseError) { + throw err; + } + } + } + }, handler.awaitHandlers))); + } +} +class CallbackManagerForToolRun extends BaseRunManager { + getChild(tag) { + // eslint-disable-next-line @typescript-eslint/no-use-before-define + const manager = new CallbackManager(this.runId); + manager.setHandlers(this.inheritableHandlers); + manager.addTags(this.inheritableTags); + manager.addMetadata(this.inheritableMetadata); + if (tag) { + manager.addTags([tag], false); + } + return manager; + } + async handleToolError(err) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreAgent) { + try { + await handler.handleToolError?.(err, this.runId, this._parentRunId, this.tags); + } + catch (err) { + const logFunction = handler.raiseError + ? console.error + : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleToolError: ${err}`); + if (handler.raiseError) { + throw err; + } + } + } + }, handler.awaitHandlers))); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + async handleToolEnd(output) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreAgent) { + try { + await handler.handleToolEnd?.(output, this.runId, this._parentRunId, this.tags); + } + catch (err) { + const logFunction = handler.raiseError + ? console.error + : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleToolEnd: ${err}`); + if (handler.raiseError) { + throw err; + } + } + } + }, handler.awaitHandlers))); + } +} +/** + * @example + * ```typescript + * const prompt = PromptTemplate.fromTemplate("What is the answer to {question}?"); + * + * // Example of using LLMChain with OpenAI and a simple prompt + * const chain = new LLMChain({ + * llm: new ChatOpenAI({ model: "gpt-4o-mini", temperature: 0.9 }), + * prompt, + * }); + * + * // Running the chain with a single question + * const result = await chain.call({ + * question: "What is the airspeed velocity of an unladen swallow?", + * }); + * console.log("The answer is:", result); + * ``` + */ +class CallbackManager extends BaseCallbackManager { + constructor(parentRunId, options) { + super(); + Object.defineProperty(this, "handlers", { enumerable: true, configurable: true, writable: true, - value: void 0 + value: [] }); - Object.defineProperty(this, "events", { + Object.defineProperty(this, "inheritableHandlers", { enumerable: true, configurable: true, writable: true, - value: void 0 + value: [] }); - Object.defineProperty(this, "trace_id", { + Object.defineProperty(this, "tags", { enumerable: true, configurable: true, writable: true, - value: void 0 + value: [] }); - Object.defineProperty(this, "dotted_order", { + Object.defineProperty(this, "inheritableTags", { enumerable: true, configurable: true, writable: true, - value: void 0 + value: [] }); - Object.defineProperty(this, "tracingEnabled", { + Object.defineProperty(this, "metadata", { enumerable: true, configurable: true, writable: true, - value: void 0 + value: {} }); - Object.defineProperty(this, "execution_order", { + Object.defineProperty(this, "inheritableMetadata", { enumerable: true, configurable: true, writable: true, - value: void 0 + value: {} }); - Object.defineProperty(this, "child_execution_order", { + Object.defineProperty(this, "name", { enumerable: true, configurable: true, writable: true, - value: void 0 + value: "callback_manager" }); - /** - * Attachments associated with the run. - * Each entry is a tuple of [mime_type, bytes] - */ - Object.defineProperty(this, "attachments", { + Object.defineProperty(this, "_parentRunId", { enumerable: true, configurable: true, writable: true, value: void 0 }); - // If you pass in a run tree directly, return a shallow clone - if (run_trees_isRunTree(originalConfig)) { - Object.assign(this, { ...originalConfig }); - return; - } - const defaultConfig = run_trees_RunTree.getDefaultConfig(); - const { metadata, ...config } = originalConfig; - const client = config.client ?? run_trees_RunTree.getSharedClient(); - const dedupedMetadata = { - ...metadata, - ...config?.extra?.metadata, - }; - config.extra = { ...config.extra, metadata: dedupedMetadata }; - Object.assign(this, { ...defaultConfig, ...config, client }); - if (!this.trace_id) { - if (this.parent_run) { - this.trace_id = this.parent_run.trace_id ?? this.id; + this.handlers = options?.handlers ?? this.handlers; + this.inheritableHandlers = + options?.inheritableHandlers ?? this.inheritableHandlers; + this.tags = options?.tags ?? this.tags; + this.inheritableTags = options?.inheritableTags ?? this.inheritableTags; + this.metadata = options?.metadata ?? this.metadata; + this.inheritableMetadata = + options?.inheritableMetadata ?? this.inheritableMetadata; + this._parentRunId = parentRunId; + } + /** + * Gets the parent run ID, if any. + * + * @returns The parent run ID. + */ + getParentRunId() { + return this._parentRunId; + } + async handleLLMStart(llm, prompts, runId = undefined, _parentRunId = undefined, extraParams = undefined, _tags = undefined, _metadata = undefined, runName = undefined) { + return Promise.all(prompts.map(async (prompt, idx) => { + // Can't have duplicate runs with the same run ID (if provided) + const runId_ = idx === 0 && runId ? runId : v4(); + await Promise.all(this.handlers.map((handler) => { + if (handler.ignoreLLM) { + return; + } + if (isBaseTracer(handler)) { + // Create and add run to the run map. + // We do this synchronously to avoid race conditions + // when callbacks are backgrounded. + handler._createRunForLLMStart(llm, [prompt], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName); + } + return consumeCallback(async () => { + try { + await handler.handleLLMStart?.(llm, [prompt], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName); + } + catch (err) { + const logFunction = handler.raiseError + ? console.error + : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleLLMStart: ${err}`); + if (handler.raiseError) { + throw err; + } + } + }, handler.awaitHandlers); + })); + return new CallbackManagerForLLMRun(runId_, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); + })); + } + async handleChatModelStart(llm, messages, runId = undefined, _parentRunId = undefined, extraParams = undefined, _tags = undefined, _metadata = undefined, runName = undefined) { + return Promise.all(messages.map(async (messageGroup, idx) => { + // Can't have duplicate runs with the same run ID (if provided) + const runId_ = idx === 0 && runId ? runId : v4(); + await Promise.all(this.handlers.map((handler) => { + if (handler.ignoreLLM) { + return; + } + if (isBaseTracer(handler)) { + // Create and add run to the run map. + // We do this synchronously to avoid race conditions + // when callbacks are backgrounded. + handler._createRunForChatModelStart(llm, [messageGroup], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName); + } + return consumeCallback(async () => { + try { + if (handler.handleChatModelStart) { + await handler.handleChatModelStart?.(llm, [messageGroup], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName); + } + else if (handler.handleLLMStart) { + const messageString = getBufferString(messageGroup); + await handler.handleLLMStart?.(llm, [messageString], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName); + } + } + catch (err) { + const logFunction = handler.raiseError + ? console.error + : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleLLMStart: ${err}`); + if (handler.raiseError) { + throw err; + } + } + }, handler.awaitHandlers); + })); + return new CallbackManagerForLLMRun(runId_, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); + })); + } + async handleChainStart(chain, inputs, runId = v4(), runType = undefined, _tags = undefined, _metadata = undefined, runName = undefined) { + await Promise.all(this.handlers.map((handler) => { + if (handler.ignoreChain) { + return; } - else { - this.trace_id = this.id; + if (isBaseTracer(handler)) { + // Create and add run to the run map. + // We do this synchronously to avoid race conditions + // when callbacks are backgrounded. + handler._createRunForChainStart(chain, inputs, runId, this._parentRunId, this.tags, this.metadata, runType, runName); } - } - this.execution_order ??= 1; - this.child_execution_order ??= 1; - if (!this.dotted_order) { - const currentDottedOrder = convertToDottedOrderFormat(this.start_time, this.id, this.execution_order); - if (this.parent_run) { - this.dotted_order = - this.parent_run.dotted_order + "." + currentDottedOrder; + return consumeCallback(async () => { + try { + await handler.handleChainStart?.(chain, inputs, runId, this._parentRunId, this.tags, this.metadata, runType, runName); + } + catch (err) { + const logFunction = handler.raiseError + ? console.error + : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleChainStart: ${err}`); + if (handler.raiseError) { + throw err; + } + } + }, handler.awaitHandlers); + })); + return new CallbackManagerForChainRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); + } + async handleToolStart(tool, input, runId = v4(), _parentRunId = undefined, _tags = undefined, _metadata = undefined, runName = undefined) { + await Promise.all(this.handlers.map((handler) => { + if (handler.ignoreAgent) { + return; } - else { - this.dotted_order = currentDottedOrder; + if (isBaseTracer(handler)) { + // Create and add run to the run map. + // We do this synchronously to avoid race conditions + // when callbacks are backgrounded. + handler._createRunForToolStart(tool, input, runId, this._parentRunId, this.tags, this.metadata, runName); } - } - } - static getDefaultConfig() { - return { - id: v4(), - run_type: "chain", - project_name: getLangSmithEnvironmentVariable("PROJECT") ?? - getEnvironmentVariable("LANGCHAIN_SESSION") ?? // TODO: Deprecate - "default", - child_runs: [], - api_url: getEnvironmentVariable("LANGCHAIN_ENDPOINT") ?? "http://localhost:1984", - api_key: getEnvironmentVariable("LANGCHAIN_API_KEY"), - caller_options: {}, - start_time: Date.now(), - serialized: {}, - inputs: {}, - extra: {}, - }; - } - static getSharedClient() { - if (!run_trees_RunTree.sharedClient) { - run_trees_RunTree.sharedClient = new Client(); - } - return run_trees_RunTree.sharedClient; + return consumeCallback(async () => { + try { + await handler.handleToolStart?.(tool, input, runId, this._parentRunId, this.tags, this.metadata, runName); + } + catch (err) { + const logFunction = handler.raiseError + ? console.error + : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleToolStart: ${err}`); + if (handler.raiseError) { + throw err; + } + } + }, handler.awaitHandlers); + })); + return new CallbackManagerForToolRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); } - createChild(config) { - const child_execution_order = this.child_execution_order + 1; - const child = new run_trees_RunTree({ - ...config, - parent_run: this, - project_name: this.project_name, - client: this.client, - tracingEnabled: this.tracingEnabled, - execution_order: child_execution_order, - child_execution_order: child_execution_order, - }); - // Copy context vars over into the new run tree. - if (_LC_CONTEXT_VARIABLES_KEY in this) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - child[_LC_CONTEXT_VARIABLES_KEY] = - this[_LC_CONTEXT_VARIABLES_KEY]; - } - const LC_CHILD = Symbol.for("lc:child_config"); - const presentConfig = config.extra?.[LC_CHILD] ?? - this.extra[LC_CHILD]; - // tracing for LangChain is defined by the _parentRunId and runMap of the tracer - if (isRunnableConfigLike(presentConfig)) { - const newConfig = { ...presentConfig }; - const callbacks = isCallbackManagerLike(newConfig.callbacks) - ? newConfig.callbacks.copy?.() - : undefined; - if (callbacks) { - // update the parent run id - Object.assign(callbacks, { _parentRunId: child.id }); - // only populate if we're in a newer LC.JS version - callbacks.handlers - ?.find(isLangChainTracerLike) - ?.updateFromRunTree?.(child); - newConfig.callbacks = callbacks; + async handleRetrieverStart(retriever, query, runId = v4(), _parentRunId = undefined, _tags = undefined, _metadata = undefined, runName = undefined) { + await Promise.all(this.handlers.map((handler) => { + if (handler.ignoreRetriever) { + return; } - child.extra[LC_CHILD] = newConfig; - } - // propagate child_execution_order upwards - const visited = new Set(); - let current = this; - while (current != null && !visited.has(current.id)) { - visited.add(current.id); - current.child_execution_order = Math.max(current.child_execution_order, child_execution_order); - current = current.parent_run; - } - this.child_runs.push(child); - return child; - } - async end(outputs, error, endTime = Date.now(), metadata) { - this.outputs = this.outputs ?? outputs; - this.error = this.error ?? error; - this.end_time = this.end_time ?? endTime; - if (metadata && Object.keys(metadata).length > 0) { - this.extra = this.extra - ? { ...this.extra, metadata: { ...this.extra.metadata, ...metadata } } - : { metadata }; - } - } - _convertToCreate(run, runtimeEnv, excludeChildRuns = true) { - const runExtra = run.extra ?? {}; - if (!runExtra.runtime) { - runExtra.runtime = {}; - } - if (runtimeEnv) { - for (const [k, v] of Object.entries(runtimeEnv)) { - if (!runExtra.runtime[k]) { - runExtra.runtime[k] = v; - } + if (isBaseTracer(handler)) { + // Create and add run to the run map. + // We do this synchronously to avoid race conditions + // when callbacks are backgrounded. + handler._createRunForRetrieverStart(retriever, query, runId, this._parentRunId, this.tags, this.metadata, runName); } - } - let child_runs; - let parent_run_id; - if (!excludeChildRuns) { - child_runs = run.child_runs.map((child_run) => this._convertToCreate(child_run, runtimeEnv, excludeChildRuns)); - parent_run_id = undefined; - } - else { - parent_run_id = run.parent_run?.id; - child_runs = []; - } - const persistedRun = { - id: run.id, - name: run.name, - start_time: run.start_time, - end_time: run.end_time, - run_type: run.run_type, - reference_example_id: run.reference_example_id, - extra: runExtra, - serialized: run.serialized, - error: run.error, - inputs: run.inputs, - outputs: run.outputs, - session_name: run.project_name, - child_runs: child_runs, - parent_run_id: parent_run_id, - trace_id: run.trace_id, - dotted_order: run.dotted_order, - tags: run.tags, - attachments: run.attachments, - }; - return persistedRun; + return consumeCallback(async () => { + try { + await handler.handleRetrieverStart?.(retriever, query, runId, this._parentRunId, this.tags, this.metadata, runName); + } + catch (err) { + const logFunction = handler.raiseError + ? console.error + : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleRetrieverStart: ${err}`); + if (handler.raiseError) { + throw err; + } + } + }, handler.awaitHandlers); + })); + return new CallbackManagerForRetrieverRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); } - async postRun(excludeChildRuns = true) { - try { - const runtimeEnv = getRuntimeEnvironment(); - const runCreate = await this._convertToCreate(this, runtimeEnv, true); - await this.client.createRun(runCreate); - if (!excludeChildRuns) { - warnOnce("Posting with excludeChildRuns=false is deprecated and will be removed in a future version."); - for (const childRun of this.child_runs) { - await childRun.postRun(false); + async handleCustomEvent(eventName, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + data, runId, _tags, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + _metadata) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreCustomEvent) { + try { + await handler.handleCustomEvent?.(eventName, data, runId, this.tags, this.metadata); + } + catch (err) { + const logFunction = handler.raiseError + ? console.error + : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleCustomEvent: ${err}`); + if (handler.raiseError) { + throw err; + } } } - } - catch (error) { - console.error(`Error in postRun for run ${this.id}:`, error); - } + }, handler.awaitHandlers))); } - async patchRun() { - try { - const runUpdate = { - end_time: this.end_time, - error: this.error, - inputs: this.inputs, - outputs: this.outputs, - parent_run_id: this.parent_run?.id, - reference_example_id: this.reference_example_id, - extra: this.extra, - events: this.events, - dotted_order: this.dotted_order, - trace_id: this.trace_id, - tags: this.tags, - attachments: this.attachments, - session_name: this.project_name, - }; - await this.client.updateRun(this.id, runUpdate); - } - catch (error) { - console.error(`Error in patchRun for run ${this.id}`, error); + addHandler(handler, inherit = true) { + this.handlers.push(handler); + if (inherit) { + this.inheritableHandlers.push(handler); } } - toJSON() { - return this._convertToCreate(this, undefined, false); + removeHandler(handler) { + this.handlers = this.handlers.filter((_handler) => _handler !== handler); + this.inheritableHandlers = this.inheritableHandlers.filter((_handler) => _handler !== handler); } - /** - * Add an event to the run tree. - * @param event - A single event or string to add - */ - addEvent(event) { - if (!this.events) { - this.events = []; - } - if (typeof event === "string") { - this.events.push({ - name: "event", - time: new Date().toISOString(), - message: event, - }); - } - else { - this.events.push({ - ...event, - time: event.time ?? new Date().toISOString(), - }); + setHandlers(handlers, inherit = true) { + this.handlers = []; + this.inheritableHandlers = []; + for (const handler of handlers) { + this.addHandler(handler, inherit); } } - static fromRunnableConfig(parentConfig, props) { - // We only handle the callback manager case for now - const callbackManager = parentConfig?.callbacks; - let parentRun; - let projectName; - let client; - let tracingEnabled = isTracingEnabled(); - if (callbackManager) { - const parentRunId = callbackManager?.getParentRunId?.() ?? ""; - const langChainTracer = callbackManager?.handlers?.find((handler) => handler?.name == "langchain_tracer"); - parentRun = langChainTracer?.getRun?.(parentRunId); - projectName = langChainTracer?.projectName; - client = langChainTracer?.client; - tracingEnabled = tracingEnabled || !!langChainTracer; - } - if (!parentRun) { - return new run_trees_RunTree({ - ...props, - client, - tracingEnabled, - project_name: projectName, - }); + addTags(tags, inherit = true) { + this.removeTags(tags); // Remove duplicates + this.tags.push(...tags); + if (inherit) { + this.inheritableTags.push(...tags); } - const parentRunTree = new run_trees_RunTree({ - name: parentRun.name, - id: parentRun.id, - trace_id: parentRun.trace_id, - dotted_order: parentRun.dotted_order, - client, - tracingEnabled, - project_name: projectName, - tags: [ - ...new Set((parentRun?.tags ?? []).concat(parentConfig?.tags ?? [])), - ], - extra: { - metadata: { - ...parentRun?.extra?.metadata, - ...parentConfig?.metadata, - }, - }, - }); - return parentRunTree.createChild(props); - } - static fromDottedOrder(dottedOrder) { - return this.fromHeaders({ "langsmith-trace": dottedOrder }); } - static fromHeaders(headers, inheritArgs) { - const rawHeaders = "get" in headers && typeof headers.get === "function" - ? { - "langsmith-trace": headers.get("langsmith-trace"), - baggage: headers.get("baggage"), - } - : headers; - const headerTrace = rawHeaders["langsmith-trace"]; - if (!headerTrace || typeof headerTrace !== "string") - return undefined; - const parentDottedOrder = headerTrace.trim(); - const parsedDottedOrder = parentDottedOrder.split(".").map((part) => { - const [strTime, uuid] = part.split("Z"); - return { strTime, time: Date.parse(strTime + "Z"), uuid }; - }); - const traceId = parsedDottedOrder[0].uuid; - const config = { - ...inheritArgs, - name: inheritArgs?.["name"] ?? "parent", - run_type: inheritArgs?.["run_type"] ?? "chain", - start_time: inheritArgs?.["start_time"] ?? Date.now(), - id: parsedDottedOrder.at(-1)?.uuid, - trace_id: traceId, - dotted_order: parentDottedOrder, - }; - if (rawHeaders["baggage"] && typeof rawHeaders["baggage"] === "string") { - const baggage = Baggage.fromHeader(rawHeaders["baggage"]); - config.metadata = baggage.metadata; - config.tags = baggage.tags; - config.project_name = baggage.project_name; - } - return new run_trees_RunTree(config); + removeTags(tags) { + this.tags = this.tags.filter((tag) => !tags.includes(tag)); + this.inheritableTags = this.inheritableTags.filter((tag) => !tags.includes(tag)); } - toHeaders(headers) { - const result = { - "langsmith-trace": this.dotted_order, - baggage: new Baggage(this.extra?.metadata, this.tags, this.project_name).toHeader(), - }; - if (headers) { - for (const [key, value] of Object.entries(result)) { - headers.set(key, value); - } + addMetadata(metadata, inherit = true) { + this.metadata = { ...this.metadata, ...metadata }; + if (inherit) { + this.inheritableMetadata = { ...this.inheritableMetadata, ...metadata }; } - return result; - } -} -Object.defineProperty(run_trees_RunTree, "sharedClient", { - enumerable: true, - configurable: true, - writable: true, - value: null -}); -function run_trees_isRunTree(x) { - return (x !== undefined && - typeof x.createChild === "function" && - typeof x.postRun === "function"); -} -function isLangChainTracerLike(x) { - return (typeof x === "object" && - x != null && - typeof x.name === "string" && - x.name === "langchain_tracer"); -} -function containsLangChainTracerLike(x) { - return (Array.isArray(x) && x.some((callback) => isLangChainTracerLike(callback))); -} -function isCallbackManagerLike(x) { - return (typeof x === "object" && - x != null && - Array.isArray(x.handlers)); -} -function isRunnableConfigLike(x) { - // Check that it's an object with a callbacks arg - // that has either a CallbackManagerLike object with a langchain tracer within it - // or an array with a LangChainTracerLike object within it - return (x !== undefined && - typeof x.callbacks === "object" && - // Callback manager with a langchain tracer - (containsLangChainTracerLike(x.callbacks?.handlers) || - // Or it's an array with a LangChainTracerLike object within it - containsLangChainTracerLike(x.callbacks))); -} - -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/singletons/traceable.js - -class MockAsyncLocalStorage { - getStore() { - return undefined; - } - run(_, callback) { - return callback(); - } -} -const TRACING_ALS_KEY = Symbol.for("ls:tracing_async_local_storage"); -const mockAsyncLocalStorage = new MockAsyncLocalStorage(); -class AsyncLocalStorageProvider { - getInstance() { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - return globalThis[TRACING_ALS_KEY] ?? mockAsyncLocalStorage; } - initializeGlobalInstance(instance) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - if (globalThis[TRACING_ALS_KEY] === undefined) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - globalThis[TRACING_ALS_KEY] = instance; + removeMetadata(metadata) { + for (const key of Object.keys(metadata)) { + delete this.metadata[key]; + delete this.inheritableMetadata[key]; } } -} -const AsyncLocalStorageProviderSingleton = new AsyncLocalStorageProvider(); -/** - * Return the current run tree from within a traceable-wrapped function. - * Will throw an error if called outside of a traceable function. - * - * @returns The run tree for the given context. - */ -const getCurrentRunTree = () => { - const runTree = AsyncLocalStorageProviderSingleton.getInstance().getStore(); - if (!run_trees_isRunTree(runTree)) { - throw new Error([ - "Could not get the current run tree.", - "", - "Please make sure you are calling this method within a traceable function and that tracing is enabled.", - ].join("\n")); - } - return runTree; -}; -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function withRunTree(runTree, fn) { - const storage = AsyncLocalStorageProviderSingleton.getInstance(); - return new Promise((resolve, reject) => { - storage.run(runTree, () => void Promise.resolve(fn()).then(resolve).catch(reject)); - }); -} -const ROOT = Symbol.for("langsmith:traceable:root"); -function isTraceableFunction(x -// eslint-disable-next-line @typescript-eslint/no-explicit-any -) { - return typeof x === "function" && "langsmith:traceable" in x; -} - -;// CONCATENATED MODULE: ./node_modules/langsmith/singletons/traceable.js - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/fast-json-patch/src/helpers.js -// @ts-nocheck -// Inlined because of ESM import issues -/*! - * https://github.com/Starcounter-Jack/JSON-Patch - * (c) 2017-2022 Joachim Wester - * MIT licensed - */ -const _hasOwnProperty = Object.prototype.hasOwnProperty; -function helpers_hasOwnProperty(obj, key) { - return _hasOwnProperty.call(obj, key); -} -function _objectKeys(obj) { - if (Array.isArray(obj)) { - const keys = new Array(obj.length); - for (let k = 0; k < keys.length; k++) { - keys[k] = "" + k; + copy(additionalHandlers = [], inherit = true) { + const manager = new CallbackManager(this._parentRunId); + for (const handler of this.handlers) { + const inheritable = this.inheritableHandlers.includes(handler); + manager.addHandler(handler, inheritable); } - return keys; - } - if (Object.keys) { - return Object.keys(obj); + for (const tag of this.tags) { + const inheritable = this.inheritableTags.includes(tag); + manager.addTags([tag], inheritable); + } + for (const key of Object.keys(this.metadata)) { + const inheritable = Object.keys(this.inheritableMetadata).includes(key); + manager.addMetadata({ [key]: this.metadata[key] }, inheritable); + } + for (const handler of additionalHandlers) { + if ( + // Prevent multiple copies of console_callback_handler + manager.handlers + .filter((h) => h.name === "console_callback_handler") + .some((h) => h.name === handler.name)) { + continue; + } + manager.addHandler(handler, inherit); + } + return manager; } - let keys = []; - for (let i in obj) { - if (helpers_hasOwnProperty(obj, i)) { - keys.push(i); + static fromHandlers(handlers) { + class Handler extends BaseCallbackHandler { + constructor() { + super(); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: v4() + }); + Object.assign(this, handlers); + } } + const manager = new this(); + manager.addHandler(new Handler()); + return manager; } - return keys; -} -/** - * Deeply clone the object. - * https://jsperf.com/deep-copy-vs-json-stringify-json-parse/25 (recursiveDeepCopy) - * @param {any} obj value to clone - * @return {any} cloned obj - */ -function helpers_deepClone(obj) { - switch (typeof obj) { - case "object": - return JSON.parse(JSON.stringify(obj)); //Faster than ES5 clone - http://jsperf.com/deep-cloning-of-objects/5 - case "undefined": - return null; //this is how JSON.stringify behaves for array items - default: - return obj; //no need to clone primitives + static configure(inheritableHandlers, localHandlers, inheritableTags, localTags, inheritableMetadata, localMetadata, options) { + return this._configureSync(inheritableHandlers, localHandlers, inheritableTags, localTags, inheritableMetadata, localMetadata, options); } -} -//3x faster than cached /^\d+$/.test(str) -function isInteger(str) { - let i = 0; - const len = str.length; - let charCode; - while (i < len) { - charCode = str.charCodeAt(i); - if (charCode >= 48 && charCode <= 57) { - i++; - continue; + // TODO: Deprecate async method in favor of this one. + static _configureSync(inheritableHandlers, localHandlers, inheritableTags, localTags, inheritableMetadata, localMetadata, options) { + let callbackManager; + if (inheritableHandlers || localHandlers) { + if (Array.isArray(inheritableHandlers) || !inheritableHandlers) { + callbackManager = new CallbackManager(); + callbackManager.setHandlers(inheritableHandlers?.map(ensureHandler) ?? [], true); + } + else { + callbackManager = inheritableHandlers; + } + callbackManager = callbackManager.copy(Array.isArray(localHandlers) + ? localHandlers.map(ensureHandler) + : localHandlers?.handlers, false); } - return false; - } - return true; -} -/** - * Escapes a json pointer path - * @param path The raw pointer - * @return the Escaped path - */ -function escapePathComponent(path) { - if (path.indexOf("/") === -1 && path.indexOf("~") === -1) - return path; - return path.replace(/~/g, "~0").replace(/\//g, "~1"); -} -/** - * Unescapes a json pointer path - * @param path The escaped pointer - * @return The unescaped path - */ -function unescapePathComponent(path) { - return path.replace(/~1/g, "/").replace(/~0/g, "~"); -} -function _getPathRecursive(root, obj) { - let found; - for (let key in root) { - if (helpers_hasOwnProperty(root, key)) { - if (root[key] === obj) { - return escapePathComponent(key) + "/"; + const verboseEnabled = env_getEnvironmentVariable("LANGCHAIN_VERBOSE") === "true" || + options?.verbose; + const tracingV2Enabled = tracer_langchain_LangChainTracer.getTraceableRunTree()?.tracingEnabled || + callbacks_isTracingEnabled(); + const tracingEnabled = tracingV2Enabled || + (env_getEnvironmentVariable("LANGCHAIN_TRACING") ?? false); + if (verboseEnabled || tracingEnabled) { + if (!callbackManager) { + callbackManager = new CallbackManager(); } - else if (typeof root[key] === "object") { - found = _getPathRecursive(root[key], obj); - if (found != "") { - return escapePathComponent(key) + "/" + found; + if (verboseEnabled && + !callbackManager.handlers.some((handler) => handler.name === ConsoleCallbackHandler.prototype.name)) { + const consoleHandler = new ConsoleCallbackHandler(); + callbackManager.addHandler(consoleHandler, true); + } + if (tracingEnabled && + !callbackManager.handlers.some((handler) => handler.name === "langchain_tracer")) { + if (tracingV2Enabled) { + const tracerV2 = new tracer_langchain_LangChainTracer(); + callbackManager.addHandler(tracerV2, true); + // handoff between langchain and langsmith/traceable + // override the parent run ID + callbackManager._parentRunId = + tracer_langchain_LangChainTracer.getTraceableRunTree()?.id ?? + callbackManager._parentRunId; } } } - } - return ""; -} -function getPath(root, obj) { - if (root === obj) { - return "/"; - } - const path = _getPathRecursive(root, obj); - if (path === "") { - throw new Error("Object not found in root"); - } - return `/${path}`; -} -/** - * Recursively checks whether an object has any undefined values inside. - */ -function hasUndefined(obj) { - if (obj === undefined) { - return true; - } - if (obj) { - if (Array.isArray(obj)) { - for (let i = 0, len = obj.length; i < len; i++) { - if (hasUndefined(obj[i])) { - return true; + for (const { contextVar, inheritable = true, handlerClass, envVar, } of _getConfigureHooks()) { + const createIfNotInContext = envVar && env_getEnvironmentVariable(envVar) === "true" && handlerClass; + let handler; + const contextVarValue = contextVar !== undefined ? getContextVariable(contextVar) : undefined; + if (contextVarValue && isBaseCallbackHandler(contextVarValue)) { + handler = contextVarValue; + } + else if (createIfNotInContext) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + handler = new handlerClass({}); + } + if (handler !== undefined) { + if (!callbackManager) { + callbackManager = new CallbackManager(); + } + if (!callbackManager.handlers.some((h) => h.name === handler.name)) { + callbackManager.addHandler(handler, inheritable); } } } - else if (typeof obj === "object") { - const objKeys = _objectKeys(obj); - const objKeysLength = objKeys.length; - for (var i = 0; i < objKeysLength; i++) { - if (hasUndefined(obj[objKeys[i]])) { - return true; - } + if (inheritableTags || localTags) { + if (callbackManager) { + callbackManager.addTags(inheritableTags ?? []); + callbackManager.addTags(localTags ?? [], false); + } + } + if (inheritableMetadata || localMetadata) { + if (callbackManager) { + callbackManager.addMetadata(inheritableMetadata ?? {}); + callbackManager.addMetadata(localMetadata ?? {}, false); } } + return callbackManager; } - return false; } -function patchErrorMessageFormatter(message, args) { - const messageParts = [message]; - for (const key in args) { - const value = typeof args[key] === "object" - ? JSON.stringify(args[key], null, 2) - : args[key]; // pretty print - if (typeof value !== "undefined") { - messageParts.push(`${key}: ${value}`); - } +function ensureHandler(handler) { + if ("name" in handler) { + return handler; } - return messageParts.join("\n"); + return BaseCallbackHandler.fromMethods(handler); } -class PatchError extends Error { - constructor(message, name, index, operation, tree) { - super(patchErrorMessageFormatter(message, { name, index, operation, tree })); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: name - }); - Object.defineProperty(this, "index", { +/** + * @deprecated Use [`traceable`](https://docs.smith.langchain.com/observability/how_to_guides/tracing/annotate_code) + * from "langsmith" instead. + */ +class TraceGroup { + constructor(groupName, options) { + Object.defineProperty(this, "groupName", { enumerable: true, configurable: true, writable: true, - value: index + value: groupName }); - Object.defineProperty(this, "operation", { + Object.defineProperty(this, "options", { enumerable: true, configurable: true, writable: true, - value: operation + value: options }); - Object.defineProperty(this, "tree", { + Object.defineProperty(this, "runManager", { enumerable: true, configurable: true, writable: true, - value: tree - }); - Object.setPrototypeOf(this, new.target.prototype); // restore prototype chain, see https://stackoverflow.com/a/48342359 - this.message = patchErrorMessageFormatter(message, { - name, - index, - operation, - tree, + value: void 0 }); } -} - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/fast-json-patch/src/core.js -// @ts-nocheck - -const JsonPatchError = PatchError; -const deepClone = helpers_deepClone; -/* We use a Javascript hash to store each - function. Each hash entry (property) uses - the operation identifiers specified in rfc6902. - In this way, we can map each patch operation - to its dedicated function in efficient way. - */ -/* The operations applicable to an object */ -const objOps = { - add: function (obj, key, document) { - obj[key] = this.value; - return { newDocument: document }; - }, - remove: function (obj, key, document) { - var removed = obj[key]; - delete obj[key]; - return { newDocument: document, removed }; - }, - replace: function (obj, key, document) { - var removed = obj[key]; - obj[key] = this.value; - return { newDocument: document, removed }; - }, - move: function (obj, key, document) { - /* in case move target overwrites an existing value, - return the removed value, this can be taxing performance-wise, - and is potentially unneeded */ - let removed = getValueByPointer(document, this.path); - if (removed) { - removed = helpers_deepClone(removed); - } - const originalValue = applyOperation(document, { - op: "remove", - path: this.from, - }).removed; - applyOperation(document, { - op: "add", - path: this.path, - value: originalValue, - }); - return { newDocument: document, removed }; - }, - copy: function (obj, key, document) { - const valueToCopy = getValueByPointer(document, this.from); - // enforce copy by value so further operations don't affect source (see issue #177) - applyOperation(document, { - op: "add", - path: this.path, - value: helpers_deepClone(valueToCopy), - }); - return { newDocument: document }; - }, - test: function (obj, key, document) { - return { newDocument: document, test: _areEquals(obj[key], this.value) }; - }, - _get: function (obj, key, document) { - this.value = obj[key]; - return { newDocument: document }; - }, -}; -/* The operations applicable to an array. Many are the same as for the object */ -var arrOps = { - add: function (arr, i, document) { - if (isInteger(i)) { - arr.splice(i, 0, this.value); - } - else { - // array props - arr[i] = this.value; + async getTraceGroupCallbackManager(group_name, inputs, options) { + const cb = new LangChainTracer(options); + const cm = await CallbackManager.configure([cb]); + const runManager = await cm?.handleChainStart({ + lc: 1, + type: "not_implemented", + id: ["langchain", "callbacks", "groups", group_name], + }, inputs ?? {}); + if (!runManager) { + throw new Error("Failed to create run group callback manager."); } - // this may be needed when using '-' in an array - return { newDocument: document, index: i }; - }, - remove: function (arr, i, document) { - var removedList = arr.splice(i, 1); - return { newDocument: document, removed: removedList[0] }; - }, - replace: function (arr, i, document) { - var removed = arr[i]; - arr[i] = this.value; - return { newDocument: document, removed }; - }, - move: objOps.move, - copy: objOps.copy, - test: objOps.test, - _get: objOps._get, -}; -/** - * Retrieves a value from a JSON document by a JSON pointer. - * Returns the value. - * - * @param document The document to get the value from - * @param pointer an escaped JSON pointer - * @return The retrieved value - */ -function getValueByPointer(document, pointer) { - if (pointer == "") { - return document; + return runManager; } - var getOriginalDestination = { op: "_get", path: pointer }; - applyOperation(document, getOriginalDestination); - return getOriginalDestination.value; -} -/** - * Apply a single JSON Patch Operation on a JSON document. - * Returns the {newDocument, result} of the operation. - * It modifies the `document` and `operation` objects - it gets the values by reference. - * If you would like to avoid touching your values, clone them: - * `jsonpatch.applyOperation(document, jsonpatch._deepClone(operation))`. - * - * @param document The document to patch - * @param operation The operation to apply - * @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. - * @param mutateDocument Whether to mutate the original document or clone it before applying - * @param banPrototypeModifications Whether to ban modifications to `__proto__`, defaults to `true`. - * @return `{newDocument, result}` after the operation - */ -function applyOperation(document, operation, validateOperation = false, mutateDocument = true, banPrototypeModifications = true, index = 0) { - if (validateOperation) { - if (typeof validateOperation == "function") { - validateOperation(operation, 0, document, operation.path); - } - else { - validator(operation, 0); + async start(inputs) { + if (!this.runManager) { + this.runManager = await this.getTraceGroupCallbackManager(this.groupName, inputs, this.options); } + return this.runManager.getChild(); } - /* ROOT OPERATIONS */ - if (operation.path === "") { - let returnValue = { newDocument: document }; - if (operation.op === "add") { - returnValue.newDocument = operation.value; - return returnValue; - } - else if (operation.op === "replace") { - returnValue.newDocument = operation.value; - returnValue.removed = document; //document we removed - return returnValue; - } - else if (operation.op === "move" || operation.op === "copy") { - // it's a move or copy to root - returnValue.newDocument = getValueByPointer(document, operation.from); // get the value by json-pointer in `from` field - if (operation.op === "move") { - // report removed item - returnValue.removed = document; - } - return returnValue; - } - else if (operation.op === "test") { - returnValue.test = _areEquals(document, operation.value); - if (returnValue.test === false) { - throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index, operation, document); - } - returnValue.newDocument = document; - return returnValue; + async error(err) { + if (this.runManager) { + await this.runManager.handleChainError(err); + this.runManager = undefined; } - else if (operation.op === "remove") { - // a remove on root - returnValue.removed = document; - returnValue.newDocument = null; - return returnValue; + } + async end(output) { + if (this.runManager) { + await this.runManager.handleChainEnd(output ?? {}); + this.runManager = undefined; } - else if (operation.op === "_get") { - operation.value = document; - return returnValue; + } +} +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function manager_coerceToDict(value, defaultKey) { + return value && !Array.isArray(value) && typeof value === "object" + ? value + : { [defaultKey]: value }; +} +// eslint-disable-next-line @typescript-eslint/no-explicit-any +async function traceAsGroup(groupOptions, enclosedCode, ...args) { + const traceGroup = new TraceGroup(groupOptions.name, groupOptions); + const callbackManager = await traceGroup.start({ ...args }); + try { + const result = await enclosedCode(callbackManager, ...args); + await traceGroup.end(manager_coerceToDict(result, "output")); + return result; + } + catch (err) { + await traceGroup.error(err); + throw err; + } +} + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/singletons/async_local_storage/index.js +/* eslint-disable @typescript-eslint/no-explicit-any */ + + + +class async_local_storage_MockAsyncLocalStorage { + getStore() { + return undefined; + } + run(_store, callback) { + return callback(); + } + enterWith(_store) { + return undefined; + } +} +const async_local_storage_mockAsyncLocalStorage = new async_local_storage_MockAsyncLocalStorage(); +const LC_CHILD_KEY = Symbol.for("lc:child_config"); +class async_local_storage_AsyncLocalStorageProvider { + getInstance() { + return globals_getGlobalAsyncLocalStorageInstance() ?? async_local_storage_mockAsyncLocalStorage; + } + getRunnableConfig() { + const storage = this.getInstance(); + // this has the runnable config + // which means that we should also have an instance of a LangChainTracer + // with the run map prepopulated + return storage.getStore()?.extra?.[LC_CHILD_KEY]; + } + runWithConfig(config, callback, avoidCreatingRootRunTree) { + const callbackManager = CallbackManager._configureSync(config?.callbacks, undefined, config?.tags, undefined, config?.metadata); + const storage = this.getInstance(); + const previousValue = storage.getStore(); + const parentRunId = callbackManager?.getParentRunId(); + const langChainTracer = callbackManager?.handlers?.find((handler) => handler?.name === "langchain_tracer"); + let runTree; + if (langChainTracer && parentRunId) { + runTree = langChainTracer.getRunTreeWithTracingConfig(parentRunId); } - else { - /* bad operation */ - if (validateOperation) { - throw new JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902", "OPERATION_OP_INVALID", index, operation, document); - } - else { - return returnValue; - } + else if (!avoidCreatingRootRunTree) { + runTree = new run_trees_RunTree({ + name: "", + tracingEnabled: false, + }); } - } /* END ROOT OPERATIONS */ - else { - if (!mutateDocument) { - document = helpers_deepClone(document); + if (runTree) { + runTree.extra = { ...runTree.extra, [LC_CHILD_KEY]: config }; } - const path = operation.path || ""; - const keys = path.split("/"); - let obj = document; - let t = 1; //skip empty element - http://jsperf.com/to-shift-or-not-to-shift - let len = keys.length; - let existingPathFragment = undefined; - let key; - let validateFunction; - if (typeof validateOperation == "function") { - validateFunction = validateOperation; + if (previousValue !== undefined && + previousValue[globals_CONTEXT_VARIABLES_KEY] !== undefined) { + if (runTree === undefined) { + runTree = {}; + } + runTree[globals_CONTEXT_VARIABLES_KEY] = + previousValue[globals_CONTEXT_VARIABLES_KEY]; } - else { - validateFunction = validator; + return storage.run(runTree, callback); + } + initializeGlobalInstance(instance) { + if (globals_getGlobalAsyncLocalStorageInstance() === undefined) { + setGlobalAsyncLocalStorageInstance(instance); } - while (true) { - key = keys[t]; - if (key && key.indexOf("~") != -1) { - key = unescapePathComponent(key); + } +} +const async_local_storage_AsyncLocalStorageProviderSingleton = new async_local_storage_AsyncLocalStorageProvider(); + + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/singletons/index.js + + + + + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/config.js + + +const DEFAULT_RECURSION_LIMIT = 25; +async function getCallbackManagerForConfig(config) { + return CallbackManager._configureSync(config?.callbacks, undefined, config?.tags, undefined, config?.metadata); +} +function mergeConfigs(...configs) { + // We do not want to call ensureConfig on the empty state here as this may cause + // double loading of callbacks if async local storage is being used. + const copy = {}; + for (const options of configs.filter((c) => !!c)) { + for (const key of Object.keys(options)) { + if (key === "metadata") { + copy[key] = { ...copy[key], ...options[key] }; } - if (banPrototypeModifications && - (key == "__proto__" || - (key == "prototype" && t > 0 && keys[t - 1] == "constructor"))) { - throw new TypeError("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"); + else if (key === "tags") { + const baseKeys = copy[key] ?? []; + copy[key] = [...new Set(baseKeys.concat(options[key] ?? []))]; } - if (validateOperation) { - if (existingPathFragment === undefined) { - if (obj[key] === undefined) { - existingPathFragment = keys.slice(0, t).join("/"); - } - else if (t == len - 1) { - existingPathFragment = operation.path; - } - if (existingPathFragment !== undefined) { - validateFunction(operation, 0, document, existingPathFragment); - } + else if (key === "configurable") { + copy[key] = { ...copy[key], ...options[key] }; + } + else if (key === "timeout") { + if (copy.timeout === undefined) { + copy.timeout = options.timeout; + } + else if (options.timeout !== undefined) { + copy.timeout = Math.min(copy.timeout, options.timeout); } } - t++; - if (Array.isArray(obj)) { - if (key === "-") { - key = obj.length; + else if (key === "signal") { + if (copy.signal === undefined) { + copy.signal = options.signal; } - else { - if (validateOperation && !isInteger(key)) { - throw new JsonPatchError("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index", "OPERATION_PATH_ILLEGAL_ARRAY_INDEX", index, operation, document); - } // only parse key when it's an integer for `arr.prop` to work - else if (isInteger(key)) { - key = ~~key; + else if (options.signal !== undefined) { + if ("any" in AbortSignal) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + copy.signal = AbortSignal.any([ + copy.signal, + options.signal, + ]); + } + else { + copy.signal = options.signal; } } - if (t >= len) { - if (validateOperation && operation.op === "add" && key > obj.length) { - throw new JsonPatchError("The specified index MUST NOT be greater than the number of elements in the array", "OPERATION_VALUE_OUT_OF_BOUNDS", index, operation, document); + } + else if (key === "callbacks") { + const baseCallbacks = copy.callbacks; + const providedCallbacks = options.callbacks; + // callbacks can be either undefined, Array or manager + // so merging two callbacks values has 6 cases + if (Array.isArray(providedCallbacks)) { + if (!baseCallbacks) { + copy.callbacks = providedCallbacks; } - const returnValue = arrOps[operation.op].call(operation, obj, key, document); // Apply patch - if (returnValue.test === false) { - throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index, operation, document); + else if (Array.isArray(baseCallbacks)) { + copy.callbacks = baseCallbacks.concat(providedCallbacks); + } + else { + // baseCallbacks is a manager + const manager = baseCallbacks.copy(); + for (const callback of providedCallbacks) { + manager.addHandler(ensureHandler(callback), true); + } + copy.callbacks = manager; } - return returnValue; } - } - else { - if (t >= len) { - const returnValue = objOps[operation.op].call(operation, obj, key, document); // Apply patch - if (returnValue.test === false) { - throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index, operation, document); + else if (providedCallbacks) { + // providedCallbacks is a manager + if (!baseCallbacks) { + copy.callbacks = providedCallbacks; + } + else if (Array.isArray(baseCallbacks)) { + const manager = providedCallbacks.copy(); + for (const callback of baseCallbacks) { + manager.addHandler(ensureHandler(callback), true); + } + copy.callbacks = manager; + } + else { + // baseCallbacks is also a manager + copy.callbacks = new CallbackManager(providedCallbacks._parentRunId, { + handlers: baseCallbacks.handlers.concat(providedCallbacks.handlers), + inheritableHandlers: baseCallbacks.inheritableHandlers.concat(providedCallbacks.inheritableHandlers), + tags: Array.from(new Set(baseCallbacks.tags.concat(providedCallbacks.tags))), + inheritableTags: Array.from(new Set(baseCallbacks.inheritableTags.concat(providedCallbacks.inheritableTags))), + metadata: { + ...baseCallbacks.metadata, + ...providedCallbacks.metadata, + }, + }); } - return returnValue; } } - obj = obj[key]; - // If we have more keys in the path, but the next value isn't a non-null object, - // throw an OPERATION_PATH_UNRESOLVABLE error instead of iterating again. - if (validateOperation && t < len && (!obj || typeof obj !== "object")) { - throw new JsonPatchError("Cannot perform operation at the desired path", "OPERATION_PATH_UNRESOLVABLE", index, operation, document); + else { + const typedKey = key; + copy[typedKey] = options[typedKey] ?? copy[typedKey]; } } } + return copy; } +const PRIMITIVES = new Set(["string", "number", "boolean"]); /** - * Apply a full JSON Patch array on a JSON document. - * Returns the {newDocument, result} of the patch. - * It modifies the `document` object and `patch` - it gets the values by reference. - * If you would like to avoid touching your values, clone them: - * `jsonpatch.applyPatch(document, jsonpatch._deepClone(patch))`. - * - * @param document The document to patch - * @param patch The patch to apply - * @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. - * @param mutateDocument Whether to mutate the original document or clone it before applying - * @param banPrototypeModifications Whether to ban modifications to `__proto__`, defaults to `true`. - * @return An array of `{newDocument, result}` after the patch + * Ensure that a passed config is an object with all required keys present. */ -function core_applyPatch(document, patch, validateOperation, mutateDocument = true, banPrototypeModifications = true) { - if (validateOperation) { - if (!Array.isArray(patch)) { - throw new JsonPatchError("Patch sequence must be an array", "SEQUENCE_NOT_AN_ARRAY"); - } +function ensureConfig(config) { + const implicitConfig = async_local_storage_AsyncLocalStorageProviderSingleton.getRunnableConfig(); + let empty = { + tags: [], + metadata: {}, + recursionLimit: 25, + runId: undefined, + }; + if (implicitConfig) { + // Don't allow runId and runName to be loaded implicitly, as this can cause + // child runs to improperly inherit their parents' run ids. + // eslint-disable-next-line @typescript-eslint/no-unused-vars + const { runId, runName, ...rest } = implicitConfig; + empty = Object.entries(rest).reduce( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (currentConfig, [key, value]) => { + if (value !== undefined) { + // eslint-disable-next-line no-param-reassign + currentConfig[key] = value; + } + return currentConfig; + }, empty); } - if (!mutateDocument) { - document = helpers_deepClone(document); + if (config) { + empty = Object.entries(config).reduce( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (currentConfig, [key, value]) => { + if (value !== undefined) { + // eslint-disable-next-line no-param-reassign + currentConfig[key] = value; + } + return currentConfig; + }, empty); } - const results = new Array(patch.length); - for (let i = 0, length = patch.length; i < length; i++) { - // we don't need to pass mutateDocument argument because if it was true, we already deep cloned the object, we'll just pass `true` - results[i] = applyOperation(document, patch[i], validateOperation, true, banPrototypeModifications, i); - document = results[i].newDocument; // in case root was replaced + if (empty?.configurable) { + for (const key of Object.keys(empty.configurable)) { + if (PRIMITIVES.has(typeof empty.configurable[key]) && + !empty.metadata?.[key]) { + if (!empty.metadata) { + empty.metadata = {}; + } + empty.metadata[key] = empty.configurable[key]; + } + } } - results.newDocument = document; - return results; -} -/** - * Apply a single JSON Patch Operation on a JSON document. - * Returns the updated document. - * Suitable as a reducer. - * - * @param document The document to patch - * @param operation The operation to apply - * @return The updated document - */ -function applyReducer(document, operation, index) { - const operationResult = applyOperation(document, operation); - if (operationResult.test === false) { - // failed test - throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index, operation, document); + if (empty.timeout !== undefined) { + if (empty.timeout <= 0) { + throw new Error("Timeout must be a positive number"); + } + const timeoutSignal = AbortSignal.timeout(empty.timeout); + if (empty.signal !== undefined) { + if ("any" in AbortSignal) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + empty.signal = AbortSignal.any([empty.signal, timeoutSignal]); + } + } + else { + empty.signal = timeoutSignal; + } + delete empty.timeout; } - return operationResult.newDocument; + return empty; } /** - * Validates a single operation. Called from `jsonpatch.validate`. Throws `JsonPatchError` in case of an error. - * @param {object} operation - operation object (patch) - * @param {number} index - index of operation in the sequence - * @param {object} [document] - object where the operation is supposed to be applied - * @param {string} [existingPathFragment] - comes along with `document` + * Helper function that patches runnable configs with updated properties. */ -function validator(operation, index, document, existingPathFragment) { - if (typeof operation !== "object" || - operation === null || - Array.isArray(operation)) { - throw new JsonPatchError("Operation is not an object", "OPERATION_NOT_AN_OBJECT", index, operation, document); +function patchConfig(config = {}, { callbacks, maxConcurrency, recursionLimit, runName, configurable, runId, } = {}) { + const newConfig = ensureConfig(config); + if (callbacks !== undefined) { + /** + * If we're replacing callbacks we need to unset runName + * since that should apply only to the same run as the original callbacks + */ + delete newConfig.runName; + newConfig.callbacks = callbacks; } - else if (!objOps[operation.op]) { - throw new JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902", "OPERATION_OP_INVALID", index, operation, document); + if (recursionLimit !== undefined) { + newConfig.recursionLimit = recursionLimit; } - else if (typeof operation.path !== "string") { - throw new JsonPatchError("Operation `path` property is not a string", "OPERATION_PATH_INVALID", index, operation, document); + if (maxConcurrency !== undefined) { + newConfig.maxConcurrency = maxConcurrency; } - else if (operation.path.indexOf("/") !== 0 && operation.path.length > 0) { - // paths that aren't empty string should start with "/" - throw new JsonPatchError('Operation `path` property must start with "/"', "OPERATION_PATH_INVALID", index, operation, document); + if (runName !== undefined) { + newConfig.runName = runName; } - else if ((operation.op === "move" || operation.op === "copy") && - typeof operation.from !== "string") { - throw new JsonPatchError("Operation `from` property is not present (applicable in `move` and `copy` operations)", "OPERATION_FROM_REQUIRED", index, operation, document); + if (configurable !== undefined) { + newConfig.configurable = { ...newConfig.configurable, ...configurable }; } - else if ((operation.op === "add" || - operation.op === "replace" || - operation.op === "test") && - operation.value === undefined) { - throw new JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)", "OPERATION_VALUE_REQUIRED", index, operation, document); + if (runId !== undefined) { + delete newConfig.runId; } - else if ((operation.op === "add" || - operation.op === "replace" || - operation.op === "test") && - hasUndefined(operation.value)) { - throw new JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)", "OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED", index, operation, document); + return newConfig; +} +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function pickRunnableConfigKeys(config) { + return config + ? { + configurable: config.configurable, + recursionLimit: config.recursionLimit, + callbacks: config.callbacks, + tags: config.tags, + metadata: config.metadata, + maxConcurrency: config.maxConcurrency, + timeout: config.timeout, + signal: config.signal, + } + : undefined; +} + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/signal.js +async function raceWithSignal(promise, signal) { + if (signal === undefined) { + return promise; } - else if (document) { - if (operation.op == "add") { - var pathLen = operation.path.split("/").length; - var existingPathLen = existingPathFragment.split("/").length; - if (pathLen !== existingPathLen + 1 && pathLen !== existingPathLen) { - throw new JsonPatchError("Cannot perform an `add` operation at the desired path", "OPERATION_PATH_CANNOT_ADD", index, operation, document); + let listener; + return Promise.race([ + promise.catch((err) => { + if (!signal?.aborted) { + throw err; + } + else { + return undefined; + } + }), + new Promise((_, reject) => { + listener = () => { + reject(new Error("Aborted")); + }; + signal.addEventListener("abort", listener); + // Must be here inside the promise to avoid a race condition + if (signal.aborted) { + reject(new Error("Aborted")); } + }), + ]).finally(() => signal.removeEventListener("abort", listener)); +} + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/stream.js + + + +/* + * Support async iterator syntax for ReadableStreams in all environments. + * Source: https://github.com/MattiasBuelens/web-streams-polyfill/pull/122#issuecomment-1627354490 + */ +class IterableReadableStream extends ReadableStream { + constructor() { + super(...arguments); + Object.defineProperty(this, "reader", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + } + ensureReader() { + if (!this.reader) { + this.reader = this.getReader(); } - else if (operation.op === "replace" || - operation.op === "remove" || - operation.op === "_get") { - if (operation.path !== existingPathFragment) { - throw new JsonPatchError("Cannot perform the operation at a path that does not exist", "OPERATION_PATH_UNRESOLVABLE", index, operation, document); + } + async next() { + this.ensureReader(); + try { + const result = await this.reader.read(); + if (result.done) { + this.reader.releaseLock(); // release lock when stream becomes closed + return { + done: true, + value: undefined, + }; + } + else { + return { + done: false, + value: result.value, + }; } } - else if (operation.op === "move" || operation.op === "copy") { - var existingValue = { - op: "_get", - path: operation.from, - value: undefined, - }; - var error = core_validate([existingValue], document); - if (error && error.name === "OPERATION_PATH_UNRESOLVABLE") { - throw new JsonPatchError("Cannot perform the operation from a path that does not exist", "OPERATION_FROM_UNRESOLVABLE", index, operation, document); + catch (e) { + this.reader.releaseLock(); // release lock when stream becomes errored + throw e; + } + } + async return() { + this.ensureReader(); + // If wrapped in a Node stream, cancel is already called. + if (this.locked) { + const cancelPromise = this.reader.cancel(); // cancel first, but don't await yet + this.reader.releaseLock(); // release lock first + await cancelPromise; // now await it + } + return { done: true, value: undefined }; + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + async throw(e) { + this.ensureReader(); + if (this.locked) { + const cancelPromise = this.reader.cancel(); // cancel first, but don't await yet + this.reader.releaseLock(); // release lock first + await cancelPromise; // now await it + } + throw e; + } + [Symbol.asyncIterator]() { + return this; + } + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore Not present in Node 18 types, required in latest Node 22 + async [Symbol.asyncDispose]() { + await this.return(); + } + static fromReadableStream(stream) { + // From https://developer.mozilla.org/en-US/docs/Web/API/Streams_API/Using_readable_streams#reading_the_stream + const reader = stream.getReader(); + return new IterableReadableStream({ + start(controller) { + return pump(); + function pump() { + return reader.read().then(({ done, value }) => { + // When no more data needs to be consumed, close the stream + if (done) { + controller.close(); + return; + } + // Enqueue the next data chunk into our target stream + controller.enqueue(value); + return pump(); + }); + } + }, + cancel() { + reader.releaseLock(); + }, + }); + } + static fromAsyncGenerator(generator) { + return new IterableReadableStream({ + async pull(controller) { + const { value, done } = await generator.next(); + // When no more data needs to be consumed, close the stream + if (done) { + controller.close(); + } + // Fix: `else if (value)` will hang the streaming when nullish value (e.g. empty string) is pulled + controller.enqueue(value); + }, + async cancel(reason) { + await generator.return(reason); + }, + }); + } +} +function atee(iter, length = 2) { + const buffers = Array.from({ length }, () => []); + return buffers.map(async function* makeIter(buffer) { + while (true) { + if (buffer.length === 0) { + const result = await iter.next(); + for (const buffer of buffers) { + buffer.push(result); + } } - } - } -} -/** - * Validates a sequence of operations. If `document` parameter is provided, the sequence is additionally validated against the object document. - * If error is encountered, returns a JsonPatchError object - * @param sequence - * @param document - * @returns {JsonPatchError|undefined} - */ -function core_validate(sequence, document, externalValidator) { - try { - if (!Array.isArray(sequence)) { - throw new JsonPatchError("Patch sequence must be an array", "SEQUENCE_NOT_AN_ARRAY"); - } - if (document) { - //clone document and sequence so that we can safely try applying operations - core_applyPatch(helpers_deepClone(document), helpers_deepClone(sequence), externalValidator || true); - } - else { - externalValidator = externalValidator || validator; - for (var i = 0; i < sequence.length; i++) { - externalValidator(sequence[i], i, document, undefined); + else if (buffer[0].done) { + return; + } + else { + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + yield buffer.shift().value; } } + }); +} +function concat(first, second) { + if (Array.isArray(first) && Array.isArray(second)) { + return first.concat(second); } - catch (e) { - if (e instanceof JsonPatchError) { - return e; - } - else { - throw e; - } + else if (typeof first === "string" && typeof second === "string") { + return (first + second); } -} -// based on https://github.com/epoberezkin/fast-deep-equal -// MIT License -// Copyright (c) 2017 Evgeny Poberezkin -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -// SOFTWARE. -function _areEquals(a, b) { - if (a === b) - return true; - if (a && b && typeof a == "object" && typeof b == "object") { - var arrA = Array.isArray(a), arrB = Array.isArray(b), i, length, key; - if (arrA && arrB) { - length = a.length; - if (length != b.length) - return false; - for (i = length; i-- !== 0;) - if (!_areEquals(a[i], b[i])) - return false; - return true; - } - if (arrA != arrB) - return false; - var keys = Object.keys(a); - length = keys.length; - if (length !== Object.keys(b).length) - return false; - for (i = length; i-- !== 0;) - if (!b.hasOwnProperty(keys[i])) - return false; - for (i = length; i-- !== 0;) { - key = keys[i]; - if (!_areEquals(a[key], b[key])) - return false; + else if (typeof first === "number" && typeof second === "number") { + return (first + second); + } + else if ( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + "concat" in first && + // eslint-disable-next-line @typescript-eslint/no-explicit-any + typeof first.concat === "function") { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return first.concat(second); + } + else if (typeof first === "object" && typeof second === "object") { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const chunk = { ...first }; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + for (const [key, value] of Object.entries(second)) { + if (key in chunk && !Array.isArray(chunk[key])) { + chunk[key] = concat(chunk[key], value); + } + else { + chunk[key] = value; + } } - return true; + return chunk; + } + else { + throw new Error(`Cannot concat ${typeof first} and ${typeof second}`); } - return a !== a && b !== b; } - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/fast-json-patch/src/duplex.js -// @ts-nocheck -// Inlined because of ESM import issues -/*! - * https://github.com/Starcounter-Jack/JSON-Patch - * (c) 2013-2021 Joachim Wester - * MIT license - */ - - -var beforeDict = new WeakMap(); -class Mirror { - constructor(obj) { - Object.defineProperty(this, "obj", { +class AsyncGeneratorWithSetup { + constructor(params) { + Object.defineProperty(this, "generator", { enumerable: true, configurable: true, writable: true, value: void 0 }); - Object.defineProperty(this, "observers", { + Object.defineProperty(this, "setup", { enumerable: true, configurable: true, writable: true, - value: new Map() + value: void 0 }); - Object.defineProperty(this, "value", { + Object.defineProperty(this, "config", { enumerable: true, configurable: true, writable: true, value: void 0 }); - this.obj = obj; - } -} -class ObserverInfo { - constructor(callback, observer) { - Object.defineProperty(this, "callback", { + Object.defineProperty(this, "signal", { enumerable: true, configurable: true, writable: true, value: void 0 }); - Object.defineProperty(this, "observer", { + Object.defineProperty(this, "firstResult", { enumerable: true, configurable: true, writable: true, value: void 0 }); - this.callback = callback; - this.observer = observer; - } -} -function getMirror(obj) { - return beforeDict.get(obj); -} -function getObserverFromMirror(mirror, callback) { - return mirror.observers.get(callback); -} -function removeObserverFromMirror(mirror, observer) { - mirror.observers.delete(observer.callback); -} -/** - * Detach an observer from an object - */ -function unobserve(root, observer) { - observer.unobserve(); -} -/** - * Observes changes made to an object, which can then be retrieved using generate - */ -function observe(obj, callback) { - var patches = []; - var observer; - var mirror = getMirror(obj); - if (!mirror) { - mirror = new Mirror(obj); - beforeDict.set(obj, mirror); - } - else { - const observerInfo = getObserverFromMirror(mirror, callback); - observer = observerInfo && observerInfo.observer; - } - if (observer) { - return observer; - } - observer = {}; - mirror.value = _deepClone(obj); - if (callback) { - observer.callback = callback; - observer.next = null; - var dirtyCheck = () => { - duplex_generate(observer); - }; - var fastCheck = () => { - clearTimeout(observer.next); - observer.next = setTimeout(dirtyCheck); - }; - if (typeof window !== "undefined") { - //not Node - window.addEventListener("mouseup", fastCheck); - window.addEventListener("keyup", fastCheck); - window.addEventListener("mousedown", fastCheck); - window.addEventListener("keydown", fastCheck); - window.addEventListener("change", fastCheck); - } - } - observer.patches = patches; - observer.object = obj; - observer.unobserve = () => { - duplex_generate(observer); - clearTimeout(observer.next); - removeObserverFromMirror(mirror, observer); - if (typeof window !== "undefined") { - window.removeEventListener("mouseup", fastCheck); - window.removeEventListener("keyup", fastCheck); - window.removeEventListener("mousedown", fastCheck); - window.removeEventListener("keydown", fastCheck); - window.removeEventListener("change", fastCheck); - } - }; - mirror.observers.set(callback, new ObserverInfo(callback, observer)); - return observer; -} -/** - * Generate an array of patches from an observer - */ -function duplex_generate(observer, invertible = false) { - var mirror = beforeDict.get(observer.object); - _generate(mirror.value, observer.object, observer.patches, "", invertible); - if (observer.patches.length) { - applyPatch(mirror.value, observer.patches); + Object.defineProperty(this, "firstResultUsed", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + this.generator = params.generator; + this.config = params.config; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + this.signal = params.signal ?? this.config?.signal; + // setup is a promise that resolves only after the first iterator value + // is available. this is useful when setup of several piped generators + // needs to happen in logical order, ie. in the order in which input to + // to each generator is available. + this.setup = new Promise((resolve, reject) => { + void async_local_storage_AsyncLocalStorageProviderSingleton.runWithConfig(pickRunnableConfigKeys(params.config), async () => { + this.firstResult = params.generator.next(); + if (params.startSetup) { + this.firstResult.then(params.startSetup).then(resolve, reject); + } + else { + this.firstResult.then((_result) => resolve(undefined), reject); + } + }, true); + }); } - var temp = observer.patches; - if (temp.length > 0) { - observer.patches = []; - if (observer.callback) { - observer.callback(temp); + async next(...args) { + this.signal?.throwIfAborted(); + if (!this.firstResultUsed) { + this.firstResultUsed = true; + return this.firstResult; } + return async_local_storage_AsyncLocalStorageProviderSingleton.runWithConfig(pickRunnableConfigKeys(this.config), this.signal + ? async () => { + return raceWithSignal(this.generator.next(...args), this.signal); + } + : async () => { + return this.generator.next(...args); + }, true); } - return temp; -} -// Dirty check if obj is different from mirror, generate patches and update mirror -function _generate(mirror, obj, patches, path, invertible) { - if (obj === mirror) { - return; - } - if (typeof obj.toJSON === "function") { - obj = obj.toJSON(); + async return(value) { + return this.generator.return(value); } - var newKeys = _objectKeys(obj); - var oldKeys = _objectKeys(mirror); - var changed = false; - var deleted = false; - //if ever "move" operation is implemented here, make sure this test runs OK: "should not generate the same patch twice (move)" - for (var t = oldKeys.length - 1; t >= 0; t--) { - var key = oldKeys[t]; - var oldVal = mirror[key]; - if (helpers_hasOwnProperty(obj, key) && - !(obj[key] === undefined && - oldVal !== undefined && - Array.isArray(obj) === false)) { - var newVal = obj[key]; - if (typeof oldVal == "object" && - oldVal != null && - typeof newVal == "object" && - newVal != null && - Array.isArray(oldVal) === Array.isArray(newVal)) { - _generate(oldVal, newVal, patches, path + "/" + escapePathComponent(key), invertible); - } - else { - if (oldVal !== newVal) { - changed = true; - if (invertible) { - patches.push({ - op: "test", - path: path + "/" + escapePathComponent(key), - value: helpers_deepClone(oldVal), - }); - } - patches.push({ - op: "replace", - path: path + "/" + escapePathComponent(key), - value: helpers_deepClone(newVal), - }); - } - } - } - else if (Array.isArray(mirror) === Array.isArray(obj)) { - if (invertible) { - patches.push({ - op: "test", - path: path + "/" + escapePathComponent(key), - value: helpers_deepClone(oldVal), - }); - } - patches.push({ - op: "remove", - path: path + "/" + escapePathComponent(key), - }); - deleted = true; // property has been deleted - } - else { - if (invertible) { - patches.push({ op: "test", path, value: mirror }); - } - patches.push({ op: "replace", path, value: obj }); - changed = true; - } + async throw(e) { + return this.generator.throw(e); } - if (!deleted && newKeys.length == oldKeys.length) { - return; + [Symbol.asyncIterator]() { + return this; } - for (var t = 0; t < newKeys.length; t++) { - var key = newKeys[t]; - if (!helpers_hasOwnProperty(mirror, key) && obj[key] !== undefined) { - patches.push({ - op: "add", - path: path + "/" + escapePathComponent(key), - value: helpers_deepClone(obj[key]), - }); - } + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore Not present in Node 18 types, required in latest Node 22 + async [Symbol.asyncDispose]() { + await this.return(); } } -/** - * Create an array of patches from the differences in two objects - */ -function compare(tree1, tree2, invertible = false) { - var patches = []; - _generate(tree1, tree2, patches, "", invertible); - return patches; +async function pipeGeneratorWithSetup(to, generator, startSetup, signal, ...args) { + const gen = new AsyncGeneratorWithSetup({ + generator, + startSetup, + signal, + }); + const setup = await gen.setup; + return { output: to(gen, setup, ...args), setup }; } -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/fast-json-patch/index.js +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/tracers/log_stream.js + /** - * Default export for backwards compat + * List of jsonpatch JSONPatchOperations, which describe how to create the run state + * from an empty dict. This is the minimal representation of the log, designed to + * be serialized as JSON and sent over the wire to reconstruct the log on the other + * side. Reconstruction of the state can be done with any jsonpatch-compliant library, + * see https://jsonpatch.com for more information. */ - - -/* harmony default export */ const fast_json_patch = ({ - ...src_core_namespaceObject, - // ...duplex, - JsonPatchError: PatchError, - deepClone: helpers_deepClone, - escapePathComponent: escapePathComponent, - unescapePathComponent: unescapePathComponent, -}); - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/env.js -const env_isBrowser = () => typeof window !== "undefined" && typeof window.document !== "undefined"; -const env_isWebWorker = () => typeof globalThis === "object" && - globalThis.constructor && - globalThis.constructor.name === "DedicatedWorkerGlobalScope"; -const env_isJsDom = () => (typeof window !== "undefined" && window.name === "nodejs") || - (typeof navigator !== "undefined" && - (navigator.userAgent.includes("Node.js") || - navigator.userAgent.includes("jsdom"))); -// Supabase Edge Function provides a `Deno` global object -// without `version` property -const env_isDeno = () => typeof Deno !== "undefined"; -// Mark not-as-node if in Supabase Edge Function -const env_isNode = () => typeof process !== "undefined" && - typeof process.versions !== "undefined" && - typeof process.versions.node !== "undefined" && - !env_isDeno(); -const env_getEnv = () => { - let env; - if (env_isBrowser()) { - env = "browser"; - } - else if (env_isNode()) { - env = "node"; - } - else if (env_isWebWorker()) { - env = "webworker"; - } - else if (env_isJsDom()) { - env = "jsdom"; - } - else if (env_isDeno()) { - env = "deno"; - } - else { - env = "other"; +class RunLogPatch { + constructor(fields) { + Object.defineProperty(this, "ops", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.ops = fields.ops ?? []; } - return env; -}; -let env_runtimeEnvironment; -async function env_getRuntimeEnvironment() { - if (env_runtimeEnvironment === undefined) { - const env = env_getEnv(); - env_runtimeEnvironment = { - library: "langchain-js", - runtime: env, - }; + concat(other) { + const ops = this.ops.concat(other.ops); + const states = core_applyPatch({}, ops); + // eslint-disable-next-line @typescript-eslint/no-use-before-define + return new RunLog({ + ops, + state: states[states.length - 1].newDocument, + }); } - return env_runtimeEnvironment; } -function env_getEnvironmentVariable(name) { - // Certain Deno setups will throw an error if you try to access environment variables - // https://github.com/langchain-ai/langchainjs/issues/1412 - try { - if (typeof process !== "undefined") { - // eslint-disable-next-line no-process-env - return process.env?.[name]; - } - else if (env_isDeno()) { - return Deno?.env.get(name); - } - else { - return undefined; - } +class RunLog extends RunLogPatch { + constructor(fields) { + super(fields); + Object.defineProperty(this, "state", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.state = fields.state; } - catch (e) { - return undefined; + concat(other) { + const ops = this.ops.concat(other.ops); + const states = core_applyPatch(this.state, other.ops); + return new RunLog({ ops, state: states[states.length - 1].newDocument }); + } + static fromRunLogPatch(patch) { + const states = core_applyPatch({}, patch.ops); + // eslint-disable-next-line @typescript-eslint/no-use-before-define + return new RunLog({ + ops: patch.ops, + state: states[states.length - 1].newDocument, + }); } } - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/callbacks/base.js - - - -/** - * Abstract class that provides a set of optional methods that can be - * overridden in derived classes to handle various events during the - * execution of a LangChain application. - */ -class BaseCallbackHandlerMethodsClass { -} -function callbackHandlerPrefersStreaming(x) { - return "lc_prefer_streaming" in x && x.lc_prefer_streaming; -} +const isLogStreamHandler = (handler) => handler.name === "log_stream_tracer"; /** - * Abstract base class for creating callback handlers in the LangChain - * framework. It provides a set of optional methods that can be overridden - * in derived classes to handle various events during the execution of a - * LangChain application. + * Extract standardized inputs from a run. + * + * Standardizes the inputs based on the type of the runnable used. + * + * @param run - Run object + * @param schemaFormat - The schema format to use. + * + * @returns Valid inputs are only dict. By conventions, inputs always represented + * invocation using named arguments. + * A null means that the input is not yet known! */ -class BaseCallbackHandler extends BaseCallbackHandlerMethodsClass { - get lc_namespace() { - return ["langchain_core", "callbacks", this.name]; - } - get lc_secrets() { - return undefined; +async function _getStandardizedInputs(run, schemaFormat) { + if (schemaFormat === "original") { + throw new Error("Do not assign inputs with original schema drop the key for now. " + + "When inputs are added to streamLog they should be added with " + + "standardized schema for streaming events."); } - get lc_attributes() { - return undefined; + const { inputs } = run; + if (["retriever", "llm", "prompt"].includes(run.run_type)) { + return inputs; } - get lc_aliases() { + if (Object.keys(inputs).length === 1 && inputs?.input === "") { return undefined; } - get lc_serializable_keys() { - return undefined; + // new style chains + // These nest an additional 'input' key inside the 'inputs' to make sure + // the input is always a dict. We need to unpack and user the inner value. + // We should try to fix this in Runnables and callbacks/tracers + // Runnables should be using a null type here not a placeholder + // dict. + return inputs.input; +} +async function _getStandardizedOutputs(run, schemaFormat) { + const { outputs } = run; + if (schemaFormat === "original") { + // Return the old schema, without standardizing anything + return outputs; } - /** - * The name of the serializable. Override to provide an alias or - * to preserve the serialized module name in minified environments. - * - * Implemented as a static method to support loading logic. - */ - static lc_name() { - return this.name; + if (["retriever", "llm", "prompt"].includes(run.run_type)) { + return outputs; } - /** - * The final serialized identifier for the module. - */ - get lc_id() { - return [ - ...this.lc_namespace, - get_lc_unique_name(this.constructor), - ]; + // TODO: Remove this hacky check + if (outputs !== undefined && + Object.keys(outputs).length === 1 && + outputs?.output !== undefined) { + return outputs.output; } - constructor(input) { - super(); - Object.defineProperty(this, "lc_serializable", { + return outputs; +} +function isChatGenerationChunk(x) { + return x !== undefined && x.message !== undefined; +} +/** + * Class that extends the `BaseTracer` class from the + * `langchain.callbacks.tracers.base` module. It represents a callback + * handler that logs the execution of runs and emits `RunLog` instances to a + * `RunLogStream`. + */ +class LogStreamCallbackHandler extends BaseTracer { + constructor(fields) { + super({ _awaitHandler: true, ...fields }); + Object.defineProperty(this, "autoClose", { enumerable: true, configurable: true, writable: true, - value: false + value: true }); - Object.defineProperty(this, "lc_kwargs", { + Object.defineProperty(this, "includeNames", { enumerable: true, configurable: true, writable: true, value: void 0 }); - Object.defineProperty(this, "ignoreLLM", { + Object.defineProperty(this, "includeTypes", { enumerable: true, configurable: true, writable: true, - value: false + value: void 0 }); - Object.defineProperty(this, "ignoreChain", { + Object.defineProperty(this, "includeTags", { enumerable: true, configurable: true, writable: true, - value: false + value: void 0 }); - Object.defineProperty(this, "ignoreAgent", { + Object.defineProperty(this, "excludeNames", { enumerable: true, configurable: true, writable: true, - value: false + value: void 0 }); - Object.defineProperty(this, "ignoreRetriever", { + Object.defineProperty(this, "excludeTypes", { enumerable: true, configurable: true, writable: true, - value: false + value: void 0 }); - Object.defineProperty(this, "ignoreCustomEvent", { + Object.defineProperty(this, "excludeTags", { enumerable: true, configurable: true, writable: true, - value: false + value: void 0 }); - Object.defineProperty(this, "raiseError", { + Object.defineProperty(this, "_schemaFormat", { enumerable: true, configurable: true, writable: true, - value: false + value: "original" }); - Object.defineProperty(this, "awaitHandlers", { + Object.defineProperty(this, "rootId", { enumerable: true, configurable: true, writable: true, - value: env_getEnvironmentVariable("LANGCHAIN_CALLBACKS_BACKGROUND") === "false" + value: void 0 }); - this.lc_kwargs = input || {}; - if (input) { - this.ignoreLLM = input.ignoreLLM ?? this.ignoreLLM; - this.ignoreChain = input.ignoreChain ?? this.ignoreChain; - this.ignoreAgent = input.ignoreAgent ?? this.ignoreAgent; - this.ignoreRetriever = input.ignoreRetriever ?? this.ignoreRetriever; - this.ignoreCustomEvent = - input.ignoreCustomEvent ?? this.ignoreCustomEvent; - this.raiseError = input.raiseError ?? this.raiseError; - this.awaitHandlers = - this.raiseError || (input._awaitHandler ?? this.awaitHandlers); + Object.defineProperty(this, "keyMapByRunId", { + enumerable: true, + configurable: true, + writable: true, + value: {} + }); + Object.defineProperty(this, "counterMapByRunName", { + enumerable: true, + configurable: true, + writable: true, + value: {} + }); + Object.defineProperty(this, "transformStream", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "writer", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "receiveStream", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "log_stream_tracer" + }); + Object.defineProperty(this, "lc_prefer_streaming", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + this.autoClose = fields?.autoClose ?? true; + this.includeNames = fields?.includeNames; + this.includeTypes = fields?.includeTypes; + this.includeTags = fields?.includeTags; + this.excludeNames = fields?.excludeNames; + this.excludeTypes = fields?.excludeTypes; + this.excludeTags = fields?.excludeTags; + this._schemaFormat = fields?._schemaFormat ?? this._schemaFormat; + this.transformStream = new TransformStream(); + this.writer = this.transformStream.writable.getWriter(); + this.receiveStream = IterableReadableStream.fromReadableStream(this.transformStream.readable); + } + [Symbol.asyncIterator]() { + return this.receiveStream; + } + async persistRun(_run) { + // This is a legacy method only called once for an entire run tree + // and is therefore not useful here + } + _includeRun(run) { + if (run.id === this.rootId) { + return false; + } + const runTags = run.tags ?? []; + let include = this.includeNames === undefined && + this.includeTags === undefined && + this.includeTypes === undefined; + if (this.includeNames !== undefined) { + include = include || this.includeNames.includes(run.name); + } + if (this.includeTypes !== undefined) { + include = include || this.includeTypes.includes(run.run_type); } + if (this.includeTags !== undefined) { + include = + include || + runTags.find((tag) => this.includeTags?.includes(tag)) !== undefined; + } + if (this.excludeNames !== undefined) { + include = include && !this.excludeNames.includes(run.name); + } + if (this.excludeTypes !== undefined) { + include = include && !this.excludeTypes.includes(run.run_type); + } + if (this.excludeTags !== undefined) { + include = + include && runTags.every((tag) => !this.excludeTags?.includes(tag)); + } + return include; } - copy() { - return new this.constructor(this); + async *tapOutputIterable(runId, output) { + // Tap an output async iterator to stream its values to the log. + for await (const chunk of output) { + // root run is handled in .streamLog() + if (runId !== this.rootId) { + // if we can't find the run silently ignore + // eg. because this run wasn't included in the log + const key = this.keyMapByRunId[runId]; + if (key) { + await this.writer.write(new RunLogPatch({ + ops: [ + { + op: "add", + path: `/logs/${key}/streamed_output/-`, + value: chunk, + }, + ], + })); + } + } + yield chunk; + } } - toJSON() { - return Serializable.prototype.toJSON.call(this); + async onRunCreate(run) { + if (this.rootId === undefined) { + this.rootId = run.id; + await this.writer.write(new RunLogPatch({ + ops: [ + { + op: "replace", + path: "", + value: { + id: run.id, + name: run.name, + type: run.run_type, + streamed_output: [], + final_output: undefined, + logs: {}, + }, + }, + ], + })); + } + if (!this._includeRun(run)) { + return; + } + if (this.counterMapByRunName[run.name] === undefined) { + this.counterMapByRunName[run.name] = 0; + } + this.counterMapByRunName[run.name] += 1; + const count = this.counterMapByRunName[run.name]; + this.keyMapByRunId[run.id] = + count === 1 ? run.name : `${run.name}:${count}`; + const logEntry = { + id: run.id, + name: run.name, + type: run.run_type, + tags: run.tags ?? [], + metadata: run.extra?.metadata ?? {}, + start_time: new Date(run.start_time).toISOString(), + streamed_output: [], + streamed_output_str: [], + final_output: undefined, + end_time: undefined, + }; + if (this._schemaFormat === "streaming_events") { + logEntry.inputs = await _getStandardizedInputs(run, this._schemaFormat); + } + await this.writer.write(new RunLogPatch({ + ops: [ + { + op: "add", + path: `/logs/${this.keyMapByRunId[run.id]}`, + value: logEntry, + }, + ], + })); } - toJSONNotImplemented() { - return Serializable.prototype.toJSONNotImplemented.call(this); + async onRunUpdate(run) { + try { + const runName = this.keyMapByRunId[run.id]; + if (runName === undefined) { + return; + } + const ops = []; + if (this._schemaFormat === "streaming_events") { + ops.push({ + op: "replace", + path: `/logs/${runName}/inputs`, + value: await _getStandardizedInputs(run, this._schemaFormat), + }); + } + ops.push({ + op: "add", + path: `/logs/${runName}/final_output`, + value: await _getStandardizedOutputs(run, this._schemaFormat), + }); + if (run.end_time !== undefined) { + ops.push({ + op: "add", + path: `/logs/${runName}/end_time`, + value: new Date(run.end_time).toISOString(), + }); + } + const patch = new RunLogPatch({ ops }); + await this.writer.write(patch); + } + finally { + if (run.id === this.rootId) { + const patch = new RunLogPatch({ + ops: [ + { + op: "replace", + path: "/final_output", + value: await _getStandardizedOutputs(run, this._schemaFormat), + }, + ], + }); + await this.writer.write(patch); + if (this.autoClose) { + await this.writer.close(); + } + } + } } - static fromMethods(methods) { - class Handler extends BaseCallbackHandler { - constructor() { - super(); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: v4() + async onLLMNewToken(run, token, kwargs) { + const runName = this.keyMapByRunId[run.id]; + if (runName === undefined) { + return; + } + // TODO: Remove hack + const isChatModel = run.inputs.messages !== undefined; + let streamedOutputValue; + if (isChatModel) { + if (isChatGenerationChunk(kwargs?.chunk)) { + streamedOutputValue = kwargs?.chunk; + } + else { + streamedOutputValue = new ai_AIMessageChunk({ + id: `run-${run.id}`, + content: token, }); - Object.assign(this, methods); } } - return new Handler(); + else { + streamedOutputValue = token; + } + const patch = new RunLogPatch({ + ops: [ + { + op: "add", + path: `/logs/${runName}/streamed_output_str/-`, + value: token, + }, + { + op: "add", + path: `/logs/${runName}/streamed_output/-`, + value: streamedOutputValue, + }, + ], + }); + await this.writer.write(patch); } } -const isBaseCallbackHandler = (x) => { - const callbackHandler = x; - return (callbackHandler !== undefined && - typeof callbackHandler.copy === "function" && - typeof callbackHandler.name === "string" && - typeof callbackHandler.awaitHandlers === "boolean"); -}; -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/tracers/base.js - -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function _coerceToDict(value, defaultKey) { - return value && !Array.isArray(value) && typeof value === "object" - ? value - : { [defaultKey]: value }; -} -function base_stripNonAlphanumeric(input) { - return input.replace(/[-:.]/g, ""); +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/outputs.js +const RUN_KEY = "__run"; +/** + * Chunk of a single generation. Used for streaming. + */ +class GenerationChunk { + constructor(fields) { + Object.defineProperty(this, "text", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + Object.defineProperty(this, "generationInfo", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.text = fields.text; + this.generationInfo = fields.generationInfo; + } + concat(chunk) { + return new GenerationChunk({ + text: this.text + chunk.text, + generationInfo: { + ...this.generationInfo, + ...chunk.generationInfo, + }, + }); + } } -function base_convertToDottedOrderFormat(epoch, runId, executionOrder) { - const paddedOrder = executionOrder.toFixed(0).slice(0, 3).padStart(3, "0"); - return (base_stripNonAlphanumeric(`${new Date(epoch).toISOString().slice(0, -1)}${paddedOrder}Z`) + runId); +class ChatGenerationChunk extends GenerationChunk { + constructor(fields) { + super(fields); + Object.defineProperty(this, "message", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.message = fields.message; + } + concat(chunk) { + return new ChatGenerationChunk({ + text: this.text + chunk.text, + generationInfo: { + ...this.generationInfo, + ...chunk.generationInfo, + }, + message: this.message.concat(chunk.message), + }); + } } -function isBaseTracer(x) { - return typeof x._addRunToRunMap === "function"; + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/tracers/event_stream.js + + + + +function assignName({ name, serialized, }) { + if (name !== undefined) { + return name; + } + if (serialized?.name !== undefined) { + return serialized.name; + } + else if (serialized?.id !== undefined && Array.isArray(serialized?.id)) { + return serialized.id[serialized.id.length - 1]; + } + return "Unnamed"; } -class BaseTracer extends BaseCallbackHandler { - constructor(_fields) { - super(...arguments); - Object.defineProperty(this, "runMap", { +const isStreamEventsHandler = (handler) => handler.name === "event_stream_tracer"; +/** + * Class that extends the `BaseTracer` class from the + * `langchain.callbacks.tracers.base` module. It represents a callback + * handler that logs the execution of runs and emits `RunLog` instances to a + * `RunLogStream`. + */ +class EventStreamCallbackHandler extends BaseTracer { + constructor(fields) { + super({ _awaitHandler: true, ...fields }); + Object.defineProperty(this, "autoClose", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "includeNames", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "includeTypes", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "includeTags", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "excludeNames", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "excludeTypes", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "excludeTags", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "runInfoMap", { + enumerable: true, + configurable: true, + writable: true, + value: new Map() + }); + Object.defineProperty(this, "tappedPromises", { enumerable: true, configurable: true, writable: true, value: new Map() }); + Object.defineProperty(this, "transformStream", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "writer", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "receiveStream", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "event_stream_tracer" + }); + Object.defineProperty(this, "lc_prefer_streaming", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + this.autoClose = fields?.autoClose ?? true; + this.includeNames = fields?.includeNames; + this.includeTypes = fields?.includeTypes; + this.includeTags = fields?.includeTags; + this.excludeNames = fields?.excludeNames; + this.excludeTypes = fields?.excludeTypes; + this.excludeTags = fields?.excludeTags; + this.transformStream = new TransformStream(); + this.writer = this.transformStream.writable.getWriter(); + this.receiveStream = IterableReadableStream.fromReadableStream(this.transformStream.readable); } - copy() { - return this; + [Symbol.asyncIterator]() { + return this.receiveStream; } - stringifyError(error) { - // eslint-disable-next-line no-instanceof/no-instanceof - if (error instanceof Error) { - return error.message + (error?.stack ? `\n\n${error.stack}` : ""); + async persistRun(_run) { + // This is a legacy method only called once for an entire run tree + // and is therefore not useful here + } + _includeRun(run) { + const runTags = run.tags ?? []; + let include = this.includeNames === undefined && + this.includeTags === undefined && + this.includeTypes === undefined; + if (this.includeNames !== undefined) { + include = include || this.includeNames.includes(run.name); } - if (typeof error === "string") { - return error; + if (this.includeTypes !== undefined) { + include = include || this.includeTypes.includes(run.runType); } - return `${error}`; - } - _addChildRun(parentRun, childRun) { - parentRun.child_runs.push(childRun); + if (this.includeTags !== undefined) { + include = + include || + runTags.find((tag) => this.includeTags?.includes(tag)) !== undefined; + } + if (this.excludeNames !== undefined) { + include = include && !this.excludeNames.includes(run.name); + } + if (this.excludeTypes !== undefined) { + include = include && !this.excludeTypes.includes(run.runType); + } + if (this.excludeTags !== undefined) { + include = + include && runTags.every((tag) => !this.excludeTags?.includes(tag)); + } + return include; } - _addRunToRunMap(run) { - const currentDottedOrder = base_convertToDottedOrderFormat(run.start_time, run.id, run.execution_order); - const storedRun = { ...run }; - if (storedRun.parent_run_id !== undefined) { - const parentRun = this.runMap.get(storedRun.parent_run_id); - if (parentRun) { - this._addChildRun(parentRun, storedRun); - parentRun.child_execution_order = Math.max(parentRun.child_execution_order, storedRun.child_execution_order); - storedRun.trace_id = parentRun.trace_id; - if (parentRun.dotted_order !== undefined) { - storedRun.dotted_order = [ - parentRun.dotted_order, - currentDottedOrder, - ].join("."); - } - else { - // This can happen naturally for callbacks added within a run - // console.debug(`Parent run with UUID ${storedRun.parent_run_id} has no dotted order.`); + async *tapOutputIterable(runId, outputStream) { + const firstChunk = await outputStream.next(); + if (firstChunk.done) { + return; + } + const runInfo = this.runInfoMap.get(runId); + // Run has finished, don't issue any stream events. + // An example of this is for runnables that use the default + // implementation of .stream(), which delegates to .invoke() + // and calls .onChainEnd() before passing it to the iterator. + if (runInfo === undefined) { + yield firstChunk.value; + return; + } + // Match format from handlers below + function _formatOutputChunk(eventType, data) { + if (eventType === "llm" && typeof data === "string") { + return new GenerationChunk({ text: data }); + } + return data; + } + let tappedPromise = this.tappedPromises.get(runId); + // if we are the first to tap, issue stream events + if (tappedPromise === undefined) { + let tappedPromiseResolver; + tappedPromise = new Promise((resolve) => { + tappedPromiseResolver = resolve; + }); + this.tappedPromises.set(runId, tappedPromise); + try { + const event = { + event: `on_${runInfo.runType}_stream`, + run_id: runId, + name: runInfo.name, + tags: runInfo.tags, + metadata: runInfo.metadata, + data: {}, + }; + await this.send({ + ...event, + data: { + chunk: _formatOutputChunk(runInfo.runType, firstChunk.value), + }, + }, runInfo); + yield firstChunk.value; + for await (const chunk of outputStream) { + // Don't yield tool and retriever stream events + if (runInfo.runType !== "tool" && runInfo.runType !== "retriever") { + await this.send({ + ...event, + data: { + chunk: _formatOutputChunk(runInfo.runType, chunk), + }, + }, runInfo); + } + yield chunk; } } - else { - // This can happen naturally for callbacks added within a run - // console.debug( - // `Parent run with UUID ${storedRun.parent_run_id} not found.` - // ); + finally { + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + tappedPromiseResolver(); + // Don't delete from the promises map to keep track of which runs have been tapped. } } else { - storedRun.trace_id = storedRun.id; - storedRun.dotted_order = currentDottedOrder; + // otherwise just pass through + yield firstChunk.value; + for await (const chunk of outputStream) { + yield chunk; + } } - this.runMap.set(storedRun.id, storedRun); - return storedRun; } - async _endTrace(run) { - const parentRun = run.parent_run_id !== undefined && this.runMap.get(run.parent_run_id); - if (parentRun) { - parentRun.child_execution_order = Math.max(parentRun.child_execution_order, run.child_execution_order); - } - else { - await this.persistRun(run); + async send(payload, run) { + if (this._includeRun(run)) { + await this.writer.write(payload); } - this.runMap.delete(run.id); - await this.onRunUpdate?.(run); } - _getExecutionOrder(parentRunId) { - const parentRun = parentRunId !== undefined && this.runMap.get(parentRunId); - // If a run has no parent then execution order is 1 - if (!parentRun) { - return 1; + async sendEndEvent(payload, run) { + const tappedPromise = this.tappedPromises.get(payload.run_id); + if (tappedPromise !== undefined) { + void tappedPromise.then(() => { + void this.send(payload, run); + }); + } + else { + await this.send(payload, run); } - return parentRun.child_execution_order + 1; - } - /** - * Create and add a run to the run map for LLM start events. - * This must sometimes be done synchronously to avoid race conditions - * when callbacks are backgrounded, so we expose it as a separate method here. - */ - _createRunForLLMStart(llm, prompts, runId, parentRunId, extraParams, tags, metadata, name) { - const execution_order = this._getExecutionOrder(parentRunId); - const start_time = Date.now(); - const finalExtraParams = metadata - ? { ...extraParams, metadata } - : extraParams; - const run = { - id: runId, - name: name ?? llm.id[llm.id.length - 1], - parent_run_id: parentRunId, - start_time, - serialized: llm, - events: [ - { - name: "start", - time: new Date(start_time).toISOString(), - }, - ], - inputs: { prompts }, - execution_order, - child_runs: [], - child_execution_order: execution_order, - run_type: "llm", - extra: finalExtraParams ?? {}, - tags: tags || [], - }; - return this._addRunToRunMap(run); - } - async handleLLMStart(llm, prompts, runId, parentRunId, extraParams, tags, metadata, name) { - const run = this.runMap.get(runId) ?? - this._createRunForLLMStart(llm, prompts, runId, parentRunId, extraParams, tags, metadata, name); - await this.onRunCreate?.(run); - await this.onLLMStart?.(run); - return run; } - /** - * Create and add a run to the run map for chat model start events. - * This must sometimes be done synchronously to avoid race conditions - * when callbacks are backgrounded, so we expose it as a separate method here. - */ - _createRunForChatModelStart(llm, messages, runId, parentRunId, extraParams, tags, metadata, name) { - const execution_order = this._getExecutionOrder(parentRunId); - const start_time = Date.now(); - const finalExtraParams = metadata - ? { ...extraParams, metadata } - : extraParams; - const run = { - id: runId, - name: name ?? llm.id[llm.id.length - 1], - parent_run_id: parentRunId, - start_time, - serialized: llm, - events: [ - { - name: "start", - time: new Date(start_time).toISOString(), - }, - ], - inputs: { messages }, - execution_order, - child_runs: [], - child_execution_order: execution_order, - run_type: "llm", - extra: finalExtraParams ?? {}, - tags: tags || [], + async onLLMStart(run) { + const runName = assignName(run); + const runType = run.inputs.messages !== undefined ? "chat_model" : "llm"; + const runInfo = { + tags: run.tags ?? [], + metadata: run.extra?.metadata ?? {}, + name: runName, + runType, + inputs: run.inputs, }; - return this._addRunToRunMap(run); - } - async handleChatModelStart(llm, messages, runId, parentRunId, extraParams, tags, metadata, name) { - const run = this.runMap.get(runId) ?? - this._createRunForChatModelStart(llm, messages, runId, parentRunId, extraParams, tags, metadata, name); - await this.onRunCreate?.(run); - await this.onLLMStart?.(run); - return run; + this.runInfoMap.set(run.id, runInfo); + const eventName = `on_${runType}_start`; + await this.send({ + event: eventName, + data: { + input: run.inputs, + }, + name: runName, + tags: run.tags ?? [], + run_id: run.id, + metadata: run.extra?.metadata ?? {}, + }, runInfo); } - async handleLLMEnd(output, runId, _parentRunId, _tags, extraParams) { - const run = this.runMap.get(runId); - if (!run || run?.run_type !== "llm") { - throw new Error("No LLM run to end."); + async onLLMNewToken(run, token, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + kwargs) { + const runInfo = this.runInfoMap.get(run.id); + let chunk; + let eventName; + if (runInfo === undefined) { + throw new Error(`onLLMNewToken: Run ID ${run.id} not found in run map.`); } - run.end_time = Date.now(); - run.outputs = output; - run.events.push({ - name: "end", - time: new Date(run.end_time).toISOString(), - }); - run.extra = { ...run.extra, ...extraParams }; - await this.onLLMEnd?.(run); - await this._endTrace(run); - return run; - } - async handleLLMError(error, runId, _parentRunId, _tags, extraParams) { - const run = this.runMap.get(runId); - if (!run || run?.run_type !== "llm") { - throw new Error("No LLM run to end."); + // Top-level streaming events are covered by tapOutputIterable + if (this.runInfoMap.size === 1) { + return; } - run.end_time = Date.now(); - run.error = this.stringifyError(error); - run.events.push({ - name: "error", - time: new Date(run.end_time).toISOString(), - }); - run.extra = { ...run.extra, ...extraParams }; - await this.onLLMError?.(run); - await this._endTrace(run); - return run; - } - /** - * Create and add a run to the run map for chain start events. - * This must sometimes be done synchronously to avoid race conditions - * when callbacks are backgrounded, so we expose it as a separate method here. - */ - _createRunForChainStart(chain, inputs, runId, parentRunId, tags, metadata, runType, name) { - const execution_order = this._getExecutionOrder(parentRunId); - const start_time = Date.now(); - const run = { - id: runId, - name: name ?? chain.id[chain.id.length - 1], - parent_run_id: parentRunId, - start_time, - serialized: chain, - events: [ - { - name: "start", - time: new Date(start_time).toISOString(), - }, - ], - inputs, - execution_order, - child_execution_order: execution_order, - run_type: runType ?? "chain", - child_runs: [], - extra: metadata ? { metadata } : {}, - tags: tags || [], - }; - return this._addRunToRunMap(run); - } - async handleChainStart(chain, inputs, runId, parentRunId, tags, metadata, runType, name) { - const run = this.runMap.get(runId) ?? - this._createRunForChainStart(chain, inputs, runId, parentRunId, tags, metadata, runType, name); - await this.onRunCreate?.(run); - await this.onChainStart?.(run); - return run; + if (runInfo.runType === "chat_model") { + eventName = "on_chat_model_stream"; + if (kwargs?.chunk === undefined) { + chunk = new ai_AIMessageChunk({ content: token, id: `run-${run.id}` }); + } + else { + chunk = kwargs.chunk.message; + } + } + else if (runInfo.runType === "llm") { + eventName = "on_llm_stream"; + if (kwargs?.chunk === undefined) { + chunk = new GenerationChunk({ text: token }); + } + else { + chunk = kwargs.chunk; + } + } + else { + throw new Error(`Unexpected run type ${runInfo.runType}`); + } + await this.send({ + event: eventName, + data: { + chunk, + }, + run_id: run.id, + name: runInfo.name, + tags: runInfo.tags, + metadata: runInfo.metadata, + }, runInfo); } - async handleChainEnd(outputs, runId, _parentRunId, _tags, kwargs) { - const run = this.runMap.get(runId); - if (!run) { - throw new Error("No chain run to end."); + async onLLMEnd(run) { + const runInfo = this.runInfoMap.get(run.id); + this.runInfoMap.delete(run.id); + let eventName; + if (runInfo === undefined) { + throw new Error(`onLLMEnd: Run ID ${run.id} not found in run map.`); } - run.end_time = Date.now(); - run.outputs = _coerceToDict(outputs, "output"); - run.events.push({ - name: "end", - time: new Date(run.end_time).toISOString(), - }); - if (kwargs?.inputs !== undefined) { - run.inputs = _coerceToDict(kwargs.inputs, "input"); + const generations = run.outputs?.generations; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let output; + if (runInfo.runType === "chat_model") { + for (const generation of generations ?? []) { + if (output !== undefined) { + break; + } + output = generation[0]?.message; + } + eventName = "on_chat_model_end"; } - await this.onChainEnd?.(run); - await this._endTrace(run); - return run; + else if (runInfo.runType === "llm") { + output = { + generations: generations?.map((generation) => { + return generation.map((chunk) => { + return { + text: chunk.text, + generationInfo: chunk.generationInfo, + }; + }); + }), + llmOutput: run.outputs?.llmOutput ?? {}, + }; + eventName = "on_llm_end"; + } + else { + throw new Error(`onLLMEnd: Unexpected run type: ${runInfo.runType}`); + } + await this.sendEndEvent({ + event: eventName, + data: { + output, + input: runInfo.inputs, + }, + run_id: run.id, + name: runInfo.name, + tags: runInfo.tags, + metadata: runInfo.metadata, + }, runInfo); } - async handleChainError(error, runId, _parentRunId, _tags, kwargs) { - const run = this.runMap.get(runId); - if (!run) { - throw new Error("No chain run to end."); + async onChainStart(run) { + const runName = assignName(run); + const runType = run.run_type ?? "chain"; + const runInfo = { + tags: run.tags ?? [], + metadata: run.extra?.metadata ?? {}, + name: runName, + runType: run.run_type, + }; + let eventData = {}; + // Workaround Runnable core code not sending input when transform streaming. + if (run.inputs.input === "" && Object.keys(run.inputs).length === 1) { + eventData = {}; + runInfo.inputs = {}; + } + else if (run.inputs.input !== undefined) { + eventData.input = run.inputs.input; + runInfo.inputs = run.inputs.input; } - run.end_time = Date.now(); - run.error = this.stringifyError(error); - run.events.push({ - name: "error", - time: new Date(run.end_time).toISOString(), - }); - if (kwargs?.inputs !== undefined) { - run.inputs = _coerceToDict(kwargs.inputs, "input"); + else { + eventData.input = run.inputs; + runInfo.inputs = run.inputs; } - await this.onChainError?.(run); - await this._endTrace(run); - return run; + this.runInfoMap.set(run.id, runInfo); + await this.send({ + event: `on_${runType}_start`, + data: eventData, + name: runName, + tags: run.tags ?? [], + run_id: run.id, + metadata: run.extra?.metadata ?? {}, + }, runInfo); } - /** - * Create and add a run to the run map for tool start events. - * This must sometimes be done synchronously to avoid race conditions - * when callbacks are backgrounded, so we expose it as a separate method here. - */ - _createRunForToolStart(tool, input, runId, parentRunId, tags, metadata, name) { - const execution_order = this._getExecutionOrder(parentRunId); - const start_time = Date.now(); - const run = { - id: runId, - name: name ?? tool.id[tool.id.length - 1], - parent_run_id: parentRunId, - start_time, - serialized: tool, - events: [ - { - name: "start", - time: new Date(start_time).toISOString(), - }, - ], - inputs: { input }, - execution_order, - child_execution_order: execution_order, - run_type: "tool", - child_runs: [], - extra: metadata ? { metadata } : {}, - tags: tags || [], + async onChainEnd(run) { + const runInfo = this.runInfoMap.get(run.id); + this.runInfoMap.delete(run.id); + if (runInfo === undefined) { + throw new Error(`onChainEnd: Run ID ${run.id} not found in run map.`); + } + const eventName = `on_${run.run_type}_end`; + const inputs = run.inputs ?? runInfo.inputs ?? {}; + const outputs = run.outputs?.output ?? run.outputs; + const data = { + output: outputs, + input: inputs, }; - return this._addRunToRunMap(run); - } - async handleToolStart(tool, input, runId, parentRunId, tags, metadata, name) { - const run = this.runMap.get(runId) ?? - this._createRunForToolStart(tool, input, runId, parentRunId, tags, metadata, name); - await this.onRunCreate?.(run); - await this.onToolStart?.(run); - return run; - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - async handleToolEnd(output, runId) { - const run = this.runMap.get(runId); - if (!run || run?.run_type !== "tool") { - throw new Error("No tool run to end"); + if (inputs.input && Object.keys(inputs).length === 1) { + data.input = inputs.input; + runInfo.inputs = inputs.input; } - run.end_time = Date.now(); - run.outputs = { output }; - run.events.push({ - name: "end", - time: new Date(run.end_time).toISOString(), - }); - await this.onToolEnd?.(run); - await this._endTrace(run); - return run; + await this.sendEndEvent({ + event: eventName, + data, + run_id: run.id, + name: runInfo.name, + tags: runInfo.tags, + metadata: runInfo.metadata ?? {}, + }, runInfo); } - async handleToolError(error, runId) { - const run = this.runMap.get(runId); - if (!run || run?.run_type !== "tool") { - throw new Error("No tool run to end"); - } - run.end_time = Date.now(); - run.error = this.stringifyError(error); - run.events.push({ - name: "error", - time: new Date(run.end_time).toISOString(), - }); - await this.onToolError?.(run); - await this._endTrace(run); - return run; + async onToolStart(run) { + const runName = assignName(run); + const runInfo = { + tags: run.tags ?? [], + metadata: run.extra?.metadata ?? {}, + name: runName, + runType: "tool", + inputs: run.inputs ?? {}, + }; + this.runInfoMap.set(run.id, runInfo); + await this.send({ + event: "on_tool_start", + data: { + input: run.inputs ?? {}, + }, + name: runName, + run_id: run.id, + tags: run.tags ?? [], + metadata: run.extra?.metadata ?? {}, + }, runInfo); } - async handleAgentAction(action, runId) { - const run = this.runMap.get(runId); - if (!run || run?.run_type !== "chain") { - return; + async onToolEnd(run) { + const runInfo = this.runInfoMap.get(run.id); + this.runInfoMap.delete(run.id); + if (runInfo === undefined) { + throw new Error(`onToolEnd: Run ID ${run.id} not found in run map.`); } - const agentRun = run; - agentRun.actions = agentRun.actions || []; - agentRun.actions.push(action); - agentRun.events.push({ - name: "agent_action", - time: new Date().toISOString(), - kwargs: { action }, - }); - await this.onAgentAction?.(run); - } - async handleAgentEnd(action, runId) { - const run = this.runMap.get(runId); - if (!run || run?.run_type !== "chain") { - return; + if (runInfo.inputs === undefined) { + throw new Error(`onToolEnd: Run ID ${run.id} is a tool call, and is expected to have traced inputs.`); } - run.events.push({ - name: "agent_end", - time: new Date().toISOString(), - kwargs: { action }, - }); - await this.onAgentEnd?.(run); + const output = run.outputs?.output === undefined ? run.outputs : run.outputs.output; + await this.sendEndEvent({ + event: "on_tool_end", + data: { + output, + input: runInfo.inputs, + }, + run_id: run.id, + name: runInfo.name, + tags: runInfo.tags, + metadata: runInfo.metadata, + }, runInfo); } - /** - * Create and add a run to the run map for retriever start events. - * This must sometimes be done synchronously to avoid race conditions - * when callbacks are backgrounded, so we expose it as a separate method here. - */ - _createRunForRetrieverStart(retriever, query, runId, parentRunId, tags, metadata, name) { - const execution_order = this._getExecutionOrder(parentRunId); - const start_time = Date.now(); - const run = { - id: runId, - name: name ?? retriever.id[retriever.id.length - 1], - parent_run_id: parentRunId, - start_time, - serialized: retriever, - events: [ - { - name: "start", - time: new Date(start_time).toISOString(), - }, - ], - inputs: { query }, - execution_order, - child_execution_order: execution_order, - run_type: "retriever", - child_runs: [], - extra: metadata ? { metadata } : {}, - tags: tags || [], + async onRetrieverStart(run) { + const runName = assignName(run); + const runType = "retriever"; + const runInfo = { + tags: run.tags ?? [], + metadata: run.extra?.metadata ?? {}, + name: runName, + runType, + inputs: { + query: run.inputs.query, + }, }; - return this._addRunToRunMap(run); - } - async handleRetrieverStart(retriever, query, runId, parentRunId, tags, metadata, name) { - const run = this.runMap.get(runId) ?? - this._createRunForRetrieverStart(retriever, query, runId, parentRunId, tags, metadata, name); - await this.onRunCreate?.(run); - await this.onRetrieverStart?.(run); - return run; - } - async handleRetrieverEnd(documents, runId) { - const run = this.runMap.get(runId); - if (!run || run?.run_type !== "retriever") { - throw new Error("No retriever run to end"); - } - run.end_time = Date.now(); - run.outputs = { documents }; - run.events.push({ - name: "end", - time: new Date(run.end_time).toISOString(), - }); - await this.onRetrieverEnd?.(run); - await this._endTrace(run); - return run; + this.runInfoMap.set(run.id, runInfo); + await this.send({ + event: "on_retriever_start", + data: { + input: { + query: run.inputs.query, + }, + }, + name: runName, + tags: run.tags ?? [], + run_id: run.id, + metadata: run.extra?.metadata ?? {}, + }, runInfo); } - async handleRetrieverError(error, runId) { - const run = this.runMap.get(runId); - if (!run || run?.run_type !== "retriever") { - throw new Error("No retriever run to end"); + async onRetrieverEnd(run) { + const runInfo = this.runInfoMap.get(run.id); + this.runInfoMap.delete(run.id); + if (runInfo === undefined) { + throw new Error(`onRetrieverEnd: Run ID ${run.id} not found in run map.`); } - run.end_time = Date.now(); - run.error = this.stringifyError(error); - run.events.push({ - name: "error", - time: new Date(run.end_time).toISOString(), - }); - await this.onRetrieverError?.(run); - await this._endTrace(run); - return run; + await this.sendEndEvent({ + event: "on_retriever_end", + data: { + output: run.outputs?.documents ?? run.outputs, + input: runInfo.inputs, + }, + run_id: run.id, + name: runInfo.name, + tags: runInfo.tags, + metadata: runInfo.metadata, + }, runInfo); } - async handleText(text, runId) { - const run = this.runMap.get(runId); - if (!run || run?.run_type !== "chain") { - return; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + async handleCustomEvent(eventName, data, runId) { + const runInfo = this.runInfoMap.get(runId); + if (runInfo === undefined) { + throw new Error(`handleCustomEvent: Run ID ${runId} not found in run map.`); } - run.events.push({ - name: "text", - time: new Date().toISOString(), - kwargs: { text }, - }); - await this.onText?.(run); + await this.send({ + event: "on_custom_event", + run_id: runId, + name: eventName, + tags: runInfo.tags, + metadata: runInfo.metadata, + data, + }, runInfo); } - async handleLLMNewToken(token, idx, runId, _parentRunId, _tags, fields) { - const run = this.runMap.get(runId); - if (!run || run?.run_type !== "llm") { - throw new Error(`Invalid "runId" provided to "handleLLMNewToken" callback.`); - } - run.events.push({ - name: "new_token", - time: new Date().toISOString(), - kwargs: { token, idx, chunk: fields?.chunk }, + async finish() { + const pendingPromises = [...this.tappedPromises.values()]; + void Promise.all(pendingPromises).finally(() => { + void this.writer.close(); }); - await this.onLLMNewToken?.(run, token, { chunk: fields?.chunk }); - return run; } } -// EXTERNAL MODULE: ./node_modules/@langchain/core/node_modules/ansi-styles/index.js -var ansi_styles = __nccwpck_require__(2227); -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/tracers/console.js +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/async_caller.js -function wrap(style, text) { - return `${style.open}${text}${style.close}`; -} -function tryJsonStringify(obj, fallback) { - try { - return JSON.stringify(obj, null, 2); - } - catch (err) { - return fallback; +const async_caller_STATUS_NO_RETRY = [ + 400, // Bad Request + 401, // Unauthorized + 402, // Payment Required + 403, // Forbidden + 404, // Not Found + 405, // Method Not Allowed + 406, // Not Acceptable + 407, // Proxy Authentication Required + 409, // Conflict +]; +// eslint-disable-next-line @typescript-eslint/no-explicit-any +const defaultFailedAttemptHandler = (error) => { + if (error.message.startsWith("Cancel") || + error.message.startsWith("AbortError") || + error.name === "AbortError") { + throw error; } -} -function formatKVMapItem(value) { - if (typeof value === "string") { - return value.trim(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + if (error?.code === "ECONNABORTED") { + throw error; } - if (value === null || value === undefined) { - return value; + const status = + // eslint-disable-next-line @typescript-eslint/no-explicit-any + error?.response?.status ?? error?.status; + if (status && async_caller_STATUS_NO_RETRY.includes(+status)) { + throw error; } - return tryJsonStringify(value, value.toString()); -} -function elapsed(run) { - if (!run.end_time) - return ""; - const elapsed = run.end_time - run.start_time; - if (elapsed < 1000) { - return `${elapsed}ms`; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + if (error?.error?.code === "insufficient_quota") { + const err = new Error(error?.message); + err.name = "InsufficientQuotaError"; + throw err; } - return `${(elapsed / 1000).toFixed(2)}s`; -} -const { color } = ansi_styles; +}; /** - * A tracer that logs all events to the console. It extends from the - * `BaseTracer` class and overrides its methods to provide custom logging - * functionality. - * @example - * ```typescript + * A class that can be used to make async calls with concurrency and retry logic. * - * const llm = new ChatAnthropic({ - * temperature: 0, - * tags: ["example", "callbacks", "constructor"], - * callbacks: [new ConsoleCallbackHandler()], - * }); + * This is useful for making calls to any kind of "expensive" external resource, + * be it because it's rate-limited, subject to network issues, etc. * - * ``` + * Concurrent calls are limited by the `maxConcurrency` parameter, which defaults + * to `Infinity`. This means that by default, all calls will be made in parallel. + * + * Retries are limited by the `maxRetries` parameter, which defaults to 6. This + * means that by default, each call will be retried up to 6 times, with an + * exponential backoff between each attempt. */ -class ConsoleCallbackHandler extends BaseTracer { - constructor() { - super(...arguments); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "console_callback_handler" - }); - } - /** - * Method used to persist the run. In this case, it simply returns a - * resolved promise as there's no persistence logic. - * @param _run The run to persist. - * @returns A resolved promise. - */ - persistRun(_run) { - return Promise.resolve(); - } - // utility methods - /** - * Method used to get all the parent runs of a given run. - * @param run The run whose parents are to be retrieved. - * @returns An array of parent runs. - */ - getParents(run) { - const parents = []; - let currentRun = run; - while (currentRun.parent_run_id) { - const parent = this.runMap.get(currentRun.parent_run_id); - if (parent) { - parents.push(parent); - currentRun = parent; - } - else { - break; - } - } - return parents; - } - /** - * Method used to get a string representation of the run's lineage, which - * is used in logging. - * @param run The run whose lineage is to be retrieved. - * @returns A string representation of the run's lineage. - */ - getBreadcrumbs(run) { - const parents = this.getParents(run).reverse(); - const string = [...parents, run] - .map((parent, i, arr) => { - const name = `${parent.execution_order}:${parent.run_type}:${parent.name}`; - return i === arr.length - 1 ? wrap(ansi_styles.bold, name) : name; - }) - .join(" > "); - return wrap(color.grey, string); - } - // logging methods - /** - * Method used to log the start of a chain run. - * @param run The chain run that has started. - * @returns void - */ - onChainStart(run) { - const crumbs = this.getBreadcrumbs(run); - console.log(`${wrap(color.green, "[chain/start]")} [${crumbs}] Entering Chain run with input: ${tryJsonStringify(run.inputs, "[inputs]")}`); - } - /** - * Method used to log the end of a chain run. - * @param run The chain run that has ended. - * @returns void - */ - onChainEnd(run) { - const crumbs = this.getBreadcrumbs(run); - console.log(`${wrap(color.cyan, "[chain/end]")} [${crumbs}] [${elapsed(run)}] Exiting Chain run with output: ${tryJsonStringify(run.outputs, "[outputs]")}`); - } - /** - * Method used to log any errors of a chain run. - * @param run The chain run that has errored. - * @returns void - */ - onChainError(run) { - const crumbs = this.getBreadcrumbs(run); - console.log(`${wrap(color.red, "[chain/error]")} [${crumbs}] [${elapsed(run)}] Chain run errored with error: ${tryJsonStringify(run.error, "[error]")}`); - } - /** - * Method used to log the start of an LLM run. - * @param run The LLM run that has started. - * @returns void - */ - onLLMStart(run) { - const crumbs = this.getBreadcrumbs(run); - const inputs = "prompts" in run.inputs - ? { prompts: run.inputs.prompts.map((p) => p.trim()) } - : run.inputs; - console.log(`${wrap(color.green, "[llm/start]")} [${crumbs}] Entering LLM run with input: ${tryJsonStringify(inputs, "[inputs]")}`); - } - /** - * Method used to log the end of an LLM run. - * @param run The LLM run that has ended. - * @returns void - */ - onLLMEnd(run) { - const crumbs = this.getBreadcrumbs(run); - console.log(`${wrap(color.cyan, "[llm/end]")} [${crumbs}] [${elapsed(run)}] Exiting LLM run with output: ${tryJsonStringify(run.outputs, "[response]")}`); - } - /** - * Method used to log any errors of an LLM run. - * @param run The LLM run that has errored. - * @returns void - */ - onLLMError(run) { - const crumbs = this.getBreadcrumbs(run); - console.log(`${wrap(color.red, "[llm/error]")} [${crumbs}] [${elapsed(run)}] LLM run errored with error: ${tryJsonStringify(run.error, "[error]")}`); - } - /** - * Method used to log the start of a tool run. - * @param run The tool run that has started. - * @returns void - */ - onToolStart(run) { - const crumbs = this.getBreadcrumbs(run); - console.log(`${wrap(color.green, "[tool/start]")} [${crumbs}] Entering Tool run with input: "${formatKVMapItem(run.inputs.input)}"`); +class async_caller_AsyncCaller { + constructor(params) { + Object.defineProperty(this, "maxConcurrency", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "maxRetries", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "onFailedAttempt", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "queue", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.maxConcurrency = params.maxConcurrency ?? Infinity; + this.maxRetries = params.maxRetries ?? 6; + this.onFailedAttempt = + params.onFailedAttempt ?? defaultFailedAttemptHandler; + const PQueue = ( true ? p_queue_dist["default"] : p_queue_dist); + this.queue = new PQueue({ concurrency: this.maxConcurrency }); } - /** - * Method used to log the end of a tool run. - * @param run The tool run that has ended. - * @returns void - */ - onToolEnd(run) { - const crumbs = this.getBreadcrumbs(run); - console.log(`${wrap(color.cyan, "[tool/end]")} [${crumbs}] [${elapsed(run)}] Exiting Tool run with output: "${formatKVMapItem(run.outputs?.output)}"`); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + call(callable, ...args) { + return this.queue.add(() => p_retry(() => callable(...args).catch((error) => { + // eslint-disable-next-line no-instanceof/no-instanceof + if (error instanceof Error) { + throw error; + } + else { + throw new Error(error); + } + }), { + onFailedAttempt: this.onFailedAttempt, + retries: this.maxRetries, + randomize: true, + // If needed we can change some of the defaults here, + // but they're quite sensible. + }), { throwOnTimeout: true }); } - /** - * Method used to log any errors of a tool run. - * @param run The tool run that has errored. - * @returns void - */ - onToolError(run) { - const crumbs = this.getBreadcrumbs(run); - console.log(`${wrap(color.red, "[tool/error]")} [${crumbs}] [${elapsed(run)}] Tool run errored with error: ${tryJsonStringify(run.error, "[error]")}`); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + callWithOptions(options, callable, ...args) { + // Note this doesn't cancel the underlying request, + // when available prefer to use the signal option of the underlying call + if (options.signal) { + return Promise.race([ + this.call(callable, ...args), + new Promise((_, reject) => { + options.signal?.addEventListener("abort", () => { + reject(new Error("AbortError")); + }); + }), + ]); + } + return this.call(callable, ...args); } - /** - * Method used to log the start of a retriever run. - * @param run The retriever run that has started. - * @returns void - */ - onRetrieverStart(run) { - const crumbs = this.getBreadcrumbs(run); - console.log(`${wrap(color.green, "[retriever/start]")} [${crumbs}] Entering Retriever run with input: ${tryJsonStringify(run.inputs, "[inputs]")}`); + fetch(...args) { + return this.call(() => fetch(...args).then((res) => (res.ok ? res : Promise.reject(res)))); } - /** - * Method used to log the end of a retriever run. - * @param run The retriever run that has ended. - * @returns void - */ - onRetrieverEnd(run) { - const crumbs = this.getBreadcrumbs(run); - console.log(`${wrap(color.cyan, "[retriever/end]")} [${crumbs}] [${elapsed(run)}] Exiting Retriever run with output: ${tryJsonStringify(run.outputs, "[outputs]")}`); +} + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/tracers/root_listener.js + +class RootListenersTracer extends BaseTracer { + constructor({ config, onStart, onEnd, onError, }) { + super({ _awaitHandler: true }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "RootListenersTracer" + }); + /** The Run's ID. Type UUID */ + Object.defineProperty(this, "rootId", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "config", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "argOnStart", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "argOnEnd", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "argOnError", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.config = config; + this.argOnStart = onStart; + this.argOnEnd = onEnd; + this.argOnError = onError; } /** - * Method used to log any errors of a retriever run. - * @param run The retriever run that has errored. - * @returns void + * This is a legacy method only called once for an entire run tree + * therefore not useful here + * @param {Run} _ Not used */ - onRetrieverError(run) { - const crumbs = this.getBreadcrumbs(run); - console.log(`${wrap(color.red, "[retriever/error]")} [${crumbs}] [${elapsed(run)}] Retriever run errored with error: ${tryJsonStringify(run.error, "[error]")}`); + persistRun(_) { + return Promise.resolve(); } - /** - * Method used to log the action selected by the agent. - * @param run The run in which the agent action occurred. - * @returns void - */ - onAgentAction(run) { - const agentRun = run; - const crumbs = this.getBreadcrumbs(run); - console.log(`${wrap(color.blue, "[agent/action]")} [${crumbs}] Agent selected action: ${tryJsonStringify(agentRun.actions[agentRun.actions.length - 1], "[action]")}`); + async onRunCreate(run) { + if (this.rootId) { + return; + } + this.rootId = run.id; + if (this.argOnStart) { + await this.argOnStart(run, this.config); + } } -} - -;// CONCATENATED MODULE: ./node_modules/langsmith/run_trees.js - -;// CONCATENATED MODULE: ./node_modules/langsmith/index.js - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/singletons/tracer.js - - -let client; -const getDefaultLangChainClientSingleton = () => { - if (client === undefined) { - const clientParams = env_getEnvironmentVariable("LANGCHAIN_CALLBACKS_BACKGROUND") === "false" - ? { - // LangSmith has its own backgrounding system - blockOnRootRunFinalization: true, + async onRunUpdate(run) { + if (run.id !== this.rootId) { + return; + } + if (!run.error) { + if (this.argOnEnd) { + await this.argOnEnd(run, this.config); } - : {}; - client = new Client(clientParams); + } + else if (this.argOnError) { + await this.argOnError(run, this.config); + } } - return client; -}; -const setDefaultLangChainClientSingleton = (newClient) => { - client = newClient; -}; - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/tracers/tracer_langchain.js - - - - +} -class tracer_langchain_LangChainTracer extends BaseTracer { - constructor(fields = {}) { - super(fields); - Object.defineProperty(this, "name", { +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/utils.js +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function isRunnableInterface(thing) { + return thing ? thing.lc_runnable : false; +} +/** + * Utility to filter the root event in the streamEvents implementation. + * This is simply binding the arguments to the namespace to make save on + * a bit of typing in the streamEvents implementation. + * + * TODO: Refactor and remove. + */ +class _RootEventFilter { + constructor(fields) { + Object.defineProperty(this, "includeNames", { enumerable: true, configurable: true, writable: true, - value: "langchain_tracer" + value: void 0 }); - Object.defineProperty(this, "projectName", { + Object.defineProperty(this, "includeTypes", { enumerable: true, configurable: true, writable: true, value: void 0 }); - Object.defineProperty(this, "exampleId", { + Object.defineProperty(this, "includeTags", { enumerable: true, configurable: true, writable: true, value: void 0 }); - Object.defineProperty(this, "client", { + Object.defineProperty(this, "excludeNames", { enumerable: true, configurable: true, writable: true, value: void 0 }); - const { exampleId, projectName, client } = fields; - this.projectName = - projectName ?? - env_getEnvironmentVariable("LANGCHAIN_PROJECT") ?? - env_getEnvironmentVariable("LANGCHAIN_SESSION"); - this.exampleId = exampleId; - this.client = client ?? getDefaultLangChainClientSingleton(); - const traceableTree = tracer_langchain_LangChainTracer.getTraceableRunTree(); - if (traceableTree) { - this.updateFromRunTree(traceableTree); + Object.defineProperty(this, "excludeTypes", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "excludeTags", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.includeNames = fields.includeNames; + this.includeTypes = fields.includeTypes; + this.includeTags = fields.includeTags; + this.excludeNames = fields.excludeNames; + this.excludeTypes = fields.excludeTypes; + this.excludeTags = fields.excludeTags; + } + includeEvent(event, rootType) { + let include = this.includeNames === undefined && + this.includeTypes === undefined && + this.includeTags === undefined; + const eventTags = event.tags ?? []; + if (this.includeNames !== undefined) { + include = include || this.includeNames.includes(event.name); + } + if (this.includeTypes !== undefined) { + include = include || this.includeTypes.includes(rootType); + } + if (this.includeTags !== undefined) { + include = + include || eventTags.some((tag) => this.includeTags?.includes(tag)); + } + if (this.excludeNames !== undefined) { + include = include && !this.excludeNames.includes(event.name); + } + if (this.excludeTypes !== undefined) { + include = include && !this.excludeTypes.includes(rootType); } + if (this.excludeTags !== undefined) { + include = + include && eventTags.every((tag) => !this.excludeTags?.includes(tag)); + } + return include; } - async _convertToCreate(run, example_id = undefined) { - return { - ...run, - extra: { - ...run.extra, - runtime: await env_getRuntimeEnvironment(), - }, - child_runs: undefined, - session_name: this.projectName, - reference_example_id: run.parent_run_id ? undefined : example_id, +} + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/graph_mermaid.js +function _escapeNodeLabel(nodeLabel) { + // Escapes the node label for Mermaid syntax. + return nodeLabel.replace(/[^a-zA-Z-_0-9]/g, "_"); +} +const MARKDOWN_SPECIAL_CHARS = ["*", "_", "`"]; +function _generateMermaidGraphStyles(nodeColors) { + let styles = ""; + for (const [className, color] of Object.entries(nodeColors)) { + styles += `\tclassDef ${className} ${color};\n`; + } + return styles; +} +/** + * Draws a Mermaid graph using the provided graph data + */ +function drawMermaid(nodes, edges, config) { + const { firstNode, lastNode, nodeColors, withStyles = true, curveStyle = "linear", wrapLabelNWords = 9, } = config ?? {}; + // Initialize Mermaid graph configuration + let mermaidGraph = withStyles + ? `%%{init: {'flowchart': {'curve': '${curveStyle}'}}}%%\ngraph TD;\n` + : "graph TD;\n"; + if (withStyles) { + // Node formatting templates + const defaultClassLabel = "default"; + const formatDict = { + [defaultClassLabel]: "{0}({1})", }; + if (firstNode !== undefined) { + formatDict[firstNode] = "{0}([{1}]):::first"; + } + if (lastNode !== undefined) { + formatDict[lastNode] = "{0}([{1}]):::last"; + } + // Add nodes to the graph + for (const [key, node] of Object.entries(nodes)) { + const nodeName = node.name.split(":").pop() ?? ""; + const label = MARKDOWN_SPECIAL_CHARS.some((char) => nodeName.startsWith(char) && nodeName.endsWith(char)) + ? `

${nodeName}

` + : nodeName; + let finalLabel = label; + if (Object.keys(node.metadata ?? {}).length) { + finalLabel += `
${Object.entries(node.metadata ?? {}) + .map(([k, v]) => `${k} = ${v}`) + .join("\n")}`; + } + const nodeLabel = (formatDict[key] ?? formatDict[defaultClassLabel]) + .replace("{0}", _escapeNodeLabel(key)) + .replace("{1}", finalLabel); + mermaidGraph += `\t${nodeLabel}\n`; + } } - async persistRun(_run) { } - async onRunCreate(run) { - const persistedRun = await this._convertToCreate(run, this.exampleId); - await this.client.createRun(persistedRun); + // Group edges by their common prefixes + const edgeGroups = {}; + for (const edge of edges) { + const srcParts = edge.source.split(":"); + const tgtParts = edge.target.split(":"); + const commonPrefix = srcParts + .filter((src, i) => src === tgtParts[i]) + .join(":"); + if (!edgeGroups[commonPrefix]) { + edgeGroups[commonPrefix] = []; + } + edgeGroups[commonPrefix].push(edge); } - async onRunUpdate(run) { - const runUpdate = { - end_time: run.end_time, - error: run.error, - outputs: run.outputs, - events: run.events, - inputs: run.inputs, - trace_id: run.trace_id, - dotted_order: run.dotted_order, - parent_run_id: run.parent_run_id, - extra: run.extra, - session_name: this.projectName, - }; - await this.client.updateRun(run.id, runUpdate); + const seenSubgraphs = new Set(); + function addSubgraph(edges, prefix) { + const selfLoop = edges.length === 1 && edges[0].source === edges[0].target; + if (prefix && !selfLoop) { + const subgraph = prefix.split(":").pop(); + if (seenSubgraphs.has(subgraph)) { + throw new Error(`Found duplicate subgraph '${subgraph}' -- this likely means that ` + + "you're reusing a subgraph node with the same name. " + + "Please adjust your graph to have subgraph nodes with unique names."); + } + seenSubgraphs.add(subgraph); + mermaidGraph += `\tsubgraph ${subgraph}\n`; + } + for (const edge of edges) { + const { source, target, data, conditional } = edge; + let edgeLabel = ""; + if (data !== undefined) { + let edgeData = data; + const words = edgeData.split(" "); + if (words.length > wrapLabelNWords) { + edgeData = Array.from({ length: Math.ceil(words.length / wrapLabelNWords) }, (_, i) => words + .slice(i * wrapLabelNWords, (i + 1) * wrapLabelNWords) + .join(" ")).join(" 
 "); + } + edgeLabel = conditional + ? ` -.  ${edgeData}  .-> ` + : ` --  ${edgeData}  --> `; + } + else { + edgeLabel = conditional ? " -.-> " : " --> "; + } + mermaidGraph += `\t${_escapeNodeLabel(source)}${edgeLabel}${_escapeNodeLabel(target)};\n`; + } + // Recursively add nested subgraphs + for (const nestedPrefix in edgeGroups) { + if (nestedPrefix.startsWith(`${prefix}:`) && nestedPrefix !== prefix) { + addSubgraph(edgeGroups[nestedPrefix], nestedPrefix); + } + } + if (prefix && !selfLoop) { + mermaidGraph += "\tend\n"; + } + } + // Start with the top-level edges (no common prefix) + addSubgraph(edgeGroups[""] ?? [], ""); + // Add remaining subgraphs + for (const prefix in edgeGroups) { + if (!prefix.includes(":") && prefix !== "") { + addSubgraph(edgeGroups[prefix], prefix); + } + } + // Add custom styles for nodes + if (withStyles) { + mermaidGraph += _generateMermaidGraphStyles(nodeColors ?? {}); + } + return mermaidGraph; +} +/** + * Renders Mermaid graph using the Mermaid.INK API. + */ +async function drawMermaidPng(mermaidSyntax, config) { + let { backgroundColor = "white" } = config ?? {}; + // Use btoa for compatibility, assume ASCII + const mermaidSyntaxEncoded = btoa(mermaidSyntax); + // Check if the background color is a hexadecimal color code using regex + if (backgroundColor !== undefined) { + const hexColorPattern = /^#(?:[0-9a-fA-F]{3}){1,2}$/; + if (!hexColorPattern.test(backgroundColor)) { + backgroundColor = `!${backgroundColor}`; + } + } + const imageUrl = `https://mermaid.ink/img/${mermaidSyntaxEncoded}?bgColor=${backgroundColor}`; + const res = await fetch(imageUrl); + if (!res.ok) { + throw new Error([ + `Failed to render the graph using the Mermaid.INK API.`, + `Status code: ${res.status}`, + `Status text: ${res.statusText}`, + ].join("\n")); + } + const content = await res.blob(); + return content; +} + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/core/core.js +function $constructor(name, initializer, params) { + function init(inst, def) { + var _a; + Object.defineProperty(inst, "_zod", { + value: inst._zod ?? {}, + enumerable: false, + }); + (_a = inst._zod).traits ?? (_a.traits = new Set()); + inst._zod.traits.add(name); + initializer(inst, def); + // support prototype modifications + for (const k in _.prototype) { + if (!(k in inst)) + Object.defineProperty(inst, k, { value: _.prototype[k].bind(inst) }); + } + inst._zod.constr = _; + inst._zod.def = def; + } + // doesn't work if Parent has a constructor with arguments + const Parent = params?.Parent ?? Object; + class Definition extends Parent { + } + Object.defineProperty(Definition, "name", { value: name }); + function _(def) { + var _a; + const inst = params?.Parent ? new Definition() : this; + init(inst, def); + (_a = inst._zod).deferred ?? (_a.deferred = []); + for (const fn of inst._zod.deferred) { + fn(); + } + return inst; + } + Object.defineProperty(_, "init", { value: init }); + Object.defineProperty(_, Symbol.hasInstance, { + value: (inst) => { + if (params?.Parent && inst instanceof params.Parent) + return true; + return inst?._zod?.traits?.has(name); + }, + }); + Object.defineProperty(_, "name", { value: name }); + return _; +} +////////////////////////////// UTILITIES /////////////////////////////////////// +const $brand = Symbol("zod_brand"); +class $ZodAsyncError extends Error { + constructor() { + super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`); + } +} +const globalConfig = {}; +function config(newConfig) { + if (newConfig) + Object.assign(globalConfig, newConfig); + return globalConfig; +} + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/core/util.js +// functions +function assertEqual(val) { + return val; +} +function assertNotEqual(val) { + return val; +} +function assertIs(_arg) { } +function util_assertNever(_x) { + throw new Error(); +} +function assert(_) { } +function getEnumValues(entries) { + const numericValues = Object.values(entries).filter((v) => typeof v === "number"); + const values = Object.entries(entries) + .filter(([k, _]) => numericValues.indexOf(+k) === -1) + .map(([_, v]) => v); + return values; +} +function joinValues(array, separator = "|") { + return array.map((val) => stringifyPrimitive(val)).join(separator); +} +function jsonStringifyReplacer(_, value) { + if (typeof value === "bigint") + return value.toString(); + return value; +} +function cached(getter) { + const set = false; + return { + get value() { + if (!set) { + const value = getter(); + Object.defineProperty(this, "value", { value }); + return value; + } + throw new Error("cached value already set"); + }, + }; +} +function nullish(input) { + return input === null || input === undefined; +} +function cleanRegex(source) { + const start = source.startsWith("^") ? 1 : 0; + const end = source.endsWith("$") ? source.length - 1 : source.length; + return source.slice(start, end); +} +function util_floatSafeRemainder(val, step) { + const valDecCount = (val.toString().split(".")[1] || "").length; + const stepDecCount = (step.toString().split(".")[1] || "").length; + const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; + const valInt = Number.parseInt(val.toFixed(decCount).replace(".", "")); + const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", "")); + return (valInt % stepInt) / 10 ** decCount; +} +function defineLazy(object, key, getter) { + const set = false; + Object.defineProperty(object, key, { + get() { + if (!set) { + const value = getter(); + object[key] = value; + return value; + } + throw new Error("cached value already set"); + }, + set(v) { + Object.defineProperty(object, key, { + value: v, + // configurable: true, + }); + // object[key] = v; + }, + configurable: true, + }); +} +function assignProp(target, prop, value) { + Object.defineProperty(target, prop, { + value, + writable: true, + enumerable: true, + configurable: true, + }); +} +function getElementAtPath(obj, path) { + if (!path) + return obj; + return path.reduce((acc, key) => acc?.[key], obj); +} +function promiseAllObject(promisesObj) { + const keys = Object.keys(promisesObj); + const promises = keys.map((key) => promisesObj[key]); + return Promise.all(promises).then((results) => { + const resolvedObj = {}; + for (let i = 0; i < keys.length; i++) { + resolvedObj[keys[i]] = results[i]; + } + return resolvedObj; + }); +} +function randomString(length = 10) { + const chars = "abcdefghijklmnopqrstuvwxyz"; + let str = ""; + for (let i = 0; i < length; i++) { + str += chars[Math.floor(Math.random() * chars.length)]; + } + return str; +} +function esc(str) { + return JSON.stringify(str); +} +const captureStackTrace = Error.captureStackTrace + ? Error.captureStackTrace + : (..._args) => { }; +function isObject(data) { + return typeof data === "object" && data !== null && !Array.isArray(data); +} +const allowsEval = cached(() => { + if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) { + return false; + } + try { + const F = Function; + new F(""); + return true; } - getRun(id) { - return this.runMap.get(id); + catch (_) { + return false; } - updateFromRunTree(runTree) { - let rootRun = runTree; - const visited = new Set(); - while (rootRun.parent_run) { - if (visited.has(rootRun.id)) - break; - visited.add(rootRun.id); - if (!rootRun.parent_run) - break; - rootRun = rootRun.parent_run; +}); +function _isObject(o) { + return Object.prototype.toString.call(o) === "[object Object]"; +} +function isPlainObject(o) { + if (isObject(o) === false) + return false; + // modified constructor + const ctor = o.constructor; + if (ctor === undefined) + return true; + // modified prototype + const prot = ctor.prototype; + if (isObject(prot) === false) + return false; + // ctor doesn't have static `isPrototypeOf` + if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) { + return false; + } + return true; +} +function numKeys(data) { + let keyCount = 0; + for (const key in data) { + if (Object.prototype.hasOwnProperty.call(data, key)) { + keyCount++; } - visited.clear(); - const queue = [rootRun]; - while (queue.length > 0) { - const current = queue.shift(); - if (!current || visited.has(current.id)) - continue; - visited.add(current.id); - // @ts-expect-error Types of property 'events' are incompatible. - this.runMap.set(current.id, current); - if (current.child_runs) { - queue.push(...current.child_runs); + } + return keyCount; +} +const util_getParsedType = (data) => { + const t = typeof data; + switch (t) { + case "undefined": + return "undefined"; + case "string": + return "string"; + case "number": + return Number.isNaN(data) ? "nan" : "number"; + case "boolean": + return "boolean"; + case "function": + return "function"; + case "bigint": + return "bigint"; + case "symbol": + return "symbol"; + case "object": + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { + return "promise"; + } + if (typeof Map !== "undefined" && data instanceof Map) { + return "map"; + } + if (typeof Set !== "undefined" && data instanceof Set) { + return "set"; + } + if (typeof Date !== "undefined" && data instanceof Date) { + return "date"; + } + if (typeof File !== "undefined" && data instanceof File) { + return "file"; } + return "object"; + default: + throw new Error(`Unknown data type: ${t}`); + } +}; +const propertyKeyTypes = new Set(["string", "number", "symbol"]); +const primitiveTypes = new Set(["string", "number", "bigint", "boolean", "symbol", "undefined"]); +function escapeRegex(str) { + return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +} +// zod-specific utils +function util_clone(inst, def, params) { + const cl = new inst._zod.constr(def ?? inst._zod.def); + if (!def || params?.parent) + cl._zod.parent = inst; + return cl; +} +function normalizeParams(_params) { + const params = _params; + if (!params) + return {}; + if (typeof params === "string") + return { error: () => params }; + if (params?.message !== undefined) { + if (params?.error !== undefined) + throw new Error("Cannot specify both `message` and `error` params"); + params.error = params.message; + } + delete params.message; + if (typeof params.error === "string") + return { ...params, error: () => params.error }; + return params; +} +function createTransparentProxy(getter) { + let target; + return new Proxy({}, { + get(_, prop, receiver) { + target ?? (target = getter()); + return Reflect.get(target, prop, receiver); + }, + set(_, prop, value, receiver) { + target ?? (target = getter()); + return Reflect.set(target, prop, value, receiver); + }, + has(_, prop) { + target ?? (target = getter()); + return Reflect.has(target, prop); + }, + deleteProperty(_, prop) { + target ?? (target = getter()); + return Reflect.deleteProperty(target, prop); + }, + ownKeys(_) { + target ?? (target = getter()); + return Reflect.ownKeys(target); + }, + getOwnPropertyDescriptor(_, prop) { + target ?? (target = getter()); + return Reflect.getOwnPropertyDescriptor(target, prop); + }, + defineProperty(_, prop, descriptor) { + target ?? (target = getter()); + return Reflect.defineProperty(target, prop, descriptor); + }, + }); +} +function stringifyPrimitive(value) { + if (typeof value === "bigint") + return value.toString() + "n"; + if (typeof value === "string") + return `"${value}"`; + return `${value}`; +} +function optionalKeys(shape) { + return Object.keys(shape).filter((k) => { + return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional"; + }); +} +const NUMBER_FORMAT_RANGES = { + safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER], + int32: [-2147483648, 2147483647], + uint32: [0, 4294967295], + float32: [-3.4028234663852886e38, 3.4028234663852886e38], + float64: [-Number.MAX_VALUE, Number.MAX_VALUE], +}; +const BIGINT_FORMAT_RANGES = { + int64: [/* @__PURE__*/ BigInt("-9223372036854775808"), /* @__PURE__*/ BigInt("9223372036854775807")], + uint64: [/* @__PURE__*/ BigInt(0), /* @__PURE__*/ BigInt("18446744073709551615")], +}; +function pick(schema, mask) { + const newShape = {}; + const currDef = schema._zod.def; //.shape; + for (const key in mask) { + if (!(key in currDef.shape)) { + throw new Error(`Unrecognized key: "${key}"`); + } + if (!mask[key]) + continue; + // pick key + newShape[key] = currDef.shape[key]; + } + return util_clone(schema, { + ...schema._zod.def, + shape: newShape, + checks: [], + }); +} +function omit(schema, mask) { + const newShape = { ...schema._zod.def.shape }; + const currDef = schema._zod.def; //.shape; + for (const key in mask) { + if (!(key in currDef.shape)) { + throw new Error(`Unrecognized key: "${key}"`); } - this.client = runTree.client ?? this.client; - this.projectName = runTree.project_name ?? this.projectName; - this.exampleId = runTree.reference_example_id ?? this.exampleId; + if (!mask[key]) + continue; + delete newShape[key]; } - convertToRunTree(id) { - const runTreeMap = {}; - const runTreeList = []; - for (const [id, run] of this.runMap) { - // by converting the run map to a run tree, we are doing a copy - // thus, any mutation performed on the run tree will not be reflected - // back in the run map - // TODO: Stop using `this.runMap` in favour of LangSmith's `RunTree` - const runTree = new run_trees_RunTree({ - ...run, - child_runs: [], - parent_run: undefined, - // inherited properties - client: this.client, - project_name: this.projectName, - reference_example_id: this.exampleId, - tracingEnabled: true, - }); - runTreeMap[id] = runTree; - runTreeList.push([id, run.dotted_order]); - } - runTreeList.sort((a, b) => { - if (!a[1] || !b[1]) - return 0; - return a[1].localeCompare(b[1]); - }); - for (const [id] of runTreeList) { - const run = this.runMap.get(id); - const runTree = runTreeMap[id]; - if (!run || !runTree) - continue; - if (run.parent_run_id) { - const parentRunTree = runTreeMap[run.parent_run_id]; - if (parentRunTree) { - parentRunTree.child_runs.push(runTree); - runTree.parent_run = parentRunTree; - } + return util_clone(schema, { + ...schema._zod.def, + shape: newShape, + checks: [], + }); +} +function extend(schema, shape) { + const def = { + ...schema._zod.def, + get shape() { + const _shape = { ...schema._zod.def.shape, ...shape }; + assignProp(this, "shape", _shape); // self-caching + return _shape; + }, + checks: [], // delete existing checks + }; + return util_clone(schema, def); +} +function util_merge(a, b) { + return util_clone(a, { + ...a._zod.def, + get shape() { + const _shape = { ...a._zod.def.shape, ...b._zod.def.shape }; + assignProp(this, "shape", _shape); // self-caching + return _shape; + }, + catchall: b._zod.def.catchall, + checks: [], // delete existing checks + }); +} +function partial(Class, schema, mask) { + const oldShape = schema._zod.def.shape; + const shape = { ...oldShape }; + if (mask) { + for (const key in mask) { + if (!(key in oldShape)) { + throw new Error(`Unrecognized key: "${key}"`); } + if (!mask[key]) + continue; + shape[key] = Class + ? new Class({ + type: "optional", + innerType: oldShape[key], + }) + : oldShape[key]; } - return runTreeMap[id]; } - static getTraceableRunTree() { - try { - return getCurrentRunTree(); + else { + for (const key in oldShape) { + shape[key] = Class + ? new Class({ + type: "optional", + innerType: oldShape[key], + }) + : oldShape[key]; } - catch { - return undefined; + } + return util_clone(schema, { + ...schema._zod.def, + shape, + checks: [], + }); +} +function required(Class, schema, mask) { + const oldShape = schema._zod.def.shape; + const shape = { ...oldShape }; + if (mask) { + for (const key in mask) { + if (!(key in shape)) { + throw new Error(`Unrecognized key: "${key}"`); + } + if (!mask[key]) + continue; + // overwrite with non-optional + shape[key] = new Class({ + type: "nonoptional", + innerType: oldShape[key], + }); + } + } + else { + for (const key in oldShape) { + // overwrite with non-optional + shape[key] = new Class({ + type: "nonoptional", + innerType: oldShape[key], + }); } } + return util_clone(schema, { + ...schema._zod.def, + shape, + // optional: [], + checks: [], + }); } - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/singletons/async_local_storage/globals.js -const globals_TRACING_ALS_KEY = Symbol.for("ls:tracing_async_local_storage"); -const globals_CONTEXT_VARIABLES_KEY = Symbol.for("lc:context_variables"); -const setGlobalAsyncLocalStorageInstance = (instance) => { - globalThis[globals_TRACING_ALS_KEY] = instance; -}; -const globals_getGlobalAsyncLocalStorageInstance = () => { - return globalThis[globals_TRACING_ALS_KEY]; -}; - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/singletons/callbacks.js -/* eslint-disable @typescript-eslint/no-explicit-any */ - - -let queue; -/** - * Creates a queue using the p-queue library. The queue is configured to - * auto-start and has a concurrency of 1, meaning it will process tasks - * one at a time. - */ -function createQueue() { - const PQueue = true ? p_queue_dist["default"] : p_queue_dist; - return new PQueue({ - autoStart: true, - concurrency: 1, +function aborted(x, startIndex = 0) { + for (let i = startIndex; i < x.issues.length; i++) { + if (x.issues[i].continue !== true) + return true; + } + return false; +} +function prefixIssues(path, issues) { + return issues.map((iss) => { + var _a; + (_a = iss).path ?? (_a.path = []); + iss.path.unshift(path); + return iss; }); } -function getQueue() { - if (typeof queue === "undefined") { - queue = createQueue(); +function unwrapMessage(message) { + return typeof message === "string" ? message : message?.message; +} +function finalizeIssue(iss, ctx, config) { + const full = { ...iss, path: iss.path ?? [] }; + // for backwards compatibility + if (!iss.message) { + const message = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? + unwrapMessage(ctx?.error?.(iss)) ?? + unwrapMessage(config.customError?.(iss)) ?? + unwrapMessage(config.localeError?.(iss)) ?? + "Invalid input"; + full.message = message; + } + // delete (full as any).def; + delete full.inst; + delete full.continue; + if (!ctx?.reportInput) { + delete full.input; + } + return full; +} +function getSizableOrigin(input) { + if (input instanceof Set) + return "set"; + if (input instanceof Map) + return "map"; + if (input instanceof File) + return "file"; + return "unknown"; +} +function getLengthableOrigin(input) { + if (Array.isArray(input)) + return "array"; + if (typeof input === "string") + return "string"; + return "unknown"; +} +function issue(...args) { + const [iss, input, inst] = args; + if (typeof iss === "string") { + return { + message: iss, + code: "custom", + input, + inst, + }; } - return queue; + return { ...iss }; } -/** - * Consume a promise, either adding it to the queue or waiting for it to resolve - * @param promiseFn Promise to consume - * @param wait Whether to wait for the promise to resolve or resolve immediately - */ -async function consumeCallback(promiseFn, wait) { - if (wait === true) { - // Clear config since callbacks are not part of the root run - // Avoid using global singleton due to circuluar dependency issues - const asyncLocalStorageInstance = globals_getGlobalAsyncLocalStorageInstance(); - if (asyncLocalStorageInstance !== undefined) { - await asyncLocalStorageInstance.run(undefined, async () => promiseFn()); +function cleanEnum(obj) { + return Object.entries(obj) + .filter(([k, _]) => { + // return true if NaN, meaning it's not a number, thus a string key + return Number.isNaN(Number.parseInt(k, 10)); + }) + .map((el) => el[1]); +} +// instanceof +class util_Class { + constructor(..._args) { } +} + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/core/errors.js + + +const initializer = (inst, def) => { + inst.name = "$ZodError"; + Object.defineProperty(inst, "_zod", { + value: inst._zod, + enumerable: false, + }); + Object.defineProperty(inst, "issues", { + value: def, + enumerable: false, + }); + Object.defineProperty(inst, "message", { + get() { + return JSON.stringify(def, jsonStringifyReplacer, 2); + }, + enumerable: true, + // configurable: false, + }); +}; +const $ZodError = $constructor("$ZodError", initializer); +const $ZodRealError = $constructor("$ZodError", initializer, { Parent: Error }); +function flattenError(error, mapper = (issue) => issue.message) { + const fieldErrors = {}; + const formErrors = []; + for (const sub of error.issues) { + if (sub.path.length > 0) { + fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; + fieldErrors[sub.path[0]].push(mapper(sub)); } else { - await promiseFn(); + formErrors.push(mapper(sub)); } } - else { - queue = getQueue(); - void queue.add(async () => { - const asyncLocalStorageInstance = globals_getGlobalAsyncLocalStorageInstance(); - if (asyncLocalStorageInstance !== undefined) { - await asyncLocalStorageInstance.run(undefined, async () => promiseFn()); + return { formErrors, fieldErrors }; +} +function formatError(error, _mapper) { + const mapper = _mapper || + function (issue) { + return issue.message; + }; + const fieldErrors = { _errors: [] }; + const processError = (error) => { + for (const issue of error.issues) { + if (issue.code === "invalid_union" && issue.errors.length) { + issue.errors.map((issues) => processError({ issues })); + } + else if (issue.code === "invalid_key") { + processError({ issues: issue.issues }); + } + else if (issue.code === "invalid_element") { + processError({ issues: issue.issues }); + } + else if (issue.path.length === 0) { + fieldErrors._errors.push(mapper(issue)); } else { - await promiseFn(); + let curr = fieldErrors; + let i = 0; + while (i < issue.path.length) { + const el = issue.path[i]; + const terminal = i === issue.path.length - 1; + if (!terminal) { + curr[el] = curr[el] || { _errors: [] }; + } + else { + curr[el] = curr[el] || { _errors: [] }; + curr[el]._errors.push(mapper(issue)); + } + curr = curr[el]; + i++; + } } - }); - } + } + }; + processError(error); + return fieldErrors; } -/** - * Waits for all promises in the queue to resolve. If the queue is - * undefined, it immediately resolves a promise. - */ -function awaitAllCallbacks() { - return typeof queue !== "undefined" ? queue.onIdle() : Promise.resolve(); +function treeifyError(error, _mapper) { + const mapper = _mapper || + function (issue) { + return issue.message; + }; + const result = { errors: [] }; + const processError = (error, path = []) => { + var _a, _b; + for (const issue of error.issues) { + if (issue.code === "invalid_union" && issue.errors.length) { + // regular union error + issue.errors.map((issues) => processError({ issues }, issue.path)); + } + else if (issue.code === "invalid_key") { + processError({ issues: issue.issues }, issue.path); + } + else if (issue.code === "invalid_element") { + processError({ issues: issue.issues }, issue.path); + } + else { + const fullpath = [...path, ...issue.path]; + if (fullpath.length === 0) { + result.errors.push(mapper(issue)); + continue; + } + let curr = result; + let i = 0; + while (i < fullpath.length) { + const el = fullpath[i]; + const terminal = i === fullpath.length - 1; + if (typeof el === "string") { + curr.properties ?? (curr.properties = {}); + (_a = curr.properties)[el] ?? (_a[el] = { errors: [] }); + curr = curr.properties[el]; + } + else { + curr.items ?? (curr.items = []); + (_b = curr.items)[el] ?? (_b[el] = { errors: [] }); + curr = curr.items[el]; + } + if (terminal) { + curr.errors.push(mapper(issue)); + } + i++; + } + } + } + }; + processError(error); + return result; } - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/callbacks/promises.js - - - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/callbacks.js - -const callbacks_isTracingEnabled = (tracingEnabled) => { - if (tracingEnabled !== undefined) { - return tracingEnabled; - } - const envVars = [ - "LANGSMITH_TRACING_V2", - "LANGCHAIN_TRACING_V2", - "LANGSMITH_TRACING", - "LANGCHAIN_TRACING", - ]; - return !!envVars.find((envVar) => env_getEnvironmentVariable(envVar) === "true"); -}; - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/singletons/async_local_storage/context.js - - -/** - * Set a context variable. Context variables are scoped to any - * child runnables called by the current runnable, or globally if set outside - * of any runnable. +/** Format a ZodError as a human-readable string in the following form. * - * @remarks - * This function is only supported in environments that support AsyncLocalStorage, - * including Node.js, Deno, and Cloudflare Workers. + * From * - * @example * ```ts - * import { RunnableLambda } from "@langchain/core/runnables"; - * import { - * getContextVariable, - * setContextVariable - * } from "@langchain/core/context"; - * - * const nested = RunnableLambda.from(() => { - * // "bar" because it was set by a parent - * console.log(getContextVariable("foo")); - * - * // Override to "baz", but only for child runnables - * setContextVariable("foo", "baz"); - * - * // Now "baz", but only for child runnables - * return getContextVariable("foo"); - * }); - * - * const runnable = RunnableLambda.from(async () => { - * // Set a context variable named "foo" - * setContextVariable("foo", "bar"); - * - * const res = await nested.invoke({}); - * - * // Still "bar" since child changes do not affect parents - * console.log(getContextVariable("foo")); - * - * return res; - * }); + * ZodError { + * issues: [ + * { + * expected: 'string', + * code: 'invalid_type', + * path: [ 'username' ], + * message: 'Invalid input: expected string' + * }, + * { + * expected: 'number', + * code: 'invalid_type', + * path: [ 'favoriteNumbers', 1 ], + * message: 'Invalid input: expected number' + * } + * ]; + * } + * ``` * - * // undefined, because context variable has not been set yet - * console.log(getContextVariable("foo")); + * to * - * // Final return value is "baz" - * const result = await runnable.invoke({}); * ``` - * - * @param name The name of the context variable. - * @param value The value to set. + * username + * ✖ Expected number, received string at "username + * favoriteNumbers[0] + * ✖ Invalid input: expected number + * ``` */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function setContextVariable(name, value) { - // Avoid using global singleton due to circuluar dependency issues - const asyncLocalStorageInstance = getGlobalAsyncLocalStorageInstance(); - if (asyncLocalStorageInstance === undefined) { - throw new Error(`Internal error: Global shared async local storage instance has not been initialized.`); - } - const runTree = asyncLocalStorageInstance.getStore(); - const contextVars = { ...runTree?.[_CONTEXT_VARIABLES_KEY] }; - contextVars[name] = value; - let newValue = {}; - if (isRunTree(runTree)) { - newValue = new RunTree(runTree); +function toDotPath(path) { + const segs = []; + for (const seg of path) { + if (typeof seg === "number") + segs.push(`[${seg}]`); + else if (typeof seg === "symbol") + segs.push(`[${JSON.stringify(String(seg))}]`); + else if (/[^\w$]/.test(seg)) + segs.push(`[${JSON.stringify(seg)}]`); + else { + if (segs.length) + segs.push("."); + segs.push(seg); + } } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - newValue[_CONTEXT_VARIABLES_KEY] = contextVars; - asyncLocalStorageInstance.enterWith(newValue); + return segs.join(""); } -/** - * Get the value of a previously set context variable. Context variables - * are scoped to any child runnables called by the current runnable, - * or globally if set outside of any runnable. - * - * @remarks - * This function is only supported in environments that support AsyncLocalStorage, - * including Node.js, Deno, and Cloudflare Workers. - * - * @example - * ```ts - * import { RunnableLambda } from "@langchain/core/runnables"; - * import { - * getContextVariable, - * setContextVariable - * } from "@langchain/core/context"; - * - * const nested = RunnableLambda.from(() => { - * // "bar" because it was set by a parent - * console.log(getContextVariable("foo")); - * - * // Override to "baz", but only for child runnables - * setContextVariable("foo", "baz"); - * - * // Now "baz", but only for child runnables - * return getContextVariable("foo"); - * }); - * - * const runnable = RunnableLambda.from(async () => { - * // Set a context variable named "foo" - * setContextVariable("foo", "bar"); - * - * const res = await nested.invoke({}); - * - * // Still "bar" since child changes do not affect parents - * console.log(getContextVariable("foo")); - * - * return res; - * }); - * - * // undefined, because context variable has not been set yet - * console.log(getContextVariable("foo")); - * - * // Final return value is "baz" - * const result = await runnable.invoke({}); - * ``` - * - * @param name The name of the context variable. - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function getContextVariable(name) { - // Avoid using global singleton due to circuluar dependency issues - const asyncLocalStorageInstance = globals_getGlobalAsyncLocalStorageInstance(); - if (asyncLocalStorageInstance === undefined) { - return undefined; +function prettifyError(error) { + const lines = []; + // sort by path length + const issues = [...error.issues].sort((a, b) => a.path.length - b.path.length); + // Process each issue + for (const issue of issues) { + lines.push(`✖ ${issue.message}`); + if (issue.path?.length) + lines.push(` → at ${toDotPath(issue.path)}`); } - const runTree = asyncLocalStorageInstance.getStore(); - return runTree?.[globals_CONTEXT_VARIABLES_KEY]?.[name]; + // Convert Map to formatted string + return lines.join("\n"); } -const LC_CONFIGURE_HOOKS_KEY = Symbol("lc:configure_hooks"); -const _getConfigureHooks = () => getContextVariable(LC_CONFIGURE_HOOKS_KEY) || []; -/** - * Register a callback configure hook to automatically add callback handlers to all runs. - * - * There are two ways to use this: - * - * 1. Using a context variable: - * - Set `contextVar` to specify the variable name - * - Use `setContextVariable()` to store your handler instance - * - * 2. Using an environment variable: - * - Set both `envVar` and `handlerClass` - * - The handler will be instantiated when the env var is set to "true". - * - * @example - * ```typescript - * // Method 1: Using context variable - * import { - * registerConfigureHook, - * setContextVariable - * } from "@langchain/core/context"; - * - * const tracer = new MyCallbackHandler(); - * registerConfigureHook({ - * contextVar: "my_tracer", - * }); - * setContextVariable("my_tracer", tracer); - * - * // ...run code here - * - * // Method 2: Using environment variable - * registerConfigureHook({ - * handlerClass: MyCallbackHandler, - * envVar: "MY_TRACER_ENABLED", - * }); - * process.env.MY_TRACER_ENABLED = "true"; - * - * // ...run code here - * ``` - * - * @param config Configuration object for the hook - * @param config.contextVar Name of the context variable containing the handler instance - * @param config.inheritable Whether child runs should inherit this handler - * @param config.handlerClass Optional callback handler class (required if using envVar) - * @param config.envVar Optional environment variable name to control handler activation - */ -const registerConfigureHook = (config) => { - if (config.envVar && !config.handlerClass) { - throw new Error("If envVar is set, handlerClass must also be set to a non-None value."); + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/core/parse.js + + + +const _parse = (_Err) => (schema, value, _ctx, _params) => { + const ctx = _ctx ? Object.assign(_ctx, { async: false }) : { async: false }; + const result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) { + throw new $ZodAsyncError(); } - setContextVariable(LC_CONFIGURE_HOOKS_KEY, [..._getConfigureHooks(), config]); + if (result.issues.length) { + const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); + captureStackTrace(e, _params?.callee); + throw e; + } + return result.value; +}; +const parse_parse = /* @__PURE__*/ _parse($ZodRealError); +const _parseAsync = (_Err) => async (schema, value, _ctx, params) => { + const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true }; + let result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) + result = await result; + if (result.issues.length) { + const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); + captureStackTrace(e, params?.callee); + throw e; + } + return result.value; +}; +const parse_parseAsync = /* @__PURE__*/ _parseAsync($ZodRealError); +const _safeParse = (_Err) => (schema, value, _ctx) => { + const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; + const result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) { + throw new $ZodAsyncError(); + } + return result.issues.length + ? { + success: false, + error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))), + } + : { success: true, data: result.value }; +}; +const safeParse = /* @__PURE__*/ _safeParse($ZodRealError); +const _safeParseAsync = (_Err) => async (schema, value, _ctx) => { + const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true }; + let result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) + result = await result; + return result.issues.length + ? { + success: false, + error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))), + } + : { success: true, data: result.value }; +}; +const safeParseAsync = /* @__PURE__*/ _safeParseAsync($ZodRealError); + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/core/regexes.js +const cuid = /^[cC][^\s-]{8,}$/; +const cuid2 = /^[0-9a-z]+$/; +const ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/; +const xid = /^[0-9a-vA-V]{20}$/; +const ksuid = /^[A-Za-z0-9]{27}$/; +const nanoid = /^[a-zA-Z0-9_-]{21}$/; +/** ISO 8601-1 duration regex. Does not support the 8601-2 extensions like negative durations or fractional/negative components. */ +const duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/; +/** Implements ISO 8601-2 extensions like explicit +- prefixes, mixing weeks with other units, and fractional/negative components. */ +const extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; +/** A regex for any UUID-like identifier: 8-4-4-4-12 hex pattern */ +const guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/; +/** Returns a regex for validating an RFC 4122 UUID. + * + * @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */ +const uuid = (version) => { + if (!version) + return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/; + return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`); +}; +const regexes_uuid4 = /*@__PURE__*/ (/* unused pure expression or super */ null && (uuid(4))); +const uuid6 = /*@__PURE__*/ (/* unused pure expression or super */ null && (uuid(6))); +const uuid7 = /*@__PURE__*/ (/* unused pure expression or super */ null && (uuid(7))); +/** Practical email validation */ +const email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/; +/** Equivalent to the HTML5 input[type=email] validation implemented by browsers. Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email */ +const html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; +/** The classic emailregex.com regex for RFC 5322-compliant emails */ +const rfc5322Email = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; +/** A loose regex that allows Unicode characters, enforces length limits, and that's about it. */ +const unicodeEmail = /^[^\s@"]{1,64}@[^\s@]{1,255}$/u; +const browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; +// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression +const _emoji = (/* unused pure expression or super */ null && (`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`)); +function emoji() { + return new RegExp(_emoji, "u"); +} +const ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; +const ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/; +const cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/; +const cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; +// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript +const base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/; +const base64url = /^[A-Za-z0-9_-]*$/; +// based on https://stackoverflow.com/questions/106179/regular-expression-to-match-dns-hostname-or-ip-address +// export const hostname: RegExp = +// /^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)+([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$/; +const hostname = /^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/; +const domain = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/; +// https://blog.stevenlevithan.com/archives/validate-phone-number#r4-3 (regex sans spaces) +const e164 = /^\+(?:[0-9]){6,14}[0-9]$/; +// const dateSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`; +const dateSource = `(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`; +const date = /*@__PURE__*/ new RegExp(`^${dateSource}$`); +function timeSource(args) { + const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`; + const regex = typeof args.precision === "number" + ? args.precision === -1 + ? `${hhmm}` + : args.precision === 0 + ? `${hhmm}:[0-5]\\d` + : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` + : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`; + return regex; +} +function time(args) { + return new RegExp(`^${timeSource(args)}$`); +} +// Adapted from https://stackoverflow.com/a/3143231 +function datetime(args) { + const time = timeSource({ precision: args.precision }); + const opts = ["Z"]; + if (args.local) + opts.push(""); + if (args.offset) + opts.push(`([+-]\\d{2}:\\d{2})`); + const timeRegex = `${time}(?:${opts.join("|")})`; + return new RegExp(`^${dateSource}T(?:${timeRegex})$`); +} +const string = (params) => { + const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`; + return new RegExp(`^${regex}$`); }; +const bigint = /^\d+n?$/; +const integer = /^\d+$/; +const number = /^-?\d+(?:\.\d+)?/i; +const regexes_boolean = /true|false/i; +const _null = /null/i; -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/callbacks/manager.js +const _undefined = /undefined/i; + +// regex for string with no uppercase letters +const lowercase = /^[^A-Z]*$/; +// regex for string with no lowercase letters +const uppercase = /^[^a-z]*$/; + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/core/checks.js +// import { $ZodType } from "./schemas.js"; +const $ZodCheck = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheck", (inst, def) => { + var _a; + inst._zod ?? (inst._zod = {}); + inst._zod.def = def; + (_a = inst._zod).onattach ?? (_a.onattach = []); +}))); +const numericOriginMap = { + number: "number", + bigint: "bigint", + object: "date", +}; +const $ZodCheckLessThan = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckLessThan", (inst, def) => { + $ZodCheck.init(inst, def); + const origin = numericOriginMap[typeof def.value]; + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY; + if (def.value < curr) { + if (def.inclusive) + bag.maximum = def.value; + else + bag.exclusiveMaximum = def.value; + } + }); + inst._zod.check = (payload) => { + if (def.inclusive ? payload.value <= def.value : payload.value < def.value) { + return; + } + payload.issues.push({ + origin, + code: "too_big", + maximum: def.value, + input: payload.value, + inclusive: def.inclusive, + inst, + continue: !def.abort, + }); + }; +}))); +const $ZodCheckGreaterThan = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckGreaterThan", (inst, def) => { + $ZodCheck.init(inst, def); + const origin = numericOriginMap[typeof def.value]; + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY; + if (def.value > curr) { + if (def.inclusive) + bag.minimum = def.value; + else + bag.exclusiveMinimum = def.value; + } + }); + inst._zod.check = (payload) => { + if (def.inclusive ? payload.value >= def.value : payload.value > def.value) { + return; + } + payload.issues.push({ + origin: origin, + code: "too_small", + minimum: def.value, + input: payload.value, + inclusive: def.inclusive, + inst, + continue: !def.abort, + }); + }; +}))); +const $ZodCheckMultipleOf = +/*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckMultipleOf", (inst, def) => { + $ZodCheck.init(inst, def); + inst._zod.onattach.push((inst) => { + var _a; + (_a = inst._zod.bag).multipleOf ?? (_a.multipleOf = def.value); + }); + inst._zod.check = (payload) => { + if (typeof payload.value !== typeof def.value) + throw new Error("Cannot mix number and bigint in multiple_of check."); + const isMultiple = typeof payload.value === "bigint" + ? payload.value % def.value === BigInt(0) + : util.floatSafeRemainder(payload.value, def.value) === 0; + if (isMultiple) + return; + payload.issues.push({ + origin: typeof payload.value, + code: "not_multiple_of", + divisor: def.value, + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}))); +const $ZodCheckNumberFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckNumberFormat", (inst, def) => { + $ZodCheck.init(inst, def); // no format checks + def.format = def.format || "float64"; + const isInt = def.format?.includes("int"); + const origin = isInt ? "int" : "number"; + const [minimum, maximum] = util.NUMBER_FORMAT_RANGES[def.format]; + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.format = def.format; + bag.minimum = minimum; + bag.maximum = maximum; + if (isInt) + bag.pattern = regexes.integer; + }); + inst._zod.check = (payload) => { + const input = payload.value; + if (isInt) { + if (!Number.isInteger(input)) { + // invalid_format issue + // payload.issues.push({ + // expected: def.format, + // format: def.format, + // code: "invalid_format", + // input, + // inst, + // }); + // invalid_type issue + payload.issues.push({ + expected: origin, + format: def.format, + code: "invalid_type", + input, + inst, + }); + return; + // not_multiple_of issue + // payload.issues.push({ + // code: "not_multiple_of", + // origin: "number", + // input, + // inst, + // divisor: 1, + // }); + } + if (!Number.isSafeInteger(input)) { + if (input > 0) { + // too_big + payload.issues.push({ + input, + code: "too_big", + maximum: Number.MAX_SAFE_INTEGER, + note: "Integers must be within the safe integer range.", + inst, + origin, + continue: !def.abort, + }); + } + else { + // too_small + payload.issues.push({ + input, + code: "too_small", + minimum: Number.MIN_SAFE_INTEGER, + note: "Integers must be within the safe integer range.", + inst, + origin, + continue: !def.abort, + }); + } + return; + } + } + if (input < minimum) { + payload.issues.push({ + origin: "number", + input, + code: "too_small", + minimum, + inclusive: true, + inst, + continue: !def.abort, + }); + } + if (input > maximum) { + payload.issues.push({ + origin: "number", + input, + code: "too_big", + maximum, + inst, + }); + } + }; +}))); +const $ZodCheckBigIntFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckBigIntFormat", (inst, def) => { + $ZodCheck.init(inst, def); // no format checks + const [minimum, maximum] = util.BIGINT_FORMAT_RANGES[def.format]; + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.format = def.format; + bag.minimum = minimum; + bag.maximum = maximum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + if (input < minimum) { + payload.issues.push({ + origin: "bigint", + input, + code: "too_small", + minimum: minimum, + inclusive: true, + inst, + continue: !def.abort, + }); + } + if (input > maximum) { + payload.issues.push({ + origin: "bigint", + input, + code: "too_big", + maximum, + inst, + }); + } + }; +}))); +const $ZodCheckMaxSize = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckMaxSize", (inst, def) => { + $ZodCheck.init(inst, def); + inst._zod.when = (payload) => { + const val = payload.value; + return !util.nullish(val) && val.size !== undefined; + }; + inst._zod.onattach.push((inst) => { + const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY); + if (def.maximum < curr) + inst._zod.bag.maximum = def.maximum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const size = input.size; + if (size <= def.maximum) + return; + payload.issues.push({ + origin: util.getSizableOrigin(input), + code: "too_big", + maximum: def.maximum, + input, + inst, + continue: !def.abort, + }); + }; +}))); +const $ZodCheckMinSize = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckMinSize", (inst, def) => { + $ZodCheck.init(inst, def); + inst._zod.when = (payload) => { + const val = payload.value; + return !util.nullish(val) && val.size !== undefined; + }; + inst._zod.onattach.push((inst) => { + const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY); + if (def.minimum > curr) + inst._zod.bag.minimum = def.minimum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const size = input.size; + if (size >= def.minimum) + return; + payload.issues.push({ + origin: util.getSizableOrigin(input), + code: "too_small", + minimum: def.minimum, + input, + inst, + continue: !def.abort, + }); + }; +}))); +const $ZodCheckSizeEquals = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckSizeEquals", (inst, def) => { + $ZodCheck.init(inst, def); + inst._zod.when = (payload) => { + const val = payload.value; + return !util.nullish(val) && val.size !== undefined; + }; + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.minimum = def.size; + bag.maximum = def.size; + bag.size = def.size; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const size = input.size; + if (size === def.size) + return; + const tooBig = size > def.size; + payload.issues.push({ + origin: util.getSizableOrigin(input), + ...(tooBig ? { code: "too_big", maximum: def.size } : { code: "too_small", minimum: def.size }), + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}))); +const $ZodCheckMaxLength = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckMaxLength", (inst, def) => { + $ZodCheck.init(inst, def); + inst._zod.when = (payload) => { + const val = payload.value; + return !util.nullish(val) && val.length !== undefined; + }; + inst._zod.onattach.push((inst) => { + const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY); + if (def.maximum < curr) + inst._zod.bag.maximum = def.maximum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const length = input.length; + if (length <= def.maximum) + return; + const origin = util.getLengthableOrigin(input); + payload.issues.push({ + origin, + code: "too_big", + maximum: def.maximum, + inclusive: true, + input, + inst, + continue: !def.abort, + }); + }; +}))); +const $ZodCheckMinLength = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckMinLength", (inst, def) => { + $ZodCheck.init(inst, def); + inst._zod.when = (payload) => { + const val = payload.value; + return !util.nullish(val) && val.length !== undefined; + }; + inst._zod.onattach.push((inst) => { + const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY); + if (def.minimum > curr) + inst._zod.bag.minimum = def.minimum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const length = input.length; + if (length >= def.minimum) + return; + const origin = util.getLengthableOrigin(input); + payload.issues.push({ + origin, + code: "too_small", + minimum: def.minimum, + inclusive: true, + input, + inst, + continue: !def.abort, + }); + }; +}))); +const $ZodCheckLengthEquals = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckLengthEquals", (inst, def) => { + $ZodCheck.init(inst, def); + inst._zod.when = (payload) => { + const val = payload.value; + return !util.nullish(val) && val.length !== undefined; + }; + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.minimum = def.length; + bag.maximum = def.length; + bag.length = def.length; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const length = input.length; + if (length === def.length) + return; + const origin = util.getLengthableOrigin(input); + const tooBig = length > def.length; + payload.issues.push({ + origin, + ...(tooBig ? { code: "too_big", maximum: def.length } : { code: "too_small", minimum: def.length }), + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}))); +const $ZodCheckStringFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckStringFormat", (inst, def) => { + var _a; + $ZodCheck.init(inst, def); + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.format = def.format; + if (def.pattern) { + bag.patterns ?? (bag.patterns = new Set()); + bag.patterns.add(def.pattern); + } + }); + (_a = inst._zod).check ?? (_a.check = (payload) => { + if (!def.pattern) + throw new Error("Not implemented."); + def.pattern.lastIndex = 0; + if (def.pattern.test(payload.value)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: def.format, + input: payload.value, + ...(def.pattern ? { pattern: def.pattern.toString() } : {}), + inst, + continue: !def.abort, + }); + }); +}))); +const $ZodCheckRegex = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckRegex", (inst, def) => { + $ZodCheckStringFormat.init(inst, def); + inst._zod.check = (payload) => { + def.pattern.lastIndex = 0; + if (def.pattern.test(payload.value)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "regex", + input: payload.value, + pattern: def.pattern.toString(), + inst, + continue: !def.abort, + }); + }; +}))); +const $ZodCheckLowerCase = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckLowerCase", (inst, def) => { + def.pattern ?? (def.pattern = regexes.lowercase); + $ZodCheckStringFormat.init(inst, def); +}))); +const $ZodCheckUpperCase = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckUpperCase", (inst, def) => { + def.pattern ?? (def.pattern = regexes.uppercase); + $ZodCheckStringFormat.init(inst, def); +}))); +const $ZodCheckIncludes = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckIncludes", (inst, def) => { + $ZodCheck.init(inst, def); + const escapedRegex = util.escapeRegex(def.includes); + const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex); + def.pattern = pattern; + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.patterns ?? (bag.patterns = new Set()); + bag.patterns.add(pattern); + }); + inst._zod.check = (payload) => { + if (payload.value.includes(def.includes, def.position)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "includes", + includes: def.includes, + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}))); +const $ZodCheckStartsWith = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckStartsWith", (inst, def) => { + $ZodCheck.init(inst, def); + const pattern = new RegExp(`^${util.escapeRegex(def.prefix)}.*`); + def.pattern ?? (def.pattern = pattern); + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.patterns ?? (bag.patterns = new Set()); + bag.patterns.add(pattern); + }); + inst._zod.check = (payload) => { + if (payload.value.startsWith(def.prefix)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "starts_with", + prefix: def.prefix, + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}))); +const $ZodCheckEndsWith = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckEndsWith", (inst, def) => { + $ZodCheck.init(inst, def); + const pattern = new RegExp(`.*${util.escapeRegex(def.suffix)}$`); + def.pattern ?? (def.pattern = pattern); + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.patterns ?? (bag.patterns = new Set()); + bag.patterns.add(pattern); + }); + inst._zod.check = (payload) => { + if (payload.value.endsWith(def.suffix)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "ends_with", + suffix: def.suffix, + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}))); +/////////////////////////////////// +///// $ZodCheckProperty ///// +/////////////////////////////////// +function handleCheckPropertyResult(result, payload, property) { + if (result.issues.length) { + payload.issues.push(...util.prefixIssues(property, result.issues)); + } +} +const $ZodCheckProperty = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckProperty", (inst, def) => { + $ZodCheck.init(inst, def); + inst._zod.check = (payload) => { + const result = def.schema._zod.run({ + value: payload.value[def.property], + issues: [], + }, {}); + if (result instanceof Promise) { + return result.then((result) => handleCheckPropertyResult(result, payload, def.property)); + } + handleCheckPropertyResult(result, payload, def.property); + return; + }; +}))); +const $ZodCheckMimeType = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckMimeType", (inst, def) => { + $ZodCheck.init(inst, def); + const mimeSet = new Set(def.mime); + inst._zod.onattach.push((inst) => { + inst._zod.bag.mime = def.mime; + }); + inst._zod.check = (payload) => { + if (mimeSet.has(payload.value.type)) + return; + payload.issues.push({ + code: "invalid_value", + values: def.mime, + input: payload.value.type, + inst, + }); + }; +}))); +const $ZodCheckOverwrite = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckOverwrite", (inst, def) => { + $ZodCheck.init(inst, def); + inst._zod.check = (payload) => { + payload.value = def.tx(payload.value); + }; +}))); + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/core/versions.js +const versions_version = { + major: 4, + minor: 0, + patch: 0, +}; + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/core/schemas.js @@ -93569,2764 +93353,8224 @@ const registerConfigureHook = (config) => { -function parseCallbackConfigArg(arg) { - if (!arg) { - return {}; - } - else if (Array.isArray(arg) || "name" in arg) { - return { callbacks: arg }; - } - else { - return arg; +const $ZodType = /*@__PURE__*/ $constructor("$ZodType", (inst, def) => { + var _a; + inst ?? (inst = {}); + // avoids issues with using Math.random() in Next.js caching + defineLazy(inst._zod, "id", () => def.type + "_" + randomString(10)); + inst._zod.def = def; // set _def property + inst._zod.bag = inst._zod.bag || {}; // initialize _bag object + inst._zod.version = versions_version; + const checks = [...(inst._zod.def.checks ?? [])]; + // if inst is itself a checks.$ZodCheck, run it as a check + if (inst._zod.traits.has("$ZodCheck")) { + checks.unshift(inst); } -} -/** - * Manage callbacks from different components of LangChain. - */ -class BaseCallbackManager { - setHandler(handler) { - return this.setHandlers([handler]); + // + for (const ch of checks) { + for (const fn of ch._zod.onattach) { + fn(inst); + } } -} -/** - * Base class for run manager in LangChain. - */ -class BaseRunManager { - constructor(runId, handlers, inheritableHandlers, tags, inheritableTags, metadata, inheritableMetadata, _parentRunId) { - Object.defineProperty(this, "runId", { - enumerable: true, - configurable: true, - writable: true, - value: runId - }); - Object.defineProperty(this, "handlers", { - enumerable: true, - configurable: true, - writable: true, - value: handlers - }); - Object.defineProperty(this, "inheritableHandlers", { - enumerable: true, - configurable: true, - writable: true, - value: inheritableHandlers - }); - Object.defineProperty(this, "tags", { - enumerable: true, - configurable: true, - writable: true, - value: tags - }); - Object.defineProperty(this, "inheritableTags", { - enumerable: true, - configurable: true, - writable: true, - value: inheritableTags - }); - Object.defineProperty(this, "metadata", { - enumerable: true, - configurable: true, - writable: true, - value: metadata - }); - Object.defineProperty(this, "inheritableMetadata", { - enumerable: true, - configurable: true, - writable: true, - value: inheritableMetadata - }); - Object.defineProperty(this, "_parentRunId", { - enumerable: true, - configurable: true, - writable: true, - value: _parentRunId + if (checks.length === 0) { + // deferred initializer + // inst._zod.parse is not yet defined + (_a = inst._zod).deferred ?? (_a.deferred = []); + inst._zod.deferred?.push(() => { + inst._zod.run = inst._zod.parse; }); } - get parentRunId() { - return this._parentRunId; - } - async handleText(text) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - try { - await handler.handleText?.(text, this.runId, this._parentRunId, this.tags); - } - catch (err) { - const logFunction = handler.raiseError - ? console.error - : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleText: ${err}`); - if (handler.raiseError) { - throw err; - } - } - }, handler.awaitHandlers))); - } - async handleCustomEvent(eventName, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - data, _runId, _tags, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - _metadata) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - try { - await handler.handleCustomEvent?.(eventName, data, this.runId, this.tags, this.metadata); - } - catch (err) { - const logFunction = handler.raiseError - ? console.error - : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleCustomEvent: ${err}`); - if (handler.raiseError) { - throw err; - } - } - }, handler.awaitHandlers))); - } -} -/** - * Manages callbacks for retriever runs. - */ -class CallbackManagerForRetrieverRun extends BaseRunManager { - getChild(tag) { - // eslint-disable-next-line @typescript-eslint/no-use-before-define - const manager = new CallbackManager(this.runId); - manager.setHandlers(this.inheritableHandlers); - manager.addTags(this.inheritableTags); - manager.addMetadata(this.inheritableMetadata); - if (tag) { - manager.addTags([tag], false); - } - return manager; - } - async handleRetrieverEnd(documents) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreRetriever) { - try { - await handler.handleRetrieverEnd?.(documents, this.runId, this._parentRunId, this.tags); - } - catch (err) { - const logFunction = handler.raiseError - ? console.error - : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleRetriever`); - if (handler.raiseError) { - throw err; - } + else { + const runChecks = (payload, checks, ctx) => { + let isAborted = aborted(payload); + let asyncResult; + for (const ch of checks) { + if (ch._zod.when) { + const shouldRun = ch._zod.when(payload); + if (!shouldRun) + continue; } - } - }, handler.awaitHandlers))); - } - async handleRetrieverError(err) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreRetriever) { - try { - await handler.handleRetrieverError?.(err, this.runId, this._parentRunId, this.tags); + else if (isAborted) { + continue; } - catch (error) { - const logFunction = handler.raiseError - ? console.error - : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleRetrieverError: ${error}`); - if (handler.raiseError) { - throw err; - } + const currLen = payload.issues.length; + const _ = ch._zod.check(payload); + if (_ instanceof Promise && ctx?.async === false) { + throw new $ZodAsyncError(); } - } - }, handler.awaitHandlers))); - } -} -class CallbackManagerForLLMRun extends BaseRunManager { - async handleLLMNewToken(token, idx, _runId, _parentRunId, _tags, fields) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreLLM) { - try { - await handler.handleLLMNewToken?.(token, idx ?? { prompt: 0, completion: 0 }, this.runId, this._parentRunId, this.tags, fields); + if (asyncResult || _ instanceof Promise) { + asyncResult = (asyncResult ?? Promise.resolve()).then(async () => { + await _; + const nextLen = payload.issues.length; + if (nextLen === currLen) + return; + if (!isAborted) + isAborted = aborted(payload, currLen); + }); } - catch (err) { - const logFunction = handler.raiseError - ? console.error - : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleLLMNewToken: ${err}`); - if (handler.raiseError) { - throw err; - } + else { + const nextLen = payload.issues.length; + if (nextLen === currLen) + continue; + if (!isAborted) + isAborted = aborted(payload, currLen); } } - }, handler.awaitHandlers))); - } - async handleLLMError(err, _runId, _parentRunId, _tags, extraParams) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreLLM) { - try { - await handler.handleLLMError?.(err, this.runId, this._parentRunId, this.tags, extraParams); - } - catch (err) { - const logFunction = handler.raiseError - ? console.error - : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleLLMError: ${err}`); - if (handler.raiseError) { - throw err; - } - } + if (asyncResult) { + return asyncResult.then(() => { + return payload; + }); } - }, handler.awaitHandlers))); + return payload; + }; + inst._zod.run = (payload, ctx) => { + const result = inst._zod.parse(payload, ctx); + if (result instanceof Promise) { + if (ctx.async === false) + throw new $ZodAsyncError(); + return result.then((result) => runChecks(result, checks, ctx)); + } + return runChecks(result, checks, ctx); + }; } - async handleLLMEnd(output, _runId, _parentRunId, _tags, extraParams) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreLLM) { - try { - await handler.handleLLMEnd?.(output, this.runId, this._parentRunId, this.tags, extraParams); - } - catch (err) { - const logFunction = handler.raiseError - ? console.error - : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleLLMEnd: ${err}`); - if (handler.raiseError) { - throw err; - } - } + inst["~standard"] = { + validate: (value) => { + try { + const r = safeParse(inst, value); + return r.success ? { value: r.data } : { issues: r.error?.issues }; } - }, handler.awaitHandlers))); - } -} -class CallbackManagerForChainRun extends BaseRunManager { - getChild(tag) { - // eslint-disable-next-line @typescript-eslint/no-use-before-define - const manager = new CallbackManager(this.runId); - manager.setHandlers(this.inheritableHandlers); - manager.addTags(this.inheritableTags); - manager.addMetadata(this.inheritableMetadata); - if (tag) { - manager.addTags([tag], false); - } - return manager; - } - async handleChainError(err, _runId, _parentRunId, _tags, kwargs) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreChain) { - try { - await handler.handleChainError?.(err, this.runId, this._parentRunId, this.tags, kwargs); - } - catch (err) { - const logFunction = handler.raiseError - ? console.error - : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleChainError: ${err}`); - if (handler.raiseError) { - throw err; - } - } + catch (_) { + return safeParseAsync(inst, value).then((r) => (r.success ? { value: r.data } : { issues: r.error?.issues })); } - }, handler.awaitHandlers))); - } - async handleChainEnd(output, _runId, _parentRunId, _tags, kwargs) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreChain) { - try { - await handler.handleChainEnd?.(output, this.runId, this._parentRunId, this.tags, kwargs); - } - catch (err) { - const logFunction = handler.raiseError - ? console.error - : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleChainEnd: ${err}`); - if (handler.raiseError) { - throw err; - } + }, + vendor: "zod", + version: 1, + }; +}); + +const $ZodString = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodString", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = [...(inst?._zod.bag?.patterns ?? [])].pop() ?? regexes.string(inst._zod.bag); + inst._zod.parse = (payload, _) => { + if (def.coerce) + try { + payload.value = String(payload.value); + } + catch (_) { } + if (typeof payload.value === "string") + return payload; + payload.issues.push({ + expected: "string", + code: "invalid_type", + input: payload.value, + inst, + }); + return payload; + }; +}))); +const $ZodStringFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodStringFormat", (inst, def) => { + // check initialization must come first + checks.$ZodCheckStringFormat.init(inst, def); + $ZodString.init(inst, def); +}))); +const $ZodGUID = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodGUID", (inst, def) => { + def.pattern ?? (def.pattern = regexes.guid); + $ZodStringFormat.init(inst, def); +}))); +const $ZodUUID = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodUUID", (inst, def) => { + if (def.version) { + const versionMap = { + v1: 1, + v2: 2, + v3: 3, + v4: 4, + v5: 5, + v6: 6, + v7: 7, + v8: 8, + }; + const v = versionMap[def.version]; + if (v === undefined) + throw new Error(`Invalid UUID version: "${def.version}"`); + def.pattern ?? (def.pattern = regexes.uuid(v)); + } + else + def.pattern ?? (def.pattern = regexes.uuid()); + $ZodStringFormat.init(inst, def); +}))); +const $ZodEmail = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodEmail", (inst, def) => { + def.pattern ?? (def.pattern = regexes.email); + $ZodStringFormat.init(inst, def); +}))); +const $ZodURL = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodURL", (inst, def) => { + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + try { + const url = new URL(payload.value); + if (def.hostname) { + def.hostname.lastIndex = 0; + if (!def.hostname.test(url.hostname)) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid hostname", + pattern: regexes.hostname.source, + input: payload.value, + inst, + continue: !def.abort, + }); } } - }, handler.awaitHandlers))); - } - async handleAgentAction(action) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreAgent) { - try { - await handler.handleAgentAction?.(action, this.runId, this._parentRunId, this.tags); - } - catch (err) { - const logFunction = handler.raiseError - ? console.error - : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleAgentAction: ${err}`); - if (handler.raiseError) { - throw err; - } + if (def.protocol) { + def.protocol.lastIndex = 0; + if (!def.protocol.test(url.protocol.endsWith(":") ? url.protocol.slice(0, -1) : url.protocol)) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid protocol", + pattern: def.protocol.source, + input: payload.value, + inst, + continue: !def.abort, + }); } } - }, handler.awaitHandlers))); + return; + } + catch (_) { + payload.issues.push({ + code: "invalid_format", + format: "url", + input: payload.value, + inst, + continue: !def.abort, + }); + } + }; +}))); +const $ZodEmoji = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodEmoji", (inst, def) => { + def.pattern ?? (def.pattern = regexes.emoji()); + $ZodStringFormat.init(inst, def); +}))); +const $ZodNanoID = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodNanoID", (inst, def) => { + def.pattern ?? (def.pattern = regexes.nanoid); + $ZodStringFormat.init(inst, def); +}))); +const $ZodCUID = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCUID", (inst, def) => { + def.pattern ?? (def.pattern = regexes.cuid); + $ZodStringFormat.init(inst, def); +}))); +const $ZodCUID2 = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCUID2", (inst, def) => { + def.pattern ?? (def.pattern = regexes.cuid2); + $ZodStringFormat.init(inst, def); +}))); +const $ZodULID = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodULID", (inst, def) => { + def.pattern ?? (def.pattern = regexes.ulid); + $ZodStringFormat.init(inst, def); +}))); +const $ZodXID = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodXID", (inst, def) => { + def.pattern ?? (def.pattern = regexes.xid); + $ZodStringFormat.init(inst, def); +}))); +const $ZodKSUID = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodKSUID", (inst, def) => { + def.pattern ?? (def.pattern = regexes.ksuid); + $ZodStringFormat.init(inst, def); +}))); +const $ZodISODateTime = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodISODateTime", (inst, def) => { + def.pattern ?? (def.pattern = regexes.datetime(def)); + $ZodStringFormat.init(inst, def); + const _super = inst._zod.check; +}))); +const $ZodISODate = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodISODate", (inst, def) => { + def.pattern ?? (def.pattern = regexes.date); + $ZodStringFormat.init(inst, def); +}))); +const $ZodISOTime = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodISOTime", (inst, def) => { + def.pattern ?? (def.pattern = regexes.time(def)); + $ZodStringFormat.init(inst, def); + const _super = inst._zod.check; +}))); +const $ZodISODuration = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodISODuration", (inst, def) => { + def.pattern ?? (def.pattern = regexes.duration); + $ZodStringFormat.init(inst, def); +}))); +const $ZodIPv4 = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodIPv4", (inst, def) => { + def.pattern ?? (def.pattern = regexes.ipv4); + $ZodStringFormat.init(inst, def); + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.format = `ipv4`; + }); +}))); +const $ZodIPv6 = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodIPv6", (inst, def) => { + def.pattern ?? (def.pattern = regexes.ipv6); + $ZodStringFormat.init(inst, def); + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.format = `ipv6`; + }); + inst._zod.check = (payload) => { + try { + new URL(`http://[${payload.value}]`); + // return; + } + catch { + payload.issues.push({ + code: "invalid_format", + format: "ipv6", + input: payload.value, + inst, + continue: !def.abort, + }); + } + }; +}))); +const $ZodCIDRv4 = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCIDRv4", (inst, def) => { + def.pattern ?? (def.pattern = regexes.cidrv4); + $ZodStringFormat.init(inst, def); +}))); +const $ZodCIDRv6 = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCIDRv6", (inst, def) => { + def.pattern ?? (def.pattern = regexes.cidrv6); // not used for validation + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + const [address, prefix] = payload.value.split("/"); + try { + if (!prefix) + throw new Error(); + const prefixNum = Number(prefix); + if (`${prefixNum}` !== prefix) + throw new Error(); + if (prefixNum < 0 || prefixNum > 128) + throw new Error(); + new URL(`http://[${address}]`); + } + catch { + payload.issues.push({ + code: "invalid_format", + format: "cidrv6", + input: payload.value, + inst, + continue: !def.abort, + }); + } + }; +}))); +////////////////////////////// ZodBase64 ////////////////////////////// +function isValidBase64(data) { + if (data === "") + return true; + if (data.length % 4 !== 0) + return false; + try { + atob(data); + return true; } - async handleAgentEnd(action) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreAgent) { - try { - await handler.handleAgentEnd?.(action, this.runId, this._parentRunId, this.tags); - } - catch (err) { - const logFunction = handler.raiseError - ? console.error - : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleAgentEnd: ${err}`); - if (handler.raiseError) { - throw err; - } - } - } - }, handler.awaitHandlers))); + catch { + return false; } } -class CallbackManagerForToolRun extends BaseRunManager { - getChild(tag) { - // eslint-disable-next-line @typescript-eslint/no-use-before-define - const manager = new CallbackManager(this.runId); - manager.setHandlers(this.inheritableHandlers); - manager.addTags(this.inheritableTags); - manager.addMetadata(this.inheritableMetadata); - if (tag) { - manager.addTags([tag], false); - } - return manager; - } - async handleToolError(err) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreAgent) { - try { - await handler.handleToolError?.(err, this.runId, this._parentRunId, this.tags); - } - catch (err) { - const logFunction = handler.raiseError - ? console.error - : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleToolError: ${err}`); - if (handler.raiseError) { - throw err; - } - } - } - }, handler.awaitHandlers))); +const $ZodBase64 = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodBase64", (inst, def) => { + def.pattern ?? (def.pattern = regexes.base64); + $ZodStringFormat.init(inst, def); + inst._zod.onattach.push((inst) => { + inst._zod.bag.contentEncoding = "base64"; + }); + inst._zod.check = (payload) => { + if (isValidBase64(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: "base64", + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}))); +////////////////////////////// ZodBase64 ////////////////////////////// +function isValidBase64URL(data) { + if (!regexes.base64url.test(data)) + return false; + const base64 = data.replace(/[-_]/g, (c) => (c === "-" ? "+" : "/")); + const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, "="); + return isValidBase64(padded); +} +const $ZodBase64URL = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodBase64URL", (inst, def) => { + def.pattern ?? (def.pattern = regexes.base64url); + $ZodStringFormat.init(inst, def); + inst._zod.onattach.push((inst) => { + inst._zod.bag.contentEncoding = "base64url"; + }); + inst._zod.check = (payload) => { + if (isValidBase64URL(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: "base64url", + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}))); +const $ZodE164 = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodE164", (inst, def) => { + def.pattern ?? (def.pattern = regexes.e164); + $ZodStringFormat.init(inst, def); +}))); +////////////////////////////// ZodJWT ////////////////////////////// +function schemas_isValidJWT(token, algorithm = null) { + try { + const tokensParts = token.split("."); + if (tokensParts.length !== 3) + return false; + const [header] = tokensParts; + const parsedHeader = JSON.parse(atob(header)); + if ("typ" in parsedHeader && parsedHeader?.typ !== "JWT") + return false; + if (!parsedHeader.alg) + return false; + if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm)) + return false; + return true; } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - async handleToolEnd(output) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreAgent) { - try { - await handler.handleToolEnd?.(output, this.runId, this._parentRunId, this.tags); - } - catch (err) { - const logFunction = handler.raiseError - ? console.error - : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleToolEnd: ${err}`); - if (handler.raiseError) { - throw err; - } - } - } - }, handler.awaitHandlers))); + catch { + return false; } } -/** - * @example - * ```typescript - * const prompt = PromptTemplate.fromTemplate("What is the answer to {question}?"); - * - * // Example of using LLMChain with OpenAI and a simple prompt - * const chain = new LLMChain({ - * llm: new ChatOpenAI({ temperature: 0.9 }), - * prompt, - * }); - * - * // Running the chain with a single question - * const result = await chain.call({ - * question: "What is the airspeed velocity of an unladen swallow?", - * }); - * console.log("The answer is:", result); - * ``` - */ -class CallbackManager extends BaseCallbackManager { - constructor(parentRunId, options) { - super(); - Object.defineProperty(this, "handlers", { - enumerable: true, - configurable: true, - writable: true, - value: [] +const $ZodJWT = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodJWT", (inst, def) => { + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + if (schemas_isValidJWT(payload.value, def.alg)) + return; + payload.issues.push({ + code: "invalid_format", + format: "jwt", + input: payload.value, + inst, + continue: !def.abort, }); - Object.defineProperty(this, "inheritableHandlers", { - enumerable: true, - configurable: true, - writable: true, - value: [] + }; +}))); +const $ZodNumber = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodNumber", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = inst._zod.bag.pattern ?? regexes.number; + inst._zod.parse = (payload, _ctx) => { + if (def.coerce) + try { + payload.value = Number(payload.value); + } + catch (_) { } + const input = payload.value; + if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) { + return payload; + } + const received = typeof input === "number" + ? Number.isNaN(input) + ? "NaN" + : !Number.isFinite(input) + ? "Infinity" + : undefined + : undefined; + payload.issues.push({ + expected: "number", + code: "invalid_type", + input, + inst, + ...(received ? { received } : {}), }); - Object.defineProperty(this, "tags", { - enumerable: true, - configurable: true, - writable: true, - value: [] + return payload; + }; +}))); +const $ZodNumberFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodNumber", (inst, def) => { + checks.$ZodCheckNumberFormat.init(inst, def); + $ZodNumber.init(inst, def); // no format checksp +}))); +const $ZodBoolean = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodBoolean", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = regexes.boolean; + inst._zod.parse = (payload, _ctx) => { + if (def.coerce) + try { + payload.value = Boolean(payload.value); + } + catch (_) { } + const input = payload.value; + if (typeof input === "boolean") + return payload; + payload.issues.push({ + expected: "boolean", + code: "invalid_type", + input, + inst, }); - Object.defineProperty(this, "inheritableTags", { - enumerable: true, - configurable: true, - writable: true, - value: [] + return payload; + }; +}))); +const $ZodBigInt = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodBigInt", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = regexes.bigint; + inst._zod.parse = (payload, _ctx) => { + if (def.coerce) + try { + payload.value = BigInt(payload.value); + } + catch (_) { } + const { value: input } = payload; + if (typeof input === "bigint") + return payload; + payload.issues.push({ + expected: "bigint", + code: "invalid_type", + input, + inst, }); - Object.defineProperty(this, "metadata", { - enumerable: true, - configurable: true, - writable: true, - value: {} + return payload; + }; +}))); +const $ZodBigIntFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodBigInt", (inst, def) => { + checks.$ZodCheckBigIntFormat.init(inst, def); + $ZodBigInt.init(inst, def); // no format checks +}))); +const $ZodSymbol = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodSymbol", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + const { value: input } = payload; + if (typeof input === "symbol") + return payload; + payload.issues.push({ + expected: "symbol", + code: "invalid_type", + input, + inst, }); - Object.defineProperty(this, "inheritableMetadata", { - enumerable: true, - configurable: true, - writable: true, - value: {} + return payload; + }; +}))); +const $ZodUndefined = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodUndefined", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = regexes.undefined; + inst._zod.values = new Set([undefined]); + inst._zod.parse = (payload, _ctx) => { + const { value: input } = payload; + if (typeof input === "undefined") + return payload; + payload.issues.push({ + expected: "undefined", + code: "invalid_type", + input, + inst, }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "callback_manager" + return payload; + }; +}))); +const $ZodNull = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodNull", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = regexes.null; + inst._zod.values = new Set([null]); + inst._zod.parse = (payload, _ctx) => { + const { value: input } = payload; + if (input === null) + return payload; + payload.issues.push({ + expected: "null", + code: "invalid_type", + input, + inst, }); - Object.defineProperty(this, "_parentRunId", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 + return payload; + }; +}))); +const $ZodAny = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodAny", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload) => payload; +}))); +const schemas_$ZodUnknown = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodUnknown", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload) => payload; +}))); +const $ZodNever = /*@__PURE__*/ $constructor("$ZodNever", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + payload.issues.push({ + expected: "never", + code: "invalid_type", + input: payload.value, + inst, + }); + return payload; + }; +}); +const $ZodVoid = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodVoid", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + const { value: input } = payload; + if (typeof input === "undefined") + return payload; + payload.issues.push({ + expected: "void", + code: "invalid_type", + input, + inst, }); - this.handlers = options?.handlers ?? this.handlers; - this.inheritableHandlers = - options?.inheritableHandlers ?? this.inheritableHandlers; - this.tags = options?.tags ?? this.tags; - this.inheritableTags = options?.inheritableTags ?? this.inheritableTags; - this.metadata = options?.metadata ?? this.metadata; - this.inheritableMetadata = - options?.inheritableMetadata ?? this.inheritableMetadata; - this._parentRunId = parentRunId; - } - /** - * Gets the parent run ID, if any. - * - * @returns The parent run ID. - */ - getParentRunId() { - return this._parentRunId; + return payload; + }; +}))); +const $ZodDate = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodDate", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + if (def.coerce) { + try { + payload.value = new Date(payload.value); + } + catch (_err) { } + } + const input = payload.value; + const isDate = input instanceof Date; + const isValidDate = isDate && !Number.isNaN(input.getTime()); + if (isValidDate) + return payload; + payload.issues.push({ + expected: "date", + code: "invalid_type", + input, + ...(isDate ? { received: "Invalid Date" } : {}), + inst, + }); + return payload; + }; +}))); +function handleArrayResult(result, final, index) { + if (result.issues.length) { + final.issues.push(...util.prefixIssues(index, result.issues)); + } + final.value[index] = result.value; +} +const $ZodArray = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodArray", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!Array.isArray(input)) { + payload.issues.push({ + expected: "array", + code: "invalid_type", + input, + inst, + }); + return payload; + } + payload.value = Array(input.length); + const proms = []; + for (let i = 0; i < input.length; i++) { + const item = input[i]; + const result = def.element._zod.run({ + value: item, + issues: [], + }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result) => handleArrayResult(result, payload, i))); + } + else { + handleArrayResult(result, payload, i); + } + } + if (proms.length) { + return Promise.all(proms).then(() => payload); + } + return payload; //handleArrayResultsAsync(parseResults, final); + }; +}))); +function handleObjectResult(result, final, key) { + // if(isOptional) + if (result.issues.length) { + final.issues.push(...util.prefixIssues(key, result.issues)); + } + final.value[key] = result.value; +} +function handleOptionalObjectResult(result, final, key, input) { + if (result.issues.length) { + // validation failed against value schema + if (input[key] === undefined) { + // if input was undefined, ignore the error + if (key in input) { + final.value[key] = undefined; + } + else { + final.value[key] = result.value; + } + } + else { + final.issues.push(...util.prefixIssues(key, result.issues)); + } } - async handleLLMStart(llm, prompts, runId = undefined, _parentRunId = undefined, extraParams = undefined, _tags = undefined, _metadata = undefined, runName = undefined) { - return Promise.all(prompts.map(async (prompt, idx) => { - // Can't have duplicate runs with the same run ID (if provided) - const runId_ = idx === 0 && runId ? runId : v4(); - await Promise.all(this.handlers.map((handler) => { - if (handler.ignoreLLM) { - return; - } - if (isBaseTracer(handler)) { - // Create and add run to the run map. - // We do this synchronously to avoid race conditions - // when callbacks are backgrounded. - handler._createRunForLLMStart(llm, [prompt], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName); - } - return consumeCallback(async () => { - try { - await handler.handleLLMStart?.(llm, [prompt], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName); - } - catch (err) { - const logFunction = handler.raiseError - ? console.error - : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleLLMStart: ${err}`); - if (handler.raiseError) { - throw err; - } - } - }, handler.awaitHandlers); - })); - return new CallbackManagerForLLMRun(runId_, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); - })); + else if (result.value === undefined) { + // validation returned `undefined` + if (key in input) + final.value[key] = undefined; } - async handleChatModelStart(llm, messages, runId = undefined, _parentRunId = undefined, extraParams = undefined, _tags = undefined, _metadata = undefined, runName = undefined) { - return Promise.all(messages.map(async (messageGroup, idx) => { - // Can't have duplicate runs with the same run ID (if provided) - const runId_ = idx === 0 && runId ? runId : v4(); - await Promise.all(this.handlers.map((handler) => { - if (handler.ignoreLLM) { - return; - } - if (isBaseTracer(handler)) { - // Create and add run to the run map. - // We do this synchronously to avoid race conditions - // when callbacks are backgrounded. - handler._createRunForChatModelStart(llm, [messageGroup], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName); - } - return consumeCallback(async () => { - try { - if (handler.handleChatModelStart) { - await handler.handleChatModelStart?.(llm, [messageGroup], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName); - } - else if (handler.handleLLMStart) { - const messageString = getBufferString(messageGroup); - await handler.handleLLMStart?.(llm, [messageString], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName); - } - } - catch (err) { - const logFunction = handler.raiseError - ? console.error - : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleLLMStart: ${err}`); - if (handler.raiseError) { - throw err; - } - } - }, handler.awaitHandlers); - })); - return new CallbackManagerForLLMRun(runId_, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); - })); + else { + // non-undefined value + final.value[key] = result.value; } - async handleChainStart(chain, inputs, runId = v4(), runType = undefined, _tags = undefined, _metadata = undefined, runName = undefined) { - await Promise.all(this.handlers.map((handler) => { - if (handler.ignoreChain) { - return; +} +const $ZodObject = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodObject", (inst, def) => { + // requires cast because technically $ZodObject doesn't extend + $ZodType.init(inst, def); + const _normalized = util.cached(() => { + const keys = Object.keys(def.shape); + for (const k of keys) { + if (!(def.shape[k] instanceof $ZodType)) { + throw new Error(`Invalid element at key "${k}": expected a Zod schema`); } - if (isBaseTracer(handler)) { - // Create and add run to the run map. - // We do this synchronously to avoid race conditions - // when callbacks are backgrounded. - handler._createRunForChainStart(chain, inputs, runId, this._parentRunId, this.tags, this.metadata, runType, runName); + } + const okeys = util.optionalKeys(def.shape); + return { + shape: def.shape, + keys, + keySet: new Set(keys), + numKeys: keys.length, + optionalKeys: new Set(okeys), + }; + }); + util.defineLazy(inst._zod, "propValues", () => { + const shape = def.shape; + const propValues = {}; + for (const key in shape) { + const field = shape[key]._zod; + if (field.values) { + propValues[key] ?? (propValues[key] = new Set()); + for (const v of field.values) + propValues[key].add(v); + } + } + return propValues; + }); + const generateFastpass = (shape) => { + const doc = new Doc(["shape", "payload", "ctx"]); + const { keys, optionalKeys } = _normalized.value; + const parseStr = (key) => { + const k = util.esc(key); + return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`; + }; + doc.write(`const input = payload.value;`); + const ids = Object.create(null); + for (const key of keys) { + ids[key] = util.randomString(15); + } + // A: preserve key order { + doc.write(`const newResult = {}`); + for (const key of keys) { + if (optionalKeys.has(key)) { + const id = ids[key]; + doc.write(`const ${id} = ${parseStr(key)};`); + const k = util.esc(key); + doc.write(` + if (${id}.issues.length) { + if (input[${k}] === undefined) { + if (${k} in input) { + newResult[${k}] = undefined; } - return consumeCallback(async () => { - try { - await handler.handleChainStart?.(chain, inputs, runId, this._parentRunId, this.tags, this.metadata, runType, runName); + } else { + payload.issues = payload.issues.concat( + ${id}.issues.map((iss) => ({ + ...iss, + path: iss.path ? [${k}, ...iss.path] : [${k}], + })) + ); + } + } else if (${id}.value === undefined) { + if (${k} in input) newResult[${k}] = undefined; + } else { + newResult[${k}] = ${id}.value; + } + `); + } + else { + const id = ids[key]; + // const id = ids[key]; + doc.write(`const ${id} = ${parseStr(key)};`); + doc.write(` + if (${id}.issues.length) payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ + ...iss, + path: iss.path ? [${util.esc(key)}, ...iss.path] : [${util.esc(key)}] + })));`); + doc.write(`newResult[${util.esc(key)}] = ${id}.value`); + } + } + doc.write(`payload.value = newResult;`); + doc.write(`return payload;`); + const fn = doc.compile(); + return (payload, ctx) => fn(shape, payload, ctx); + }; + let fastpass; + const isObject = util.isObject; + const jit = !core.globalConfig.jitless; + const allowsEval = util.allowsEval; + const fastEnabled = jit && allowsEval.value; // && !def.catchall; + const { catchall } = def; + let value; + inst._zod.parse = (payload, ctx) => { + value ?? (value = _normalized.value); + const input = payload.value; + if (!isObject(input)) { + payload.issues.push({ + expected: "object", + code: "invalid_type", + input, + inst, + }); + return payload; + } + const proms = []; + if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) { + // always synchronous + if (!fastpass) + fastpass = generateFastpass(def.shape); + payload = fastpass(payload, ctx); + } + else { + payload.value = {}; + const shape = value.shape; + for (const key of value.keys) { + const el = shape[key]; + // do not add omitted optional keys + // if (!(key in input)) { + // if (optionalKeys.has(key)) continue; + // payload.issues.push({ + // code: "invalid_type", + // path: [key], + // expected: "nonoptional", + // note: `Missing required key: "${key}"`, + // input, + // inst, + // }); + // } + const r = el._zod.run({ value: input[key], issues: [] }, ctx); + const isOptional = el._zod.optin === "optional" && el._zod.optout === "optional"; + if (r instanceof Promise) { + proms.push(r.then((r) => isOptional ? handleOptionalObjectResult(r, payload, key, input) : handleObjectResult(r, payload, key))); + } + else if (isOptional) { + handleOptionalObjectResult(r, payload, key, input); } - catch (err) { - const logFunction = handler.raiseError - ? console.error - : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleChainStart: ${err}`); - if (handler.raiseError) { - throw err; - } + else { + handleObjectResult(r, payload, key); } - }, handler.awaitHandlers); - })); - return new CallbackManagerForChainRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); - } - async handleToolStart(tool, input, runId = v4(), _parentRunId = undefined, _tags = undefined, _metadata = undefined, runName = undefined) { - await Promise.all(this.handlers.map((handler) => { - if (handler.ignoreAgent) { - return; } - if (isBaseTracer(handler)) { - // Create and add run to the run map. - // We do this synchronously to avoid race conditions - // when callbacks are backgrounded. - handler._createRunForToolStart(tool, input, runId, this._parentRunId, this.tags, this.metadata, runName); + } + if (!catchall) { + // return payload; + return proms.length ? Promise.all(proms).then(() => payload) : payload; + } + const unrecognized = []; + // iterate over input keys + const keySet = value.keySet; + const _catchall = catchall._zod; + const t = _catchall.def.type; + for (const key of Object.keys(input)) { + if (keySet.has(key)) + continue; + if (t === "never") { + unrecognized.push(key); + continue; } - return consumeCallback(async () => { - try { - await handler.handleToolStart?.(tool, input, runId, this._parentRunId, this.tags, this.metadata, runName); - } - catch (err) { - const logFunction = handler.raiseError - ? console.error - : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleToolStart: ${err}`); - if (handler.raiseError) { - throw err; - } - } - }, handler.awaitHandlers); - })); - return new CallbackManagerForToolRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); - } - async handleRetrieverStart(retriever, query, runId = v4(), _parentRunId = undefined, _tags = undefined, _metadata = undefined, runName = undefined) { - await Promise.all(this.handlers.map((handler) => { - if (handler.ignoreRetriever) { - return; + const r = _catchall.run({ value: input[key], issues: [] }, ctx); + if (r instanceof Promise) { + proms.push(r.then((r) => handleObjectResult(r, payload, key))); } - if (isBaseTracer(handler)) { - // Create and add run to the run map. - // We do this synchronously to avoid race conditions - // when callbacks are backgrounded. - handler._createRunForRetrieverStart(retriever, query, runId, this._parentRunId, this.tags, this.metadata, runName); + else { + handleObjectResult(r, payload, key); } - return consumeCallback(async () => { - try { - await handler.handleRetrieverStart?.(retriever, query, runId, this._parentRunId, this.tags, this.metadata, runName); - } - catch (err) { - const logFunction = handler.raiseError - ? console.error - : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleRetrieverStart: ${err}`); - if (handler.raiseError) { - throw err; - } - } - }, handler.awaitHandlers); - })); - return new CallbackManagerForRetrieverRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); + } + if (unrecognized.length) { + payload.issues.push({ + code: "unrecognized_keys", + keys: unrecognized, + input, + inst, + }); + } + if (!proms.length) + return payload; + return Promise.all(proms).then(() => { + return payload; + }); + }; +}))); +function handleUnionResults(results, final, inst, ctx) { + for (const result of results) { + if (result.issues.length === 0) { + final.value = result.value; + return final; + } } - async handleCustomEvent(eventName, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - data, runId, _tags, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - _metadata) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreCustomEvent) { - try { - await handler.handleCustomEvent?.(eventName, data, runId, this.tags, this.metadata); - } - catch (err) { - const logFunction = handler.raiseError - ? console.error - : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleCustomEvent: ${err}`); - if (handler.raiseError) { - throw err; - } + final.issues.push({ + code: "invalid_union", + input: final.value, + inst, + errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))), + }); + return final; +} +const $ZodUnion = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodUnion", (inst, def) => { + $ZodType.init(inst, def); + util.defineLazy(inst._zod, "values", () => { + if (def.options.every((o) => o._zod.values)) { + return new Set(def.options.flatMap((option) => Array.from(option._zod.values))); + } + return undefined; + }); + util.defineLazy(inst._zod, "pattern", () => { + if (def.options.every((o) => o._zod.pattern)) { + const patterns = def.options.map((o) => o._zod.pattern); + return new RegExp(`^(${patterns.map((p) => util.cleanRegex(p.source)).join("|")})$`); + } + return undefined; + }); + inst._zod.parse = (payload, ctx) => { + let async = false; + const results = []; + for (const option of def.options) { + const result = option._zod.run({ + value: payload.value, + issues: [], + }, ctx); + if (result instanceof Promise) { + results.push(result); + async = true; + } + else { + if (result.issues.length === 0) + return result; + results.push(result); + } + } + if (!async) + return handleUnionResults(results, payload, inst, ctx); + return Promise.all(results).then((results) => { + return handleUnionResults(results, payload, inst, ctx); + }); + }; +}))); +const $ZodDiscriminatedUnion = +/*@__PURE__*/ +(/* unused pure expression or super */ null && (core.$constructor("$ZodDiscriminatedUnion", (inst, def) => { + $ZodUnion.init(inst, def); + const _super = inst._zod.parse; + util.defineLazy(inst._zod, "propValues", () => { + const propValues = {}; + for (const option of def.options) { + const pv = option._zod.propValues; + if (!pv || Object.keys(pv).length === 0) + throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`); + for (const [k, v] of Object.entries(pv)) { + if (!propValues[k]) + propValues[k] = new Set(); + for (const val of v) { + propValues[k].add(val); + } + } + } + return propValues; + }); + const disc = util.cached(() => { + const opts = def.options; + const map = new Map(); + for (const o of opts) { + const values = o._zod.propValues[def.discriminator]; + if (!values || values.size === 0) + throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`); + for (const v of values) { + if (map.has(v)) { + throw new Error(`Duplicate discriminator value "${String(v)}"`); } + map.set(v, o); } - }, handler.awaitHandlers))); - } - addHandler(handler, inherit = true) { - this.handlers.push(handler); - if (inherit) { - this.inheritableHandlers.push(handler); } - } - removeHandler(handler) { - this.handlers = this.handlers.filter((_handler) => _handler !== handler); - this.inheritableHandlers = this.inheritableHandlers.filter((_handler) => _handler !== handler); - } - setHandlers(handlers, inherit = true) { - this.handlers = []; - this.inheritableHandlers = []; - for (const handler of handlers) { - this.addHandler(handler, inherit); + return map; + }); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!util.isObject(input)) { + payload.issues.push({ + code: "invalid_type", + expected: "object", + input, + inst, + }); + return payload; } - } - addTags(tags, inherit = true) { - this.removeTags(tags); // Remove duplicates - this.tags.push(...tags); - if (inherit) { - this.inheritableTags.push(...tags); + const opt = disc.value.get(input?.[def.discriminator]); + if (opt) { + return opt._zod.run(payload, ctx); } - } - removeTags(tags) { - this.tags = this.tags.filter((tag) => !tags.includes(tag)); - this.inheritableTags = this.inheritableTags.filter((tag) => !tags.includes(tag)); - } - addMetadata(metadata, inherit = true) { - this.metadata = { ...this.metadata, ...metadata }; - if (inherit) { - this.inheritableMetadata = { ...this.inheritableMetadata, ...metadata }; + if (def.unionFallback) { + return _super(payload, ctx); } - } - removeMetadata(metadata) { - for (const key of Object.keys(metadata)) { - delete this.metadata[key]; - delete this.inheritableMetadata[key]; + // no matching discriminator + payload.issues.push({ + code: "invalid_union", + errors: [], + note: "No matching discriminator", + input, + path: [def.discriminator], + inst, + }); + return payload; + }; +}))); +const $ZodIntersection = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodIntersection", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + const { value: input } = payload; + const left = def.left._zod.run({ value: input, issues: [] }, ctx); + const right = def.right._zod.run({ value: input, issues: [] }, ctx); + const async = left instanceof Promise || right instanceof Promise; + if (async) { + return Promise.all([left, right]).then(([left, right]) => { + return handleIntersectionResults(payload, left, right); + }); } + return handleIntersectionResults(payload, left, right); + }; +}))); +function schemas_mergeValues(a, b) { + // const aType = parse.t(a); + // const bType = parse.t(b); + if (a === b) { + return { valid: true, data: a }; } - copy(additionalHandlers = [], inherit = true) { - const manager = new CallbackManager(this._parentRunId); - for (const handler of this.handlers) { - const inheritable = this.inheritableHandlers.includes(handler); - manager.addHandler(handler, inheritable); - } - for (const tag of this.tags) { - const inheritable = this.inheritableTags.includes(tag); - manager.addTags([tag], inheritable); + if (a instanceof Date && b instanceof Date && +a === +b) { + return { valid: true, data: a }; + } + if (util.isPlainObject(a) && util.isPlainObject(b)) { + const bKeys = Object.keys(b); + const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1); + const newObj = { ...a, ...b }; + for (const key of sharedKeys) { + const sharedValue = schemas_mergeValues(a[key], b[key]); + if (!sharedValue.valid) { + return { + valid: false, + mergeErrorPath: [key, ...sharedValue.mergeErrorPath], + }; + } + newObj[key] = sharedValue.data; } - for (const key of Object.keys(this.metadata)) { - const inheritable = Object.keys(this.inheritableMetadata).includes(key); - manager.addMetadata({ [key]: this.metadata[key] }, inheritable); + return { valid: true, data: newObj }; + } + if (Array.isArray(a) && Array.isArray(b)) { + if (a.length !== b.length) { + return { valid: false, mergeErrorPath: [] }; } - for (const handler of additionalHandlers) { - if ( - // Prevent multiple copies of console_callback_handler - manager.handlers - .filter((h) => h.name === "console_callback_handler") - .some((h) => h.name === handler.name)) { - continue; + const newArray = []; + for (let index = 0; index < a.length; index++) { + const itemA = a[index]; + const itemB = b[index]; + const sharedValue = schemas_mergeValues(itemA, itemB); + if (!sharedValue.valid) { + return { + valid: false, + mergeErrorPath: [index, ...sharedValue.mergeErrorPath], + }; } - manager.addHandler(handler, inherit); + newArray.push(sharedValue.data); } - return manager; + return { valid: true, data: newArray }; } - static fromHandlers(handlers) { - class Handler extends BaseCallbackHandler { - constructor() { - super(); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: v4() + return { valid: false, mergeErrorPath: [] }; +} +function handleIntersectionResults(result, left, right) { + if (left.issues.length) { + result.issues.push(...left.issues); + } + if (right.issues.length) { + result.issues.push(...right.issues); + } + if (util.aborted(result)) + return result; + const merged = schemas_mergeValues(left.value, right.value); + if (!merged.valid) { + throw new Error(`Unmergable intersection. Error path: ` + `${JSON.stringify(merged.mergeErrorPath)}`); + } + result.value = merged.data; + return result; +} +const schemas_$ZodTuple = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodTuple", (inst, def) => { + $ZodType.init(inst, def); + const items = def.items; + const optStart = items.length - [...items].reverse().findIndex((item) => item._zod.optin !== "optional"); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!Array.isArray(input)) { + payload.issues.push({ + input, + inst, + expected: "tuple", + code: "invalid_type", + }); + return payload; + } + payload.value = []; + const proms = []; + if (!def.rest) { + const tooBig = input.length > items.length; + const tooSmall = input.length < optStart - 1; + if (tooBig || tooSmall) { + payload.issues.push({ + input, + inst, + origin: "array", + ...(tooBig ? { code: "too_big", maximum: items.length } : { code: "too_small", minimum: items.length }), }); - Object.assign(this, handlers); + return payload; } } - const manager = new this(); - manager.addHandler(new Handler()); - return manager; - } - static configure(inheritableHandlers, localHandlers, inheritableTags, localTags, inheritableMetadata, localMetadata, options) { - return this._configureSync(inheritableHandlers, localHandlers, inheritableTags, localTags, inheritableMetadata, localMetadata, options); - } - // TODO: Deprecate async method in favor of this one. - static _configureSync(inheritableHandlers, localHandlers, inheritableTags, localTags, inheritableMetadata, localMetadata, options) { - let callbackManager; - if (inheritableHandlers || localHandlers) { - if (Array.isArray(inheritableHandlers) || !inheritableHandlers) { - callbackManager = new CallbackManager(); - callbackManager.setHandlers(inheritableHandlers?.map(ensureHandler) ?? [], true); + let i = -1; + for (const item of items) { + i++; + if (i >= input.length) + if (i >= optStart) + continue; + const result = item._zod.run({ + value: input[i], + issues: [], + }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result) => handleTupleResult(result, payload, i))); } else { - callbackManager = inheritableHandlers; + handleTupleResult(result, payload, i); } - callbackManager = callbackManager.copy(Array.isArray(localHandlers) - ? localHandlers.map(ensureHandler) - : localHandlers?.handlers, false); } - const verboseEnabled = env_getEnvironmentVariable("LANGCHAIN_VERBOSE") === "true" || - options?.verbose; - const tracingV2Enabled = tracer_langchain_LangChainTracer.getTraceableRunTree()?.tracingEnabled || - callbacks_isTracingEnabled(); - const tracingEnabled = tracingV2Enabled || - (env_getEnvironmentVariable("LANGCHAIN_TRACING") ?? false); - if (verboseEnabled || tracingEnabled) { - if (!callbackManager) { - callbackManager = new CallbackManager(); + if (def.rest) { + const rest = input.slice(items.length); + for (const el of rest) { + i++; + const result = def.rest._zod.run({ + value: el, + issues: [], + }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result) => handleTupleResult(result, payload, i))); + } + else { + handleTupleResult(result, payload, i); + } } - if (verboseEnabled && - !callbackManager.handlers.some((handler) => handler.name === ConsoleCallbackHandler.prototype.name)) { - const consoleHandler = new ConsoleCallbackHandler(); - callbackManager.addHandler(consoleHandler, true); + } + if (proms.length) + return Promise.all(proms).then(() => payload); + return payload; + }; +}))); +function handleTupleResult(result, final, index) { + if (result.issues.length) { + final.issues.push(...util.prefixIssues(index, result.issues)); + } + final.value[index] = result.value; +} +const $ZodRecord = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodRecord", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!util.isPlainObject(input)) { + payload.issues.push({ + expected: "record", + code: "invalid_type", + input, + inst, + }); + return payload; + } + const proms = []; + if (def.keyType._zod.values) { + const values = def.keyType._zod.values; + payload.value = {}; + for (const key of values) { + if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") { + const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result) => { + if (result.issues.length) { + payload.issues.push(...util.prefixIssues(key, result.issues)); + } + payload.value[key] = result.value; + })); + } + else { + if (result.issues.length) { + payload.issues.push(...util.prefixIssues(key, result.issues)); + } + payload.value[key] = result.value; + } + } } - if (tracingEnabled && - !callbackManager.handlers.some((handler) => handler.name === "langchain_tracer")) { - if (tracingV2Enabled) { - const tracerV2 = new tracer_langchain_LangChainTracer(); - callbackManager.addHandler(tracerV2, true); - // handoff between langchain and langsmith/traceable - // override the parent run ID - callbackManager._parentRunId = - tracer_langchain_LangChainTracer.getTraceableRunTree()?.id ?? - callbackManager._parentRunId; + let unrecognized; + for (const key in input) { + if (!values.has(key)) { + unrecognized = unrecognized ?? []; + unrecognized.push(key); } } + if (unrecognized && unrecognized.length > 0) { + payload.issues.push({ + code: "unrecognized_keys", + input, + inst, + keys: unrecognized, + }); + } } - for (const { contextVar, inheritable = true, handlerClass, envVar, } of _getConfigureHooks()) { - const createIfNotInContext = envVar && env_getEnvironmentVariable(envVar) === "true" && handlerClass; - let handler; - const contextVarValue = contextVar !== undefined ? getContextVariable(contextVar) : undefined; - if (contextVarValue && isBaseCallbackHandler(contextVarValue)) { - handler = contextVarValue; + else { + payload.value = {}; + for (const key of Reflect.ownKeys(input)) { + if (key === "__proto__") + continue; + const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); + if (keyResult instanceof Promise) { + throw new Error("Async schemas not supported in object keys currently"); + } + if (keyResult.issues.length) { + payload.issues.push({ + origin: "record", + code: "invalid_key", + issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())), + input: key, + path: [key], + inst, + }); + payload.value[keyResult.value] = keyResult.value; + continue; + } + const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result) => { + if (result.issues.length) { + payload.issues.push(...util.prefixIssues(key, result.issues)); + } + payload.value[keyResult.value] = result.value; + })); + } + else { + if (result.issues.length) { + payload.issues.push(...util.prefixIssues(key, result.issues)); + } + payload.value[keyResult.value] = result.value; + } } - else if (createIfNotInContext) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - handler = new handlerClass({}); + } + if (proms.length) { + return Promise.all(proms).then(() => payload); + } + return payload; + }; +}))); +const $ZodMap = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodMap", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!(input instanceof Map)) { + payload.issues.push({ + expected: "map", + code: "invalid_type", + input, + inst, + }); + return payload; + } + const proms = []; + payload.value = new Map(); + for (const [key, value] of input) { + const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); + const valueResult = def.valueType._zod.run({ value: value, issues: [] }, ctx); + if (keyResult instanceof Promise || valueResult instanceof Promise) { + proms.push(Promise.all([keyResult, valueResult]).then(([keyResult, valueResult]) => { + handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx); + })); } - if (handler !== undefined) { - if (!callbackManager) { - callbackManager = new CallbackManager(); - } - if (!callbackManager.handlers.some((h) => h.name === handler.name)) { - callbackManager.addHandler(handler, inheritable); + else { + handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx); + } + } + if (proms.length) + return Promise.all(proms).then(() => payload); + return payload; + }; +}))); +function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { + if (keyResult.issues.length) { + if (util.propertyKeyTypes.has(typeof key)) { + final.issues.push(...util.prefixIssues(key, keyResult.issues)); + } + else { + final.issues.push({ + origin: "map", + code: "invalid_key", + input, + inst, + issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())), + }); + } + } + if (valueResult.issues.length) { + if (util.propertyKeyTypes.has(typeof key)) { + final.issues.push(...util.prefixIssues(key, valueResult.issues)); + } + else { + final.issues.push({ + origin: "map", + code: "invalid_element", + input, + inst, + key: key, + issues: valueResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())), + }); + } + } + final.value.set(keyResult.value, valueResult.value); +} +const $ZodSet = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodSet", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!(input instanceof Set)) { + payload.issues.push({ + input, + inst, + expected: "set", + code: "invalid_type", + }); + return payload; + } + const proms = []; + payload.value = new Set(); + for (const item of input) { + const result = def.valueType._zod.run({ value: item, issues: [] }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result) => handleSetResult(result, payload))); + } + else + handleSetResult(result, payload); + } + if (proms.length) + return Promise.all(proms).then(() => payload); + return payload; + }; +}))); +function handleSetResult(result, final) { + if (result.issues.length) { + final.issues.push(...result.issues); + } + final.value.add(result.value); +} +const $ZodEnum = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodEnum", (inst, def) => { + $ZodType.init(inst, def); + const values = util.getEnumValues(def.entries); + inst._zod.values = new Set(values); + inst._zod.pattern = new RegExp(`^(${values + .filter((k) => util.propertyKeyTypes.has(typeof k)) + .map((o) => (typeof o === "string" ? util.escapeRegex(o) : o.toString())) + .join("|")})$`); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (inst._zod.values.has(input)) { + return payload; + } + payload.issues.push({ + code: "invalid_value", + values, + input, + inst, + }); + return payload; + }; +}))); +const $ZodLiteral = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodLiteral", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.values = new Set(def.values); + inst._zod.pattern = new RegExp(`^(${def.values + .map((o) => (typeof o === "string" ? util.escapeRegex(o) : o ? o.toString() : String(o))) + .join("|")})$`); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (inst._zod.values.has(input)) { + return payload; + } + payload.issues.push({ + code: "invalid_value", + values: def.values, + input, + inst, + }); + return payload; + }; +}))); +const $ZodFile = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodFile", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (input instanceof File) + return payload; + payload.issues.push({ + expected: "file", + code: "invalid_type", + input, + inst, + }); + return payload; + }; +}))); +const $ZodTransform = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodTransform", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + const _out = def.transform(payload.value, payload); + if (_ctx.async) { + const output = _out instanceof Promise ? _out : Promise.resolve(_out); + return output.then((output) => { + payload.value = output; + return payload; + }); + } + if (_out instanceof Promise) { + throw new core.$ZodAsyncError(); + } + payload.value = _out; + return payload; + }; +}))); +const schemas_$ZodOptional = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodOptional", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.optin = "optional"; + inst._zod.optout = "optional"; + util.defineLazy(inst._zod, "values", () => { + return def.innerType._zod.values ? new Set([...def.innerType._zod.values, undefined]) : undefined; + }); + util.defineLazy(inst._zod, "pattern", () => { + const pattern = def.innerType._zod.pattern; + return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)})?$`) : undefined; + }); + inst._zod.parse = (payload, ctx) => { + if (payload.value === undefined) { + return payload; + } + return def.innerType._zod.run(payload, ctx); + }; +}))); +const $ZodNullable = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodNullable", (inst, def) => { + $ZodType.init(inst, def); + util.defineLazy(inst._zod, "optin", () => def.innerType._zod.optin); + util.defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); + util.defineLazy(inst._zod, "pattern", () => { + const pattern = def.innerType._zod.pattern; + return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)}|null)$`) : undefined; + }); + util.defineLazy(inst._zod, "values", () => { + return def.innerType._zod.values ? new Set([...def.innerType._zod.values, null]) : undefined; + }); + inst._zod.parse = (payload, ctx) => { + if (payload.value === null) + return payload; + return def.innerType._zod.run(payload, ctx); + }; +}))); +const $ZodDefault = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodDefault", (inst, def) => { + $ZodType.init(inst, def); + // inst._zod.qin = "true"; + inst._zod.optin = "optional"; + util.defineLazy(inst._zod, "values", () => def.innerType._zod.values); + inst._zod.parse = (payload, ctx) => { + if (payload.value === undefined) { + payload.value = def.defaultValue; + /** + * $ZodDefault always returns the default value immediately. + * It doesn't pass the default value into the validator ("prefault"). There's no reason to pass the default value through validation. The validity of the default is enforced by TypeScript statically. Otherwise, it's the responsibility of the user to ensure the default is valid. In the case of pipes with divergent in/out types, you can specify the default on the `in` schema of your ZodPipe to set a "prefault" for the pipe. */ + return payload; + } + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then((result) => handleDefaultResult(result, def)); + } + return handleDefaultResult(result, def); + }; +}))); +function handleDefaultResult(payload, def) { + if (payload.value === undefined) { + payload.value = def.defaultValue; + } + return payload; +} +const $ZodPrefault = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodPrefault", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.optin = "optional"; + util.defineLazy(inst._zod, "values", () => def.innerType._zod.values); + inst._zod.parse = (payload, ctx) => { + if (payload.value === undefined) { + payload.value = def.defaultValue; + } + return def.innerType._zod.run(payload, ctx); + }; +}))); +const $ZodNonOptional = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodNonOptional", (inst, def) => { + $ZodType.init(inst, def); + util.defineLazy(inst._zod, "values", () => { + const v = def.innerType._zod.values; + return v ? new Set([...v].filter((x) => x !== undefined)) : undefined; + }); + inst._zod.parse = (payload, ctx) => { + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then((result) => handleNonOptionalResult(result, inst)); + } + return handleNonOptionalResult(result, inst); + }; +}))); +function handleNonOptionalResult(payload, inst) { + if (!payload.issues.length && payload.value === undefined) { + payload.issues.push({ + code: "invalid_type", + expected: "nonoptional", + input: payload.value, + inst, + }); + } + return payload; +} +const $ZodSuccess = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodSuccess", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then((result) => { + payload.value = result.issues.length === 0; + return payload; + }); + } + payload.value = result.issues.length === 0; + return payload; + }; +}))); +const $ZodCatch = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCatch", (inst, def) => { + $ZodType.init(inst, def); + util.defineLazy(inst._zod, "optin", () => def.innerType._zod.optin); + util.defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); + util.defineLazy(inst._zod, "values", () => def.innerType._zod.values); + inst._zod.parse = (payload, ctx) => { + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then((result) => { + payload.value = result.value; + if (result.issues.length) { + payload.value = def.catchValue({ + ...payload, + error: { + issues: result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())), + }, + input: payload.value, + }); + payload.issues = []; } - } + return payload; + }); } - if (inheritableTags || localTags) { - if (callbackManager) { - callbackManager.addTags(inheritableTags ?? []); - callbackManager.addTags(localTags ?? [], false); - } + payload.value = result.value; + if (result.issues.length) { + payload.value = def.catchValue({ + ...payload, + error: { + issues: result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())), + }, + input: payload.value, + }); + payload.issues = []; } - if (inheritableMetadata || localMetadata) { - if (callbackManager) { - callbackManager.addMetadata(inheritableMetadata ?? {}); - callbackManager.addMetadata(localMetadata ?? {}, false); - } + return payload; + }; +}))); +const $ZodNaN = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodNaN", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + if (typeof payload.value !== "number" || !Number.isNaN(payload.value)) { + payload.issues.push({ + input: payload.value, + inst, + expected: "nan", + code: "invalid_type", + }); + return payload; } - return callbackManager; - } -} -function ensureHandler(handler) { - if ("name" in handler) { - return handler; + return payload; + }; +}))); +const $ZodPipe = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodPipe", (inst, def) => { + $ZodType.init(inst, def); + util.defineLazy(inst._zod, "values", () => def.in._zod.values); + util.defineLazy(inst._zod, "optin", () => def.in._zod.optin); + util.defineLazy(inst._zod, "optout", () => def.out._zod.optout); + inst._zod.parse = (payload, ctx) => { + const left = def.in._zod.run(payload, ctx); + if (left instanceof Promise) { + return left.then((left) => handlePipeResult(left, def, ctx)); + } + return handlePipeResult(left, def, ctx); + }; +}))); +function handlePipeResult(left, def, ctx) { + if (util.aborted(left)) { + return left; } - return BaseCallbackHandler.fromMethods(handler); + return def.out._zod.run({ value: left.value, issues: left.issues }, ctx); } -/** - * @deprecated Use [`traceable`](https://docs.smith.langchain.com/observability/how_to_guides/tracing/annotate_code) - * from "langsmith" instead. - */ -class TraceGroup { - constructor(groupName, options) { - Object.defineProperty(this, "groupName", { - enumerable: true, - configurable: true, - writable: true, - value: groupName - }); - Object.defineProperty(this, "options", { - enumerable: true, - configurable: true, - writable: true, - value: options - }); - Object.defineProperty(this, "runManager", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - } - async getTraceGroupCallbackManager(group_name, inputs, options) { - const cb = new LangChainTracer(options); - const cm = await CallbackManager.configure([cb]); - const runManager = await cm?.handleChainStart({ - lc: 1, - type: "not_implemented", - id: ["langchain", "callbacks", "groups", group_name], - }, inputs ?? {}); - if (!runManager) { - throw new Error("Failed to create run group callback manager."); +const $ZodReadonly = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodReadonly", (inst, def) => { + $ZodType.init(inst, def); + util.defineLazy(inst._zod, "propValues", () => def.innerType._zod.propValues); + util.defineLazy(inst._zod, "optin", () => def.innerType._zod.optin); + util.defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); + inst._zod.parse = (payload, ctx) => { + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then(handleReadonlyResult); } - return runManager; - } - async start(inputs) { - if (!this.runManager) { - this.runManager = await this.getTraceGroupCallbackManager(this.groupName, inputs, this.options); + return handleReadonlyResult(result); + }; +}))); +function handleReadonlyResult(payload) { + payload.value = Object.freeze(payload.value); + return payload; +} +const $ZodTemplateLiteral = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodTemplateLiteral", (inst, def) => { + $ZodType.init(inst, def); + const regexParts = []; + for (const part of def.parts) { + if (part instanceof $ZodType) { + if (!part._zod.pattern) { + // if (!source) + throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`); + } + const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern; + if (!source) + throw new Error(`Invalid template literal part: ${part._zod.traits}`); + const start = source.startsWith("^") ? 1 : 0; + const end = source.endsWith("$") ? source.length - 1 : source.length; + regexParts.push(source.slice(start, end)); + } + else if (part === null || util.primitiveTypes.has(typeof part)) { + regexParts.push(util.escapeRegex(`${part}`)); } - return this.runManager.getChild(); - } - async error(err) { - if (this.runManager) { - await this.runManager.handleChainError(err); - this.runManager = undefined; + else { + throw new Error(`Invalid template literal part: ${part}`); } } - async end(output) { - if (this.runManager) { - await this.runManager.handleChainEnd(output ?? {}); - this.runManager = undefined; + inst._zod.pattern = new RegExp(`^${regexParts.join("")}$`); + inst._zod.parse = (payload, _ctx) => { + if (typeof payload.value !== "string") { + payload.issues.push({ + input: payload.value, + inst, + expected: "template_literal", + code: "invalid_type", + }); + return payload; + } + inst._zod.pattern.lastIndex = 0; + if (!inst._zod.pattern.test(payload.value)) { + payload.issues.push({ + input: payload.value, + inst, + code: "invalid_format", + format: "template_literal", + pattern: inst._zod.pattern.source, + }); + return payload; + } + return payload; + }; +}))); +const $ZodPromise = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodPromise", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx)); + }; +}))); +const $ZodLazy = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodLazy", (inst, def) => { + $ZodType.init(inst, def); + util.defineLazy(inst._zod, "innerType", () => def.getter()); + util.defineLazy(inst._zod, "pattern", () => inst._zod.innerType._zod.pattern); + util.defineLazy(inst._zod, "propValues", () => inst._zod.innerType._zod.propValues); + util.defineLazy(inst._zod, "optin", () => inst._zod.innerType._zod.optin); + util.defineLazy(inst._zod, "optout", () => inst._zod.innerType._zod.optout); + inst._zod.parse = (payload, ctx) => { + const inner = inst._zod.innerType; + return inner._zod.run(payload, ctx); + }; +}))); +const $ZodCustom = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCustom", (inst, def) => { + checks.$ZodCheck.init(inst, def); + $ZodType.init(inst, def); + inst._zod.parse = (payload, _) => { + return payload; + }; + inst._zod.check = (payload) => { + const input = payload.value; + const r = def.fn(input); + if (r instanceof Promise) { + return r.then((r) => handleRefineResult(r, payload, input, inst)); } + handleRefineResult(r, payload, input, inst); + return; + }; +}))); +function handleRefineResult(result, payload, input, inst) { + if (!result) { + const _iss = { + code: "custom", + input, + inst, // incorporates params.error into issue reporting + path: [...(inst._zod.def.path ?? [])], // incorporates params.error into issue reporting + continue: !inst._zod.def.abort, + // params: inst._zod.def.params, + }; + if (inst._zod.def.params) + _iss.params = inst._zod.def.params; + payload.issues.push(util.issue(_iss)); } } -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function manager_coerceToDict(value, defaultKey) { - return value && !Array.isArray(value) && typeof value === "object" - ? value - : { [defaultKey]: value }; -} -// eslint-disable-next-line @typescript-eslint/no-explicit-any -async function traceAsGroup(groupOptions, enclosedCode, ...args) { - const traceGroup = new TraceGroup(groupOptions.name, groupOptions); - const callbackManager = await traceGroup.start({ ...args }); - try { - const result = await enclosedCode(callbackManager, ...args); - await traceGroup.end(manager_coerceToDict(result, "output")); - return result; - } - catch (err) { - await traceGroup.error(err); - throw err; + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/ar.js + +const error = () => { + const Sizable = { + string: { unit: "حرف", verb: "أن يحوي" }, + file: { unit: "بايت", verb: "أن يحوي" }, + array: { unit: "عنصر", verb: "أن يحوي" }, + set: { unit: "عنصر", verb: "أن يحوي" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "number"; + } + case "object": { + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; + }; + const Nouns = { + regex: "مدخل", + email: "بريد إلكتروني", + url: "رابط", + emoji: "إيموجي", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "تاريخ ووقت بمعيار ISO", + date: "تاريخ بمعيار ISO", + time: "وقت بمعيار ISO", + duration: "مدة بمعيار ISO", + ipv4: "عنوان IPv4", + ipv6: "عنوان IPv6", + cidrv4: "مدى عناوين بصيغة IPv4", + cidrv6: "مدى عناوين بصيغة IPv6", + base64: "نَص بترميز base64-encoded", + base64url: "نَص بترميز base64url-encoded", + json_string: "نَص على هيئة JSON", + e164: "رقم هاتف بمعيار E.164", + jwt: "JWT", + template_literal: "مدخل", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `مدخلات غير مقبولة: يفترض إدخال ${issue.expected}، ولكن تم إدخال ${parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `مدخلات غير مقبولة: يفترض إدخال ${util.stringifyPrimitive(issue.values[0])}`; + return `اختيار غير مقبول: يتوقع انتقاء أحد هذه الخيارات: ${util.joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return ` أكبر من اللازم: يفترض أن تكون ${issue.origin ?? "القيمة"} ${adj} ${issue.maximum.toString()} ${sizing.unit ?? "عنصر"}`; + return `أكبر من اللازم: يفترض أن تكون ${issue.origin ?? "القيمة"} ${adj} ${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `أصغر من اللازم: يفترض لـ ${issue.origin} أن يكون ${adj} ${issue.minimum.toString()} ${sizing.unit}`; + } + return `أصغر من اللازم: يفترض لـ ${issue.origin} أن يكون ${adj} ${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `نَص غير مقبول: يجب أن يبدأ بـ "${issue.prefix}"`; + if (_issue.format === "ends_with") + return `نَص غير مقبول: يجب أن ينتهي بـ "${_issue.suffix}"`; + if (_issue.format === "includes") + return `نَص غير مقبول: يجب أن يتضمَّن "${_issue.includes}"`; + if (_issue.format === "regex") + return `نَص غير مقبول: يجب أن يطابق النمط ${_issue.pattern}`; + return `${Nouns[_issue.format] ?? issue.format} غير مقبول`; + } + case "not_multiple_of": + return `رقم غير مقبول: يجب أن يكون من مضاعفات ${issue.divisor}`; + case "unrecognized_keys": + return `معرف${issue.keys.length > 1 ? "ات" : ""} غريب${issue.keys.length > 1 ? "ة" : ""}: ${util.joinValues(issue.keys, "، ")}`; + case "invalid_key": + return `معرف غير مقبول في ${issue.origin}`; + case "invalid_union": + return "مدخل غير مقبول"; + case "invalid_element": + return `مدخل غير مقبول في ${issue.origin}`; + default: + return "مدخل غير مقبول"; + } + }; +}; +/* harmony default export */ function ar() { + return { + localeError: error(), + }; } -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/singletons/async_local_storage/index.js -/* eslint-disable @typescript-eslint/no-explicit-any */ +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/az.js +const az_error = () => { + const Sizable = { + string: { unit: "simvol", verb: "olmalıdır" }, + file: { unit: "bayt", verb: "olmalıdır" }, + array: { unit: "element", verb: "olmalıdır" }, + set: { unit: "element", verb: "olmalıdır" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "number"; + } + case "object": { + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; + }; + const Nouns = { + regex: "input", + email: "email address", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO datetime", + date: "ISO date", + time: "ISO time", + duration: "ISO duration", + ipv4: "IPv4 address", + ipv6: "IPv6 address", + cidrv4: "IPv4 range", + cidrv6: "IPv6 range", + base64: "base64-encoded string", + base64url: "base64url-encoded string", + json_string: "JSON string", + e164: "E.164 number", + jwt: "JWT", + template_literal: "input", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Yanlış dəyər: gözlənilən ${issue.expected}, daxil olan ${parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Yanlış dəyər: gözlənilən ${util.stringifyPrimitive(issue.values[0])}`; + return `Yanlış seçim: aşağıdakılardan biri olmalıdır: ${util.joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Çox böyük: gözlənilən ${issue.origin ?? "dəyər"} ${adj}${issue.maximum.toString()} ${sizing.unit ?? "element"}`; + return `Çox böyük: gözlənilən ${issue.origin ?? "dəyər"} ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Çox kiçik: gözlənilən ${issue.origin} ${adj}${issue.minimum.toString()} ${sizing.unit}`; + return `Çox kiçik: gözlənilən ${issue.origin} ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `Yanlış mətn: "${_issue.prefix}" ilə başlamalıdır`; + if (_issue.format === "ends_with") + return `Yanlış mətn: "${_issue.suffix}" ilə bitməlidir`; + if (_issue.format === "includes") + return `Yanlış mətn: "${_issue.includes}" daxil olmalıdır`; + if (_issue.format === "regex") + return `Yanlış mətn: ${_issue.pattern} şablonuna uyğun olmalıdır`; + return `Yanlış ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Yanlış ədəd: ${issue.divisor} ilə bölünə bilən olmalıdır`; + case "unrecognized_keys": + return `Tanınmayan açar${issue.keys.length > 1 ? "lar" : ""}: ${util.joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `${issue.origin} daxilində yanlış açar`; + case "invalid_union": + return "Yanlış dəyər"; + case "invalid_element": + return `${issue.origin} daxilində yanlış dəyər`; + default: + return `Yanlış dəyər`; + } + }; +}; +/* harmony default export */ function az() { + return { + localeError: az_error(), + }; +} +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/be.js -class async_local_storage_MockAsyncLocalStorage { - getStore() { - return undefined; +function getBelarusianPlural(count, one, few, many) { + const absCount = Math.abs(count); + const lastDigit = absCount % 10; + const lastTwoDigits = absCount % 100; + if (lastTwoDigits >= 11 && lastTwoDigits <= 19) { + return many; } - run(_store, callback) { - return callback(); + if (lastDigit === 1) { + return one; } - enterWith(_store) { - return undefined; + if (lastDigit >= 2 && lastDigit <= 4) { + return few; } + return many; } -const async_local_storage_mockAsyncLocalStorage = new async_local_storage_MockAsyncLocalStorage(); -const LC_CHILD_KEY = Symbol.for("lc:child_config"); -class async_local_storage_AsyncLocalStorageProvider { - getInstance() { - return globals_getGlobalAsyncLocalStorageInstance() ?? async_local_storage_mockAsyncLocalStorage; - } - getRunnableConfig() { - const storage = this.getInstance(); - // this has the runnable config - // which means that we should also have an instance of a LangChainTracer - // with the run map prepopulated - return storage.getStore()?.extra?.[LC_CHILD_KEY]; +const be_error = () => { + const Sizable = { + string: { + unit: { + one: "сімвал", + few: "сімвалы", + many: "сімвалаў", + }, + verb: "мець", + }, + array: { + unit: { + one: "элемент", + few: "элементы", + many: "элементаў", + }, + verb: "мець", + }, + set: { + unit: { + one: "элемент", + few: "элементы", + many: "элементаў", + }, + verb: "мець", + }, + file: { + unit: { + one: "байт", + few: "байты", + many: "байтаў", + }, + verb: "мець", + }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; } - runWithConfig(config, callback, avoidCreatingRootRunTree) { - const callbackManager = CallbackManager._configureSync(config?.callbacks, undefined, config?.tags, undefined, config?.metadata); - const storage = this.getInstance(); - const previousValue = storage.getStore(); - const parentRunId = callbackManager?.getParentRunId(); - const langChainTracer = callbackManager?.handlers?.find((handler) => handler?.name === "langchain_tracer"); - let runTree; - if (langChainTracer && parentRunId) { - runTree = langChainTracer.convertToRunTree(parentRunId); - } - else if (!avoidCreatingRootRunTree) { - runTree = new run_trees_RunTree({ - name: "", - tracingEnabled: false, - }); + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "лік"; + } + case "object": { + if (Array.isArray(data)) { + return "масіў"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } } - if (runTree) { - runTree.extra = { ...runTree.extra, [LC_CHILD_KEY]: config }; + return t; + }; + const Nouns = { + regex: "увод", + email: "email адрас", + url: "URL", + emoji: "эмодзі", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO дата і час", + date: "ISO дата", + time: "ISO час", + duration: "ISO працягласць", + ipv4: "IPv4 адрас", + ipv6: "IPv6 адрас", + cidrv4: "IPv4 дыяпазон", + cidrv6: "IPv6 дыяпазон", + base64: "радок у фармаце base64", + base64url: "радок у фармаце base64url", + json_string: "JSON радок", + e164: "нумар E.164", + jwt: "JWT", + template_literal: "увод", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Няправільны ўвод: чакаўся ${issue.expected}, атрымана ${parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Няправільны ўвод: чакалася ${util.stringifyPrimitive(issue.values[0])}`; + return `Няправільны варыянт: чакаўся адзін з ${util.joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) { + const maxValue = Number(issue.maximum); + const unit = getBelarusianPlural(maxValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); + return `Занадта вялікі: чакалася, што ${issue.origin ?? "значэнне"} павінна ${sizing.verb} ${adj}${issue.maximum.toString()} ${unit}`; + } + return `Занадта вялікі: чакалася, што ${issue.origin ?? "значэнне"} павінна быць ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + const minValue = Number(issue.minimum); + const unit = getBelarusianPlural(minValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); + return `Занадта малы: чакалася, што ${issue.origin} павінна ${sizing.verb} ${adj}${issue.minimum.toString()} ${unit}`; + } + return `Занадта малы: чакалася, што ${issue.origin} павінна быць ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `Няправільны радок: павінен пачынацца з "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Няправільны радок: павінен заканчвацца на "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Няправільны радок: павінен змяшчаць "${_issue.includes}"`; + if (_issue.format === "regex") + return `Няправільны радок: павінен адпавядаць шаблону ${_issue.pattern}`; + return `Няправільны ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Няправільны лік: павінен быць кратным ${issue.divisor}`; + case "unrecognized_keys": + return `Нераспазнаны ${issue.keys.length > 1 ? "ключы" : "ключ"}: ${util.joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Няправільны ключ у ${issue.origin}`; + case "invalid_union": + return "Няправільны ўвод"; + case "invalid_element": + return `Няправільнае значэнне ў ${issue.origin}`; + default: + return `Няправільны ўвод`; } - if (previousValue !== undefined && - previousValue[globals_CONTEXT_VARIABLES_KEY] !== undefined) { - if (runTree === undefined) { - runTree = {}; + }; +}; +/* harmony default export */ function be() { + return { + localeError: be_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/ca.js + +const ca_error = () => { + const Sizable = { + string: { unit: "caràcters", verb: "contenir" }, + file: { unit: "bytes", verb: "contenir" }, + array: { unit: "elements", verb: "contenir" }, + set: { unit: "elements", verb: "contenir" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "number"; + } + case "object": { + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } } - runTree[globals_CONTEXT_VARIABLES_KEY] = - previousValue[globals_CONTEXT_VARIABLES_KEY]; } - return storage.run(runTree, callback); - } - initializeGlobalInstance(instance) { - if (globals_getGlobalAsyncLocalStorageInstance() === undefined) { - setGlobalAsyncLocalStorageInstance(instance); + return t; + }; + const Nouns = { + regex: "entrada", + email: "adreça electrònica", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "data i hora ISO", + date: "data ISO", + time: "hora ISO", + duration: "durada ISO", + ipv4: "adreça IPv4", + ipv6: "adreça IPv6", + cidrv4: "rang IPv4", + cidrv6: "rang IPv6", + base64: "cadena codificada en base64", + base64url: "cadena codificada en base64url", + json_string: "cadena JSON", + e164: "número E.164", + jwt: "JWT", + template_literal: "entrada", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Tipus invàlid: s'esperava ${issue.expected}, s'ha rebut ${parsedType(issue.input)}`; + // return `Tipus invàlid: s'esperava ${issue.expected}, s'ha rebut ${util.getParsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Valor invàlid: s'esperava ${util.stringifyPrimitive(issue.values[0])}`; + return `Opció invàlida: s'esperava una de ${util.joinValues(issue.values, " o ")}`; + case "too_big": { + const adj = issue.inclusive ? "com a màxim" : "menys de"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Massa gran: s'esperava que ${issue.origin ?? "el valor"} contingués ${adj} ${issue.maximum.toString()} ${sizing.unit ?? "elements"}`; + return `Massa gran: s'esperava que ${issue.origin ?? "el valor"} fos ${adj} ${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? "com a mínim" : "més de"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Massa petit: s'esperava que ${issue.origin} contingués ${adj} ${issue.minimum.toString()} ${sizing.unit}`; + } + return `Massa petit: s'esperava que ${issue.origin} fos ${adj} ${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") { + return `Format invàlid: ha de començar amb "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `Format invàlid: ha d'acabar amb "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Format invàlid: ha d'incloure "${_issue.includes}"`; + if (_issue.format === "regex") + return `Format invàlid: ha de coincidir amb el patró ${_issue.pattern}`; + return `Format invàlid per a ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Número invàlid: ha de ser múltiple de ${issue.divisor}`; + case "unrecognized_keys": + return `Clau${issue.keys.length > 1 ? "s" : ""} no reconeguda${issue.keys.length > 1 ? "s" : ""}: ${util.joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Clau invàlida a ${issue.origin}`; + case "invalid_union": + return "Entrada invàlida"; // Could also be "Tipus d'unió invàlid" but "Entrada invàlida" is more general + case "invalid_element": + return `Element invàlid a ${issue.origin}`; + default: + return `Entrada invàlida`; } - } + }; +}; +/* harmony default export */ function ca() { + return { + localeError: ca_error(), + }; } -const async_local_storage_AsyncLocalStorageProviderSingleton = new async_local_storage_AsyncLocalStorageProvider(); - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/singletons/index.js +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/cs.js +const cs_error = () => { + const Sizable = { + string: { unit: "znaků", verb: "mít" }, + file: { unit: "bajtů", verb: "mít" }, + array: { unit: "prvků", verb: "mít" }, + set: { unit: "prvků", verb: "mít" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "číslo"; + } + case "string": { + return "řetězec"; + } + case "boolean": { + return "boolean"; + } + case "bigint": { + return "bigint"; + } + case "function": { + return "funkce"; + } + case "symbol": { + return "symbol"; + } + case "undefined": { + return "undefined"; + } + case "object": { + if (Array.isArray(data)) { + return "pole"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; + }; + const Nouns = { + regex: "regulární výraz", + email: "e-mailová adresa", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "datum a čas ve formátu ISO", + date: "datum ve formátu ISO", + time: "čas ve formátu ISO", + duration: "doba trvání ISO", + ipv4: "IPv4 adresa", + ipv6: "IPv6 adresa", + cidrv4: "rozsah IPv4", + cidrv6: "rozsah IPv6", + base64: "řetězec zakódovaný ve formátu base64", + base64url: "řetězec zakódovaný ve formátu base64url", + json_string: "řetězec ve formátu JSON", + e164: "číslo E.164", + jwt: "JWT", + template_literal: "vstup", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Neplatný vstup: očekáváno ${issue.expected}, obdrženo ${parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Neplatný vstup: očekáváno ${util.stringifyPrimitive(issue.values[0])}`; + return `Neplatná možnost: očekávána jedna z hodnot ${util.joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Hodnota je příliš velká: ${issue.origin ?? "hodnota"} musí mít ${adj}${issue.maximum.toString()} ${sizing.unit ?? "prvků"}`; + } + return `Hodnota je příliš velká: ${issue.origin ?? "hodnota"} musí být ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Hodnota je příliš malá: ${issue.origin ?? "hodnota"} musí mít ${adj}${issue.minimum.toString()} ${sizing.unit ?? "prvků"}`; + } + return `Hodnota je příliš malá: ${issue.origin ?? "hodnota"} musí být ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `Neplatný řetězec: musí začínat na "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Neplatný řetězec: musí končit na "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Neplatný řetězec: musí obsahovat "${_issue.includes}"`; + if (_issue.format === "regex") + return `Neplatný řetězec: musí odpovídat vzoru ${_issue.pattern}`; + return `Neplatný formát ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Neplatné číslo: musí být násobkem ${issue.divisor}`; + case "unrecognized_keys": + return `Neznámé klíče: ${util.joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Neplatný klíč v ${issue.origin}`; + case "invalid_union": + return "Neplatný vstup"; + case "invalid_element": + return `Neplatná hodnota v ${issue.origin}`; + default: + return `Neplatný vstup`; + } + }; +}; +/* harmony default export */ function cs() { + return { + localeError: cs_error(), + }; +} +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/de.js +const de_error = () => { + const Sizable = { + string: { unit: "Zeichen", verb: "zu haben" }, + file: { unit: "Bytes", verb: "zu haben" }, + array: { unit: "Elemente", verb: "zu haben" }, + set: { unit: "Elemente", verb: "zu haben" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "Zahl"; + } + case "object": { + if (Array.isArray(data)) { + return "Array"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; + }; + const Nouns = { + regex: "Eingabe", + email: "E-Mail-Adresse", + url: "URL", + emoji: "Emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO-Datum und -Uhrzeit", + date: "ISO-Datum", + time: "ISO-Uhrzeit", + duration: "ISO-Dauer", + ipv4: "IPv4-Adresse", + ipv6: "IPv6-Adresse", + cidrv4: "IPv4-Bereich", + cidrv6: "IPv6-Bereich", + base64: "Base64-codierter String", + base64url: "Base64-URL-codierter String", + json_string: "JSON-String", + e164: "E.164-Nummer", + jwt: "JWT", + template_literal: "Eingabe", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Ungültige Eingabe: erwartet ${issue.expected}, erhalten ${parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Ungültige Eingabe: erwartet ${util.stringifyPrimitive(issue.values[0])}`; + return `Ungültige Option: erwartet eine von ${util.joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Zu groß: erwartet, dass ${issue.origin ?? "Wert"} ${adj}${issue.maximum.toString()} ${sizing.unit ?? "Elemente"} hat`; + return `Zu groß: erwartet, dass ${issue.origin ?? "Wert"} ${adj}${issue.maximum.toString()} ist`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Zu klein: erwartet, dass ${issue.origin} ${adj}${issue.minimum.toString()} ${sizing.unit} hat`; + } + return `Zu klein: erwartet, dass ${issue.origin} ${adj}${issue.minimum.toString()} ist`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `Ungültiger String: muss mit "${_issue.prefix}" beginnen`; + if (_issue.format === "ends_with") + return `Ungültiger String: muss mit "${_issue.suffix}" enden`; + if (_issue.format === "includes") + return `Ungültiger String: muss "${_issue.includes}" enthalten`; + if (_issue.format === "regex") + return `Ungültiger String: muss dem Muster ${_issue.pattern} entsprechen`; + return `Ungültig: ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Ungültige Zahl: muss ein Vielfaches von ${issue.divisor} sein`; + case "unrecognized_keys": + return `${issue.keys.length > 1 ? "Unbekannte Schlüssel" : "Unbekannter Schlüssel"}: ${util.joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Ungültiger Schlüssel in ${issue.origin}`; + case "invalid_union": + return "Ungültige Eingabe"; + case "invalid_element": + return `Ungültiger Wert in ${issue.origin}`; + default: + return `Ungültige Eingabe`; + } + }; +}; +/* harmony default export */ function de() { + return { + localeError: de_error(), + }; +} +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/en.js -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/config.js +const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "number"; + } + case "object": { + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; +}; +const en_error = () => { + const Sizable = { + string: { unit: "characters", verb: "to have" }, + file: { unit: "bytes", verb: "to have" }, + array: { unit: "items", verb: "to have" }, + set: { unit: "items", verb: "to have" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const Nouns = { + regex: "input", + email: "email address", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO datetime", + date: "ISO date", + time: "ISO time", + duration: "ISO duration", + ipv4: "IPv4 address", + ipv6: "IPv6 address", + cidrv4: "IPv4 range", + cidrv6: "IPv6 range", + base64: "base64-encoded string", + base64url: "base64url-encoded string", + json_string: "JSON string", + e164: "E.164 number", + jwt: "JWT", + template_literal: "input", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Invalid input: expected ${issue.expected}, received ${parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Invalid input: expected ${util.stringifyPrimitive(issue.values[0])}`; + return `Invalid option: expected one of ${util.joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Too big: expected ${issue.origin ?? "value"} to have ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elements"}`; + return `Too big: expected ${issue.origin ?? "value"} to be ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Too small: expected ${issue.origin} to have ${adj}${issue.minimum.toString()} ${sizing.unit}`; + } + return `Too small: expected ${issue.origin} to be ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") { + return `Invalid string: must start with "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `Invalid string: must end with "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Invalid string: must include "${_issue.includes}"`; + if (_issue.format === "regex") + return `Invalid string: must match pattern ${_issue.pattern}`; + return `Invalid ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Invalid number: must be a multiple of ${issue.divisor}`; + case "unrecognized_keys": + return `Unrecognized key${issue.keys.length > 1 ? "s" : ""}: ${util.joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Invalid key in ${issue.origin}`; + case "invalid_union": + return "Invalid input"; + case "invalid_element": + return `Invalid value in ${issue.origin}`; + default: + return `Invalid input`; + } + }; +}; +/* harmony default export */ function locales_en() { + return { + localeError: en_error(), + }; +} +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/es.js -const DEFAULT_RECURSION_LIMIT = 25; -async function getCallbackManagerForConfig(config) { - return CallbackManager._configureSync(config?.callbacks, undefined, config?.tags, undefined, config?.metadata); -} -function mergeConfigs(...configs) { - // We do not want to call ensureConfig on the empty state here as this may cause - // double loading of callbacks if async local storage is being used. - const copy = {}; - for (const options of configs.filter((c) => !!c)) { - for (const key of Object.keys(options)) { - if (key === "metadata") { - copy[key] = { ...copy[key], ...options[key] }; +const es_error = () => { + const Sizable = { + string: { unit: "caracteres", verb: "tener" }, + file: { unit: "bytes", verb: "tener" }, + array: { unit: "elementos", verb: "tener" }, + set: { unit: "elementos", verb: "tener" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "número"; } - else if (key === "tags") { - const baseKeys = copy[key] ?? []; - copy[key] = [...new Set(baseKeys.concat(options[key] ?? []))]; + case "object": { + if (Array.isArray(data)) { + return "arreglo"; + } + if (data === null) { + return "nulo"; + } + if (Object.getPrototypeOf(data) !== Object.prototype) { + return data.constructor.name; + } } - else if (key === "configurable") { - copy[key] = { ...copy[key], ...options[key] }; + } + return t; + }; + const Nouns = { + regex: "entrada", + email: "dirección de correo electrónico", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "fecha y hora ISO", + date: "fecha ISO", + time: "hora ISO", + duration: "duración ISO", + ipv4: "dirección IPv4", + ipv6: "dirección IPv6", + cidrv4: "rango IPv4", + cidrv6: "rango IPv6", + base64: "cadena codificada en base64", + base64url: "URL codificada en base64", + json_string: "cadena JSON", + e164: "número E.164", + jwt: "JWT", + template_literal: "entrada", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Entrada inválida: se esperaba ${issue.expected}, recibido ${parsedType(issue.input)}`; + // return `Entrada inválida: se esperaba ${issue.expected}, recibido ${util.getParsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Entrada inválida: se esperaba ${util.stringifyPrimitive(issue.values[0])}`; + return `Opción inválida: se esperaba una de ${util.joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Demasiado grande: se esperaba que ${issue.origin ?? "valor"} tuviera ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elementos"}`; + return `Demasiado grande: se esperaba que ${issue.origin ?? "valor"} fuera ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Demasiado pequeño: se esperaba que ${issue.origin} tuviera ${adj}${issue.minimum.toString()} ${sizing.unit}`; + } + return `Demasiado pequeño: se esperaba que ${issue.origin} fuera ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `Cadena inválida: debe comenzar con "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Cadena inválida: debe terminar en "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Cadena inválida: debe incluir "${_issue.includes}"`; + if (_issue.format === "regex") + return `Cadena inválida: debe coincidir con el patrón ${_issue.pattern}`; + return `Inválido ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Número inválido: debe ser múltiplo de ${issue.divisor}`; + case "unrecognized_keys": + return `Llave${issue.keys.length > 1 ? "s" : ""} desconocida${issue.keys.length > 1 ? "s" : ""}: ${util.joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Llave inválida en ${issue.origin}`; + case "invalid_union": + return "Entrada inválida"; + case "invalid_element": + return `Valor inválido en ${issue.origin}`; + default: + return `Entrada inválida`; + } + }; +}; +/* harmony default export */ function es() { + return { + localeError: es_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/fa.js + +const fa_error = () => { + const Sizable = { + string: { unit: "کاراکتر", verb: "داشته باشد" }, + file: { unit: "بایت", verb: "داشته باشد" }, + array: { unit: "آیتم", verb: "داشته باشد" }, + set: { unit: "آیتم", verb: "داشته باشد" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "عدد"; } - else if (key === "timeout") { - if (copy.timeout === undefined) { - copy.timeout = options.timeout; + case "object": { + if (Array.isArray(data)) { + return "آرایه"; } - else if (options.timeout !== undefined) { - copy.timeout = Math.min(copy.timeout, options.timeout); + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; } } - else if (key === "signal") { - if (copy.signal === undefined) { - copy.signal = options.signal; + } + return t; + }; + const Nouns = { + regex: "ورودی", + email: "آدرس ایمیل", + url: "URL", + emoji: "ایموجی", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "تاریخ و زمان ایزو", + date: "تاریخ ایزو", + time: "زمان ایزو", + duration: "مدت زمان ایزو", + ipv4: "IPv4 آدرس", + ipv6: "IPv6 آدرس", + cidrv4: "IPv4 دامنه", + cidrv6: "IPv6 دامنه", + base64: "base64-encoded رشته", + base64url: "base64url-encoded رشته", + json_string: "JSON رشته", + e164: "E.164 عدد", + jwt: "JWT", + template_literal: "ورودی", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `ورودی نامعتبر: می‌بایست ${issue.expected} می‌بود، ${parsedType(issue.input)} دریافت شد`; + case "invalid_value": + if (issue.values.length === 1) { + return `ورودی نامعتبر: می‌بایست ${util.stringifyPrimitive(issue.values[0])} می‌بود`; + } + return `گزینه نامعتبر: می‌بایست یکی از ${util.joinValues(issue.values, "|")} می‌بود`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `خیلی بزرگ: ${issue.origin ?? "مقدار"} باید ${adj}${issue.maximum.toString()} ${sizing.unit ?? "عنصر"} باشد`; + } + return `خیلی بزرگ: ${issue.origin ?? "مقدار"} باید ${adj}${issue.maximum.toString()} باشد`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `خیلی کوچک: ${issue.origin} باید ${adj}${issue.minimum.toString()} ${sizing.unit} باشد`; + } + return `خیلی کوچک: ${issue.origin} باید ${adj}${issue.minimum.toString()} باشد`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") { + return `رشته نامعتبر: باید با "${_issue.prefix}" شروع شود`; + } + if (_issue.format === "ends_with") { + return `رشته نامعتبر: باید با "${_issue.suffix}" تمام شود`; + } + if (_issue.format === "includes") { + return `رشته نامعتبر: باید شامل "${_issue.includes}" باشد`; + } + if (_issue.format === "regex") { + return `رشته نامعتبر: باید با الگوی ${_issue.pattern} مطابقت داشته باشد`; + } + return `${Nouns[_issue.format] ?? issue.format} نامعتبر`; + } + case "not_multiple_of": + return `عدد نامعتبر: باید مضرب ${issue.divisor} باشد`; + case "unrecognized_keys": + return `کلید${issue.keys.length > 1 ? "های" : ""} ناشناس: ${util.joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `کلید ناشناس در ${issue.origin}`; + case "invalid_union": + return `ورودی نامعتبر`; + case "invalid_element": + return `مقدار نامعتبر در ${issue.origin}`; + default: + return `ورودی نامعتبر`; + } + }; +}; +/* harmony default export */ function fa() { + return { + localeError: fa_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/fi.js + +const fi_error = () => { + const Sizable = { + string: { unit: "merkkiä", subject: "merkkijonon" }, + file: { unit: "tavua", subject: "tiedoston" }, + array: { unit: "alkiota", subject: "listan" }, + set: { unit: "alkiota", subject: "joukon" }, + number: { unit: "", subject: "luvun" }, + bigint: { unit: "", subject: "suuren kokonaisluvun" }, + int: { unit: "", subject: "kokonaisluvun" }, + date: { unit: "", subject: "päivämäärän" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "number"; + } + case "object": { + if (Array.isArray(data)) { + return "array"; } - else if (options.signal !== undefined) { - if ("any" in AbortSignal) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - copy.signal = AbortSignal.any([ - copy.signal, - options.signal, - ]); - } - else { - copy.signal = options.signal; - } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; } } - else if (key === "callbacks") { - const baseCallbacks = copy.callbacks; - const providedCallbacks = options.callbacks; - // callbacks can be either undefined, Array or manager - // so merging two callbacks values has 6 cases - if (Array.isArray(providedCallbacks)) { - if (!baseCallbacks) { - copy.callbacks = providedCallbacks; - } - else if (Array.isArray(baseCallbacks)) { - copy.callbacks = baseCallbacks.concat(providedCallbacks); - } - else { - // baseCallbacks is a manager - const manager = baseCallbacks.copy(); - for (const callback of providedCallbacks) { - manager.addHandler(ensureHandler(callback), true); - } - copy.callbacks = manager; - } + } + return t; + }; + const Nouns = { + regex: "säännöllinen lauseke", + email: "sähköpostiosoite", + url: "URL-osoite", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO-aikaleima", + date: "ISO-päivämäärä", + time: "ISO-aika", + duration: "ISO-kesto", + ipv4: "IPv4-osoite", + ipv6: "IPv6-osoite", + cidrv4: "IPv4-alue", + cidrv6: "IPv6-alue", + base64: "base64-koodattu merkkijono", + base64url: "base64url-koodattu merkkijono", + json_string: "JSON-merkkijono", + e164: "E.164-luku", + jwt: "JWT", + template_literal: "templaattimerkkijono", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Virheellinen tyyppi: odotettiin ${issue.expected}, oli ${parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Virheellinen syöte: täytyy olla ${util.stringifyPrimitive(issue.values[0])}`; + return `Virheellinen valinta: täytyy olla yksi seuraavista: ${util.joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Liian suuri: ${sizing.subject} täytyy olla ${adj}${issue.maximum.toString()} ${sizing.unit}`.trim(); + } + return `Liian suuri: arvon täytyy olla ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Liian pieni: ${sizing.subject} täytyy olla ${adj}${issue.minimum.toString()} ${sizing.unit}`.trim(); + } + return `Liian pieni: arvon täytyy olla ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `Virheellinen syöte: täytyy alkaa "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Virheellinen syöte: täytyy loppua "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Virheellinen syöte: täytyy sisältää "${_issue.includes}"`; + if (_issue.format === "regex") { + return `Virheellinen syöte: täytyy vastata säännöllistä lauseketta ${_issue.pattern}`; + } + return `Virheellinen ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Virheellinen luku: täytyy olla luvun ${issue.divisor} monikerta`; + case "unrecognized_keys": + return `${issue.keys.length > 1 ? "Tuntemattomat avaimet" : "Tuntematon avain"}: ${util.joinValues(issue.keys, ", ")}`; + case "invalid_key": + return "Virheellinen avain tietueessa"; + case "invalid_union": + return "Virheellinen unioni"; + case "invalid_element": + return "Virheellinen arvo joukossa"; + default: + return `Virheellinen syöte`; + } + }; +}; +/* harmony default export */ function fi() { + return { + localeError: fi_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/fr.js + +const fr_error = () => { + const Sizable = { + string: { unit: "caractères", verb: "avoir" }, + file: { unit: "octets", verb: "avoir" }, + array: { unit: "éléments", verb: "avoir" }, + set: { unit: "éléments", verb: "avoir" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "nombre"; + } + case "object": { + if (Array.isArray(data)) { + return "tableau"; } - else if (providedCallbacks) { - // providedCallbacks is a manager - if (!baseCallbacks) { - copy.callbacks = providedCallbacks; - } - else if (Array.isArray(baseCallbacks)) { - const manager = providedCallbacks.copy(); - for (const callback of baseCallbacks) { - manager.addHandler(ensureHandler(callback), true); - } - copy.callbacks = manager; - } - else { - // baseCallbacks is also a manager - copy.callbacks = new CallbackManager(providedCallbacks._parentRunId, { - handlers: baseCallbacks.handlers.concat(providedCallbacks.handlers), - inheritableHandlers: baseCallbacks.inheritableHandlers.concat(providedCallbacks.inheritableHandlers), - tags: Array.from(new Set(baseCallbacks.tags.concat(providedCallbacks.tags))), - inheritableTags: Array.from(new Set(baseCallbacks.inheritableTags.concat(providedCallbacks.inheritableTags))), - metadata: { - ...baseCallbacks.metadata, - ...providedCallbacks.metadata, - }, - }); - } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; } - } - else { - const typedKey = key; - copy[typedKey] = options[typedKey] ?? copy[typedKey]; } } - } - return copy; + return t; + }; + const Nouns = { + regex: "entrée", + email: "adresse e-mail", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "date et heure ISO", + date: "date ISO", + time: "heure ISO", + duration: "durée ISO", + ipv4: "adresse IPv4", + ipv6: "adresse IPv6", + cidrv4: "plage IPv4", + cidrv6: "plage IPv6", + base64: "chaîne encodée en base64", + base64url: "chaîne encodée en base64url", + json_string: "chaîne JSON", + e164: "numéro E.164", + jwt: "JWT", + template_literal: "entrée", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Entrée invalide : ${issue.expected} attendu, ${parsedType(issue.input)} reçu`; + case "invalid_value": + if (issue.values.length === 1) + return `Entrée invalide : ${util.stringifyPrimitive(issue.values[0])} attendu`; + return `Option invalide : une valeur parmi ${util.joinValues(issue.values, "|")} attendue`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Trop grand : ${issue.origin ?? "valeur"} doit ${sizing.verb} ${adj}${issue.maximum.toString()} ${sizing.unit ?? "élément(s)"}`; + return `Trop grand : ${issue.origin ?? "valeur"} doit être ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Trop petit : ${issue.origin} doit ${sizing.verb} ${adj}${issue.minimum.toString()} ${sizing.unit}`; + } + return `Trop petit : ${issue.origin} doit être ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `Chaîne invalide : doit commencer par "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Chaîne invalide : doit se terminer par "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Chaîne invalide : doit inclure "${_issue.includes}"`; + if (_issue.format === "regex") + return `Chaîne invalide : doit correspondre au modèle ${_issue.pattern}`; + return `${Nouns[_issue.format] ?? issue.format} invalide`; + } + case "not_multiple_of": + return `Nombre invalide : doit être un multiple de ${issue.divisor}`; + case "unrecognized_keys": + return `Clé${issue.keys.length > 1 ? "s" : ""} non reconnue${issue.keys.length > 1 ? "s" : ""} : ${util.joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Clé invalide dans ${issue.origin}`; + case "invalid_union": + return "Entrée invalide"; + case "invalid_element": + return `Valeur invalide dans ${issue.origin}`; + default: + return `Entrée invalide`; + } + }; +}; +/* harmony default export */ function fr() { + return { + localeError: fr_error(), + }; } -const PRIMITIVES = new Set(["string", "number", "boolean"]); -/** - * Ensure that a passed config is an object with all required keys present. - */ -function ensureConfig(config) { - const implicitConfig = async_local_storage_AsyncLocalStorageProviderSingleton.getRunnableConfig(); - let empty = { - tags: [], - metadata: {}, - recursionLimit: 25, - runId: undefined, + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/fr-CA.js + +const fr_CA_error = () => { + const Sizable = { + string: { unit: "caractères", verb: "avoir" }, + file: { unit: "octets", verb: "avoir" }, + array: { unit: "éléments", verb: "avoir" }, + set: { unit: "éléments", verb: "avoir" }, }; - if (implicitConfig) { - // Don't allow runId and runName to be loaded implicitly, as this can cause - // child runs to improperly inherit their parents' run ids. - // eslint-disable-next-line @typescript-eslint/no-unused-vars - const { runId, runName, ...rest } = implicitConfig; - empty = Object.entries(rest).reduce( - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (currentConfig, [key, value]) => { - if (value !== undefined) { - // eslint-disable-next-line no-param-reassign - currentConfig[key] = value; - } - return currentConfig; - }, empty); + function getSizing(origin) { + return Sizable[origin] ?? null; } - if (config) { - empty = Object.entries(config).reduce( - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (currentConfig, [key, value]) => { - if (value !== undefined) { - // eslint-disable-next-line no-param-reassign - currentConfig[key] = value; + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "number"; } - return currentConfig; - }, empty); + case "object": { + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; + }; + const Nouns = { + regex: "entrée", + email: "adresse courriel", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "date-heure ISO", + date: "date ISO", + time: "heure ISO", + duration: "durée ISO", + ipv4: "adresse IPv4", + ipv6: "adresse IPv6", + cidrv4: "plage IPv4", + cidrv6: "plage IPv6", + base64: "chaîne encodée en base64", + base64url: "chaîne encodée en base64url", + json_string: "chaîne JSON", + e164: "numéro E.164", + jwt: "JWT", + template_literal: "entrée", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Entrée invalide : attendu ${issue.expected}, reçu ${parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Entrée invalide : attendu ${util.stringifyPrimitive(issue.values[0])}`; + return `Option invalide : attendu l'une des valeurs suivantes ${util.joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "≤" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Trop grand : attendu que ${issue.origin ?? "la valeur"} ait ${adj}${issue.maximum.toString()} ${sizing.unit}`; + return `Trop grand : attendu que ${issue.origin ?? "la valeur"} soit ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? "≥" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Trop petit : attendu que ${issue.origin} ait ${adj}${issue.minimum.toString()} ${sizing.unit}`; + } + return `Trop petit : attendu que ${issue.origin} soit ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") { + return `Chaîne invalide : doit commencer par "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `Chaîne invalide : doit se terminer par "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Chaîne invalide : doit inclure "${_issue.includes}"`; + if (_issue.format === "regex") + return `Chaîne invalide : doit correspondre au motif ${_issue.pattern}`; + return `${Nouns[_issue.format] ?? issue.format} invalide`; + } + case "not_multiple_of": + return `Nombre invalide : doit être un multiple de ${issue.divisor}`; + case "unrecognized_keys": + return `Clé${issue.keys.length > 1 ? "s" : ""} non reconnue${issue.keys.length > 1 ? "s" : ""} : ${util.joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Clé invalide dans ${issue.origin}`; + case "invalid_union": + return "Entrée invalide"; + case "invalid_element": + return `Valeur invalide dans ${issue.origin}`; + default: + return `Entrée invalide`; + } + }; +}; +/* harmony default export */ function fr_CA() { + return { + localeError: fr_CA_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/he.js + +const he_error = () => { + const Sizable = { + string: { unit: "אותיות", verb: "לכלול" }, + file: { unit: "בייטים", verb: "לכלול" }, + array: { unit: "פריטים", verb: "לכלול" }, + set: { unit: "פריטים", verb: "לכלול" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; } - if (empty?.configurable) { - for (const key of Object.keys(empty.configurable)) { - if (PRIMITIVES.has(typeof empty.configurable[key]) && - !empty.metadata?.[key]) { - if (!empty.metadata) { - empty.metadata = {}; + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "number"; + } + case "object": { + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; } - empty.metadata[key] = empty.configurable[key]; } } - } - if (empty.timeout !== undefined) { - if (empty.timeout <= 0) { - throw new Error("Timeout must be a positive number"); + return t; + }; + const Nouns = { + regex: "קלט", + email: "כתובת אימייל", + url: "כתובת רשת", + emoji: "אימוג'י", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "תאריך וזמן ISO", + date: "תאריך ISO", + time: "זמן ISO", + duration: "משך זמן ISO", + ipv4: "כתובת IPv4", + ipv6: "כתובת IPv6", + cidrv4: "טווח IPv4", + cidrv6: "טווח IPv6", + base64: "מחרוזת בבסיס 64", + base64url: "מחרוזת בבסיס 64 לכתובות רשת", + json_string: "מחרוזת JSON", + e164: "מספר E.164", + jwt: "JWT", + template_literal: "קלט", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `קלט לא תקין: צריך ${issue.expected}, התקבל ${parsedType(issue.input)}`; + // return `Invalid input: expected ${issue.expected}, received ${util.getParsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `קלט לא תקין: צריך ${util.stringifyPrimitive(issue.values[0])}`; + return `קלט לא תקין: צריך אחת מהאפשרויות ${util.joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `גדול מדי: ${issue.origin ?? "value"} צריך להיות ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elements"}`; + return `גדול מדי: ${issue.origin ?? "value"} צריך להיות ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `קטן מדי: ${issue.origin} צריך להיות ${adj}${issue.minimum.toString()} ${sizing.unit}`; + } + return `קטן מדי: ${issue.origin} צריך להיות ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `מחרוזת לא תקינה: חייבת להתחיל ב"${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `מחרוזת לא תקינה: חייבת להסתיים ב "${_issue.suffix}"`; + if (_issue.format === "includes") + return `מחרוזת לא תקינה: חייבת לכלול "${_issue.includes}"`; + if (_issue.format === "regex") + return `מחרוזת לא תקינה: חייבת להתאים לתבנית ${_issue.pattern}`; + return `${Nouns[_issue.format] ?? issue.format} לא תקין`; + } + case "not_multiple_of": + return `מספר לא תקין: חייב להיות מכפלה של ${issue.divisor}`; + case "unrecognized_keys": + return `מפתח${issue.keys.length > 1 ? "ות" : ""} לא מזוה${issue.keys.length > 1 ? "ים" : "ה"}: ${util.joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `מפתח לא תקין ב${issue.origin}`; + case "invalid_union": + return "קלט לא תקין"; + case "invalid_element": + return `ערך לא תקין ב${issue.origin}`; + default: + return `קלט לא תקין`; } - const timeoutSignal = AbortSignal.timeout(empty.timeout); - if (empty.signal !== undefined) { - if ("any" in AbortSignal) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - empty.signal = AbortSignal.any([empty.signal, timeoutSignal]); + }; +}; +/* harmony default export */ function he() { + return { + localeError: he_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/hu.js + +const hu_error = () => { + const Sizable = { + string: { unit: "karakter", verb: "legyen" }, + file: { unit: "byte", verb: "legyen" }, + array: { unit: "elem", verb: "legyen" }, + set: { unit: "elem", verb: "legyen" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "szám"; + } + case "object": { + if (Array.isArray(data)) { + return "tömb"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } } } - else { - empty.signal = timeoutSignal; + return t; + }; + const Nouns = { + regex: "bemenet", + email: "email cím", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO időbélyeg", + date: "ISO dátum", + time: "ISO idő", + duration: "ISO időintervallum", + ipv4: "IPv4 cím", + ipv6: "IPv6 cím", + cidrv4: "IPv4 tartomány", + cidrv6: "IPv6 tartomány", + base64: "base64-kódolt string", + base64url: "base64url-kódolt string", + json_string: "JSON string", + e164: "E.164 szám", + jwt: "JWT", + template_literal: "bemenet", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Érvénytelen bemenet: a várt érték ${issue.expected}, a kapott érték ${parsedType(issue.input)}`; + // return `Invalid input: expected ${issue.expected}, received ${util.getParsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Érvénytelen bemenet: a várt érték ${util.stringifyPrimitive(issue.values[0])}`; + return `Érvénytelen opció: valamelyik érték várt ${util.joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Túl nagy: ${issue.origin ?? "érték"} mérete túl nagy ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elem"}`; + return `Túl nagy: a bemeneti érték ${issue.origin ?? "érték"} túl nagy: ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Túl kicsi: a bemeneti érték ${issue.origin} mérete túl kicsi ${adj}${issue.minimum.toString()} ${sizing.unit}`; + } + return `Túl kicsi: a bemeneti érték ${issue.origin} túl kicsi ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `Érvénytelen string: "${_issue.prefix}" értékkel kell kezdődnie`; + if (_issue.format === "ends_with") + return `Érvénytelen string: "${_issue.suffix}" értékkel kell végződnie`; + if (_issue.format === "includes") + return `Érvénytelen string: "${_issue.includes}" értéket kell tartalmaznia`; + if (_issue.format === "regex") + return `Érvénytelen string: ${_issue.pattern} mintának kell megfelelnie`; + return `Érvénytelen ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Érvénytelen szám: ${issue.divisor} többszörösének kell lennie`; + case "unrecognized_keys": + return `Ismeretlen kulcs${issue.keys.length > 1 ? "s" : ""}: ${util.joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Érvénytelen kulcs ${issue.origin}`; + case "invalid_union": + return "Érvénytelen bemenet"; + case "invalid_element": + return `Érvénytelen érték: ${issue.origin}`; + default: + return `Érvénytelen bemenet`; } - delete empty.timeout; - } - return empty; + }; +}; +/* harmony default export */ function hu() { + return { + localeError: hu_error(), + }; } -/** - * Helper function that patches runnable configs with updated properties. - */ -function patchConfig(config = {}, { callbacks, maxConcurrency, recursionLimit, runName, configurable, runId, } = {}) { - const newConfig = ensureConfig(config); - if (callbacks !== undefined) { - /** - * If we're replacing callbacks we need to unset runName - * since that should apply only to the same run as the original callbacks - */ - delete newConfig.runName; - newConfig.callbacks = callbacks; - } - if (recursionLimit !== undefined) { - newConfig.recursionLimit = recursionLimit; - } - if (maxConcurrency !== undefined) { - newConfig.maxConcurrency = maxConcurrency; - } - if (runName !== undefined) { - newConfig.runName = runName; - } - if (configurable !== undefined) { - newConfig.configurable = { ...newConfig.configurable, ...configurable }; - } - if (runId !== undefined) { - delete newConfig.runId; + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/id.js + +const id_error = () => { + const Sizable = { + string: { unit: "karakter", verb: "memiliki" }, + file: { unit: "byte", verb: "memiliki" }, + array: { unit: "item", verb: "memiliki" }, + set: { unit: "item", verb: "memiliki" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; } - return newConfig; -} -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function pickRunnableConfigKeys(config) { - return config - ? { - configurable: config.configurable, - recursionLimit: config.recursionLimit, - callbacks: config.callbacks, - tags: config.tags, - metadata: config.metadata, - maxConcurrency: config.maxConcurrency, - timeout: config.timeout, - signal: config.signal, + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "number"; + } + case "object": { + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } } - : undefined; + return t; + }; + const Nouns = { + regex: "input", + email: "alamat email", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "tanggal dan waktu format ISO", + date: "tanggal format ISO", + time: "jam format ISO", + duration: "durasi format ISO", + ipv4: "alamat IPv4", + ipv6: "alamat IPv6", + cidrv4: "rentang alamat IPv4", + cidrv6: "rentang alamat IPv6", + base64: "string dengan enkode base64", + base64url: "string dengan enkode base64url", + json_string: "string JSON", + e164: "angka E.164", + jwt: "JWT", + template_literal: "input", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Input tidak valid: diharapkan ${issue.expected}, diterima ${parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Input tidak valid: diharapkan ${util.stringifyPrimitive(issue.values[0])}`; + return `Pilihan tidak valid: diharapkan salah satu dari ${util.joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Terlalu besar: diharapkan ${issue.origin ?? "value"} memiliki ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elemen"}`; + return `Terlalu besar: diharapkan ${issue.origin ?? "value"} menjadi ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Terlalu kecil: diharapkan ${issue.origin} memiliki ${adj}${issue.minimum.toString()} ${sizing.unit}`; + } + return `Terlalu kecil: diharapkan ${issue.origin} menjadi ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `String tidak valid: harus dimulai dengan "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `String tidak valid: harus berakhir dengan "${_issue.suffix}"`; + if (_issue.format === "includes") + return `String tidak valid: harus menyertakan "${_issue.includes}"`; + if (_issue.format === "regex") + return `String tidak valid: harus sesuai pola ${_issue.pattern}`; + return `${Nouns[_issue.format] ?? issue.format} tidak valid`; + } + case "not_multiple_of": + return `Angka tidak valid: harus kelipatan dari ${issue.divisor}`; + case "unrecognized_keys": + return `Kunci tidak dikenali ${issue.keys.length > 1 ? "s" : ""}: ${util.joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Kunci tidak valid di ${issue.origin}`; + case "invalid_union": + return "Input tidak valid"; + case "invalid_element": + return `Nilai tidak valid di ${issue.origin}`; + default: + return `Input tidak valid`; + } + }; +}; +/* harmony default export */ function id() { + return { + localeError: id_error(), + }; } -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/signal.js -async function raceWithSignal(promise, signal) { - if (signal === undefined) { - return promise; +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/it.js + +const it_error = () => { + const Sizable = { + string: { unit: "caratteri", verb: "avere" }, + file: { unit: "byte", verb: "avere" }, + array: { unit: "elementi", verb: "avere" }, + set: { unit: "elementi", verb: "avere" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; } - let listener; - return Promise.race([ - promise.catch((err) => { - if (!signal?.aborted) { - throw err; - } - else { - return undefined; + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "numero"; } - }), - new Promise((_, reject) => { - listener = () => { - reject(new Error("Aborted")); - }; - signal.addEventListener("abort", listener); - // Must be here inside the promise to avoid a race condition - if (signal.aborted) { - reject(new Error("Aborted")); + case "object": { + if (Array.isArray(data)) { + return "vettore"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } } - }), - ]).finally(() => signal.removeEventListener("abort", listener)); + } + return t; + }; + const Nouns = { + regex: "input", + email: "indirizzo email", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "data e ora ISO", + date: "data ISO", + time: "ora ISO", + duration: "durata ISO", + ipv4: "indirizzo IPv4", + ipv6: "indirizzo IPv6", + cidrv4: "intervallo IPv4", + cidrv6: "intervallo IPv6", + base64: "stringa codificata in base64", + base64url: "URL codificata in base64", + json_string: "stringa JSON", + e164: "numero E.164", + jwt: "JWT", + template_literal: "input", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Input non valido: atteso ${issue.expected}, ricevuto ${parsedType(issue.input)}`; + // return `Input non valido: atteso ${issue.expected}, ricevuto ${util.getParsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Input non valido: atteso ${util.stringifyPrimitive(issue.values[0])}`; + return `Opzione non valida: atteso uno tra ${util.joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Troppo grande: ${issue.origin ?? "valore"} deve avere ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elementi"}`; + return `Troppo grande: ${issue.origin ?? "valore"} deve essere ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Troppo piccolo: ${issue.origin} deve avere ${adj}${issue.minimum.toString()} ${sizing.unit}`; + } + return `Troppo piccolo: ${issue.origin} deve essere ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `Stringa non valida: deve iniziare con "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Stringa non valida: deve terminare con "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Stringa non valida: deve includere "${_issue.includes}"`; + if (_issue.format === "regex") + return `Stringa non valida: deve corrispondere al pattern ${_issue.pattern}`; + return `Invalid ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Numero non valido: deve essere un multiplo di ${issue.divisor}`; + case "unrecognized_keys": + return `Chiav${issue.keys.length > 1 ? "i" : "e"} non riconosciut${issue.keys.length > 1 ? "e" : "a"}: ${util.joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Chiave non valida in ${issue.origin}`; + case "invalid_union": + return "Input non valido"; + case "invalid_element": + return `Valore non valido in ${issue.origin}`; + default: + return `Input non valido`; + } + }; +}; +/* harmony default export */ function it() { + return { + localeError: it_error(), + }; } -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/stream.js +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/ja.js +const ja_error = () => { + const Sizable = { + string: { unit: "文字", verb: "である" }, + file: { unit: "バイト", verb: "である" }, + array: { unit: "要素", verb: "である" }, + set: { unit: "要素", verb: "である" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "数値"; + } + case "object": { + if (Array.isArray(data)) { + return "配列"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; + }; + const Nouns = { + regex: "入力値", + email: "メールアドレス", + url: "URL", + emoji: "絵文字", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO日時", + date: "ISO日付", + time: "ISO時刻", + duration: "ISO期間", + ipv4: "IPv4アドレス", + ipv6: "IPv6アドレス", + cidrv4: "IPv4範囲", + cidrv6: "IPv6範囲", + base64: "base64エンコード文字列", + base64url: "base64urlエンコード文字列", + json_string: "JSON文字列", + e164: "E.164番号", + jwt: "JWT", + template_literal: "入力値", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `無効な入力: ${issue.expected}が期待されましたが、${parsedType(issue.input)}が入力されました`; + case "invalid_value": + if (issue.values.length === 1) + return `無効な入力: ${util.stringifyPrimitive(issue.values[0])}が期待されました`; + return `無効な選択: ${util.joinValues(issue.values, "、")}のいずれかである必要があります`; + case "too_big": { + const adj = issue.inclusive ? "以下である" : "より小さい"; + const sizing = getSizing(issue.origin); + if (sizing) + return `大きすぎる値: ${issue.origin ?? "値"}は${issue.maximum.toString()}${sizing.unit ?? "要素"}${adj}必要があります`; + return `大きすぎる値: ${issue.origin ?? "値"}は${issue.maximum.toString()}${adj}必要があります`; + } + case "too_small": { + const adj = issue.inclusive ? "以上である" : "より大きい"; + const sizing = getSizing(issue.origin); + if (sizing) + return `小さすぎる値: ${issue.origin}は${issue.minimum.toString()}${sizing.unit}${adj}必要があります`; + return `小さすぎる値: ${issue.origin}は${issue.minimum.toString()}${adj}必要があります`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `無効な文字列: "${_issue.prefix}"で始まる必要があります`; + if (_issue.format === "ends_with") + return `無効な文字列: "${_issue.suffix}"で終わる必要があります`; + if (_issue.format === "includes") + return `無効な文字列: "${_issue.includes}"を含む必要があります`; + if (_issue.format === "regex") + return `無効な文字列: パターン${_issue.pattern}に一致する必要があります`; + return `無効な${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `無効な数値: ${issue.divisor}の倍数である必要があります`; + case "unrecognized_keys": + return `認識されていないキー${issue.keys.length > 1 ? "群" : ""}: ${util.joinValues(issue.keys, "、")}`; + case "invalid_key": + return `${issue.origin}内の無効なキー`; + case "invalid_union": + return "無効な入力"; + case "invalid_element": + return `${issue.origin}内の無効な値`; + default: + return `無効な入力`; + } + }; +}; +/* harmony default export */ function ja() { + return { + localeError: ja_error(), + }; +} +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/kh.js -/* - * Support async iterator syntax for ReadableStreams in all environments. - * Source: https://github.com/MattiasBuelens/web-streams-polyfill/pull/122#issuecomment-1627354490 - */ -class IterableReadableStream extends ReadableStream { - constructor() { - super(...arguments); - Object.defineProperty(this, "reader", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); +const kh_error = () => { + const Sizable = { + string: { unit: "តួអក្សរ", verb: "គួរមាន" }, + file: { unit: "បៃ", verb: "គួរមាន" }, + array: { unit: "ធាតុ", verb: "គួរមាន" }, + set: { unit: "ធាតុ", verb: "គួរមាន" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; } - ensureReader() { - if (!this.reader) { - this.reader = this.getReader(); + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "មិនមែនជាលេខ (NaN)" : "លេខ"; + } + case "object": { + if (Array.isArray(data)) { + return "អារេ (Array)"; + } + if (data === null) { + return "គ្មានតម្លៃ (null)"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; + }; + const Nouns = { + regex: "ទិន្នន័យបញ្ចូល", + email: "អាសយដ្ឋានអ៊ីមែល", + url: "URL", + emoji: "សញ្ញាអារម្មណ៍", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "កាលបរិច្ឆេទ និងម៉ោង ISO", + date: "កាលបរិច្ឆេទ ISO", + time: "ម៉ោង ISO", + duration: "រយៈពេល ISO", + ipv4: "អាសយដ្ឋាន IPv4", + ipv6: "អាសយដ្ឋាន IPv6", + cidrv4: "ដែនអាសយដ្ឋាន IPv4", + cidrv6: "ដែនអាសយដ្ឋាន IPv6", + base64: "ខ្សែអក្សរអ៊ិកូដ base64", + base64url: "ខ្សែអក្សរអ៊ិកូដ base64url", + json_string: "ខ្សែអក្សរ JSON", + e164: "លេខ E.164", + jwt: "JWT", + template_literal: "ទិន្នន័យបញ្ចូល", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${issue.expected} ប៉ុន្តែទទួលបាន ${parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${util.stringifyPrimitive(issue.values[0])}`; + return `ជម្រើសមិនត្រឹមត្រូវ៖ ត្រូវជាមួយក្នុងចំណោម ${util.joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `ធំពេក៖ ត្រូវការ ${issue.origin ?? "តម្លៃ"} ${adj} ${issue.maximum.toString()} ${sizing.unit ?? "ធាតុ"}`; + return `ធំពេក៖ ត្រូវការ ${issue.origin ?? "តម្លៃ"} ${adj} ${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `តូចពេក៖ ត្រូវការ ${issue.origin} ${adj} ${issue.minimum.toString()} ${sizing.unit}`; + } + return `តូចពេក៖ ត្រូវការ ${issue.origin} ${adj} ${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") { + return `ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវចាប់ផ្តើមដោយ "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវបញ្ចប់ដោយ "${_issue.suffix}"`; + if (_issue.format === "includes") + return `ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវមាន "${_issue.includes}"`; + if (_issue.format === "regex") + return `ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវតែផ្គូផ្គងនឹងទម្រង់ដែលបានកំណត់ ${_issue.pattern}`; + return `មិនត្រឹមត្រូវ៖ ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `លេខមិនត្រឹមត្រូវ៖ ត្រូវតែជាពហុគុណនៃ ${issue.divisor}`; + case "unrecognized_keys": + return `រកឃើញសោមិនស្គាល់៖ ${util.joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `សោមិនត្រឹមត្រូវនៅក្នុង ${issue.origin}`; + case "invalid_union": + return `ទិន្នន័យមិនត្រឹមត្រូវ`; + case "invalid_element": + return `ទិន្នន័យមិនត្រឹមត្រូវនៅក្នុង ${issue.origin}`; + default: + return `ទិន្នន័យមិនត្រឹមត្រូវ`; } + }; +}; +/* harmony default export */ function kh() { + return { + localeError: kh_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/ko.js + +const ko_error = () => { + const Sizable = { + string: { unit: "문자", verb: "to have" }, + file: { unit: "바이트", verb: "to have" }, + array: { unit: "개", verb: "to have" }, + set: { unit: "개", verb: "to have" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; } - async next() { - this.ensureReader(); - try { - const result = await this.reader.read(); - if (result.done) { - this.reader.releaseLock(); // release lock when stream becomes closed - return { - done: true, - value: undefined, - }; + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "number"; } - else { - return { - done: false, - value: result.value, - }; + case "object": { + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } } } - catch (e) { - this.reader.releaseLock(); // release lock when stream becomes errored - throw e; + return t; + }; + const Nouns = { + regex: "입력", + email: "이메일 주소", + url: "URL", + emoji: "이모지", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO 날짜시간", + date: "ISO 날짜", + time: "ISO 시간", + duration: "ISO 기간", + ipv4: "IPv4 주소", + ipv6: "IPv6 주소", + cidrv4: "IPv4 범위", + cidrv6: "IPv6 범위", + base64: "base64 인코딩 문자열", + base64url: "base64url 인코딩 문자열", + json_string: "JSON 문자열", + e164: "E.164 번호", + jwt: "JWT", + template_literal: "입력", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `잘못된 입력: 예상 타입은 ${issue.expected}, 받은 타입은 ${parsedType(issue.input)}입니다`; + case "invalid_value": + if (issue.values.length === 1) + return `잘못된 입력: 값은 ${util.stringifyPrimitive(issue.values[0])} 이어야 합니다`; + return `잘못된 옵션: ${util.joinValues(issue.values, "또는 ")} 중 하나여야 합니다`; + case "too_big": { + const adj = issue.inclusive ? "이하" : "미만"; + const suffix = adj === "미만" ? "이어야 합니다" : "여야 합니다"; + const sizing = getSizing(issue.origin); + const unit = sizing?.unit ?? "요소"; + if (sizing) + return `${issue.origin ?? "값"}이 너무 큽니다: ${issue.maximum.toString()}${unit} ${adj}${suffix}`; + return `${issue.origin ?? "값"}이 너무 큽니다: ${issue.maximum.toString()} ${adj}${suffix}`; + } + case "too_small": { + const adj = issue.inclusive ? "이상" : "초과"; + const suffix = adj === "이상" ? "이어야 합니다" : "여야 합니다"; + const sizing = getSizing(issue.origin); + const unit = sizing?.unit ?? "요소"; + if (sizing) { + return `${issue.origin ?? "값"}이 너무 작습니다: ${issue.minimum.toString()}${unit} ${adj}${suffix}`; + } + return `${issue.origin ?? "값"}이 너무 작습니다: ${issue.minimum.toString()} ${adj}${suffix}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") { + return `잘못된 문자열: "${_issue.prefix}"(으)로 시작해야 합니다`; + } + if (_issue.format === "ends_with") + return `잘못된 문자열: "${_issue.suffix}"(으)로 끝나야 합니다`; + if (_issue.format === "includes") + return `잘못된 문자열: "${_issue.includes}"을(를) 포함해야 합니다`; + if (_issue.format === "regex") + return `잘못된 문자열: 정규식 ${_issue.pattern} 패턴과 일치해야 합니다`; + return `잘못된 ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `잘못된 숫자: ${issue.divisor}의 배수여야 합니다`; + case "unrecognized_keys": + return `인식할 수 없는 키: ${util.joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `잘못된 키: ${issue.origin}`; + case "invalid_union": + return `잘못된 입력`; + case "invalid_element": + return `잘못된 값: ${issue.origin}`; + default: + return `잘못된 입력`; } + }; +}; +/* harmony default export */ function ko() { + return { + localeError: ko_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/mk.js + +const mk_error = () => { + const Sizable = { + string: { unit: "знаци", verb: "да имаат" }, + file: { unit: "бајти", verb: "да имаат" }, + array: { unit: "ставки", verb: "да имаат" }, + set: { unit: "ставки", verb: "да имаат" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; } - async return() { - this.ensureReader(); - // If wrapped in a Node stream, cancel is already called. - if (this.locked) { - const cancelPromise = this.reader.cancel(); // cancel first, but don't await yet - this.reader.releaseLock(); // release lock first - await cancelPromise; // now await it + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "број"; + } + case "object": { + if (Array.isArray(data)) { + return "низа"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } } - return { done: true, value: undefined }; - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - async throw(e) { - this.ensureReader(); - if (this.locked) { - const cancelPromise = this.reader.cancel(); // cancel first, but don't await yet - this.reader.releaseLock(); // release lock first - await cancelPromise; // now await it + return t; + }; + const Nouns = { + regex: "внес", + email: "адреса на е-пошта", + url: "URL", + emoji: "емоџи", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO датум и време", + date: "ISO датум", + time: "ISO време", + duration: "ISO времетраење", + ipv4: "IPv4 адреса", + ipv6: "IPv6 адреса", + cidrv4: "IPv4 опсег", + cidrv6: "IPv6 опсег", + base64: "base64-енкодирана низа", + base64url: "base64url-енкодирана низа", + json_string: "JSON низа", + e164: "E.164 број", + jwt: "JWT", + template_literal: "внес", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Грешен внес: се очекува ${issue.expected}, примено ${parsedType(issue.input)}`; + // return `Invalid input: expected ${issue.expected}, received ${util.getParsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Invalid input: expected ${util.stringifyPrimitive(issue.values[0])}`; + return `Грешана опција: се очекува една ${util.joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Премногу голем: се очекува ${issue.origin ?? "вредноста"} да има ${adj}${issue.maximum.toString()} ${sizing.unit ?? "елементи"}`; + return `Премногу голем: се очекува ${issue.origin ?? "вредноста"} да биде ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Премногу мал: се очекува ${issue.origin} да има ${adj}${issue.minimum.toString()} ${sizing.unit}`; + } + return `Премногу мал: се очекува ${issue.origin} да биде ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") { + return `Неважечка низа: мора да започнува со "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `Неважечка низа: мора да завршува со "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Неважечка низа: мора да вклучува "${_issue.includes}"`; + if (_issue.format === "regex") + return `Неважечка низа: мора да одгоара на патернот ${_issue.pattern}`; + return `Invalid ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Грешен број: мора да биде делив со ${issue.divisor}`; + case "unrecognized_keys": + return `${issue.keys.length > 1 ? "Непрепознаени клучеви" : "Непрепознаен клуч"}: ${util.joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Грешен клуч во ${issue.origin}`; + case "invalid_union": + return "Грешен внес"; + case "invalid_element": + return `Грешна вредност во ${issue.origin}`; + default: + return `Грешен внес`; } - throw e; - } - [Symbol.asyncIterator]() { - return this; - } - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - // @ts-ignore Not present in Node 18 types, required in latest Node 22 - async [Symbol.asyncDispose]() { - await this.return(); + }; +}; +/* harmony default export */ function mk() { + return { + localeError: mk_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/ms.js + +const ms_error = () => { + const Sizable = { + string: { unit: "aksara", verb: "mempunyai" }, + file: { unit: "bait", verb: "mempunyai" }, + array: { unit: "elemen", verb: "mempunyai" }, + set: { unit: "elemen", verb: "mempunyai" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; } - static fromReadableStream(stream) { - // From https://developer.mozilla.org/en-US/docs/Web/API/Streams_API/Using_readable_streams#reading_the_stream - const reader = stream.getReader(); - return new IterableReadableStream({ - start(controller) { - return pump(); - function pump() { - return reader.read().then(({ done, value }) => { - // When no more data needs to be consumed, close the stream - if (done) { - controller.close(); - return; - } - // Enqueue the next data chunk into our target stream - controller.enqueue(value); - return pump(); - }); + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "nombor"; + } + case "object": { + if (Array.isArray(data)) { + return "array"; } - }, - cancel() { - reader.releaseLock(); - }, - }); - } - static fromAsyncGenerator(generator) { - return new IterableReadableStream({ - async pull(controller) { - const { value, done } = await generator.next(); - // When no more data needs to be consumed, close the stream - if (done) { - controller.close(); + if (data === null) { + return "null"; } - // Fix: `else if (value)` will hang the streaming when nullish value (e.g. empty string) is pulled - controller.enqueue(value); - }, - async cancel(reason) { - await generator.return(reason); - }, - }); - } -} -function atee(iter, length = 2) { - const buffers = Array.from({ length }, () => []); - return buffers.map(async function* makeIter(buffer) { - while (true) { - if (buffer.length === 0) { - const result = await iter.next(); - for (const buffer of buffers) { - buffer.push(result); + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; } } - else if (buffer[0].done) { - return; + } + return t; + }; + const Nouns = { + regex: "input", + email: "alamat e-mel", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "tarikh masa ISO", + date: "tarikh ISO", + time: "masa ISO", + duration: "tempoh ISO", + ipv4: "alamat IPv4", + ipv6: "alamat IPv6", + cidrv4: "julat IPv4", + cidrv6: "julat IPv6", + base64: "string dikodkan base64", + base64url: "string dikodkan base64url", + json_string: "string JSON", + e164: "nombor E.164", + jwt: "JWT", + template_literal: "input", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Input tidak sah: dijangka ${issue.expected}, diterima ${parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Input tidak sah: dijangka ${util.stringifyPrimitive(issue.values[0])}`; + return `Pilihan tidak sah: dijangka salah satu daripada ${util.joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Terlalu besar: dijangka ${issue.origin ?? "nilai"} ${sizing.verb} ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elemen"}`; + return `Terlalu besar: dijangka ${issue.origin ?? "nilai"} adalah ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Terlalu kecil: dijangka ${issue.origin} ${sizing.verb} ${adj}${issue.minimum.toString()} ${sizing.unit}`; + } + return `Terlalu kecil: dijangka ${issue.origin} adalah ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `String tidak sah: mesti bermula dengan "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `String tidak sah: mesti berakhir dengan "${_issue.suffix}"`; + if (_issue.format === "includes") + return `String tidak sah: mesti mengandungi "${_issue.includes}"`; + if (_issue.format === "regex") + return `String tidak sah: mesti sepadan dengan corak ${_issue.pattern}`; + return `${Nouns[_issue.format] ?? issue.format} tidak sah`; + } + case "not_multiple_of": + return `Nombor tidak sah: perlu gandaan ${issue.divisor}`; + case "unrecognized_keys": + return `Kunci tidak dikenali: ${util.joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Kunci tidak sah dalam ${issue.origin}`; + case "invalid_union": + return "Input tidak sah"; + case "invalid_element": + return `Nilai tidak sah dalam ${issue.origin}`; + default: + return `Input tidak sah`; + } + }; +}; +/* harmony default export */ function ms() { + return { + localeError: ms_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/nl.js + +const nl_error = () => { + const Sizable = { + string: { unit: "tekens" }, + file: { unit: "bytes" }, + array: { unit: "elementen" }, + set: { unit: "elementen" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "getal"; } - else { - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - yield buffer.shift().value; + case "object": { + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } } } - }); + return t; + }; + const Nouns = { + regex: "invoer", + email: "emailadres", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO datum en tijd", + date: "ISO datum", + time: "ISO tijd", + duration: "ISO duur", + ipv4: "IPv4-adres", + ipv6: "IPv6-adres", + cidrv4: "IPv4-bereik", + cidrv6: "IPv6-bereik", + base64: "base64-gecodeerde tekst", + base64url: "base64 URL-gecodeerde tekst", + json_string: "JSON string", + e164: "E.164-nummer", + jwt: "JWT", + template_literal: "invoer", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Ongeldige invoer: verwacht ${issue.expected}, ontving ${parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Ongeldige invoer: verwacht ${util.stringifyPrimitive(issue.values[0])}`; + return `Ongeldige optie: verwacht één van ${util.joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Te lang: verwacht dat ${issue.origin ?? "waarde"} ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elementen"} bevat`; + return `Te lang: verwacht dat ${issue.origin ?? "waarde"} ${adj}${issue.maximum.toString()} is`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Te kort: verwacht dat ${issue.origin} ${adj}${issue.minimum.toString()} ${sizing.unit} bevat`; + } + return `Te kort: verwacht dat ${issue.origin} ${adj}${issue.minimum.toString()} is`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") { + return `Ongeldige tekst: moet met "${_issue.prefix}" beginnen`; + } + if (_issue.format === "ends_with") + return `Ongeldige tekst: moet op "${_issue.suffix}" eindigen`; + if (_issue.format === "includes") + return `Ongeldige tekst: moet "${_issue.includes}" bevatten`; + if (_issue.format === "regex") + return `Ongeldige tekst: moet overeenkomen met patroon ${_issue.pattern}`; + return `Ongeldig: ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Ongeldig getal: moet een veelvoud van ${issue.divisor} zijn`; + case "unrecognized_keys": + return `Onbekende key${issue.keys.length > 1 ? "s" : ""}: ${util.joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Ongeldige key in ${issue.origin}`; + case "invalid_union": + return "Ongeldige invoer"; + case "invalid_element": + return `Ongeldige waarde in ${issue.origin}`; + default: + return `Ongeldige invoer`; + } + }; +}; +/* harmony default export */ function nl() { + return { + localeError: nl_error(), + }; } -function concat(first, second) { - if (Array.isArray(first) && Array.isArray(second)) { - return first.concat(second); - } - else if (typeof first === "string" && typeof second === "string") { - return (first + second); - } - else if (typeof first === "number" && typeof second === "number") { - return (first + second); - } - else if ( - // eslint-disable-next-line @typescript-eslint/no-explicit-any - "concat" in first && - // eslint-disable-next-line @typescript-eslint/no-explicit-any - typeof first.concat === "function") { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - return first.concat(second); + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/no.js + +const no_error = () => { + const Sizable = { + string: { unit: "tegn", verb: "å ha" }, + file: { unit: "bytes", verb: "å ha" }, + array: { unit: "elementer", verb: "å inneholde" }, + set: { unit: "elementer", verb: "å inneholde" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; } - else if (typeof first === "object" && typeof second === "object") { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const chunk = { ...first }; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - for (const [key, value] of Object.entries(second)) { - if (key in chunk && !Array.isArray(chunk[key])) { - chunk[key] = concat(chunk[key], value); + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "tall"; } - else { - chunk[key] = value; + case "object": { + if (Array.isArray(data)) { + return "liste"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } } } - return chunk; - } - else { - throw new Error(`Cannot concat ${typeof first} and ${typeof second}`); - } + return t; + }; + const Nouns = { + regex: "input", + email: "e-postadresse", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO dato- og klokkeslett", + date: "ISO-dato", + time: "ISO-klokkeslett", + duration: "ISO-varighet", + ipv4: "IPv4-område", + ipv6: "IPv6-område", + cidrv4: "IPv4-spekter", + cidrv6: "IPv6-spekter", + base64: "base64-enkodet streng", + base64url: "base64url-enkodet streng", + json_string: "JSON-streng", + e164: "E.164-nummer", + jwt: "JWT", + template_literal: "input", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Ugyldig input: forventet ${issue.expected}, fikk ${parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Ugyldig verdi: forventet ${util.stringifyPrimitive(issue.values[0])}`; + return `Ugyldig valg: forventet en av ${util.joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `For stor(t): forventet ${issue.origin ?? "value"} til å ha ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elementer"}`; + return `For stor(t): forventet ${issue.origin ?? "value"} til å ha ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `For lite(n): forventet ${issue.origin} til å ha ${adj}${issue.minimum.toString()} ${sizing.unit}`; + } + return `For lite(n): forventet ${issue.origin} til å ha ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `Ugyldig streng: må starte med "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Ugyldig streng: må ende med "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Ugyldig streng: må inneholde "${_issue.includes}"`; + if (_issue.format === "regex") + return `Ugyldig streng: må matche mønsteret ${_issue.pattern}`; + return `Ugyldig ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Ugyldig tall: må være et multiplum av ${issue.divisor}`; + case "unrecognized_keys": + return `${issue.keys.length > 1 ? "Ukjente nøkler" : "Ukjent nøkkel"}: ${util.joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Ugyldig nøkkel i ${issue.origin}`; + case "invalid_union": + return "Ugyldig input"; + case "invalid_element": + return `Ugyldig verdi i ${issue.origin}`; + default: + return `Ugyldig input`; + } + }; +}; +/* harmony default export */ function no() { + return { + localeError: no_error(), + }; } -class AsyncGeneratorWithSetup { - constructor(params) { - Object.defineProperty(this, "generator", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "setup", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "config", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "signal", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "firstResult", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "firstResultUsed", { - enumerable: true, - configurable: true, - writable: true, - value: false - }); - this.generator = params.generator; - this.config = params.config; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - this.signal = params.signal ?? this.config?.signal; - // setup is a promise that resolves only after the first iterator value - // is available. this is useful when setup of several piped generators - // needs to happen in logical order, ie. in the order in which input to - // to each generator is available. - this.setup = new Promise((resolve, reject) => { - void async_local_storage_AsyncLocalStorageProviderSingleton.runWithConfig(pickRunnableConfigKeys(params.config), async () => { - this.firstResult = params.generator.next(); - if (params.startSetup) { - this.firstResult.then(params.startSetup).then(resolve, reject); + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/ota.js + +const ota_error = () => { + const Sizable = { + string: { unit: "harf", verb: "olmalıdır" }, + file: { unit: "bayt", verb: "olmalıdır" }, + array: { unit: "unsur", verb: "olmalıdır" }, + set: { unit: "unsur", verb: "olmalıdır" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "numara"; + } + case "object": { + if (Array.isArray(data)) { + return "saf"; } - else { - this.firstResult.then((_result) => resolve(undefined), reject); + if (data === null) { + return "gayb"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; } - }, true); - }); - } - async next(...args) { - this.signal?.throwIfAborted(); - if (!this.firstResultUsed) { - this.firstResultUsed = true; - return this.firstResult; - } - return async_local_storage_AsyncLocalStorageProviderSingleton.runWithConfig(pickRunnableConfigKeys(this.config), this.signal - ? async () => { - return raceWithSignal(this.generator.next(...args), this.signal); } - : async () => { - return this.generator.next(...args); - }, true); - } - async return(value) { - return this.generator.return(value); - } - async throw(e) { - return this.generator.throw(e); - } - [Symbol.asyncIterator]() { - return this; - } - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - // @ts-ignore Not present in Node 18 types, required in latest Node 22 - async [Symbol.asyncDispose]() { - await this.return(); - } -} -async function pipeGeneratorWithSetup(to, generator, startSetup, signal, ...args) { - const gen = new AsyncGeneratorWithSetup({ - generator, - startSetup, - signal, - }); - const setup = await gen.setup; - return { output: to(gen, setup, ...args), setup }; + } + return t; + }; + const Nouns = { + regex: "giren", + email: "epostagâh", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO hengâmı", + date: "ISO tarihi", + time: "ISO zamanı", + duration: "ISO müddeti", + ipv4: "IPv4 nişânı", + ipv6: "IPv6 nişânı", + cidrv4: "IPv4 menzili", + cidrv6: "IPv6 menzili", + base64: "base64-şifreli metin", + base64url: "base64url-şifreli metin", + json_string: "JSON metin", + e164: "E.164 sayısı", + jwt: "JWT", + template_literal: "giren", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Fâsit giren: umulan ${issue.expected}, alınan ${parsedType(issue.input)}`; + // return `Fâsit giren: umulan ${issue.expected}, alınan ${util.getParsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Fâsit giren: umulan ${util.stringifyPrimitive(issue.values[0])}`; + return `Fâsit tercih: mûteberler ${util.joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Fazla büyük: ${issue.origin ?? "value"}, ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elements"} sahip olmalıydı.`; + return `Fazla büyük: ${issue.origin ?? "value"}, ${adj}${issue.maximum.toString()} olmalıydı.`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Fazla küçük: ${issue.origin}, ${adj}${issue.minimum.toString()} ${sizing.unit} sahip olmalıydı.`; + } + return `Fazla küçük: ${issue.origin}, ${adj}${issue.minimum.toString()} olmalıydı.`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `Fâsit metin: "${_issue.prefix}" ile başlamalı.`; + if (_issue.format === "ends_with") + return `Fâsit metin: "${_issue.suffix}" ile bitmeli.`; + if (_issue.format === "includes") + return `Fâsit metin: "${_issue.includes}" ihtivâ etmeli.`; + if (_issue.format === "regex") + return `Fâsit metin: ${_issue.pattern} nakşına uymalı.`; + return `Fâsit ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Fâsit sayı: ${issue.divisor} katı olmalıydı.`; + case "unrecognized_keys": + return `Tanınmayan anahtar ${issue.keys.length > 1 ? "s" : ""}: ${util.joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `${issue.origin} için tanınmayan anahtar var.`; + case "invalid_union": + return "Giren tanınamadı."; + case "invalid_element": + return `${issue.origin} için tanınmayan kıymet var.`; + default: + return `Kıymet tanınamadı.`; + } + }; +}; +/* harmony default export */ function ota() { + return { + localeError: ota_error(), + }; } -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/tracers/log_stream.js - +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/ps.js +const ps_error = () => { + const Sizable = { + string: { unit: "توکي", verb: "ولري" }, + file: { unit: "بایټس", verb: "ولري" }, + array: { unit: "توکي", verb: "ولري" }, + set: { unit: "توکي", verb: "ولري" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "عدد"; + } + case "object": { + if (Array.isArray(data)) { + return "ارې"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; + }; + const Nouns = { + regex: "ورودي", + email: "بریښنالیک", + url: "یو آر ال", + emoji: "ایموجي", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "نیټه او وخت", + date: "نېټه", + time: "وخت", + duration: "موده", + ipv4: "د IPv4 پته", + ipv6: "د IPv6 پته", + cidrv4: "د IPv4 ساحه", + cidrv6: "د IPv6 ساحه", + base64: "base64-encoded متن", + base64url: "base64url-encoded متن", + json_string: "JSON متن", + e164: "د E.164 شمېره", + jwt: "JWT", + template_literal: "ورودي", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `ناسم ورودي: باید ${issue.expected} وای, مګر ${parsedType(issue.input)} ترلاسه شو`; + case "invalid_value": + if (issue.values.length === 1) { + return `ناسم ورودي: باید ${util.stringifyPrimitive(issue.values[0])} وای`; + } + return `ناسم انتخاب: باید یو له ${util.joinValues(issue.values, "|")} څخه وای`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `ډیر لوی: ${issue.origin ?? "ارزښت"} باید ${adj}${issue.maximum.toString()} ${sizing.unit ?? "عنصرونه"} ولري`; + } + return `ډیر لوی: ${issue.origin ?? "ارزښت"} باید ${adj}${issue.maximum.toString()} وي`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `ډیر کوچنی: ${issue.origin} باید ${adj}${issue.minimum.toString()} ${sizing.unit} ولري`; + } + return `ډیر کوچنی: ${issue.origin} باید ${adj}${issue.minimum.toString()} وي`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") { + return `ناسم متن: باید د "${_issue.prefix}" سره پیل شي`; + } + if (_issue.format === "ends_with") { + return `ناسم متن: باید د "${_issue.suffix}" سره پای ته ورسيږي`; + } + if (_issue.format === "includes") { + return `ناسم متن: باید "${_issue.includes}" ولري`; + } + if (_issue.format === "regex") { + return `ناسم متن: باید د ${_issue.pattern} سره مطابقت ولري`; + } + return `${Nouns[_issue.format] ?? issue.format} ناسم دی`; + } + case "not_multiple_of": + return `ناسم عدد: باید د ${issue.divisor} مضرب وي`; + case "unrecognized_keys": + return `ناسم ${issue.keys.length > 1 ? "کلیډونه" : "کلیډ"}: ${util.joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `ناسم کلیډ په ${issue.origin} کې`; + case "invalid_union": + return `ناسمه ورودي`; + case "invalid_element": + return `ناسم عنصر په ${issue.origin} کې`; + default: + return `ناسمه ورودي`; + } + }; +}; +/* harmony default export */ function ps() { + return { + localeError: ps_error(), + }; +} +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/pl.js -/** - * List of jsonpatch JSONPatchOperations, which describe how to create the run state - * from an empty dict. This is the minimal representation of the log, designed to - * be serialized as JSON and sent over the wire to reconstruct the log on the other - * side. Reconstruction of the state can be done with any jsonpatch-compliant library, - * see https://jsonpatch.com for more information. - */ -class RunLogPatch { - constructor(fields) { - Object.defineProperty(this, "ops", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.ops = fields.ops ?? []; - } - concat(other) { - const ops = this.ops.concat(other.ops); - const states = core_applyPatch({}, ops); - // eslint-disable-next-line @typescript-eslint/no-use-before-define - return new RunLog({ - ops, - state: states[states.length - 1].newDocument, - }); +const pl_error = () => { + const Sizable = { + string: { unit: "znaków", verb: "mieć" }, + file: { unit: "bajtów", verb: "mieć" }, + array: { unit: "elementów", verb: "mieć" }, + set: { unit: "elementów", verb: "mieć" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "liczba"; + } + case "object": { + if (Array.isArray(data)) { + return "tablica"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; + }; + const Nouns = { + regex: "wyrażenie", + email: "adres email", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "data i godzina w formacie ISO", + date: "data w formacie ISO", + time: "godzina w formacie ISO", + duration: "czas trwania ISO", + ipv4: "adres IPv4", + ipv6: "adres IPv6", + cidrv4: "zakres IPv4", + cidrv6: "zakres IPv6", + base64: "ciąg znaków zakodowany w formacie base64", + base64url: "ciąg znaków zakodowany w formacie base64url", + json_string: "ciąg znaków w formacie JSON", + e164: "liczba E.164", + jwt: "JWT", + template_literal: "wejście", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Nieprawidłowe dane wejściowe: oczekiwano ${issue.expected}, otrzymano ${parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Nieprawidłowe dane wejściowe: oczekiwano ${util.stringifyPrimitive(issue.values[0])}`; + return `Nieprawidłowa opcja: oczekiwano jednej z wartości ${util.joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Za duża wartość: oczekiwano, że ${issue.origin ?? "wartość"} będzie mieć ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elementów"}`; + } + return `Zbyt duż(y/a/e): oczekiwano, że ${issue.origin ?? "wartość"} będzie wynosić ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Za mała wartość: oczekiwano, że ${issue.origin ?? "wartość"} będzie mieć ${adj}${issue.minimum.toString()} ${sizing.unit ?? "elementów"}`; + } + return `Zbyt mał(y/a/e): oczekiwano, że ${issue.origin ?? "wartość"} będzie wynosić ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `Nieprawidłowy ciąg znaków: musi zaczynać się od "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Nieprawidłowy ciąg znaków: musi kończyć się na "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Nieprawidłowy ciąg znaków: musi zawierać "${_issue.includes}"`; + if (_issue.format === "regex") + return `Nieprawidłowy ciąg znaków: musi odpowiadać wzorcowi ${_issue.pattern}`; + return `Nieprawidłow(y/a/e) ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Nieprawidłowa liczba: musi być wielokrotnością ${issue.divisor}`; + case "unrecognized_keys": + return `Nierozpoznane klucze${issue.keys.length > 1 ? "s" : ""}: ${util.joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Nieprawidłowy klucz w ${issue.origin}`; + case "invalid_union": + return "Nieprawidłowe dane wejściowe"; + case "invalid_element": + return `Nieprawidłowa wartość w ${issue.origin}`; + default: + return `Nieprawidłowe dane wejściowe`; + } + }; +}; +/* harmony default export */ function pl() { + return { + localeError: pl_error(), + }; } -class RunLog extends RunLogPatch { - constructor(fields) { - super(fields); - Object.defineProperty(this, "state", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.state = fields.state; - } - concat(other) { - const ops = this.ops.concat(other.ops); - const states = core_applyPatch(this.state, other.ops); - return new RunLog({ ops, state: states[states.length - 1].newDocument }); - } - static fromRunLogPatch(patch) { - const states = core_applyPatch({}, patch.ops); - // eslint-disable-next-line @typescript-eslint/no-use-before-define - return new RunLog({ - ops: patch.ops, - state: states[states.length - 1].newDocument, - }); + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/pt.js + +const pt_error = () => { + const Sizable = { + string: { unit: "caracteres", verb: "ter" }, + file: { unit: "bytes", verb: "ter" }, + array: { unit: "itens", verb: "ter" }, + set: { unit: "itens", verb: "ter" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "número"; + } + case "object": { + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "nulo"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; + }; + const Nouns = { + regex: "padrão", + email: "endereço de e-mail", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "data e hora ISO", + date: "data ISO", + time: "hora ISO", + duration: "duração ISO", + ipv4: "endereço IPv4", + ipv6: "endereço IPv6", + cidrv4: "faixa de IPv4", + cidrv6: "faixa de IPv6", + base64: "texto codificado em base64", + base64url: "URL codificada em base64", + json_string: "texto JSON", + e164: "número E.164", + jwt: "JWT", + template_literal: "entrada", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Tipo inválido: esperado ${issue.expected}, recebido ${parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Entrada inválida: esperado ${util.stringifyPrimitive(issue.values[0])}`; + return `Opção inválida: esperada uma das ${util.joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Muito grande: esperado que ${issue.origin ?? "valor"} tivesse ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elementos"}`; + return `Muito grande: esperado que ${issue.origin ?? "valor"} fosse ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Muito pequeno: esperado que ${issue.origin} tivesse ${adj}${issue.minimum.toString()} ${sizing.unit}`; + } + return `Muito pequeno: esperado que ${issue.origin} fosse ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `Texto inválido: deve começar com "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Texto inválido: deve terminar com "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Texto inválido: deve incluir "${_issue.includes}"`; + if (_issue.format === "regex") + return `Texto inválido: deve corresponder ao padrão ${_issue.pattern}`; + return `${Nouns[_issue.format] ?? issue.format} inválido`; + } + case "not_multiple_of": + return `Número inválido: deve ser múltiplo de ${issue.divisor}`; + case "unrecognized_keys": + return `Chave${issue.keys.length > 1 ? "s" : ""} desconhecida${issue.keys.length > 1 ? "s" : ""}: ${util.joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Chave inválida em ${issue.origin}`; + case "invalid_union": + return "Entrada inválida"; + case "invalid_element": + return `Valor inválido em ${issue.origin}`; + default: + return `Campo inválido`; + } + }; +}; +/* harmony default export */ function pt() { + return { + localeError: pt_error(), + }; } -const isLogStreamHandler = (handler) => handler.name === "log_stream_tracer"; -/** - * Extract standardized inputs from a run. - * - * Standardizes the inputs based on the type of the runnable used. - * - * @param run - Run object - * @param schemaFormat - The schema format to use. - * - * @returns Valid inputs are only dict. By conventions, inputs always represented - * invocation using named arguments. - * A null means that the input is not yet known! - */ -async function _getStandardizedInputs(run, schemaFormat) { - if (schemaFormat === "original") { - throw new Error("Do not assign inputs with original schema drop the key for now. " + - "When inputs are added to streamLog they should be added with " + - "standardized schema for streaming events."); + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/ru.js + +function getRussianPlural(count, one, few, many) { + const absCount = Math.abs(count); + const lastDigit = absCount % 10; + const lastTwoDigits = absCount % 100; + if (lastTwoDigits >= 11 && lastTwoDigits <= 19) { + return many; } - const { inputs } = run; - if (["retriever", "llm", "prompt"].includes(run.run_type)) { - return inputs; + if (lastDigit === 1) { + return one; } - if (Object.keys(inputs).length === 1 && inputs?.input === "") { - return undefined; + if (lastDigit >= 2 && lastDigit <= 4) { + return few; } - // new style chains - // These nest an additional 'input' key inside the 'inputs' to make sure - // the input is always a dict. We need to unpack and user the inner value. - // We should try to fix this in Runnables and callbacks/tracers - // Runnables should be using a null type here not a placeholder - // dict. - return inputs.input; + return many; } -async function _getStandardizedOutputs(run, schemaFormat) { - const { outputs } = run; - if (schemaFormat === "original") { - // Return the old schema, without standardizing anything - return outputs; - } - if (["retriever", "llm", "prompt"].includes(run.run_type)) { - return outputs; - } - // TODO: Remove this hacky check - if (outputs !== undefined && - Object.keys(outputs).length === 1 && - outputs?.output !== undefined) { - return outputs.output; +const ru_error = () => { + const Sizable = { + string: { + unit: { + one: "символ", + few: "символа", + many: "символов", + }, + verb: "иметь", + }, + file: { + unit: { + one: "байт", + few: "байта", + many: "байт", + }, + verb: "иметь", + }, + array: { + unit: { + one: "элемент", + few: "элемента", + many: "элементов", + }, + verb: "иметь", + }, + set: { + unit: { + one: "элемент", + few: "элемента", + many: "элементов", + }, + verb: "иметь", + }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; } - return outputs; -} -function isChatGenerationChunk(x) { - return x !== undefined && x.message !== undefined; + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "число"; + } + case "object": { + if (Array.isArray(data)) { + return "массив"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; + }; + const Nouns = { + regex: "ввод", + email: "email адрес", + url: "URL", + emoji: "эмодзи", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO дата и время", + date: "ISO дата", + time: "ISO время", + duration: "ISO длительность", + ipv4: "IPv4 адрес", + ipv6: "IPv6 адрес", + cidrv4: "IPv4 диапазон", + cidrv6: "IPv6 диапазон", + base64: "строка в формате base64", + base64url: "строка в формате base64url", + json_string: "JSON строка", + e164: "номер E.164", + jwt: "JWT", + template_literal: "ввод", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Неверный ввод: ожидалось ${issue.expected}, получено ${parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Неверный ввод: ожидалось ${util.stringifyPrimitive(issue.values[0])}`; + return `Неверный вариант: ожидалось одно из ${util.joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) { + const maxValue = Number(issue.maximum); + const unit = getRussianPlural(maxValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); + return `Слишком большое значение: ожидалось, что ${issue.origin ?? "значение"} будет иметь ${adj}${issue.maximum.toString()} ${unit}`; + } + return `Слишком большое значение: ожидалось, что ${issue.origin ?? "значение"} будет ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + const minValue = Number(issue.minimum); + const unit = getRussianPlural(minValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); + return `Слишком маленькое значение: ожидалось, что ${issue.origin} будет иметь ${adj}${issue.minimum.toString()} ${unit}`; + } + return `Слишком маленькое значение: ожидалось, что ${issue.origin} будет ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `Неверная строка: должна начинаться с "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Неверная строка: должна заканчиваться на "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Неверная строка: должна содержать "${_issue.includes}"`; + if (_issue.format === "regex") + return `Неверная строка: должна соответствовать шаблону ${_issue.pattern}`; + return `Неверный ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Неверное число: должно быть кратным ${issue.divisor}`; + case "unrecognized_keys": + return `Нераспознанн${issue.keys.length > 1 ? "ые" : "ый"} ключ${issue.keys.length > 1 ? "и" : ""}: ${util.joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Неверный ключ в ${issue.origin}`; + case "invalid_union": + return "Неверные входные данные"; + case "invalid_element": + return `Неверное значение в ${issue.origin}`; + default: + return `Неверные входные данные`; + } + }; +}; +/* harmony default export */ function ru() { + return { + localeError: ru_error(), + }; } -/** - * Class that extends the `BaseTracer` class from the - * `langchain.callbacks.tracers.base` module. It represents a callback - * handler that logs the execution of runs and emits `RunLog` instances to a - * `RunLogStream`. - */ -class LogStreamCallbackHandler extends BaseTracer { - constructor(fields) { - super({ _awaitHandler: true, ...fields }); - Object.defineProperty(this, "autoClose", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - Object.defineProperty(this, "includeNames", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "includeTypes", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "includeTags", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "excludeNames", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "excludeTypes", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "excludeTags", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "_schemaFormat", { - enumerable: true, - configurable: true, - writable: true, - value: "original" - }); - Object.defineProperty(this, "rootId", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "keyMapByRunId", { - enumerable: true, - configurable: true, - writable: true, - value: {} - }); - Object.defineProperty(this, "counterMapByRunName", { - enumerable: true, - configurable: true, - writable: true, - value: {} - }); - Object.defineProperty(this, "transformStream", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "writer", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "receiveStream", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "log_stream_tracer" - }); - Object.defineProperty(this, "lc_prefer_streaming", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - this.autoClose = fields?.autoClose ?? true; - this.includeNames = fields?.includeNames; - this.includeTypes = fields?.includeTypes; - this.includeTags = fields?.includeTags; - this.excludeNames = fields?.excludeNames; - this.excludeTypes = fields?.excludeTypes; - this.excludeTags = fields?.excludeTags; - this._schemaFormat = fields?._schemaFormat ?? this._schemaFormat; - this.transformStream = new TransformStream(); - this.writer = this.transformStream.writable.getWriter(); - this.receiveStream = IterableReadableStream.fromReadableStream(this.transformStream.readable); - } - [Symbol.asyncIterator]() { - return this.receiveStream; - } - async persistRun(_run) { - // This is a legacy method only called once for an entire run tree - // and is therefore not useful here + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/sl.js + +const sl_error = () => { + const Sizable = { + string: { unit: "znakov", verb: "imeti" }, + file: { unit: "bajtov", verb: "imeti" }, + array: { unit: "elementov", verb: "imeti" }, + set: { unit: "elementov", verb: "imeti" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; } - _includeRun(run) { - if (run.id === this.rootId) { - return false; - } - const runTags = run.tags ?? []; - let include = this.includeNames === undefined && - this.includeTags === undefined && - this.includeTypes === undefined; - if (this.includeNames !== undefined) { - include = include || this.includeNames.includes(run.name); + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "število"; + } + case "object": { + if (Array.isArray(data)) { + return "tabela"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } } - if (this.includeTypes !== undefined) { - include = include || this.includeTypes.includes(run.run_type); + return t; + }; + const Nouns = { + regex: "vnos", + email: "e-poštni naslov", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO datum in čas", + date: "ISO datum", + time: "ISO čas", + duration: "ISO trajanje", + ipv4: "IPv4 naslov", + ipv6: "IPv6 naslov", + cidrv4: "obseg IPv4", + cidrv6: "obseg IPv6", + base64: "base64 kodiran niz", + base64url: "base64url kodiran niz", + json_string: "JSON niz", + e164: "E.164 številka", + jwt: "JWT", + template_literal: "vnos", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Neveljaven vnos: pričakovano ${issue.expected}, prejeto ${parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Neveljaven vnos: pričakovano ${util.stringifyPrimitive(issue.values[0])}`; + return `Neveljavna možnost: pričakovano eno izmed ${util.joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Preveliko: pričakovano, da bo ${issue.origin ?? "vrednost"} imelo ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elementov"}`; + return `Preveliko: pričakovano, da bo ${issue.origin ?? "vrednost"} ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Premajhno: pričakovano, da bo ${issue.origin} imelo ${adj}${issue.minimum.toString()} ${sizing.unit}`; + } + return `Premajhno: pričakovano, da bo ${issue.origin} ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") { + return `Neveljaven niz: mora se začeti z "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `Neveljaven niz: mora se končati z "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Neveljaven niz: mora vsebovati "${_issue.includes}"`; + if (_issue.format === "regex") + return `Neveljaven niz: mora ustrezati vzorcu ${_issue.pattern}`; + return `Neveljaven ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Neveljavno število: mora biti večkratnik ${issue.divisor}`; + case "unrecognized_keys": + return `Neprepoznan${issue.keys.length > 1 ? "i ključi" : " ključ"}: ${util.joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Neveljaven ključ v ${issue.origin}`; + case "invalid_union": + return "Neveljaven vnos"; + case "invalid_element": + return `Neveljavna vrednost v ${issue.origin}`; + default: + return "Neveljaven vnos"; } - if (this.includeTags !== undefined) { - include = - include || - runTags.find((tag) => this.includeTags?.includes(tag)) !== undefined; + }; +}; +/* harmony default export */ function sl() { + return { + localeError: sl_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/sv.js + +const sv_error = () => { + const Sizable = { + string: { unit: "tecken", verb: "att ha" }, + file: { unit: "bytes", verb: "att ha" }, + array: { unit: "objekt", verb: "att innehålla" }, + set: { unit: "objekt", verb: "att innehålla" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "antal"; + } + case "object": { + if (Array.isArray(data)) { + return "lista"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } } - if (this.excludeNames !== undefined) { - include = include && !this.excludeNames.includes(run.name); + return t; + }; + const Nouns = { + regex: "reguljärt uttryck", + email: "e-postadress", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO-datum och tid", + date: "ISO-datum", + time: "ISO-tid", + duration: "ISO-varaktighet", + ipv4: "IPv4-intervall", + ipv6: "IPv6-intervall", + cidrv4: "IPv4-spektrum", + cidrv6: "IPv6-spektrum", + base64: "base64-kodad sträng", + base64url: "base64url-kodad sträng", + json_string: "JSON-sträng", + e164: "E.164-nummer", + jwt: "JWT", + template_literal: "mall-literal", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Ogiltig inmatning: förväntat ${issue.expected}, fick ${parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Ogiltig inmatning: förväntat ${util.stringifyPrimitive(issue.values[0])}`; + return `Ogiltigt val: förväntade en av ${util.joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `För stor(t): förväntade ${issue.origin ?? "värdet"} att ha ${adj}${issue.maximum.toString()} ${sizing.unit ?? "element"}`; + } + return `För stor(t): förväntat ${issue.origin ?? "värdet"} att ha ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `För lite(t): förväntade ${issue.origin ?? "värdet"} att ha ${adj}${issue.minimum.toString()} ${sizing.unit}`; + } + return `För lite(t): förväntade ${issue.origin ?? "värdet"} att ha ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") { + return `Ogiltig sträng: måste börja med "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `Ogiltig sträng: måste sluta med "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Ogiltig sträng: måste innehålla "${_issue.includes}"`; + if (_issue.format === "regex") + return `Ogiltig sträng: måste matcha mönstret "${_issue.pattern}"`; + return `Ogiltig(t) ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Ogiltigt tal: måste vara en multipel av ${issue.divisor}`; + case "unrecognized_keys": + return `${issue.keys.length > 1 ? "Okända nycklar" : "Okänd nyckel"}: ${util.joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Ogiltig nyckel i ${issue.origin ?? "värdet"}`; + case "invalid_union": + return "Ogiltig input"; + case "invalid_element": + return `Ogiltigt värde i ${issue.origin ?? "värdet"}`; + default: + return `Ogiltig input`; } - if (this.excludeTypes !== undefined) { - include = include && !this.excludeTypes.includes(run.run_type); + }; +}; +/* harmony default export */ function sv() { + return { + localeError: sv_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/ta.js + +const ta_error = () => { + const Sizable = { + string: { unit: "எழுத்துக்கள்", verb: "கொண்டிருக்க வேண்டும்" }, + file: { unit: "பைட்டுகள்", verb: "கொண்டிருக்க வேண்டும்" }, + array: { unit: "உறுப்புகள்", verb: "கொண்டிருக்க வேண்டும்" }, + set: { unit: "உறுப்புகள்", verb: "கொண்டிருக்க வேண்டும்" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "எண் அல்லாதது" : "எண்"; + } + case "object": { + if (Array.isArray(data)) { + return "அணி"; + } + if (data === null) { + return "வெறுமை"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } } - if (this.excludeTags !== undefined) { - include = - include && runTags.every((tag) => !this.excludeTags?.includes(tag)); + return t; + }; + const Nouns = { + regex: "உள்ளீடு", + email: "மின்னஞ்சல் முகவரி", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO தேதி நேரம்", + date: "ISO தேதி", + time: "ISO நேரம்", + duration: "ISO கால அளவு", + ipv4: "IPv4 முகவரி", + ipv6: "IPv6 முகவரி", + cidrv4: "IPv4 வரம்பு", + cidrv6: "IPv6 வரம்பு", + base64: "base64-encoded சரம்", + base64url: "base64url-encoded சரம்", + json_string: "JSON சரம்", + e164: "E.164 எண்", + jwt: "JWT", + template_literal: "input", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${issue.expected}, பெறப்பட்டது ${parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${util.stringifyPrimitive(issue.values[0])}`; + return `தவறான விருப்பம்: எதிர்பார்க்கப்பட்டது ${util.joinValues(issue.values, "|")} இல் ஒன்று`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `மிக பெரியது: எதிர்பார்க்கப்பட்டது ${issue.origin ?? "மதிப்பு"} ${adj}${issue.maximum.toString()} ${sizing.unit ?? "உறுப்புகள்"} ஆக இருக்க வேண்டும்`; + } + return `மிக பெரியது: எதிர்பார்க்கப்பட்டது ${issue.origin ?? "மதிப்பு"} ${adj}${issue.maximum.toString()} ஆக இருக்க வேண்டும்`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${issue.origin} ${adj}${issue.minimum.toString()} ${sizing.unit} ஆக இருக்க வேண்டும்`; // + } + return `மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${issue.origin} ${adj}${issue.minimum.toString()} ஆக இருக்க வேண்டும்`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `தவறான சரம்: "${_issue.prefix}" இல் தொடங்க வேண்டும்`; + if (_issue.format === "ends_with") + return `தவறான சரம்: "${_issue.suffix}" இல் முடிவடைய வேண்டும்`; + if (_issue.format === "includes") + return `தவறான சரம்: "${_issue.includes}" ஐ உள்ளடக்க வேண்டும்`; + if (_issue.format === "regex") + return `தவறான சரம்: ${_issue.pattern} முறைபாட்டுடன் பொருந்த வேண்டும்`; + return `தவறான ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `தவறான எண்: ${issue.divisor} இன் பலமாக இருக்க வேண்டும்`; + case "unrecognized_keys": + return `அடையாளம் தெரியாத விசை${issue.keys.length > 1 ? "கள்" : ""}: ${util.joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `${issue.origin} இல் தவறான விசை`; + case "invalid_union": + return "தவறான உள்ளீடு"; + case "invalid_element": + return `${issue.origin} இல் தவறான மதிப்பு`; + default: + return `தவறான உள்ளீடு`; } - return include; + }; +}; +/* harmony default export */ function ta() { + return { + localeError: ta_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/th.js + +const th_error = () => { + const Sizable = { + string: { unit: "ตัวอักษร", verb: "ควรมี" }, + file: { unit: "ไบต์", verb: "ควรมี" }, + array: { unit: "รายการ", verb: "ควรมี" }, + set: { unit: "รายการ", verb: "ควรมี" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; } - async *tapOutputIterable(runId, output) { - // Tap an output async iterator to stream its values to the log. - for await (const chunk of output) { - // root run is handled in .streamLog() - if (runId !== this.rootId) { - // if we can't find the run silently ignore - // eg. because this run wasn't included in the log - const key = this.keyMapByRunId[runId]; - if (key) { - await this.writer.write(new RunLogPatch({ - ops: [ - { - op: "add", - path: `/logs/${key}/streamed_output/-`, - value: chunk, - }, - ], - })); + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "ไม่ใช่ตัวเลข (NaN)" : "ตัวเลข"; + } + case "object": { + if (Array.isArray(data)) { + return "อาร์เรย์ (Array)"; + } + if (data === null) { + return "ไม่มีค่า (null)"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; } } - yield chunk; } - } - async onRunCreate(run) { - if (this.rootId === undefined) { - this.rootId = run.id; - await this.writer.write(new RunLogPatch({ - ops: [ - { - op: "replace", - path: "", - value: { - id: run.id, - name: run.name, - type: run.run_type, - streamed_output: [], - final_output: undefined, - logs: {}, - }, - }, - ], - })); + return t; + }; + const Nouns = { + regex: "ข้อมูลที่ป้อน", + email: "ที่อยู่อีเมล", + url: "URL", + emoji: "อิโมจิ", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "วันที่เวลาแบบ ISO", + date: "วันที่แบบ ISO", + time: "เวลาแบบ ISO", + duration: "ช่วงเวลาแบบ ISO", + ipv4: "ที่อยู่ IPv4", + ipv6: "ที่อยู่ IPv6", + cidrv4: "ช่วง IP แบบ IPv4", + cidrv6: "ช่วง IP แบบ IPv6", + base64: "ข้อความแบบ Base64", + base64url: "ข้อความแบบ Base64 สำหรับ URL", + json_string: "ข้อความแบบ JSON", + e164: "เบอร์โทรศัพท์ระหว่างประเทศ (E.164)", + jwt: "โทเคน JWT", + template_literal: "ข้อมูลที่ป้อน", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `ประเภทข้อมูลไม่ถูกต้อง: ควรเป็น ${issue.expected} แต่ได้รับ ${parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `ค่าไม่ถูกต้อง: ควรเป็น ${util.stringifyPrimitive(issue.values[0])}`; + return `ตัวเลือกไม่ถูกต้อง: ควรเป็นหนึ่งใน ${util.joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "ไม่เกิน" : "น้อยกว่า"; + const sizing = getSizing(issue.origin); + if (sizing) + return `เกินกำหนด: ${issue.origin ?? "ค่า"} ควรมี${adj} ${issue.maximum.toString()} ${sizing.unit ?? "รายการ"}`; + return `เกินกำหนด: ${issue.origin ?? "ค่า"} ควรมี${adj} ${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? "อย่างน้อย" : "มากกว่า"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `น้อยกว่ากำหนด: ${issue.origin} ควรมี${adj} ${issue.minimum.toString()} ${sizing.unit}`; + } + return `น้อยกว่ากำหนด: ${issue.origin} ควรมี${adj} ${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") { + return `รูปแบบไม่ถูกต้อง: ข้อความต้องขึ้นต้นด้วย "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `รูปแบบไม่ถูกต้อง: ข้อความต้องลงท้ายด้วย "${_issue.suffix}"`; + if (_issue.format === "includes") + return `รูปแบบไม่ถูกต้อง: ข้อความต้องมี "${_issue.includes}" อยู่ในข้อความ`; + if (_issue.format === "regex") + return `รูปแบบไม่ถูกต้อง: ต้องตรงกับรูปแบบที่กำหนด ${_issue.pattern}`; + return `รูปแบบไม่ถูกต้อง: ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `ตัวเลขไม่ถูกต้อง: ต้องเป็นจำนวนที่หารด้วย ${issue.divisor} ได้ลงตัว`; + case "unrecognized_keys": + return `พบคีย์ที่ไม่รู้จัก: ${util.joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `คีย์ไม่ถูกต้องใน ${issue.origin}`; + case "invalid_union": + return "ข้อมูลไม่ถูกต้อง: ไม่ตรงกับรูปแบบยูเนียนที่กำหนดไว้"; + case "invalid_element": + return `ข้อมูลไม่ถูกต้องใน ${issue.origin}`; + default: + return `ข้อมูลไม่ถูกต้อง`; } - if (!this._includeRun(run)) { - return; + }; +}; +/* harmony default export */ function th() { + return { + localeError: th_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/tr.js + +const tr_parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "number"; } - if (this.counterMapByRunName[run.name] === undefined) { - this.counterMapByRunName[run.name] = 0; + case "object": { + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } } - this.counterMapByRunName[run.name] += 1; - const count = this.counterMapByRunName[run.name]; - this.keyMapByRunId[run.id] = - count === 1 ? run.name : `${run.name}:${count}`; - const logEntry = { - id: run.id, - name: run.name, - type: run.run_type, - tags: run.tags ?? [], - metadata: run.extra?.metadata ?? {}, - start_time: new Date(run.start_time).toISOString(), - streamed_output: [], - streamed_output_str: [], - final_output: undefined, - end_time: undefined, - }; - if (this._schemaFormat === "streaming_events") { - logEntry.inputs = await _getStandardizedInputs(run, this._schemaFormat); + } + return t; +}; +const tr_error = () => { + const Sizable = { + string: { unit: "karakter", verb: "olmalı" }, + file: { unit: "bayt", verb: "olmalı" }, + array: { unit: "öğe", verb: "olmalı" }, + set: { unit: "öğe", verb: "olmalı" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const Nouns = { + regex: "girdi", + email: "e-posta adresi", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO tarih ve saat", + date: "ISO tarih", + time: "ISO saat", + duration: "ISO süre", + ipv4: "IPv4 adresi", + ipv6: "IPv6 adresi", + cidrv4: "IPv4 aralığı", + cidrv6: "IPv6 aralığı", + base64: "base64 ile şifrelenmiş metin", + base64url: "base64url ile şifrelenmiş metin", + json_string: "JSON dizesi", + e164: "E.164 sayısı", + jwt: "JWT", + template_literal: "Şablon dizesi", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Geçersiz değer: beklenen ${issue.expected}, alınan ${tr_parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Geçersiz değer: beklenen ${util.stringifyPrimitive(issue.values[0])}`; + return `Geçersiz seçenek: aşağıdakilerden biri olmalı: ${util.joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Çok büyük: beklenen ${issue.origin ?? "değer"} ${adj}${issue.maximum.toString()} ${sizing.unit ?? "öğe"}`; + return `Çok büyük: beklenen ${issue.origin ?? "değer"} ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Çok küçük: beklenen ${issue.origin} ${adj}${issue.minimum.toString()} ${sizing.unit}`; + return `Çok küçük: beklenen ${issue.origin} ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `Geçersiz metin: "${_issue.prefix}" ile başlamalı`; + if (_issue.format === "ends_with") + return `Geçersiz metin: "${_issue.suffix}" ile bitmeli`; + if (_issue.format === "includes") + return `Geçersiz metin: "${_issue.includes}" içermeli`; + if (_issue.format === "regex") + return `Geçersiz metin: ${_issue.pattern} desenine uymalı`; + return `Geçersiz ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Geçersiz sayı: ${issue.divisor} ile tam bölünebilmeli`; + case "unrecognized_keys": + return `Tanınmayan anahtar${issue.keys.length > 1 ? "lar" : ""}: ${util.joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `${issue.origin} içinde geçersiz anahtar`; + case "invalid_union": + return "Geçersiz değer"; + case "invalid_element": + return `${issue.origin} içinde geçersiz değer`; + default: + return `Geçersiz değer`; } - await this.writer.write(new RunLogPatch({ - ops: [ - { - op: "add", - path: `/logs/${this.keyMapByRunId[run.id]}`, - value: logEntry, - }, - ], - })); + }; +}; +/* harmony default export */ function tr() { + return { + localeError: tr_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/ua.js + +const ua_error = () => { + const Sizable = { + string: { unit: "символів", verb: "матиме" }, + file: { unit: "байтів", verb: "матиме" }, + array: { unit: "елементів", verb: "матиме" }, + set: { unit: "елементів", verb: "матиме" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; } - async onRunUpdate(run) { - try { - const runName = this.keyMapByRunId[run.id]; - if (runName === undefined) { - return; - } - const ops = []; - if (this._schemaFormat === "streaming_events") { - ops.push({ - op: "replace", - path: `/logs/${runName}/inputs`, - value: await _getStandardizedInputs(run, this._schemaFormat), - }); + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "число"; } - ops.push({ - op: "add", - path: `/logs/${runName}/final_output`, - value: await _getStandardizedOutputs(run, this._schemaFormat), - }); - if (run.end_time !== undefined) { - ops.push({ - op: "add", - path: `/logs/${runName}/end_time`, - value: new Date(run.end_time).toISOString(), - }); + case "object": { + if (Array.isArray(data)) { + return "масив"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } } - const patch = new RunLogPatch({ ops }); - await this.writer.write(patch); } - finally { - if (run.id === this.rootId) { - const patch = new RunLogPatch({ - ops: [ - { - op: "replace", - path: "/final_output", - value: await _getStandardizedOutputs(run, this._schemaFormat), - }, - ], - }); - await this.writer.write(patch); - if (this.autoClose) { - await this.writer.close(); + return t; + }; + const Nouns = { + regex: "вхідні дані", + email: "адреса електронної пошти", + url: "URL", + emoji: "емодзі", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "дата та час ISO", + date: "дата ISO", + time: "час ISO", + duration: "тривалість ISO", + ipv4: "адреса IPv4", + ipv6: "адреса IPv6", + cidrv4: "діапазон IPv4", + cidrv6: "діапазон IPv6", + base64: "рядок у кодуванні base64", + base64url: "рядок у кодуванні base64url", + json_string: "рядок JSON", + e164: "номер E.164", + jwt: "JWT", + template_literal: "вхідні дані", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Неправильні вхідні дані: очікується ${issue.expected}, отримано ${parsedType(issue.input)}`; + // return `Неправильні вхідні дані: очікується ${issue.expected}, отримано ${util.getParsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Неправильні вхідні дані: очікується ${util.stringifyPrimitive(issue.values[0])}`; + return `Неправильна опція: очікується одне з ${util.joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Занадто велике: очікується, що ${issue.origin ?? "значення"} ${sizing.verb} ${adj}${issue.maximum.toString()} ${sizing.unit ?? "елементів"}`; + return `Занадто велике: очікується, що ${issue.origin ?? "значення"} буде ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Занадто мале: очікується, що ${issue.origin} ${sizing.verb} ${adj}${issue.minimum.toString()} ${sizing.unit}`; + } + return `Занадто мале: очікується, що ${issue.origin} буде ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `Неправильний рядок: повинен починатися з "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Неправильний рядок: повинен закінчуватися на "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Неправильний рядок: повинен містити "${_issue.includes}"`; + if (_issue.format === "regex") + return `Неправильний рядок: повинен відповідати шаблону ${_issue.pattern}`; + return `Неправильний ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Неправильне число: повинно бути кратним ${issue.divisor}`; + case "unrecognized_keys": + return `Нерозпізнаний ключ${issue.keys.length > 1 ? "і" : ""}: ${util.joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Неправильний ключ у ${issue.origin}`; + case "invalid_union": + return "Неправильні вхідні дані"; + case "invalid_element": + return `Неправильне значення у ${issue.origin}`; + default: + return `Неправильні вхідні дані`; + } + }; +}; +/* harmony default export */ function ua() { + return { + localeError: ua_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/ur.js + +const ur_error = () => { + const Sizable = { + string: { unit: "حروف", verb: "ہونا" }, + file: { unit: "بائٹس", verb: "ہونا" }, + array: { unit: "آئٹمز", verb: "ہونا" }, + set: { unit: "آئٹمز", verb: "ہونا" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "نمبر"; + } + case "object": { + if (Array.isArray(data)) { + return "آرے"; + } + if (data === null) { + return "نل"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; } } } + return t; + }; + const Nouns = { + regex: "ان پٹ", + email: "ای میل ایڈریس", + url: "یو آر ایل", + emoji: "ایموجی", + uuid: "یو یو آئی ڈی", + uuidv4: "یو یو آئی ڈی وی 4", + uuidv6: "یو یو آئی ڈی وی 6", + nanoid: "نینو آئی ڈی", + guid: "جی یو آئی ڈی", + cuid: "سی یو آئی ڈی", + cuid2: "سی یو آئی ڈی 2", + ulid: "یو ایل آئی ڈی", + xid: "ایکس آئی ڈی", + ksuid: "کے ایس یو آئی ڈی", + datetime: "آئی ایس او ڈیٹ ٹائم", + date: "آئی ایس او تاریخ", + time: "آئی ایس او وقت", + duration: "آئی ایس او مدت", + ipv4: "آئی پی وی 4 ایڈریس", + ipv6: "آئی پی وی 6 ایڈریس", + cidrv4: "آئی پی وی 4 رینج", + cidrv6: "آئی پی وی 6 رینج", + base64: "بیس 64 ان کوڈڈ سٹرنگ", + base64url: "بیس 64 یو آر ایل ان کوڈڈ سٹرنگ", + json_string: "جے ایس او این سٹرنگ", + e164: "ای 164 نمبر", + jwt: "جے ڈبلیو ٹی", + template_literal: "ان پٹ", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `غلط ان پٹ: ${issue.expected} متوقع تھا، ${parsedType(issue.input)} موصول ہوا`; + case "invalid_value": + if (issue.values.length === 1) + return `غلط ان پٹ: ${util.stringifyPrimitive(issue.values[0])} متوقع تھا`; + return `غلط آپشن: ${util.joinValues(issue.values, "|")} میں سے ایک متوقع تھا`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `بہت بڑا: ${issue.origin ?? "ویلیو"} کے ${adj}${issue.maximum.toString()} ${sizing.unit ?? "عناصر"} ہونے متوقع تھے`; + return `بہت بڑا: ${issue.origin ?? "ویلیو"} کا ${adj}${issue.maximum.toString()} ہونا متوقع تھا`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `بہت چھوٹا: ${issue.origin} کے ${adj}${issue.minimum.toString()} ${sizing.unit} ہونے متوقع تھے`; + } + return `بہت چھوٹا: ${issue.origin} کا ${adj}${issue.minimum.toString()} ہونا متوقع تھا`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") { + return `غلط سٹرنگ: "${_issue.prefix}" سے شروع ہونا چاہیے`; + } + if (_issue.format === "ends_with") + return `غلط سٹرنگ: "${_issue.suffix}" پر ختم ہونا چاہیے`; + if (_issue.format === "includes") + return `غلط سٹرنگ: "${_issue.includes}" شامل ہونا چاہیے`; + if (_issue.format === "regex") + return `غلط سٹرنگ: پیٹرن ${_issue.pattern} سے میچ ہونا چاہیے`; + return `غلط ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `غلط نمبر: ${issue.divisor} کا مضاعف ہونا چاہیے`; + case "unrecognized_keys": + return `غیر تسلیم شدہ کی${issue.keys.length > 1 ? "ز" : ""}: ${util.joinValues(issue.keys, "، ")}`; + case "invalid_key": + return `${issue.origin} میں غلط کی`; + case "invalid_union": + return "غلط ان پٹ"; + case "invalid_element": + return `${issue.origin} میں غلط ویلیو`; + default: + return `غلط ان پٹ`; + } + }; +}; +/* harmony default export */ function ur() { + return { + localeError: ur_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/vi.js + +const vi_error = () => { + const Sizable = { + string: { unit: "ký tự", verb: "có" }, + file: { unit: "byte", verb: "có" }, + array: { unit: "phần tử", verb: "có" }, + set: { unit: "phần tử", verb: "có" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; } - async onLLMNewToken(run, token, kwargs) { - const runName = this.keyMapByRunId[run.id]; - if (runName === undefined) { - return; + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "số"; + } + case "object": { + if (Array.isArray(data)) { + return "mảng"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } } - // TODO: Remove hack - const isChatModel = run.inputs.messages !== undefined; - let streamedOutputValue; - if (isChatModel) { - if (isChatGenerationChunk(kwargs?.chunk)) { - streamedOutputValue = kwargs?.chunk; + return t; + }; + const Nouns = { + regex: "đầu vào", + email: "địa chỉ email", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ngày giờ ISO", + date: "ngày ISO", + time: "giờ ISO", + duration: "khoảng thời gian ISO", + ipv4: "địa chỉ IPv4", + ipv6: "địa chỉ IPv6", + cidrv4: "dải IPv4", + cidrv6: "dải IPv6", + base64: "chuỗi mã hóa base64", + base64url: "chuỗi mã hóa base64url", + json_string: "chuỗi JSON", + e164: "số E.164", + jwt: "JWT", + template_literal: "đầu vào", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Đầu vào không hợp lệ: mong đợi ${issue.expected}, nhận được ${parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Đầu vào không hợp lệ: mong đợi ${util.stringifyPrimitive(issue.values[0])}`; + return `Tùy chọn không hợp lệ: mong đợi một trong các giá trị ${util.joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Quá lớn: mong đợi ${issue.origin ?? "giá trị"} ${sizing.verb} ${adj}${issue.maximum.toString()} ${sizing.unit ?? "phần tử"}`; + return `Quá lớn: mong đợi ${issue.origin ?? "giá trị"} ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Quá nhỏ: mong đợi ${issue.origin} ${sizing.verb} ${adj}${issue.minimum.toString()} ${sizing.unit}`; + } + return `Quá nhỏ: mong đợi ${issue.origin} ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `Chuỗi không hợp lệ: phải bắt đầu bằng "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Chuỗi không hợp lệ: phải kết thúc bằng "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Chuỗi không hợp lệ: phải bao gồm "${_issue.includes}"`; + if (_issue.format === "regex") + return `Chuỗi không hợp lệ: phải khớp với mẫu ${_issue.pattern}`; + return `${Nouns[_issue.format] ?? issue.format} không hợp lệ`; + } + case "not_multiple_of": + return `Số không hợp lệ: phải là bội số của ${issue.divisor}`; + case "unrecognized_keys": + return `Khóa không được nhận dạng: ${util.joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Khóa không hợp lệ trong ${issue.origin}`; + case "invalid_union": + return "Đầu vào không hợp lệ"; + case "invalid_element": + return `Giá trị không hợp lệ trong ${issue.origin}`; + default: + return `Đầu vào không hợp lệ`; + } + }; +}; +/* harmony default export */ function vi() { + return { + localeError: vi_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/zh-CN.js + +const zh_CN_error = () => { + const Sizable = { + string: { unit: "字符", verb: "包含" }, + file: { unit: "字节", verb: "包含" }, + array: { unit: "项", verb: "包含" }, + set: { unit: "项", verb: "包含" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "非数字(NaN)" : "数字"; } - else { - streamedOutputValue = new ai_AIMessageChunk({ - id: `run-${run.id}`, - content: token, - }); + case "object": { + if (Array.isArray(data)) { + return "数组"; + } + if (data === null) { + return "空值(null)"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } } } - else { - streamedOutputValue = token; + return t; + }; + const Nouns = { + regex: "输入", + email: "电子邮件", + url: "URL", + emoji: "表情符号", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO日期时间", + date: "ISO日期", + time: "ISO时间", + duration: "ISO时长", + ipv4: "IPv4地址", + ipv6: "IPv6地址", + cidrv4: "IPv4网段", + cidrv6: "IPv6网段", + base64: "base64编码字符串", + base64url: "base64url编码字符串", + json_string: "JSON字符串", + e164: "E.164号码", + jwt: "JWT", + template_literal: "输入", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `无效输入:期望 ${issue.expected},实际接收 ${parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `无效输入:期望 ${util.stringifyPrimitive(issue.values[0])}`; + return `无效选项:期望以下之一 ${util.joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `数值过大:期望 ${issue.origin ?? "值"} ${adj}${issue.maximum.toString()} ${sizing.unit ?? "个元素"}`; + return `数值过大:期望 ${issue.origin ?? "值"} ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `数值过小:期望 ${issue.origin} ${adj}${issue.minimum.toString()} ${sizing.unit}`; + } + return `数值过小:期望 ${issue.origin} ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `无效字符串:必须以 "${_issue.prefix}" 开头`; + if (_issue.format === "ends_with") + return `无效字符串:必须以 "${_issue.suffix}" 结尾`; + if (_issue.format === "includes") + return `无效字符串:必须包含 "${_issue.includes}"`; + if (_issue.format === "regex") + return `无效字符串:必须满足正则表达式 ${_issue.pattern}`; + return `无效${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `无效数字:必须是 ${issue.divisor} 的倍数`; + case "unrecognized_keys": + return `出现未知的键(key): ${util.joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `${issue.origin} 中的键(key)无效`; + case "invalid_union": + return "无效输入"; + case "invalid_element": + return `${issue.origin} 中包含无效值(value)`; + default: + return `无效输入`; } - const patch = new RunLogPatch({ - ops: [ - { - op: "add", - path: `/logs/${runName}/streamed_output_str/-`, - value: token, - }, - { - op: "add", - path: `/logs/${runName}/streamed_output/-`, - value: streamedOutputValue, - }, - ], - }); - await this.writer.write(patch); + }; +}; +/* harmony default export */ function zh_CN() { + return { + localeError: zh_CN_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/zh-TW.js + +const zh_TW_error = () => { + const Sizable = { + string: { unit: "字元", verb: "擁有" }, + file: { unit: "位元組", verb: "擁有" }, + array: { unit: "項目", verb: "擁有" }, + set: { unit: "項目", verb: "擁有" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "number"; + } + case "object": { + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; + }; + const Nouns = { + regex: "輸入", + email: "郵件地址", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO 日期時間", + date: "ISO 日期", + time: "ISO 時間", + duration: "ISO 期間", + ipv4: "IPv4 位址", + ipv6: "IPv6 位址", + cidrv4: "IPv4 範圍", + cidrv6: "IPv6 範圍", + base64: "base64 編碼字串", + base64url: "base64url 編碼字串", + json_string: "JSON 字串", + e164: "E.164 數值", + jwt: "JWT", + template_literal: "輸入", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `無效的輸入值:預期為 ${issue.expected},但收到 ${parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `無效的輸入值:預期為 ${util.stringifyPrimitive(issue.values[0])}`; + return `無效的選項:預期為以下其中之一 ${util.joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `數值過大:預期 ${issue.origin ?? "值"} 應為 ${adj}${issue.maximum.toString()} ${sizing.unit ?? "個元素"}`; + return `數值過大:預期 ${issue.origin ?? "值"} 應為 ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `數值過小:預期 ${issue.origin} 應為 ${adj}${issue.minimum.toString()} ${sizing.unit}`; + } + return `數值過小:預期 ${issue.origin} 應為 ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") { + return `無效的字串:必須以 "${_issue.prefix}" 開頭`; + } + if (_issue.format === "ends_with") + return `無效的字串:必須以 "${_issue.suffix}" 結尾`; + if (_issue.format === "includes") + return `無效的字串:必須包含 "${_issue.includes}"`; + if (_issue.format === "regex") + return `無效的字串:必須符合格式 ${_issue.pattern}`; + return `無效的 ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `無效的數字:必須為 ${issue.divisor} 的倍數`; + case "unrecognized_keys": + return `無法識別的鍵值${issue.keys.length > 1 ? "們" : ""}:${util.joinValues(issue.keys, "、")}`; + case "invalid_key": + return `${issue.origin} 中有無效的鍵值`; + case "invalid_union": + return "無效的輸入值"; + case "invalid_element": + return `${issue.origin} 中有無效的值`; + default: + return `無效的輸入值`; + } + }; +}; +/* harmony default export */ function zh_TW() { + return { + localeError: zh_TW_error(), + }; } -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/outputs.js -const RUN_KEY = "__run"; -/** - * Chunk of a single generation. Used for streaming. - */ -class GenerationChunk { - constructor(fields) { - Object.defineProperty(this, "text", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - Object.defineProperty(this, "generationInfo", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.text = fields.text; - this.generationInfo = fields.generationInfo; +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/index.js + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/core/registries.js +const $output = Symbol("ZodOutput"); +const $input = Symbol("ZodInput"); +class $ZodRegistry { + constructor() { + this._map = new WeakMap(); + this._idmap = new Map(); } - concat(chunk) { - return new GenerationChunk({ - text: this.text + chunk.text, - generationInfo: { - ...this.generationInfo, - ...chunk.generationInfo, - }, - }); + add(schema, ..._meta) { + const meta = _meta[0]; + this._map.set(schema, meta); + if (meta && typeof meta === "object" && "id" in meta) { + if (this._idmap.has(meta.id)) { + throw new Error(`ID ${meta.id} already exists in the registry`); + } + this._idmap.set(meta.id, schema); + } + return this; } -} -class ChatGenerationChunk extends GenerationChunk { - constructor(fields) { - super(fields); - Object.defineProperty(this, "message", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.message = fields.message; + remove(schema) { + this._map.delete(schema); + return this; } - concat(chunk) { - return new ChatGenerationChunk({ - text: this.text + chunk.text, - generationInfo: { - ...this.generationInfo, - ...chunk.generationInfo, - }, - message: this.message.concat(chunk.message), - }); + get(schema) { + // return this._map.get(schema) as any; + // inherit metadata + const p = schema._zod.parent; + if (p) { + const pm = { ...(this.get(p) ?? {}) }; + delete pm.id; // do not inherit id + return { ...pm, ...this._map.get(schema) }; + } + return this._map.get(schema); + } + has(schema) { + return this._map.has(schema); } } +// registries +function registry() { + return new $ZodRegistry(); +} +const registries_globalRegistry = /*@__PURE__*/ registry(); + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/core/api.js + + + +function _string(Class, params) { + return new Class({ + type: "string", + ...util.normalizeParams(params), + }); +} +function _coercedString(Class, params) { + return new Class({ + type: "string", + coerce: true, + ...util.normalizeParams(params), + }); +} +function _email(Class, params) { + return new Class({ + type: "string", + format: "email", + check: "string_format", + abort: false, + ...util.normalizeParams(params), + }); +} +function _guid(Class, params) { + return new Class({ + type: "string", + format: "guid", + check: "string_format", + abort: false, + ...util.normalizeParams(params), + }); +} +function _uuid(Class, params) { + return new Class({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + ...util.normalizeParams(params), + }); +} +function _uuidv4(Class, params) { + return new Class({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + version: "v4", + ...util.normalizeParams(params), + }); +} +function _uuidv6(Class, params) { + return new Class({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + version: "v6", + ...util.normalizeParams(params), + }); +} +function _uuidv7(Class, params) { + return new Class({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + version: "v7", + ...util.normalizeParams(params), + }); +} +function _url(Class, params) { + return new Class({ + type: "string", + format: "url", + check: "string_format", + abort: false, + ...util.normalizeParams(params), + }); +} +function api_emoji(Class, params) { + return new Class({ + type: "string", + format: "emoji", + check: "string_format", + abort: false, + ...util.normalizeParams(params), + }); +} +function _nanoid(Class, params) { + return new Class({ + type: "string", + format: "nanoid", + check: "string_format", + abort: false, + ...util.normalizeParams(params), + }); +} +function _cuid(Class, params) { + return new Class({ + type: "string", + format: "cuid", + check: "string_format", + abort: false, + ...util.normalizeParams(params), + }); +} +function _cuid2(Class, params) { + return new Class({ + type: "string", + format: "cuid2", + check: "string_format", + abort: false, + ...util.normalizeParams(params), + }); +} +function _ulid(Class, params) { + return new Class({ + type: "string", + format: "ulid", + check: "string_format", + abort: false, + ...util.normalizeParams(params), + }); +} +function _xid(Class, params) { + return new Class({ + type: "string", + format: "xid", + check: "string_format", + abort: false, + ...util.normalizeParams(params), + }); +} +function _ksuid(Class, params) { + return new Class({ + type: "string", + format: "ksuid", + check: "string_format", + abort: false, + ...util.normalizeParams(params), + }); +} +function _ipv4(Class, params) { + return new Class({ + type: "string", + format: "ipv4", + check: "string_format", + abort: false, + ...util.normalizeParams(params), + }); +} +function _ipv6(Class, params) { + return new Class({ + type: "string", + format: "ipv6", + check: "string_format", + abort: false, + ...util.normalizeParams(params), + }); +} +function _cidrv4(Class, params) { + return new Class({ + type: "string", + format: "cidrv4", + check: "string_format", + abort: false, + ...util.normalizeParams(params), + }); +} +function _cidrv6(Class, params) { + return new Class({ + type: "string", + format: "cidrv6", + check: "string_format", + abort: false, + ...util.normalizeParams(params), + }); +} +function _base64(Class, params) { + return new Class({ + type: "string", + format: "base64", + check: "string_format", + abort: false, + ...util.normalizeParams(params), + }); +} +function _base64url(Class, params) { + return new Class({ + type: "string", + format: "base64url", + check: "string_format", + abort: false, + ...util.normalizeParams(params), + }); +} +function _e164(Class, params) { + return new Class({ + type: "string", + format: "e164", + check: "string_format", + abort: false, + ...util.normalizeParams(params), + }); +} +function _jwt(Class, params) { + return new Class({ + type: "string", + format: "jwt", + check: "string_format", + abort: false, + ...util.normalizeParams(params), + }); +} +const TimePrecision = { + Any: null, + Minute: -1, + Second: 0, + Millisecond: 3, + Microsecond: 6, +}; +function _isoDateTime(Class, params) { + return new Class({ + type: "string", + format: "datetime", + check: "string_format", + offset: false, + local: false, + precision: null, + ...util.normalizeParams(params), + }); +} +function _isoDate(Class, params) { + return new Class({ + type: "string", + format: "date", + check: "string_format", + ...util.normalizeParams(params), + }); +} +function _isoTime(Class, params) { + return new Class({ + type: "string", + format: "time", + check: "string_format", + precision: null, + ...util.normalizeParams(params), + }); +} +function _isoDuration(Class, params) { + return new Class({ + type: "string", + format: "duration", + check: "string_format", + ...util.normalizeParams(params), + }); +} +function _number(Class, params) { + return new Class({ + type: "number", + checks: [], + ...util.normalizeParams(params), + }); +} +function _coercedNumber(Class, params) { + return new Class({ + type: "number", + coerce: true, + checks: [], + ...util.normalizeParams(params), + }); +} +function _int(Class, params) { + return new Class({ + type: "number", + check: "number_format", + abort: false, + format: "safeint", + ...util.normalizeParams(params), + }); +} +function _float32(Class, params) { + return new Class({ + type: "number", + check: "number_format", + abort: false, + format: "float32", + ...util.normalizeParams(params), + }); +} +function _float64(Class, params) { + return new Class({ + type: "number", + check: "number_format", + abort: false, + format: "float64", + ...util.normalizeParams(params), + }); +} +function _int32(Class, params) { + return new Class({ + type: "number", + check: "number_format", + abort: false, + format: "int32", + ...util.normalizeParams(params), + }); +} +function _uint32(Class, params) { + return new Class({ + type: "number", + check: "number_format", + abort: false, + format: "uint32", + ...util.normalizeParams(params), + }); +} +function _boolean(Class, params) { + return new Class({ + type: "boolean", + ...util.normalizeParams(params), + }); +} +function _coercedBoolean(Class, params) { + return new Class({ + type: "boolean", + coerce: true, + ...util.normalizeParams(params), + }); +} +function _bigint(Class, params) { + return new Class({ + type: "bigint", + ...util.normalizeParams(params), + }); +} +function _coercedBigint(Class, params) { + return new Class({ + type: "bigint", + coerce: true, + ...util.normalizeParams(params), + }); +} +function _int64(Class, params) { + return new Class({ + type: "bigint", + check: "bigint_format", + abort: false, + format: "int64", + ...util.normalizeParams(params), + }); +} +function _uint64(Class, params) { + return new Class({ + type: "bigint", + check: "bigint_format", + abort: false, + format: "uint64", + ...util.normalizeParams(params), + }); +} +function _symbol(Class, params) { + return new Class({ + type: "symbol", + ...util.normalizeParams(params), + }); +} +function api_undefined(Class, params) { + return new Class({ + type: "undefined", + ...util.normalizeParams(params), + }); +} +function api_null(Class, params) { + return new Class({ + type: "null", + ...util.normalizeParams(params), + }); +} +function _any(Class) { + return new Class({ + type: "any", + }); +} +function api_unknown(Class) { + return new Class({ + type: "unknown", + }); +} +function _never(Class, params) { + return new Class({ + type: "never", + ...normalizeParams(params), + }); +} +function _void(Class, params) { + return new Class({ + type: "void", + ...util.normalizeParams(params), + }); +} +function _date(Class, params) { + return new Class({ + type: "date", + ...util.normalizeParams(params), + }); +} +function _coercedDate(Class, params) { + return new Class({ + type: "date", + coerce: true, + ...util.normalizeParams(params), + }); +} +function _nan(Class, params) { + return new Class({ + type: "nan", + ...util.normalizeParams(params), + }); +} +function _lt(value, params) { + return new checks.$ZodCheckLessThan({ + check: "less_than", + ...util.normalizeParams(params), + value, + inclusive: false, + }); +} +function _lte(value, params) { + return new checks.$ZodCheckLessThan({ + check: "less_than", + ...util.normalizeParams(params), + value, + inclusive: true, + }); +} + +function _gt(value, params) { + return new checks.$ZodCheckGreaterThan({ + check: "greater_than", + ...util.normalizeParams(params), + value, + inclusive: false, + }); +} +function _gte(value, params) { + return new checks.$ZodCheckGreaterThan({ + check: "greater_than", + ...util.normalizeParams(params), + value, + inclusive: true, + }); +} + +function _positive(params) { + return _gt(0, params); +} +// negative +function _negative(params) { + return _lt(0, params); +} +// nonpositive +function _nonpositive(params) { + return _lte(0, params); +} +// nonnegative +function _nonnegative(params) { + return _gte(0, params); +} +function _multipleOf(value, params) { + return new checks.$ZodCheckMultipleOf({ + check: "multiple_of", + ...util.normalizeParams(params), + value, + }); +} +function _maxSize(maximum, params) { + return new checks.$ZodCheckMaxSize({ + check: "max_size", + ...util.normalizeParams(params), + maximum, + }); +} +function _minSize(minimum, params) { + return new checks.$ZodCheckMinSize({ + check: "min_size", + ...util.normalizeParams(params), + minimum, + }); +} +function _size(size, params) { + return new checks.$ZodCheckSizeEquals({ + check: "size_equals", + ...util.normalizeParams(params), + size, + }); +} +function _maxLength(maximum, params) { + const ch = new checks.$ZodCheckMaxLength({ + check: "max_length", + ...util.normalizeParams(params), + maximum, + }); + return ch; +} +function _minLength(minimum, params) { + return new checks.$ZodCheckMinLength({ + check: "min_length", + ...util.normalizeParams(params), + minimum, + }); +} +function _length(length, params) { + return new checks.$ZodCheckLengthEquals({ + check: "length_equals", + ...util.normalizeParams(params), + length, + }); +} +function _regex(pattern, params) { + return new checks.$ZodCheckRegex({ + check: "string_format", + format: "regex", + ...util.normalizeParams(params), + pattern, + }); +} +function _lowercase(params) { + return new checks.$ZodCheckLowerCase({ + check: "string_format", + format: "lowercase", + ...util.normalizeParams(params), + }); +} +function _uppercase(params) { + return new checks.$ZodCheckUpperCase({ + check: "string_format", + format: "uppercase", + ...util.normalizeParams(params), + }); +} +function _includes(includes, params) { + return new checks.$ZodCheckIncludes({ + check: "string_format", + format: "includes", + ...util.normalizeParams(params), + includes, + }); +} +function _startsWith(prefix, params) { + return new checks.$ZodCheckStartsWith({ + check: "string_format", + format: "starts_with", + ...util.normalizeParams(params), + prefix, + }); +} +function _endsWith(suffix, params) { + return new checks.$ZodCheckEndsWith({ + check: "string_format", + format: "ends_with", + ...util.normalizeParams(params), + suffix, + }); +} +function _property(property, schema, params) { + return new checks.$ZodCheckProperty({ + check: "property", + property, + schema, + ...util.normalizeParams(params), + }); +} +function _mime(types, params) { + return new checks.$ZodCheckMimeType({ + check: "mime_type", + mime: types, + ...util.normalizeParams(params), + }); +} +function _overwrite(tx) { + return new checks.$ZodCheckOverwrite({ + check: "overwrite", + tx, + }); +} +// normalize +function _normalize(form) { + return _overwrite((input) => input.normalize(form)); +} +// trim +function _trim() { + return _overwrite((input) => input.trim()); +} +// toLowerCase +function _toLowerCase() { + return _overwrite((input) => input.toLowerCase()); +} +// toUpperCase +function _toUpperCase() { + return _overwrite((input) => input.toUpperCase()); +} +function api_array(Class, element, params) { + return new Class({ + type: "array", + element, + // get element() { + // return element; + // }, + ...util.normalizeParams(params), + }); +} +function _union(Class, options, params) { + return new Class({ + type: "union", + options, + ...util.normalizeParams(params), + }); +} +function _discriminatedUnion(Class, discriminator, options, params) { + return new Class({ + type: "union", + options, + discriminator, + ...util.normalizeParams(params), + }); +} +function _intersection(Class, left, right) { + return new Class({ + type: "intersection", + left, + right, + }); +} +// export function _tuple( +// Class: util.SchemaClass, +// items: [], +// params?: string | $ZodTupleParams +// ): schemas.$ZodTuple<[], null>; +function api_tuple(Class, items, _paramsOrRest, _params) { + const hasRest = _paramsOrRest instanceof schemas.$ZodType; + const params = hasRest ? _params : _paramsOrRest; + const rest = hasRest ? _paramsOrRest : null; + return new Class({ + type: "tuple", + items, + rest, + ...util.normalizeParams(params), + }); +} +function _record(Class, keyType, valueType, params) { + return new Class({ + type: "record", + keyType, + valueType, + ...util.normalizeParams(params), + }); +} +function _map(Class, keyType, valueType, params) { + return new Class({ + type: "map", + keyType, + valueType, + ...util.normalizeParams(params), + }); +} +function _set(Class, valueType, params) { + return new Class({ + type: "set", + valueType, + ...util.normalizeParams(params), + }); +} +function _enum(Class, values, params) { + const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values; + // if (Array.isArray(values)) { + // for (const value of values) { + // entries[value] = value; + // } + // } else { + // Object.assign(entries, values); + // } + // const entries: util.EnumLike = {}; + // for (const val of values) { + // entries[val] = val; + // } + return new Class({ + type: "enum", + entries, + ...util.normalizeParams(params), + }); +} +/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead. + * + * ```ts + * enum Colors { red, green, blue } + * z.enum(Colors); + * ``` + */ +function _nativeEnum(Class, entries, params) { + return new Class({ + type: "enum", + entries, + ...util.normalizeParams(params), + }); +} +function _literal(Class, value, params) { + return new Class({ + type: "literal", + values: Array.isArray(value) ? value : [value], + ...util.normalizeParams(params), + }); +} +function _file(Class, params) { + return new Class({ + type: "file", + ...util.normalizeParams(params), + }); +} +function _transform(Class, fn) { + return new Class({ + type: "transform", + transform: fn, + }); +} +function _optional(Class, innerType) { + return new Class({ + type: "optional", + innerType, + }); +} +function _nullable(Class, innerType) { + return new Class({ + type: "nullable", + innerType, + }); +} +function _default(Class, innerType, defaultValue) { + return new Class({ + type: "default", + innerType, + get defaultValue() { + return typeof defaultValue === "function" ? defaultValue() : defaultValue; + }, + }); +} +function _nonoptional(Class, innerType, params) { + return new Class({ + type: "nonoptional", + innerType, + ...util.normalizeParams(params), + }); +} +function _success(Class, innerType) { + return new Class({ + type: "success", + innerType, + }); +} +function _catch(Class, innerType, catchValue) { + return new Class({ + type: "catch", + innerType, + catchValue: (typeof catchValue === "function" ? catchValue : () => catchValue), + }); +} +function _pipe(Class, in_, out) { + return new Class({ + type: "pipe", + in: in_, + out, + }); +} +function _readonly(Class, innerType) { + return new Class({ + type: "readonly", + innerType, + }); +} +function _templateLiteral(Class, parts, params) { + return new Class({ + type: "template_literal", + parts, + ...util.normalizeParams(params), + }); +} +function _lazy(Class, getter) { + return new Class({ + type: "lazy", + getter, + }); +} +function _promise(Class, innerType) { + return new Class({ + type: "promise", + innerType, + }); +} +function _custom(Class, fn, _params) { + const norm = util.normalizeParams(_params); + norm.abort ?? (norm.abort = true); // default to abort:false + const schema = new Class({ + type: "custom", + check: "custom", + fn: fn, + ...norm, + }); + return schema; +} +// export function _refine( +// Class: util.SchemaClass, +// fn: (arg: NoInfer) => util.MaybeAsync, +// _params: string | $ZodCustomParams = {} +// ): checks.$ZodCheck { +// return _custom(Class, fn, _params); +// } +// same as _custom but deafults to abort:false +function _refine(Class, fn, _params) { + const schema = new Class({ + type: "custom", + check: "custom", + fn: fn, + ...util.normalizeParams(_params), + }); + return schema; +} +function _stringbool(Classes, _params) { + const { case: _case, error, truthy, falsy } = util.normalizeParams(_params); + let truthyArray = truthy ?? ["true", "1", "yes", "on", "y", "enabled"]; + let falsyArray = falsy ?? ["false", "0", "no", "off", "n", "disabled"]; + if (_case !== "sensitive") { + truthyArray = truthyArray.map((v) => (typeof v === "string" ? v.toLowerCase() : v)); + falsyArray = falsyArray.map((v) => (typeof v === "string" ? v.toLowerCase() : v)); + } + const truthySet = new Set(truthyArray); + const falsySet = new Set(falsyArray); + const _Pipe = Classes.Pipe ?? schemas.$ZodPipe; + const _Boolean = Classes.Boolean ?? schemas.$ZodBoolean; + const _String = Classes.String ?? schemas.$ZodString; + const _Transform = Classes.Transform ?? schemas.$ZodTransform; + const tx = new _Transform({ + type: "transform", + transform: (input, payload) => { + let data = input; + if (_case !== "sensitive") + data = data.toLowerCase(); + if (truthySet.has(data)) { + return true; + } + else if (falsySet.has(data)) { + return false; + } + else { + payload.issues.push({ + code: "invalid_value", + expected: "stringbool", + values: [...truthySet, ...falsySet], + input: payload.value, + inst: tx, + }); + return {}; + } + }, + error, + }); + const innerPipe = new _Pipe({ + type: "pipe", + in: new _String({ type: "string", error }), + out: tx, + error, + }); + const outerPipe = new _Pipe({ + type: "pipe", + in: innerPipe, + out: new _Boolean({ + type: "boolean", + error, + }), + error, + }); + return outerPipe; +} -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/tracers/event_stream.js +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/core/function.js -function assignName({ name, serialized, }) { - if (name !== undefined) { - return name; - } - if (serialized?.name !== undefined) { - return serialized.name; - } - else if (serialized?.id !== undefined && Array.isArray(serialized?.id)) { - return serialized.id[serialized.id.length - 1]; +class $ZodFunction { + constructor(def) { + this._def = def; + this.def = def; } - return "Unnamed"; -} -const isStreamEventsHandler = (handler) => handler.name === "event_stream_tracer"; -/** - * Class that extends the `BaseTracer` class from the - * `langchain.callbacks.tracers.base` module. It represents a callback - * handler that logs the execution of runs and emits `RunLog` instances to a - * `RunLogStream`. - */ -class EventStreamCallbackHandler extends BaseTracer { - constructor(fields) { - super({ _awaitHandler: true, ...fields }); - Object.defineProperty(this, "autoClose", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - Object.defineProperty(this, "includeNames", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "includeTypes", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "includeTags", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "excludeNames", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "excludeTypes", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "excludeTags", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "runInfoMap", { - enumerable: true, - configurable: true, - writable: true, - value: new Map() - }); - Object.defineProperty(this, "tappedPromises", { - enumerable: true, - configurable: true, - writable: true, - value: new Map() - }); - Object.defineProperty(this, "transformStream", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "writer", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "receiveStream", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "event_stream_tracer" - }); - Object.defineProperty(this, "lc_prefer_streaming", { - enumerable: true, - configurable: true, - writable: true, - value: true + implement(func) { + if (typeof func !== "function") { + throw new Error("implement() must be called with a function"); + } + const impl = ((...args) => { + const parsedArgs = this._def.input ? parse(this._def.input, args, undefined, { callee: impl }) : args; + if (!Array.isArray(parsedArgs)) { + throw new Error("Invalid arguments schema: not an array or tuple schema."); + } + const output = func(...parsedArgs); + return this._def.output ? parse(this._def.output, output, undefined, { callee: impl }) : output; + }); + return impl; + } + implementAsync(func) { + if (typeof func !== "function") { + throw new Error("implement() must be called with a function"); + } + const impl = (async (...args) => { + const parsedArgs = this._def.input ? await parseAsync(this._def.input, args, undefined, { callee: impl }) : args; + if (!Array.isArray(parsedArgs)) { + throw new Error("Invalid arguments schema: not an array or tuple schema."); + } + const output = await func(...parsedArgs); + return this._def.output ? parseAsync(this._def.output, output, undefined, { callee: impl }) : output; + }); + return impl; + } + input(...args) { + const F = this.constructor; + if (Array.isArray(args[0])) { + return new F({ + type: "function", + input: new $ZodTuple({ + type: "tuple", + items: args[0], + rest: args[1], + }), + output: this._def.output, + }); + } + return new F({ + type: "function", + input: args[0], + output: this._def.output, }); - this.autoClose = fields?.autoClose ?? true; - this.includeNames = fields?.includeNames; - this.includeTypes = fields?.includeTypes; - this.includeTags = fields?.includeTags; - this.excludeNames = fields?.excludeNames; - this.excludeTypes = fields?.excludeTypes; - this.excludeTags = fields?.excludeTags; - this.transformStream = new TransformStream(); - this.writer = this.transformStream.writable.getWriter(); - this.receiveStream = IterableReadableStream.fromReadableStream(this.transformStream.readable); - } - [Symbol.asyncIterator]() { - return this.receiveStream; - } - async persistRun(_run) { - // This is a legacy method only called once for an entire run tree - // and is therefore not useful here } - _includeRun(run) { - const runTags = run.tags ?? []; - let include = this.includeNames === undefined && - this.includeTags === undefined && - this.includeTypes === undefined; - if (this.includeNames !== undefined) { - include = include || this.includeNames.includes(run.name); - } - if (this.includeTypes !== undefined) { - include = include || this.includeTypes.includes(run.runType); - } - if (this.includeTags !== undefined) { - include = - include || - runTags.find((tag) => this.includeTags?.includes(tag)) !== undefined; - } - if (this.excludeNames !== undefined) { - include = include && !this.excludeNames.includes(run.name); - } - if (this.excludeTypes !== undefined) { - include = include && !this.excludeTypes.includes(run.runType); - } - if (this.excludeTags !== undefined) { - include = - include && runTags.every((tag) => !this.excludeTags?.includes(tag)); - } - return include; + output(output) { + const F = this.constructor; + return new F({ + type: "function", + input: this._def.input, + output, + }); } - async *tapOutputIterable(runId, outputStream) { - const firstChunk = await outputStream.next(); - if (firstChunk.done) { - return; - } - const runInfo = this.runInfoMap.get(runId); - // Run has finished, don't issue any stream events. - // An example of this is for runnables that use the default - // implementation of .stream(), which delegates to .invoke() - // and calls .onChainEnd() before passing it to the iterator. - if (runInfo === undefined) { - yield firstChunk.value; - return; +} +function _function(params) { + return new $ZodFunction({ + type: "function", + input: Array.isArray(params?.input) + ? _tuple(schemas.$ZodTuple, params?.input) + : (params?.input ?? _array(schemas.$ZodArray, _unknown(schemas.$ZodUnknown))), + output: params?.output ?? _unknown(schemas.$ZodUnknown), + }); +} + + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/core/to-json-schema.js + + +class JSONSchemaGenerator { + constructor(params) { + this.counter = 0; + this.metadataRegistry = params?.metadata ?? registries_globalRegistry; + this.target = params?.target ?? "draft-2020-12"; + this.unrepresentable = params?.unrepresentable ?? "throw"; + this.override = params?.override ?? (() => { }); + this.io = params?.io ?? "output"; + this.seen = new Map(); + } + process(schema, _params = { path: [], schemaPath: [] }) { + var _a; + const def = schema._zod.def; + const formatMap = { + guid: "uuid", + url: "uri", + datetime: "date-time", + json_string: "json-string", + regex: "", // do not set + }; + // check for schema in seens + const seen = this.seen.get(schema); + if (seen) { + seen.count++; + // check if cycle + const isCycle = _params.schemaPath.includes(schema); + if (isCycle) { + seen.cycle = _params.path; + } + return seen.schema; + } + // initialize + const result = { schema: {}, count: 1, cycle: undefined }; + this.seen.set(schema, result); + // custom method overrides default behavior + const overrideSchema = schema._zod.toJSONSchema?.(); + if (overrideSchema) { + result.schema = overrideSchema; } - // Match format from handlers below - function _formatOutputChunk(eventType, data) { - if (eventType === "llm" && typeof data === "string") { - return new GenerationChunk({ text: data }); + else { + const params = { + ..._params, + schemaPath: [..._params.schemaPath, schema], + path: _params.path, + }; + const parent = schema._zod.parent; + if (parent) { + // schema was cloned from another schema + result.ref = parent; + this.process(parent, params); + this.seen.get(parent).isParent = true; } - return data; - } - let tappedPromise = this.tappedPromises.get(runId); - // if we are the first to tap, issue stream events - if (tappedPromise === undefined) { - let tappedPromiseResolver; - tappedPromise = new Promise((resolve) => { - tappedPromiseResolver = resolve; - }); - this.tappedPromises.set(runId, tappedPromise); - try { - const event = { - event: `on_${runInfo.runType}_stream`, - run_id: runId, - name: runInfo.name, - tags: runInfo.tags, - metadata: runInfo.metadata, - data: {}, - }; - await this.send({ - ...event, - data: { - chunk: _formatOutputChunk(runInfo.runType, firstChunk.value), - }, - }, runInfo); - yield firstChunk.value; - for await (const chunk of outputStream) { - // Don't yield tool and retriever stream events - if (runInfo.runType !== "tool" && runInfo.runType !== "retriever") { - await this.send({ - ...event, - data: { - chunk: _formatOutputChunk(runInfo.runType, chunk), - }, - }, runInfo); + else { + const _json = result.schema; + switch (def.type) { + case "string": { + const json = _json; + json.type = "string"; + const { minimum, maximum, format, patterns, contentEncoding } = schema._zod + .bag; + if (typeof minimum === "number") + json.minLength = minimum; + if (typeof maximum === "number") + json.maxLength = maximum; + // custom pattern overrides format + if (format) { + json.format = formatMap[format] ?? format; + if (json.format === "") + delete json.format; // empty format is not valid + } + if (contentEncoding) + json.contentEncoding = contentEncoding; + if (patterns && patterns.size > 0) { + const regexes = [...patterns]; + if (regexes.length === 1) + json.pattern = regexes[0].source; + else if (regexes.length > 1) { + result.schema.allOf = [ + ...regexes.map((regex) => ({ + ...(this.target === "draft-7" ? { type: "string" } : {}), + pattern: regex.source, + })), + ]; + } + } + break; + } + case "number": { + const json = _json; + const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag; + if (typeof format === "string" && format.includes("int")) + json.type = "integer"; + else + json.type = "number"; + if (typeof exclusiveMinimum === "number") + json.exclusiveMinimum = exclusiveMinimum; + if (typeof minimum === "number") { + json.minimum = minimum; + if (typeof exclusiveMinimum === "number") { + if (exclusiveMinimum >= minimum) + delete json.minimum; + else + delete json.exclusiveMinimum; + } + } + if (typeof exclusiveMaximum === "number") + json.exclusiveMaximum = exclusiveMaximum; + if (typeof maximum === "number") { + json.maximum = maximum; + if (typeof exclusiveMaximum === "number") { + if (exclusiveMaximum <= maximum) + delete json.maximum; + else + delete json.exclusiveMaximum; + } + } + if (typeof multipleOf === "number") + json.multipleOf = multipleOf; + break; + } + case "boolean": { + const json = _json; + json.type = "boolean"; + break; + } + case "bigint": { + if (this.unrepresentable === "throw") { + throw new Error("BigInt cannot be represented in JSON Schema"); + } + break; + } + case "symbol": { + if (this.unrepresentable === "throw") { + throw new Error("Symbols cannot be represented in JSON Schema"); + } + break; + } + case "undefined": { + const json = _json; + json.type = "null"; + break; + } + case "null": { + _json.type = "null"; + break; + } + case "any": { + break; + } + case "unknown": { + break; + } + case "never": { + _json.not = {}; + break; + } + case "void": { + if (this.unrepresentable === "throw") { + throw new Error("Void cannot be represented in JSON Schema"); + } + break; + } + case "date": { + if (this.unrepresentable === "throw") { + throw new Error("Date cannot be represented in JSON Schema"); + } + break; + } + case "array": { + const json = _json; + const { minimum, maximum } = schema._zod.bag; + if (typeof minimum === "number") + json.minItems = minimum; + if (typeof maximum === "number") + json.maxItems = maximum; + json.type = "array"; + json.items = this.process(def.element, { ...params, path: [...params.path, "items"] }); + break; + } + case "object": { + const json = _json; + json.type = "object"; + json.properties = {}; + const shape = def.shape; // params.shapeCache.get(schema)!; + for (const key in shape) { + json.properties[key] = this.process(shape[key], { + ...params, + path: [...params.path, "properties", key], + }); + } + // required keys + const allKeys = new Set(Object.keys(shape)); + // const optionalKeys = new Set(def.optional); + const requiredKeys = new Set([...allKeys].filter((key) => { + const v = def.shape[key]._zod; + if (this.io === "input") { + return v.optin === undefined; + } + else { + return v.optout === undefined; + } + })); + if (requiredKeys.size > 0) { + json.required = Array.from(requiredKeys); + } + // catchall + if (def.catchall?._zod.def.type === "never") { + // strict + json.additionalProperties = false; + } + else if (!def.catchall) { + // regular + if (this.io === "output") + json.additionalProperties = false; + } + else if (def.catchall) { + json.additionalProperties = this.process(def.catchall, { + ...params, + path: [...params.path, "additionalProperties"], + }); + } + break; + } + case "union": { + const json = _json; + json.anyOf = def.options.map((x, i) => this.process(x, { + ...params, + path: [...params.path, "anyOf", i], + })); + break; + } + case "intersection": { + const json = _json; + const a = this.process(def.left, { + ...params, + path: [...params.path, "allOf", 0], + }); + const b = this.process(def.right, { + ...params, + path: [...params.path, "allOf", 1], + }); + const isSimpleIntersection = (val) => "allOf" in val && Object.keys(val).length === 1; + const allOf = [ + ...(isSimpleIntersection(a) ? a.allOf : [a]), + ...(isSimpleIntersection(b) ? b.allOf : [b]), + ]; + json.allOf = allOf; + break; + } + case "tuple": { + const json = _json; + json.type = "array"; + const prefixItems = def.items.map((x, i) => this.process(x, { ...params, path: [...params.path, "prefixItems", i] })); + if (this.target === "draft-2020-12") { + json.prefixItems = prefixItems; + } + else { + json.items = prefixItems; + } + if (def.rest) { + const rest = this.process(def.rest, { + ...params, + path: [...params.path, "items"], + }); + if (this.target === "draft-2020-12") { + json.items = rest; + } + else { + json.additionalItems = rest; + } + } + // additionalItems + if (def.rest) { + json.items = this.process(def.rest, { + ...params, + path: [...params.path, "items"], + }); + } + // length + const { minimum, maximum } = schema._zod.bag; + if (typeof minimum === "number") + json.minItems = minimum; + if (typeof maximum === "number") + json.maxItems = maximum; + break; + } + case "record": { + const json = _json; + json.type = "object"; + json.propertyNames = this.process(def.keyType, { ...params, path: [...params.path, "propertyNames"] }); + json.additionalProperties = this.process(def.valueType, { + ...params, + path: [...params.path, "additionalProperties"], + }); + break; + } + case "map": { + if (this.unrepresentable === "throw") { + throw new Error("Map cannot be represented in JSON Schema"); + } + break; + } + case "set": { + if (this.unrepresentable === "throw") { + throw new Error("Set cannot be represented in JSON Schema"); + } + break; + } + case "enum": { + const json = _json; + const values = getEnumValues(def.entries); + // Number enums can have both string and number values + if (values.every((v) => typeof v === "number")) + json.type = "number"; + if (values.every((v) => typeof v === "string")) + json.type = "string"; + json.enum = values; + break; + } + case "literal": { + const json = _json; + const vals = []; + for (const val of def.values) { + if (val === undefined) { + if (this.unrepresentable === "throw") { + throw new Error("Literal `undefined` cannot be represented in JSON Schema"); + } + else { + // do not add to vals + } + } + else if (typeof val === "bigint") { + if (this.unrepresentable === "throw") { + throw new Error("BigInt literals cannot be represented in JSON Schema"); + } + else { + vals.push(Number(val)); + } + } + else { + vals.push(val); + } + } + if (vals.length === 0) { + // do nothing (an undefined literal was stripped) + } + else if (vals.length === 1) { + const val = vals[0]; + json.type = val === null ? "null" : typeof val; + json.const = val; + } + else { + if (vals.every((v) => typeof v === "number")) + json.type = "number"; + if (vals.every((v) => typeof v === "string")) + json.type = "string"; + if (vals.every((v) => typeof v === "boolean")) + json.type = "string"; + if (vals.every((v) => v === null)) + json.type = "null"; + json.enum = vals; + } + break; + } + case "file": { + const json = _json; + const file = { + type: "string", + format: "binary", + contentEncoding: "binary", + }; + const { minimum, maximum, mime } = schema._zod.bag; + if (minimum !== undefined) + file.minLength = minimum; + if (maximum !== undefined) + file.maxLength = maximum; + if (mime) { + if (mime.length === 1) { + file.contentMediaType = mime[0]; + Object.assign(json, file); + } + else { + json.anyOf = mime.map((m) => { + const mFile = { ...file, contentMediaType: m }; + return mFile; + }); + } + } + else { + Object.assign(json, file); + } + // if (this.unrepresentable === "throw") { + // throw new Error("File cannot be represented in JSON Schema"); + // } + break; + } + case "transform": { + if (this.unrepresentable === "throw") { + throw new Error("Transforms cannot be represented in JSON Schema"); + } + break; + } + case "nullable": { + const inner = this.process(def.innerType, params); + _json.anyOf = [inner, { type: "null" }]; + break; + } + case "nonoptional": { + this.process(def.innerType, params); + result.ref = def.innerType; + break; + } + case "success": { + const json = _json; + json.type = "boolean"; + break; + } + case "default": { + this.process(def.innerType, params); + result.ref = def.innerType; + _json.default = JSON.parse(JSON.stringify(def.defaultValue)); + break; + } + case "prefault": { + this.process(def.innerType, params); + result.ref = def.innerType; + if (this.io === "input") + _json._prefault = JSON.parse(JSON.stringify(def.defaultValue)); + break; + } + case "catch": { + // use conditionals + this.process(def.innerType, params); + result.ref = def.innerType; + let catchValue; + try { + catchValue = def.catchValue(undefined); + } + catch { + throw new Error("Dynamic catch values are not supported in JSON Schema"); + } + _json.default = catchValue; + break; + } + case "nan": { + if (this.unrepresentable === "throw") { + throw new Error("NaN cannot be represented in JSON Schema"); + } + break; + } + case "template_literal": { + const json = _json; + const pattern = schema._zod.pattern; + if (!pattern) + throw new Error("Pattern not found in template literal"); + json.type = "string"; + json.pattern = pattern.source; + break; + } + case "pipe": { + const innerType = this.io === "input" ? (def.in._zod.def.type === "transform" ? def.out : def.in) : def.out; + this.process(innerType, params); + result.ref = innerType; + break; + } + case "readonly": { + this.process(def.innerType, params); + result.ref = def.innerType; + _json.readOnly = true; + break; + } + // passthrough types + case "promise": { + this.process(def.innerType, params); + result.ref = def.innerType; + break; + } + case "optional": { + this.process(def.innerType, params); + result.ref = def.innerType; + break; + } + case "lazy": { + const innerType = schema._zod.innerType; + this.process(innerType, params); + result.ref = innerType; + break; + } + case "custom": { + if (this.unrepresentable === "throw") { + throw new Error("Custom types cannot be represented in JSON Schema"); + } + break; + } + default: { + def; } - yield chunk; } } - finally { - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - tappedPromiseResolver(); - // Don't delete from the promises map to keep track of which runs have been tapped. - } - } - else { - // otherwise just pass through - yield firstChunk.value; - for await (const chunk of outputStream) { - yield chunk; - } - } - } - async send(payload, run) { - if (this._includeRun(run)) { - await this.writer.write(payload); - } - } - async sendEndEvent(payload, run) { - const tappedPromise = this.tappedPromises.get(payload.run_id); - if (tappedPromise !== undefined) { - void tappedPromise.then(() => { - void this.send(payload, run); - }); } - else { - await this.send(payload, run); + // metadata + const meta = this.metadataRegistry.get(schema); + if (meta) + Object.assign(result.schema, meta); + if (this.io === "input" && isTransforming(schema)) { + // examples/defaults only apply to output type of pipe + delete result.schema.examples; + delete result.schema.default; } + // set prefault as default + if (this.io === "input" && result.schema._prefault) + (_a = result.schema).default ?? (_a.default = result.schema._prefault); + delete result.schema._prefault; + // pulling fresh from this.seen in case it was overwritten + const _result = this.seen.get(schema); + return _result.schema; } - async onLLMStart(run) { - const runName = assignName(run); - const runType = run.inputs.messages !== undefined ? "chat_model" : "llm"; - const runInfo = { - tags: run.tags ?? [], - metadata: run.extra?.metadata ?? {}, - name: runName, - runType, - inputs: run.inputs, + emit(schema, _params) { + const params = { + cycles: _params?.cycles ?? "ref", + reused: _params?.reused ?? "inline", + // unrepresentable: _params?.unrepresentable ?? "throw", + // uri: _params?.uri ?? ((id) => `${id}`), + external: _params?.external ?? undefined, }; - this.runInfoMap.set(run.id, runInfo); - const eventName = `on_${runType}_start`; - await this.send({ - event: eventName, - data: { - input: run.inputs, - }, - name: runName, - tags: run.tags ?? [], - run_id: run.id, - metadata: run.extra?.metadata ?? {}, - }, runInfo); - } - async onLLMNewToken(run, token, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - kwargs) { - const runInfo = this.runInfoMap.get(run.id); - let chunk; - let eventName; - if (runInfo === undefined) { - throw new Error(`onLLMNewToken: Run ID ${run.id} not found in run map.`); - } - // Top-level streaming events are covered by tapOutputIterable - if (this.runInfoMap.size === 1) { - return; - } - if (runInfo.runType === "chat_model") { - eventName = "on_chat_model_stream"; - if (kwargs?.chunk === undefined) { - chunk = new ai_AIMessageChunk({ content: token, id: `run-${run.id}` }); - } - else { - chunk = kwargs.chunk.message; - } - } - else if (runInfo.runType === "llm") { - eventName = "on_llm_stream"; - if (kwargs?.chunk === undefined) { - chunk = new GenerationChunk({ text: token }); + // iterate over seen map; + const root = this.seen.get(schema); + if (!root) + throw new Error("Unprocessed schema. This is a bug in Zod."); + // initialize result with root schema fields + // Object.assign(result, seen.cached); + const makeURI = (entry) => { + // comparing the seen objects because sometimes + // multiple schemas map to the same seen object. + // e.g. lazy + // external is configured + const defsSegment = this.target === "draft-2020-12" ? "$defs" : "definitions"; + if (params.external) { + const externalId = params.external.registry.get(entry[0])?.id; // ?? "__shared";// `__schema${this.counter++}`; + // check if schema is in the external registry + if (externalId) + return { ref: params.external.uri(externalId) }; + // otherwise, add to __shared + const id = entry[1].defId ?? entry[1].schema.id ?? `schema${this.counter++}`; + entry[1].defId = id; + return { defId: id, ref: `${params.external.uri("__shared")}#/${defsSegment}/${id}` }; + } + if (entry[1] === root) { + return { ref: "#" }; + } + // self-contained schema + const uriPrefix = `#`; + const defUriPrefix = `${uriPrefix}/${defsSegment}/`; + const defId = entry[1].schema.id ?? `__schema${this.counter++}`; + return { defId, ref: defUriPrefix + defId }; + }; + // stored cached version in `def` property + // remove all properties, set $ref + const extractToDef = (entry) => { + if (entry[1].schema.$ref) { + return; } - else { - chunk = kwargs.chunk; + const seen = entry[1]; + const { ref, defId } = makeURI(entry); + seen.def = { ...seen.schema }; + // defId won't be set if the schema is a reference to an external schema + if (defId) + seen.defId = defId; + // wipe away all properties except $ref + const schema = seen.schema; + for (const key in schema) { + delete schema[key]; + } + schema.$ref = ref; + }; + // extract schemas into $defs + for (const entry of this.seen.entries()) { + const seen = entry[1]; + // convert root schema to # $ref + // also prevents root schema from being extracted + if (schema === entry[0]) { + // do not copy to defs...this is the root schema + extractToDef(entry); + continue; } - } - else { - throw new Error(`Unexpected run type ${runInfo.runType}`); - } - await this.send({ - event: eventName, - data: { - chunk, - }, - run_id: run.id, - name: runInfo.name, - tags: runInfo.tags, - metadata: runInfo.metadata, - }, runInfo); - } - async onLLMEnd(run) { - const runInfo = this.runInfoMap.get(run.id); - this.runInfoMap.delete(run.id); - let eventName; - if (runInfo === undefined) { - throw new Error(`onLLMEnd: Run ID ${run.id} not found in run map.`); - } - const generations = run.outputs?.generations; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - let output; - if (runInfo.runType === "chat_model") { - for (const generation of generations ?? []) { - if (output !== undefined) { - break; + // extract schemas that are in the external registry + if (params.external) { + const ext = params.external.registry.get(entry[0])?.id; + if (schema !== entry[0] && ext) { + extractToDef(entry); + continue; + } + } + // extract schemas with `id` meta + const id = this.metadataRegistry.get(entry[0])?.id; + if (id) { + extractToDef(entry); + continue; + } + // break cycles + if (seen.cycle) { + if (params.cycles === "throw") { + throw new Error("Cycle detected: " + + `#/${seen.cycle?.join("/")}/` + + '\n\nSet the `cycles` parameter to `"ref"` to resolve cyclical schemas with defs.'); + } + else if (params.cycles === "ref") { + extractToDef(entry); + } + continue; + } + // extract reused schemas + if (seen.count > 1) { + if (params.reused === "ref") { + extractToDef(entry); + // biome-ignore lint: + continue; } - output = generation[0]?.message; } - eventName = "on_chat_model_end"; - } - else if (runInfo.runType === "llm") { - output = { - generations: generations?.map((generation) => { - return generation.map((chunk) => { - return { - text: chunk.text, - generationInfo: chunk.generationInfo, - }; - }); - }), - llmOutput: run.outputs?.llmOutput ?? {}, - }; - eventName = "on_llm_end"; - } - else { - throw new Error(`onLLMEnd: Unexpected run type: ${runInfo.runType}`); } - await this.sendEndEvent({ - event: eventName, - data: { - output, - input: runInfo.inputs, - }, - run_id: run.id, - name: runInfo.name, - tags: runInfo.tags, - metadata: runInfo.metadata, - }, runInfo); - } - async onChainStart(run) { - const runName = assignName(run); - const runType = run.run_type ?? "chain"; - const runInfo = { - tags: run.tags ?? [], - metadata: run.extra?.metadata ?? {}, - name: runName, - runType: run.run_type, + // flatten _refs + const flattenRef = (zodSchema, params) => { + const seen = this.seen.get(zodSchema); + const schema = seen.def ?? seen.schema; + const _cached = { ...schema }; + // already seen + if (seen.ref === null) { + return; + } + // flatten ref if defined + const ref = seen.ref; + seen.ref = null; // prevent recursion + if (ref) { + flattenRef(ref, params); + // merge referenced schema into current + const refSchema = this.seen.get(ref).schema; + if (refSchema.$ref && params.target === "draft-7") { + schema.allOf = schema.allOf ?? []; + schema.allOf.push(refSchema); + } + else { + Object.assign(schema, refSchema); + Object.assign(schema, _cached); // prevent overwriting any fields in the original schema + } + } + // execute overrides + if (!seen.isParent) + this.override({ + zodSchema: zodSchema, + jsonSchema: schema, + }); }; - let eventData = {}; - // Workaround Runnable core code not sending input when transform streaming. - if (run.inputs.input === "" && Object.keys(run.inputs).length === 1) { - eventData = {}; - runInfo.inputs = {}; + for (const entry of [...this.seen.entries()].reverse()) { + flattenRef(entry[0], { target: this.target }); } - else if (run.inputs.input !== undefined) { - eventData.input = run.inputs.input; - runInfo.inputs = run.inputs.input; + const result = {}; + if (this.target === "draft-2020-12") { + result.$schema = "https://json-schema.org/draft/2020-12/schema"; + } + else if (this.target === "draft-7") { + result.$schema = "http://json-schema.org/draft-07/schema#"; } else { - eventData.input = run.inputs; - runInfo.inputs = run.inputs; + console.warn(`Invalid target: ${this.target}`); } - this.runInfoMap.set(run.id, runInfo); - await this.send({ - event: `on_${runType}_start`, - data: eventData, - name: runName, - tags: run.tags ?? [], - run_id: run.id, - metadata: run.extra?.metadata ?? {}, - }, runInfo); - } - async onChainEnd(run) { - const runInfo = this.runInfoMap.get(run.id); - this.runInfoMap.delete(run.id); - if (runInfo === undefined) { - throw new Error(`onChainEnd: Run ID ${run.id} not found in run map.`); + Object.assign(result, root.def); + // build defs object + const defs = params.external?.defs ?? {}; + for (const entry of this.seen.entries()) { + const seen = entry[1]; + if (seen.def && seen.defId) { + defs[seen.defId] = seen.def; + } } - const eventName = `on_${run.run_type}_end`; - const inputs = run.inputs ?? runInfo.inputs ?? {}; - const outputs = run.outputs?.output ?? run.outputs; - const data = { - output: outputs, - input: inputs, - }; - if (inputs.input && Object.keys(inputs).length === 1) { - data.input = inputs.input; - runInfo.inputs = inputs.input; + // set definitions in result + if (!params.external && Object.keys(defs).length > 0) { + if (this.target === "draft-2020-12") { + result.$defs = defs; + } + else { + result.definitions = defs; + } } - await this.sendEndEvent({ - event: eventName, - data, - run_id: run.id, - name: runInfo.name, - tags: runInfo.tags, - metadata: runInfo.metadata ?? {}, - }, runInfo); - } - async onToolStart(run) { - const runName = assignName(run); - const runInfo = { - tags: run.tags ?? [], - metadata: run.extra?.metadata ?? {}, - name: runName, - runType: "tool", - inputs: run.inputs ?? {}, - }; - this.runInfoMap.set(run.id, runInfo); - await this.send({ - event: "on_tool_start", - data: { - input: run.inputs ?? {}, - }, - name: runName, - run_id: run.id, - tags: run.tags ?? [], - metadata: run.extra?.metadata ?? {}, - }, runInfo); - } - async onToolEnd(run) { - const runInfo = this.runInfoMap.get(run.id); - this.runInfoMap.delete(run.id); - if (runInfo === undefined) { - throw new Error(`onToolEnd: Run ID ${run.id} not found in run map.`); + try { + // this "finalizes" this schema and ensures all cycles are removed + // each call to .emit() is functionally independent + // though the seen map is shared + return JSON.parse(JSON.stringify(result)); } - if (runInfo.inputs === undefined) { - throw new Error(`onToolEnd: Run ID ${run.id} is a tool call, and is expected to have traced inputs.`); + catch (_err) { + throw new Error("Error converting schema to JSON."); } - const output = run.outputs?.output === undefined ? run.outputs : run.outputs.output; - await this.sendEndEvent({ - event: "on_tool_end", - data: { - output, - input: runInfo.inputs, - }, - run_id: run.id, - name: runInfo.name, - tags: runInfo.tags, - metadata: runInfo.metadata, - }, runInfo); } - async onRetrieverStart(run) { - const runName = assignName(run); - const runType = "retriever"; - const runInfo = { - tags: run.tags ?? [], - metadata: run.extra?.metadata ?? {}, - name: runName, - runType, - inputs: { - query: run.inputs.query, - }, +} +function toJSONSchema(input, _params) { + if (input instanceof $ZodRegistry) { + const gen = new JSONSchemaGenerator(_params); + const defs = {}; + for (const entry of input._idmap.entries()) { + const [_, schema] = entry; + gen.process(schema); + } + const schemas = {}; + const external = { + registry: input, + uri: _params?.uri || ((id) => id), + defs, }; - this.runInfoMap.set(run.id, runInfo); - await this.send({ - event: "on_retriever_start", - data: { - input: { - query: run.inputs.query, - }, - }, - name: runName, - tags: run.tags ?? [], - run_id: run.id, - metadata: run.extra?.metadata ?? {}, - }, runInfo); - } - async onRetrieverEnd(run) { - const runInfo = this.runInfoMap.get(run.id); - this.runInfoMap.delete(run.id); - if (runInfo === undefined) { - throw new Error(`onRetrieverEnd: Run ID ${run.id} not found in run map.`); + for (const entry of input._idmap.entries()) { + const [key, schema] = entry; + schemas[key] = gen.emit(schema, { + ..._params, + external, + }); } - await this.sendEndEvent({ - event: "on_retriever_end", - data: { - output: run.outputs?.documents ?? run.outputs, - input: runInfo.inputs, - }, - run_id: run.id, - name: runInfo.name, - tags: runInfo.tags, - metadata: runInfo.metadata, - }, runInfo); - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - async handleCustomEvent(eventName, data, runId) { - const runInfo = this.runInfoMap.get(runId); - if (runInfo === undefined) { - throw new Error(`handleCustomEvent: Run ID ${runId} not found in run map.`); + if (Object.keys(defs).length > 0) { + const defsSegment = gen.target === "draft-2020-12" ? "$defs" : "definitions"; + schemas.__shared = { + [defsSegment]: defs, + }; } - await this.send({ - event: "on_custom_event", - run_id: runId, - name: eventName, - tags: runInfo.tags, - metadata: runInfo.metadata, - data, - }, runInfo); - } - async finish() { - const pendingPromises = [...this.tappedPromises.values()]; - void Promise.all(pendingPromises).finally(() => { - void this.writer.close(); - }); + return { schemas }; } + const gen = new JSONSchemaGenerator(_params); + gen.process(input); + return gen.emit(input, _params); } - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/async_caller.js - - -const async_caller_STATUS_NO_RETRY = [ - 400, - 401, - 402, - 403, - 404, - 405, - 406, - 407, - 409, // Conflict -]; -// eslint-disable-next-line @typescript-eslint/no-explicit-any -const defaultFailedAttemptHandler = (error) => { - if (error.message.startsWith("Cancel") || - error.message.startsWith("AbortError") || - error.name === "AbortError") { - throw error; - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - if (error?.code === "ECONNABORTED") { - throw error; - } - const status = - // eslint-disable-next-line @typescript-eslint/no-explicit-any - error?.response?.status ?? error?.status; - if (status && async_caller_STATUS_NO_RETRY.includes(+status)) { - throw error; - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - if (error?.error?.code === "insufficient_quota") { - const err = new Error(error?.message); - err.name = "InsufficientQuotaError"; - throw err; - } -}; -/** - * A class that can be used to make async calls with concurrency and retry logic. - * - * This is useful for making calls to any kind of "expensive" external resource, - * be it because it's rate-limited, subject to network issues, etc. - * - * Concurrent calls are limited by the `maxConcurrency` parameter, which defaults - * to `Infinity`. This means that by default, all calls will be made in parallel. - * - * Retries are limited by the `maxRetries` parameter, which defaults to 6. This - * means that by default, each call will be retried up to 6 times, with an - * exponential backoff between each attempt. - */ -class async_caller_AsyncCaller { - constructor(params) { - Object.defineProperty(this, "maxConcurrency", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "maxRetries", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "onFailedAttempt", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "queue", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.maxConcurrency = params.maxConcurrency ?? Infinity; - this.maxRetries = params.maxRetries ?? 6; - this.onFailedAttempt = - params.onFailedAttempt ?? defaultFailedAttemptHandler; - const PQueue = true ? p_queue_dist["default"] : p_queue_dist; - this.queue = new PQueue({ concurrency: this.maxConcurrency }); - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - call(callable, ...args) { - return this.queue.add(() => p_retry(() => callable(...args).catch((error) => { - // eslint-disable-next-line no-instanceof/no-instanceof - if (error instanceof Error) { - throw error; +function isTransforming(_schema, _ctx) { + const ctx = _ctx ?? { seen: new Set() }; + if (ctx.seen.has(_schema)) + return false; + ctx.seen.add(_schema); + const schema = _schema; + const def = schema._zod.def; + switch (def.type) { + case "string": + case "number": + case "bigint": + case "boolean": + case "date": + case "symbol": + case "undefined": + case "null": + case "any": + case "unknown": + case "never": + case "void": + case "literal": + case "enum": + case "nan": + case "file": + case "template_literal": + return false; + case "array": { + return isTransforming(def.element, ctx); + } + case "object": { + for (const key in def.shape) { + if (isTransforming(def.shape[key], ctx)) + return true; } - else { - throw new Error(error); + return false; + } + case "union": { + for (const option of def.options) { + if (isTransforming(option, ctx)) + return true; } - }), { - onFailedAttempt: this.onFailedAttempt, - retries: this.maxRetries, - randomize: true, - // If needed we can change some of the defaults here, - // but they're quite sensible. - }), { throwOnTimeout: true }); - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - callWithOptions(options, callable, ...args) { - // Note this doesn't cancel the underlying request, - // when available prefer to use the signal option of the underlying call - if (options.signal) { - return Promise.race([ - this.call(callable, ...args), - new Promise((_, reject) => { - options.signal?.addEventListener("abort", () => { - reject(new Error("AbortError")); - }); - }), - ]); + return false; } - return this.call(callable, ...args); - } - fetch(...args) { - return this.call(() => fetch(...args).then((res) => (res.ok ? res : Promise.reject(res)))); - } -} - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/tracers/root_listener.js - -class RootListenersTracer extends BaseTracer { - constructor({ config, onStart, onEnd, onError, }) { - super({ _awaitHandler: true }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "RootListenersTracer" - }); - /** The Run's ID. Type UUID */ - Object.defineProperty(this, "rootId", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "config", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "argOnStart", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "argOnEnd", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "argOnError", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.config = config; - this.argOnStart = onStart; - this.argOnEnd = onEnd; - this.argOnError = onError; - } - /** - * This is a legacy method only called once for an entire run tree - * therefore not useful here - * @param {Run} _ Not used - */ - persistRun(_) { - return Promise.resolve(); - } - async onRunCreate(run) { - if (this.rootId) { - return; + case "intersection": { + return isTransforming(def.left, ctx) || isTransforming(def.right, ctx); } - this.rootId = run.id; - if (this.argOnStart) { - await this.argOnStart(run, this.config); + case "tuple": { + for (const item of def.items) { + if (isTransforming(item, ctx)) + return true; + } + if (def.rest && isTransforming(def.rest, ctx)) + return true; + return false; } - } - async onRunUpdate(run) { - if (run.id !== this.rootId) { - return; + case "record": { + return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx); } - if (!run.error) { - if (this.argOnEnd) { - await this.argOnEnd(run, this.config); - } + case "map": { + return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx); } - else if (this.argOnError) { - await this.argOnError(run, this.config); + case "set": { + return isTransforming(def.valueType, ctx); } - } -} - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/utils.js -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function isRunnableInterface(thing) { - return thing ? thing.lc_runnable : false; -} -/** - * Utility to filter the root event in the streamEvents implementation. - * This is simply binding the arguments to the namespace to make save on - * a bit of typing in the streamEvents implementation. - * - * TODO: Refactor and remove. - */ -class _RootEventFilter { - constructor(fields) { - Object.defineProperty(this, "includeNames", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "includeTypes", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "includeTags", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "excludeNames", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "excludeTypes", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "excludeTags", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.includeNames = fields.includeNames; - this.includeTypes = fields.includeTypes; - this.includeTags = fields.includeTags; - this.excludeNames = fields.excludeNames; - this.excludeTypes = fields.excludeTypes; - this.excludeTags = fields.excludeTags; - } - includeEvent(event, rootType) { - let include = this.includeNames === undefined && - this.includeTypes === undefined && - this.includeTags === undefined; - const eventTags = event.tags ?? []; - if (this.includeNames !== undefined) { - include = include || this.includeNames.includes(event.name); + // inner types + case "promise": + case "optional": + case "nonoptional": + case "nullable": + case "readonly": + return isTransforming(def.innerType, ctx); + case "lazy": + return isTransforming(def.getter(), ctx); + case "default": { + return isTransforming(def.innerType, ctx); } - if (this.includeTypes !== undefined) { - include = include || this.includeTypes.includes(rootType); + case "prefault": { + return isTransforming(def.innerType, ctx); } - if (this.includeTags !== undefined) { - include = - include || eventTags.some((tag) => this.includeTags?.includes(tag)); + case "custom": { + return false; } - if (this.excludeNames !== undefined) { - include = include && !this.excludeNames.includes(event.name); + case "transform": { + return true; } - if (this.excludeTypes !== undefined) { - include = include && !this.excludeTypes.includes(rootType); + case "pipe": { + return isTransforming(def.in, ctx) || isTransforming(def.out, ctx); } - if (this.excludeTags !== undefined) { - include = - include && eventTags.every((tag) => !this.excludeTags?.includes(tag)); + case "success": { + return false; } - return include; + case "catch": { + return false; + } + default: + def; } + throw new Error(`Unknown schema type: ${def.type}`); } +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/core/index.js + + + + + + + + + + + + + + + + ;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/Options.js const ignoreOverride = Symbol("Let zodToJsonSchema decide on which parser to use"); const jsonDescription = (jsonSchema, def) => { @@ -96363,6 +101607,7 @@ const Options_defaultOptions = { emailStrategy: "format:email", base64Strategy: "contentEncoding:base64", nameStrategy: "ref", + openAiAnyTypeName: "OpenAiAnyType" }; const getDefaultOptions = (options) => (typeof options === "string" ? { @@ -96383,6 +101628,7 @@ const getRefs = (options) => { : _options.basePath; return { ..._options, + flags: { hasReferencedOpenAiAnyType: false }, currentPath: currentPath, propertyPath: undefined, seen: new Map(Object.entries(_options.definitions).map(([name, def]) => [ @@ -96397,9 +101643,33 @@ const getRefs = (options) => { }; }; +;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/getRelativePath.js +const getRelativePath = (pathA, pathB) => { + let i = 0; + for (; i < pathA.length && i < pathB.length; i++) { + if (pathA[i] !== pathB[i]) + break; + } + return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/"); +}; + ;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/any.js -function parseAnyDef() { - return {}; + +function parseAnyDef(refs) { + if (refs.target !== "openAi") { + return {}; + } + const anyDefinitionPath = [ + ...refs.basePath, + refs.definitionPath, + refs.openAiAnyTypeName, + ]; + refs.flags.hasReferencedOpenAiAnyType = true; + return { + $ref: refs.$refStrategy === "relative" + ? getRelativePath(anyDefinitionPath, refs.currentPath) + : anyDefinitionPath.join("/"), + }; } ;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/errorMessages.js @@ -96575,10 +101845,11 @@ function parseDefaultDef(_def, refs) { ;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/effects.js + function parseEffectsDef(_def, refs) { return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs) - : {}; + : parseAnyDef(refs); } ;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/enum.js @@ -97026,6 +102297,7 @@ function stringifyRegExpWithFlags(regex, refs) { + function parseRecordDef(def, refs) { if (refs.target === "openAi") { console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."); @@ -97040,7 +102312,7 @@ function parseRecordDef(def, refs) { [key]: parseDef(def.valueType._def, { ...refs, currentPath: [...refs.currentPath, "properties", key], - }) ?? {}, + }) ?? parseAnyDef(refs), }), {}), additionalProperties: refs.rejectedAdditionalProperties, }; @@ -97086,6 +102358,7 @@ function parseRecordDef(def, refs) { ;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/map.js + function parseMapDef(def, refs) { if (refs.mapStrategy === "record") { return parseRecordDef(def, refs); @@ -97093,11 +102366,11 @@ function parseMapDef(def, refs) { const keys = parseDef(def.keyType._def, { ...refs, currentPath: [...refs.currentPath, "items", "items", "0"], - }) || {}; + }) || parseAnyDef(refs); const values = parseDef(def.valueType._def, { ...refs, currentPath: [...refs.currentPath, "items", "items", "1"], - }) || {}; + }) || parseAnyDef(refs); return { type: "array", maxItems: 125, @@ -97129,10 +102402,16 @@ function parseNativeEnumDef(def) { } ;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/never.js -function parseNeverDef() { - return { - not: {}, - }; + +function parseNeverDef(refs) { + return refs.target === "openAi" + ? undefined + : { + not: parseAnyDef({ + ...refs, + currentPath: [...refs.currentPath, "not"], + }), + }; } ;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/null.js @@ -97320,7 +102599,6 @@ function parseNumberDef(def, refs) { ;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/object.js - function parseObjectDef(def, refs) { const forceOptionalIntoNullable = refs.target === "openAi"; const result = { @@ -97336,7 +102614,7 @@ function parseObjectDef(def, refs) { } let propOptional = safeIsOptional(propDef); if (propOptional && forceOptionalIntoNullable) { - if (propDef instanceof ZodOptional) { + if (propDef._def.typeName === "ZodOptional") { propDef = propDef._def.innerType; } if (!propDef.isNullable()) { @@ -97395,6 +102673,7 @@ function safeIsOptional(schema) { ;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/optional.js + const parseOptionalDef = (def, refs) => { if (refs.currentPath.toString() === refs.propertyPath?.toString()) { return parseDef(def.innerType._def, refs); @@ -97407,12 +102686,12 @@ const parseOptionalDef = (def, refs) => { ? { anyOf: [ { - not: {}, + not: parseAnyDef(refs), }, innerSchema, ], } - : {}; + : parseAnyDef(refs); }; ;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/pipeline.js @@ -97500,15 +102779,17 @@ function parseTupleDef(def, refs) { } ;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/undefined.js -function parseUndefinedDef() { + +function parseUndefinedDef(refs) { return { - not: {}, + not: parseAnyDef(refs), }; } ;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/unknown.js -function parseUnknownDef() { - return {}; + +function parseUnknownDef(refs) { + return parseAnyDef(refs); } ;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/readonly.js @@ -97564,7 +102845,7 @@ const selectParser = (def, typeName, refs) => { case ZodFirstPartyTypeKind.ZodDate: return parseDateDef(def, refs); case ZodFirstPartyTypeKind.ZodUndefined: - return parseUndefinedDef(); + return parseUndefinedDef(refs); case ZodFirstPartyTypeKind.ZodNull: return parseNullDef(refs); case ZodFirstPartyTypeKind.ZodArray: @@ -97580,708 +102861,209 @@ const selectParser = (def, typeName, refs) => { return parseRecordDef(def, refs); case ZodFirstPartyTypeKind.ZodLiteral: return parseLiteralDef(def, refs); - case ZodFirstPartyTypeKind.ZodEnum: - return parseEnumDef(def); - case ZodFirstPartyTypeKind.ZodNativeEnum: - return parseNativeEnumDef(def); - case ZodFirstPartyTypeKind.ZodNullable: - return parseNullableDef(def, refs); - case ZodFirstPartyTypeKind.ZodOptional: - return parseOptionalDef(def, refs); - case ZodFirstPartyTypeKind.ZodMap: - return parseMapDef(def, refs); - case ZodFirstPartyTypeKind.ZodSet: - return parseSetDef(def, refs); - case ZodFirstPartyTypeKind.ZodLazy: - return () => def.getter()._def; - case ZodFirstPartyTypeKind.ZodPromise: - return parsePromiseDef(def, refs); - case ZodFirstPartyTypeKind.ZodNaN: - case ZodFirstPartyTypeKind.ZodNever: - return parseNeverDef(); - case ZodFirstPartyTypeKind.ZodEffects: - return parseEffectsDef(def, refs); - case ZodFirstPartyTypeKind.ZodAny: - return parseAnyDef(); - case ZodFirstPartyTypeKind.ZodUnknown: - return parseUnknownDef(); - case ZodFirstPartyTypeKind.ZodDefault: - return parseDefaultDef(def, refs); - case ZodFirstPartyTypeKind.ZodBranded: - return parseBrandedDef(def, refs); - case ZodFirstPartyTypeKind.ZodReadonly: - return parseReadonlyDef(def, refs); - case ZodFirstPartyTypeKind.ZodCatch: - return parseCatchDef(def, refs); - case ZodFirstPartyTypeKind.ZodPipeline: - return parsePipelineDef(def, refs); - case ZodFirstPartyTypeKind.ZodFunction: - case ZodFirstPartyTypeKind.ZodVoid: - case ZodFirstPartyTypeKind.ZodSymbol: - return undefined; - default: - /* c8 ignore next */ - return ((_) => undefined)(typeName); - } -}; - -;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parseDef.js - - -function parseDef(def, refs, forceResolution = false) { - const seenItem = refs.seen.get(def); - if (refs.override) { - const overrideResult = refs.override?.(def, refs, seenItem, forceResolution); - if (overrideResult !== ignoreOverride) { - return overrideResult; - } - } - if (seenItem && !forceResolution) { - const seenSchema = get$ref(seenItem, refs); - if (seenSchema !== undefined) { - return seenSchema; - } - } - const newItem = { def, path: refs.currentPath, jsonSchema: undefined }; - refs.seen.set(def, newItem); - const jsonSchemaOrGetter = selectParser(def, def.typeName, refs); - // If the return was a function, then the inner definition needs to be extracted before a call to parseDef (recursive) - const jsonSchema = typeof jsonSchemaOrGetter === "function" - ? parseDef(jsonSchemaOrGetter(), refs) - : jsonSchemaOrGetter; - if (jsonSchema) { - addMeta(def, refs, jsonSchema); - } - if (refs.postProcess) { - const postProcessResult = refs.postProcess(jsonSchema, def, refs); - newItem.jsonSchema = jsonSchema; - return postProcessResult; - } - newItem.jsonSchema = jsonSchema; - return jsonSchema; -} -const get$ref = (item, refs) => { - switch (refs.$refStrategy) { - case "root": - return { $ref: item.path.join("/") }; - case "relative": - return { $ref: getRelativePath(refs.currentPath, item.path) }; - case "none": - case "seen": { - if (item.path.length < refs.currentPath.length && - item.path.every((value, index) => refs.currentPath[index] === value)) { - console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`); - return {}; - } - return refs.$refStrategy === "seen" ? {} : undefined; - } - } -}; -const getRelativePath = (pathA, pathB) => { - let i = 0; - for (; i < pathA.length && i < pathB.length; i++) { - if (pathA[i] !== pathB[i]) - break; - } - return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/"); -}; -const addMeta = (def, refs, jsonSchema) => { - if (def.description) { - jsonSchema.description = def.description; - if (refs.markdownDescription) { - jsonSchema.markdownDescription = def.description; - } - } - return jsonSchema; -}; - -;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/zodToJsonSchema.js - - -const zodToJsonSchema_zodToJsonSchema = (schema, options) => { - const refs = getRefs(options); - const definitions = typeof options === "object" && options.definitions - ? Object.entries(options.definitions).reduce((acc, [name, schema]) => ({ - ...acc, - [name]: parseDef(schema._def, { - ...refs, - currentPath: [...refs.basePath, refs.definitionPath, name], - }, true) ?? {}, - }), {}) - : undefined; - const name = typeof options === "string" - ? options - : options?.nameStrategy === "title" - ? undefined - : options?.name; - const main = parseDef(schema._def, name === undefined - ? refs - : { - ...refs, - currentPath: [...refs.basePath, refs.definitionPath, name], - }, false) ?? {}; - const title = typeof options === "object" && - options.name !== undefined && - options.nameStrategy === "title" - ? options.name - : undefined; - if (title !== undefined) { - main.title = title; - } - const combined = name === undefined - ? definitions - ? { - ...main, - [refs.definitionPath]: definitions, - } - : main - : { - $ref: [ - ...(refs.$refStrategy === "relative" ? [] : refs.basePath), - refs.definitionPath, - name, - ].join("/"), - [refs.definitionPath]: { - ...definitions, - [name]: main, - }, - }; - if (refs.target === "jsonSchema7") { - combined.$schema = "http://json-schema.org/draft-07/schema#"; - } - else if (refs.target === "jsonSchema2019-09" || refs.target === "openAi") { - combined.$schema = "https://json-schema.org/draft/2019-09/schema#"; - } - if (refs.target === "openAi" && - ("anyOf" in combined || - "oneOf" in combined || - "allOf" in combined || - ("type" in combined && Array.isArray(combined.type)))) { - console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."); - } - return combined; -}; - - -;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/index.js - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -/* harmony default export */ const esm = ((/* unused pure expression or super */ null && (zodToJsonSchema))); - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/graph_mermaid.js -function _escapeNodeLabel(nodeLabel) { - // Escapes the node label for Mermaid syntax. - return nodeLabel.replace(/[^a-zA-Z-_0-9]/g, "_"); -} -const MARKDOWN_SPECIAL_CHARS = ["*", "_", "`"]; -function _generateMermaidGraphStyles(nodeColors) { - let styles = ""; - for (const [className, color] of Object.entries(nodeColors)) { - styles += `\tclassDef ${className} ${color};\n`; - } - return styles; -} -/** - * Draws a Mermaid graph using the provided graph data - */ -function drawMermaid(nodes, edges, config) { - const { firstNode, lastNode, nodeColors, withStyles = true, curveStyle = "linear", wrapLabelNWords = 9, } = config ?? {}; - // Initialize Mermaid graph configuration - let mermaidGraph = withStyles - ? `%%{init: {'flowchart': {'curve': '${curveStyle}'}}}%%\ngraph TD;\n` - : "graph TD;\n"; - if (withStyles) { - // Node formatting templates - const defaultClassLabel = "default"; - const formatDict = { - [defaultClassLabel]: "{0}({1})", - }; - if (firstNode !== undefined) { - formatDict[firstNode] = "{0}([{1}]):::first"; - } - if (lastNode !== undefined) { - formatDict[lastNode] = "{0}([{1}]):::last"; - } - // Add nodes to the graph - for (const [key, node] of Object.entries(nodes)) { - const nodeName = node.name.split(":").pop() ?? ""; - const label = MARKDOWN_SPECIAL_CHARS.some((char) => nodeName.startsWith(char) && nodeName.endsWith(char)) - ? `

${nodeName}

` - : nodeName; - let finalLabel = label; - if (Object.keys(node.metadata ?? {}).length) { - finalLabel += `
${Object.entries(node.metadata ?? {}) - .map(([k, v]) => `${k} = ${v}`) - .join("\n")}`; - } - const nodeLabel = (formatDict[key] ?? formatDict[defaultClassLabel]) - .replace("{0}", _escapeNodeLabel(key)) - .replace("{1}", finalLabel); - mermaidGraph += `\t${nodeLabel}\n`; - } - } - // Group edges by their common prefixes - const edgeGroups = {}; - for (const edge of edges) { - const srcParts = edge.source.split(":"); - const tgtParts = edge.target.split(":"); - const commonPrefix = srcParts - .filter((src, i) => src === tgtParts[i]) - .join(":"); - if (!edgeGroups[commonPrefix]) { - edgeGroups[commonPrefix] = []; - } - edgeGroups[commonPrefix].push(edge); - } - const seenSubgraphs = new Set(); - function addSubgraph(edges, prefix) { - const selfLoop = edges.length === 1 && edges[0].source === edges[0].target; - if (prefix && !selfLoop) { - const subgraph = prefix.split(":").pop(); - if (seenSubgraphs.has(subgraph)) { - throw new Error(`Found duplicate subgraph '${subgraph}' -- this likely means that ` + - "you're reusing a subgraph node with the same name. " + - "Please adjust your graph to have subgraph nodes with unique names."); - } - seenSubgraphs.add(subgraph); - mermaidGraph += `\tsubgraph ${subgraph}\n`; - } - for (const edge of edges) { - const { source, target, data, conditional } = edge; - let edgeLabel = ""; - if (data !== undefined) { - let edgeData = data; - const words = edgeData.split(" "); - if (words.length > wrapLabelNWords) { - edgeData = Array.from({ length: Math.ceil(words.length / wrapLabelNWords) }, (_, i) => words - .slice(i * wrapLabelNWords, (i + 1) * wrapLabelNWords) - .join(" ")).join(" 
 "); - } - edgeLabel = conditional - ? ` -.  ${edgeData}  .-> ` - : ` --  ${edgeData}  --> `; - } - else { - edgeLabel = conditional ? " -.-> " : " --> "; - } - mermaidGraph += `\t${_escapeNodeLabel(source)}${edgeLabel}${_escapeNodeLabel(target)};\n`; - } - // Recursively add nested subgraphs - for (const nestedPrefix in edgeGroups) { - if (nestedPrefix.startsWith(`${prefix}:`) && nestedPrefix !== prefix) { - addSubgraph(edgeGroups[nestedPrefix], nestedPrefix); - } - } - if (prefix && !selfLoop) { - mermaidGraph += "\tend\n"; - } - } - // Start with the top-level edges (no common prefix) - addSubgraph(edgeGroups[""] ?? [], ""); - // Add remaining subgraphs - for (const prefix in edgeGroups) { - if (!prefix.includes(":") && prefix !== "") { - addSubgraph(edgeGroups[prefix], prefix); - } - } - // Add custom styles for nodes - if (withStyles) { - mermaidGraph += _generateMermaidGraphStyles(nodeColors ?? {}); - } - return mermaidGraph; -} -/** - * Renders Mermaid graph using the Mermaid.INK API. - */ -async function drawMermaidPng(mermaidSyntax, config) { - let { backgroundColor = "white" } = config ?? {}; - // Use btoa for compatibility, assume ASCII - const mermaidSyntaxEncoded = btoa(mermaidSyntax); - // Check if the background color is a hexadecimal color code using regex - if (backgroundColor !== undefined) { - const hexColorPattern = /^#(?:[0-9a-fA-F]{3}){1,2}$/; - if (!hexColorPattern.test(backgroundColor)) { - backgroundColor = `!${backgroundColor}`; - } - } - const imageUrl = `https://mermaid.ink/img/${mermaidSyntaxEncoded}?bgColor=${backgroundColor}`; - const res = await fetch(imageUrl); - if (!res.ok) { - throw new Error([ - `Failed to render the graph using the Mermaid.INK API.`, - `Status code: ${res.status}`, - `Status text: ${res.statusText}`, - ].join("\n")); - } - const content = await res.blob(); - return content; -} - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/graph.js - - - - -function nodeDataStr(id, data) { - if (id !== undefined && !wrapper_validate(id)) { - return id; - } - else if (isRunnableInterface(data)) { - try { - let dataStr = data.getName(); - dataStr = dataStr.startsWith("Runnable") - ? dataStr.slice("Runnable".length) - : dataStr; - return dataStr; - } - catch (error) { - return data.getName(); - } - } - else { - return data.name ?? "UnknownSchema"; - } -} -function nodeDataJson(node) { - // if node.data implements Runnable - if (isRunnableInterface(node.data)) { - return { - type: "runnable", - data: { - id: node.data.lc_id, - name: node.data.getName(), - }, - }; - } - else { - return { - type: "schema", - data: { ...zodToJsonSchema_zodToJsonSchema(node.data.schema), title: node.data.name }, - }; - } -} -class Graph { - constructor(params) { - Object.defineProperty(this, "nodes", { - enumerable: true, - configurable: true, - writable: true, - value: {} - }); - Object.defineProperty(this, "edges", { - enumerable: true, - configurable: true, - writable: true, - value: [] - }); - this.nodes = params?.nodes ?? this.nodes; - this.edges = params?.edges ?? this.edges; - } - // Convert the graph to a JSON-serializable format. - // eslint-disable-next-line @typescript-eslint/no-explicit-any - toJSON() { - const stableNodeIds = {}; - Object.values(this.nodes).forEach((node, i) => { - stableNodeIds[node.id] = wrapper_validate(node.id) ? i : node.id; - }); - return { - nodes: Object.values(this.nodes).map((node) => ({ - id: stableNodeIds[node.id], - ...nodeDataJson(node), - })), - edges: this.edges.map((edge) => { - const item = { - source: stableNodeIds[edge.source], - target: stableNodeIds[edge.target], - }; - if (typeof edge.data !== "undefined") { - item.data = edge.data; - } - if (typeof edge.conditional !== "undefined") { - item.conditional = edge.conditional; - } - return item; - }), - }; + case ZodFirstPartyTypeKind.ZodEnum: + return parseEnumDef(def); + case ZodFirstPartyTypeKind.ZodNativeEnum: + return parseNativeEnumDef(def); + case ZodFirstPartyTypeKind.ZodNullable: + return parseNullableDef(def, refs); + case ZodFirstPartyTypeKind.ZodOptional: + return parseOptionalDef(def, refs); + case ZodFirstPartyTypeKind.ZodMap: + return parseMapDef(def, refs); + case ZodFirstPartyTypeKind.ZodSet: + return parseSetDef(def, refs); + case ZodFirstPartyTypeKind.ZodLazy: + return () => def.getter()._def; + case ZodFirstPartyTypeKind.ZodPromise: + return parsePromiseDef(def, refs); + case ZodFirstPartyTypeKind.ZodNaN: + case ZodFirstPartyTypeKind.ZodNever: + return parseNeverDef(refs); + case ZodFirstPartyTypeKind.ZodEffects: + return parseEffectsDef(def, refs); + case ZodFirstPartyTypeKind.ZodAny: + return parseAnyDef(refs); + case ZodFirstPartyTypeKind.ZodUnknown: + return parseUnknownDef(refs); + case ZodFirstPartyTypeKind.ZodDefault: + return parseDefaultDef(def, refs); + case ZodFirstPartyTypeKind.ZodBranded: + return parseBrandedDef(def, refs); + case ZodFirstPartyTypeKind.ZodReadonly: + return parseReadonlyDef(def, refs); + case ZodFirstPartyTypeKind.ZodCatch: + return parseCatchDef(def, refs); + case ZodFirstPartyTypeKind.ZodPipeline: + return parsePipelineDef(def, refs); + case ZodFirstPartyTypeKind.ZodFunction: + case ZodFirstPartyTypeKind.ZodVoid: + case ZodFirstPartyTypeKind.ZodSymbol: + return undefined; + default: + /* c8 ignore next */ + return ((_) => undefined)(typeName); } - addNode(data, id, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - metadata) { - if (id !== undefined && this.nodes[id] !== undefined) { - throw new Error(`Node with id ${id} already exists`); +}; + +;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parseDef.js + + + + +function parseDef(def, refs, forceResolution = false) { + const seenItem = refs.seen.get(def); + if (refs.override) { + const overrideResult = refs.override?.(def, refs, seenItem, forceResolution); + if (overrideResult !== ignoreOverride) { + return overrideResult; } - const nodeId = id ?? v4(); - const node = { - id: nodeId, - data, - name: nodeDataStr(id, data), - metadata, - }; - this.nodes[nodeId] = node; - return node; - } - removeNode(node) { - // Remove the node from the nodes map - delete this.nodes[node.id]; - // Filter out edges connected to the node - this.edges = this.edges.filter((edge) => edge.source !== node.id && edge.target !== node.id); } - addEdge(source, target, data, conditional) { - if (this.nodes[source.id] === undefined) { - throw new Error(`Source node ${source.id} not in graph`); - } - if (this.nodes[target.id] === undefined) { - throw new Error(`Target node ${target.id} not in graph`); + if (seenItem && !forceResolution) { + const seenSchema = get$ref(seenItem, refs); + if (seenSchema !== undefined) { + return seenSchema; } - const edge = { - source: source.id, - target: target.id, - data, - conditional, - }; - this.edges.push(edge); - return edge; } - firstNode() { - return _firstNode(this); + const newItem = { def, path: refs.currentPath, jsonSchema: undefined }; + refs.seen.set(def, newItem); + const jsonSchemaOrGetter = selectParser(def, def.typeName, refs); + // If the return was a function, then the inner definition needs to be extracted before a call to parseDef (recursive) + const jsonSchema = typeof jsonSchemaOrGetter === "function" + ? parseDef(jsonSchemaOrGetter(), refs) + : jsonSchemaOrGetter; + if (jsonSchema) { + addMeta(def, refs, jsonSchema); } - lastNode() { - return _lastNode(this); + if (refs.postProcess) { + const postProcessResult = refs.postProcess(jsonSchema, def, refs); + newItem.jsonSchema = jsonSchema; + return postProcessResult; } - /** - * Add all nodes and edges from another graph. - * Note this doesn't check for duplicates, nor does it connect the graphs. - */ - extend(graph, prefix = "") { - let finalPrefix = prefix; - const nodeIds = Object.values(graph.nodes).map((node) => node.id); - if (nodeIds.every(wrapper_validate)) { - finalPrefix = ""; + newItem.jsonSchema = jsonSchema; + return jsonSchema; +} +const get$ref = (item, refs) => { + switch (refs.$refStrategy) { + case "root": + return { $ref: item.path.join("/") }; + case "relative": + return { $ref: getRelativePath(refs.currentPath, item.path) }; + case "none": + case "seen": { + if (item.path.length < refs.currentPath.length && + item.path.every((value, index) => refs.currentPath[index] === value)) { + console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`); + return parseAnyDef(refs); + } + return refs.$refStrategy === "seen" ? parseAnyDef(refs) : undefined; } - const prefixed = (id) => { - return finalPrefix ? `${finalPrefix}:${id}` : id; - }; - Object.entries(graph.nodes).forEach(([key, value]) => { - this.nodes[prefixed(key)] = { ...value, id: prefixed(key) }; - }); - const newEdges = graph.edges.map((edge) => { - return { - ...edge, - source: prefixed(edge.source), - target: prefixed(edge.target), - }; - }); - // Add all edges from the other graph - this.edges = [...this.edges, ...newEdges]; - const first = graph.firstNode(); - const last = graph.lastNode(); - return [ - first ? { id: prefixed(first.id), data: first.data } : undefined, - last ? { id: prefixed(last.id), data: last.data } : undefined, - ]; } - trimFirstNode() { - const firstNode = this.firstNode(); - if (firstNode && _firstNode(this, [firstNode.id])) { - this.removeNode(firstNode); +}; +const addMeta = (def, refs, jsonSchema) => { + if (def.description) { + jsonSchema.description = def.description; + if (refs.markdownDescription) { + jsonSchema.markdownDescription = def.description; } } - trimLastNode() { - const lastNode = this.lastNode(); - if (lastNode && _lastNode(this, [lastNode.id])) { - this.removeNode(lastNode); + return jsonSchema; +}; + +;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/zodToJsonSchema.js + + + +const zodToJsonSchema_zodToJsonSchema = (schema, options) => { + const refs = getRefs(options); + let definitions = typeof options === "object" && options.definitions + ? Object.entries(options.definitions).reduce((acc, [name, schema]) => ({ + ...acc, + [name]: parseDef(schema._def, { + ...refs, + currentPath: [...refs.basePath, refs.definitionPath, name], + }, true) ?? parseAnyDef(refs), + }), {}) + : undefined; + const name = typeof options === "string" + ? options + : options?.nameStrategy === "title" + ? undefined + : options?.name; + const main = parseDef(schema._def, name === undefined + ? refs + : { + ...refs, + currentPath: [...refs.basePath, refs.definitionPath, name], + }, false) ?? parseAnyDef(refs); + const title = typeof options === "object" && + options.name !== undefined && + options.nameStrategy === "title" + ? options.name + : undefined; + if (title !== undefined) { + main.title = title; + } + if (refs.flags.hasReferencedOpenAiAnyType) { + if (!definitions) { + definitions = {}; + } + if (!definitions[refs.openAiAnyTypeName]) { + definitions[refs.openAiAnyTypeName] = { + // Skipping "object" as no properties can be defined and additionalProperties must be "false" + type: ["string", "number", "integer", "boolean", "array", "null"], + items: { + $ref: refs.$refStrategy === "relative" + ? "1" + : [ + ...refs.basePath, + refs.definitionPath, + refs.openAiAnyTypeName, + ].join("/"), + }, + }; } } - /** - * Return a new graph with all nodes re-identified, - * using their unique, readable names where possible. - */ - reid() { - const nodeLabels = Object.fromEntries(Object.values(this.nodes).map((node) => [node.id, node.name])); - const nodeLabelCounts = new Map(); - Object.values(nodeLabels).forEach((label) => { - nodeLabelCounts.set(label, (nodeLabelCounts.get(label) || 0) + 1); - }); - const getNodeId = (nodeId) => { - const label = nodeLabels[nodeId]; - if (wrapper_validate(nodeId) && nodeLabelCounts.get(label) === 1) { - return label; - } - else { - return nodeId; + const combined = name === undefined + ? definitions + ? { + ...main, + [refs.definitionPath]: definitions, } + : main + : { + $ref: [ + ...(refs.$refStrategy === "relative" ? [] : refs.basePath), + refs.definitionPath, + name, + ].join("/"), + [refs.definitionPath]: { + ...definitions, + [name]: main, + }, }; - return new Graph({ - nodes: Object.fromEntries(Object.entries(this.nodes).map(([id, node]) => [ - getNodeId(id), - { ...node, id: getNodeId(id) }, - ])), - edges: this.edges.map((edge) => ({ - ...edge, - source: getNodeId(edge.source), - target: getNodeId(edge.target), - })), - }); - } - drawMermaid(params) { - const { withStyles, curveStyle, nodeColors = { - default: "fill:#f2f0ff,line-height:1.2", - first: "fill-opacity:0", - last: "fill:#bfb6fc", - }, wrapLabelNWords, } = params ?? {}; - const graph = this.reid(); - const firstNode = graph.firstNode(); - const lastNode = graph.lastNode(); - return drawMermaid(graph.nodes, graph.edges, { - firstNode: firstNode?.id, - lastNode: lastNode?.id, - withStyles, - curveStyle, - nodeColors, - wrapLabelNWords, - }); - } - async drawMermaidPng(params) { - const mermaidSyntax = this.drawMermaid(params); - return drawMermaidPng(mermaidSyntax, { - backgroundColor: params?.backgroundColor, - }); + if (refs.target === "jsonSchema7") { + combined.$schema = "http://json-schema.org/draft-07/schema#"; } -} -/** - * Find the single node that is not a target of any edge. - * Exclude nodes/sources with ids in the exclude list. - * If there is no such node, or there are multiple, return undefined. - * When drawing the graph, this node would be the origin. - */ -function _firstNode(graph, exclude = []) { - const targets = new Set(graph.edges - .filter((edge) => !exclude.includes(edge.source)) - .map((edge) => edge.target)); - const found = []; - for (const node of Object.values(graph.nodes)) { - if (!exclude.includes(node.id) && !targets.has(node.id)) { - found.push(node); - } + else if (refs.target === "jsonSchema2019-09" || refs.target === "openAi") { + combined.$schema = "https://json-schema.org/draft/2019-09/schema#"; } - return found.length === 1 ? found[0] : undefined; -} -/** - * Find the single node that is not a source of any edge. - * Exclude nodes/targets with ids in the exclude list. - * If there is no such node, or there are multiple, return undefined. - * When drawing the graph, this node would be the destination. - */ -function _lastNode(graph, exclude = []) { - const sources = new Set(graph.edges - .filter((edge) => !exclude.includes(edge.target)) - .map((edge) => edge.source)); - const found = []; - for (const node of Object.values(graph.nodes)) { - if (!exclude.includes(node.id) && !sources.has(node.id)) { - found.push(node); - } + if (refs.target === "openAi" && + ("anyOf" in combined || + "oneOf" in combined || + "allOf" in combined || + ("type" in combined && Array.isArray(combined.type)))) { + console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."); } - return found.length === 1 ? found[0] : undefined; -} + return combined; +}; -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/wrappers.js -function convertToHttpEventStream(stream) { - const encoder = new TextEncoder(); - const finalStream = new ReadableStream({ - async start(controller) { - for await (const chunk of stream) { - controller.enqueue(encoder.encode(`event: data\ndata: ${JSON.stringify(chunk)}\n\n`)); - } - controller.enqueue(encoder.encode("event: end\n\n")); - controller.close(); - }, - }); - return IterableReadableStream.fromReadableStream(finalStream); -} +;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/index.js -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/iter.js -function isIterableIterator(thing) { - return (typeof thing === "object" && - thing !== null && - typeof thing[Symbol.iterator] === "function" && - // avoid detecting array/set as iterator - typeof thing.next === "function"); -} -const isIterator = (x) => x != null && - typeof x === "object" && - "next" in x && - typeof x.next === "function"; -function iter_isAsyncIterable(thing) { - return (typeof thing === "object" && - thing !== null && - typeof thing[Symbol.asyncIterator] === - "function"); -} -function* consumeIteratorInContext(context, iter) { - while (true) { - const { value, done } = async_local_storage_AsyncLocalStorageProviderSingleton.runWithConfig(pickRunnableConfigKeys(context), iter.next.bind(iter), true); - if (done) { - break; - } - else { - yield value; - } - } -} -async function* consumeAsyncIterableInContext(context, iter) { - const iterator = iter[Symbol.asyncIterator](); - while (true) { - const { value, done } = await async_local_storage_AsyncLocalStorageProviderSingleton.runWithConfig(pickRunnableConfigKeys(context), iterator.next.bind(iter), true); - if (done) { - break; - } - else { - yield value; - } - } -} -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/base.js @@ -98300,1728 +103082,2586 @@ async function* consumeAsyncIterableInContext(context, iter) { -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function base_coerceToDict(value, defaultKey) { - return value && - !Array.isArray(value) && - // eslint-disable-next-line no-instanceof/no-instanceof - !(value instanceof Date) && - typeof value === "object" - ? value - : { [defaultKey]: value }; + + + + + + + + + + + + + + + + + +/* harmony default export */ const dist_esm = ((/* unused pure expression or super */ null && (zodToJsonSchema))); + +;// CONCATENATED MODULE: ./node_modules/@cfworker/json-schema/dist/esm/deep-compare-strict.js +function deep_compare_strict_deepCompareStrict(a, b) { + const typeofa = typeof a; + if (typeofa !== typeof b) { + return false; + } + if (Array.isArray(a)) { + if (!Array.isArray(b)) { + return false; + } + const length = a.length; + if (length !== b.length) { + return false; + } + for (let i = 0; i < length; i++) { + if (!deep_compare_strict_deepCompareStrict(a[i], b[i])) { + return false; + } + } + return true; + } + if (typeofa === 'object') { + if (!a || !b) { + return a === b; + } + const aKeys = Object.keys(a); + const bKeys = Object.keys(b); + const length = aKeys.length; + if (length !== bKeys.length) { + return false; + } + for (const k of aKeys) { + if (!deep_compare_strict_deepCompareStrict(a[k], b[k])) { + return false; + } + } + return true; + } + return a === b; } -/** - * A Runnable is a generic unit of work that can be invoked, batched, streamed, and/or - * transformed. - */ -class Runnable extends Serializable { - constructor() { - super(...arguments); - Object.defineProperty(this, "lc_runnable", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); + +;// CONCATENATED MODULE: ./node_modules/@cfworker/json-schema/dist/esm/dereference.js + +const schemaKeyword = { + additionalItems: true, + unevaluatedItems: true, + items: true, + contains: true, + additionalProperties: true, + unevaluatedProperties: true, + propertyNames: true, + not: true, + if: true, + then: true, + else: true +}; +const schemaArrayKeyword = { + prefixItems: true, + items: true, + allOf: true, + anyOf: true, + oneOf: true +}; +const schemaMapKeyword = { + $defs: true, + definitions: true, + properties: true, + patternProperties: true, + dependentSchemas: true +}; +const ignoredKeyword = { + id: true, + $id: true, + $ref: true, + $schema: true, + $anchor: true, + $vocabulary: true, + $comment: true, + default: true, + enum: true, + const: true, + required: true, + type: true, + maximum: true, + minimum: true, + exclusiveMaximum: true, + exclusiveMinimum: true, + multipleOf: true, + maxLength: true, + minLength: true, + pattern: true, + format: true, + maxItems: true, + minItems: true, + uniqueItems: true, + maxProperties: true, + minProperties: true +}; +let initialBaseURI = typeof self !== 'undefined' && + self.location && + self.location.origin !== 'null' + ? + new URL(self.location.origin + self.location.pathname + location.search) + : new URL('https://github.com/cfworker'); +function dereference_dereference(schema, lookup = Object.create(null), baseURI = initialBaseURI, basePointer = '') { + if (schema && typeof schema === 'object' && !Array.isArray(schema)) { + const id = schema.$id || schema.id; + if (id) { + const url = new URL(id, baseURI.href); + if (url.hash.length > 1) { + lookup[url.href] = schema; + } + else { + url.hash = ''; + if (basePointer === '') { + baseURI = url; + } + else { + dereference_dereference(schema, lookup, baseURI); + } + } + } } - getName(suffix) { - const name = - // eslint-disable-next-line @typescript-eslint/no-explicit-any - this.name ?? this.constructor.lc_name() ?? this.constructor.name; - return suffix ? `${name}${suffix}` : name; + else if (schema !== true && schema !== false) { + return lookup; } - /** - * Bind arguments to a Runnable, returning a new Runnable. - * @param kwargs - * @returns A new RunnableBinding that, when invoked, will apply the bound args. - */ - bind(kwargs) { - // eslint-disable-next-line @typescript-eslint/no-use-before-define - return new RunnableBinding({ bound: this, kwargs, config: {} }); + const schemaURI = baseURI.href + (basePointer ? '#' + basePointer : ''); + if (lookup[schemaURI] !== undefined) { + throw new Error(`Duplicate schema URI "${schemaURI}".`); } - /** - * Return a new Runnable that maps a list of inputs to a list of outputs, - * by calling invoke() with each input. - */ - map() { - // eslint-disable-next-line @typescript-eslint/no-use-before-define - return new RunnableEach({ bound: this }); + lookup[schemaURI] = schema; + if (schema === true || schema === false) { + return lookup; } - /** - * Add retry logic to an existing runnable. - * @param kwargs - * @returns A new RunnableRetry that, when invoked, will retry according to the parameters. - */ - withRetry(fields) { - // eslint-disable-next-line @typescript-eslint/no-use-before-define - return new RunnableRetry({ - bound: this, - kwargs: {}, - config: {}, - maxAttemptNumber: fields?.stopAfterAttempt, - ...fields, + if (schema.__absolute_uri__ === undefined) { + Object.defineProperty(schema, '__absolute_uri__', { + enumerable: false, + value: schemaURI }); } - /** - * Bind config to a Runnable, returning a new Runnable. - * @param config New configuration parameters to attach to the new runnable. - * @returns A new RunnableBinding with a config matching what's passed. - */ - withConfig(config) { - // eslint-disable-next-line @typescript-eslint/no-use-before-define - return new RunnableBinding({ - bound: this, - config, - kwargs: {}, + if (schema.$ref && schema.__absolute_ref__ === undefined) { + const url = new URL(schema.$ref, baseURI.href); + url.hash = url.hash; + Object.defineProperty(schema, '__absolute_ref__', { + enumerable: false, + value: url.href }); } - /** - * Create a new runnable from the current one that will try invoking - * other passed fallback runnables if the initial invocation fails. - * @param fields.fallbacks Other runnables to call if the runnable errors. - * @returns A new RunnableWithFallbacks. - */ - withFallbacks(fields) { - const fallbacks = Array.isArray(fields) ? fields : fields.fallbacks; - // eslint-disable-next-line @typescript-eslint/no-use-before-define - return new RunnableWithFallbacks({ - runnable: this, - fallbacks, + if (schema.$recursiveRef && schema.__absolute_recursive_ref__ === undefined) { + const url = new URL(schema.$recursiveRef, baseURI.href); + url.hash = url.hash; + Object.defineProperty(schema, '__absolute_recursive_ref__', { + enumerable: false, + value: url.href }); } - _getOptionsList(options, length = 0) { - if (Array.isArray(options) && options.length !== length) { - throw new Error(`Passed "options" must be an array with the same length as the inputs, but got ${options.length} options for ${length} inputs`); - } - if (Array.isArray(options)) { - return options.map(ensureConfig); - } - if (length > 1 && !Array.isArray(options) && options.runId) { - console.warn("Provided runId will be used only for the first element of the batch."); - const subsequent = Object.fromEntries(Object.entries(options).filter(([key]) => key !== "runId")); - return Array.from({ length }, (_, i) => ensureConfig(i === 0 ? options : subsequent)); - } - return Array.from({ length }, () => ensureConfig(options)); + if (schema.$anchor) { + const url = new URL('#' + schema.$anchor, baseURI.href); + lookup[url.href] = schema; } - async batch(inputs, options, batchOptions) { - const configList = this._getOptionsList(options ?? {}, inputs.length); - const maxConcurrency = configList[0]?.maxConcurrency ?? batchOptions?.maxConcurrency; - const caller = new async_caller_AsyncCaller({ - maxConcurrency, - onFailedAttempt: (e) => { - throw e; - }, - }); - const batchCalls = inputs.map((input, i) => caller.call(async () => { - try { - const result = await this.invoke(input, configList[i]); - return result; - } - catch (e) { - if (batchOptions?.returnExceptions) { - return e; + for (let key in schema) { + if (ignoredKeyword[key]) { + continue; + } + const keyBase = `${basePointer}/${encodePointer(key)}`; + const subSchema = schema[key]; + if (Array.isArray(subSchema)) { + if (schemaArrayKeyword[key]) { + const length = subSchema.length; + for (let i = 0; i < length; i++) { + dereference_dereference(subSchema[i], lookup, baseURI, `${keyBase}/${i}`); } - throw e; } - })); - return Promise.all(batchCalls); - } - /** - * Default streaming implementation. - * Subclasses should override this method if they support streaming output. - * @param input - * @param options - */ - async *_streamIterator(input, options) { - yield this.invoke(input, options); - } - /** - * Stream output in chunks. - * @param input - * @param options - * @returns A readable stream that is also an iterable. - */ - async stream(input, options) { - // Buffer the first streamed chunk to allow for initial errors - // to surface immediately. - const config = ensureConfig(options); - const wrappedGenerator = new AsyncGeneratorWithSetup({ - generator: this._streamIterator(input, config), - config, - }); - await wrappedGenerator.setup; - return IterableReadableStream.fromAsyncGenerator(wrappedGenerator); - } - _separateRunnableConfigFromCallOptions(options) { - let runnableConfig; - if (options === undefined) { - runnableConfig = ensureConfig(options); + } + else if (schemaMapKeyword[key]) { + for (let subKey in subSchema) { + dereference_dereference(subSchema[subKey], lookup, baseURI, `${keyBase}/${encodePointer(subKey)}`); + } } else { - runnableConfig = ensureConfig({ - callbacks: options.callbacks, - tags: options.tags, - metadata: options.metadata, - runName: options.runName, - configurable: options.configurable, - recursionLimit: options.recursionLimit, - maxConcurrency: options.maxConcurrency, - runId: options.runId, - timeout: options.timeout, - signal: options.signal, - }); + dereference_dereference(subSchema, lookup, baseURI, keyBase); } - const callOptions = { ...options }; - delete callOptions.callbacks; - delete callOptions.tags; - delete callOptions.metadata; - delete callOptions.runName; - delete callOptions.configurable; - delete callOptions.recursionLimit; - delete callOptions.maxConcurrency; - delete callOptions.runId; - delete callOptions.timeout; - delete callOptions.signal; - return [runnableConfig, callOptions]; } - async _callWithConfig(func, input, options) { - const config = ensureConfig(options); - const callbackManager_ = await getCallbackManagerForConfig(config); - const runManager = await callbackManager_?.handleChainStart(this.toJSON(), base_coerceToDict(input, "input"), config.runId, config?.runType, undefined, undefined, config?.runName ?? this.getName()); - delete config.runId; - let output; - try { - const promise = func.call(this, input, config, runManager); - output = await raceWithSignal(promise, options?.signal); - } - catch (e) { - await runManager?.handleChainError(e); - throw e; - } - await runManager?.handleChainEnd(base_coerceToDict(output, "output")); - return output; + return lookup; +} + +;// CONCATENATED MODULE: ./node_modules/@cfworker/json-schema/dist/esm/format.js +const DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/; +const DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; +const TIME = /^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i; +const HOSTNAME = /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i; +const URIREF = /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; +const URITEMPLATE = /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i; +const URL_ = /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu; +const UUID = /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i; +const JSON_POINTER = /^(?:\/(?:[^~/]|~0|~1)*)*$/; +const JSON_POINTER_URI_FRAGMENT = /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i; +const RELATIVE_JSON_POINTER = /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/; +const FASTDATE = /^\d\d\d\d-[0-1]\d-[0-3]\d$/; +const FASTTIME = /^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i; +const FASTDATETIME = /^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i; +const FASTURIREFERENCE = /^(?:(?:[a-z][a-z0-9+-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i; +const EMAIL = (input) => { + if (input[0] === '"') + return false; + const [name, host, ...rest] = input.split('@'); + if (!name || + !host || + rest.length !== 0 || + name.length > 64 || + host.length > 253) + return false; + if (name[0] === '.' || name.endsWith('.') || name.includes('..')) + return false; + if (!/^[a-z0-9.-]+$/i.test(host) || + !/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(name)) + return false; + return host + .split('.') + .every(part => /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(part)); +}; +const IPV4 = /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/; +const IPV6 = /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i; +const DURATION = (input) => input.length > 1 && + input.length < 80 && + (/^P\d+([.,]\d+)?W$/.test(input) || + (/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(input) && + /^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(input))); +function bind(r) { + return r.test.bind(r); +} +const fullFormat = { + date: format_date, + time: format_time.bind(undefined, false), + 'date-time': date_time, + duration: DURATION, + uri, + 'uri-reference': bind(URIREF), + 'uri-template': bind(URITEMPLATE), + url: bind(URL_), + email: EMAIL, + hostname: bind(HOSTNAME), + ipv4: bind(IPV4), + ipv6: bind(IPV6), + regex: regex, + uuid: bind(UUID), + 'json-pointer': bind(JSON_POINTER), + 'json-pointer-uri-fragment': bind(JSON_POINTER_URI_FRAGMENT), + 'relative-json-pointer': bind(RELATIVE_JSON_POINTER) +}; +const format_fastFormat = { + ...fullFormat, + date: bind(FASTDATE), + time: bind(FASTTIME), + 'date-time': bind(FASTDATETIME), + 'uri-reference': bind(FASTURIREFERENCE) +}; +function isLeapYear(year) { + return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); +} +function format_date(str) { + const matches = str.match(DATE); + if (!matches) + return false; + const year = +matches[1]; + const month = +matches[2]; + const day = +matches[3]; + return (month >= 1 && + month <= 12 && + day >= 1 && + day <= (month == 2 && isLeapYear(year) ? 29 : DAYS[month])); +} +function format_time(full, str) { + const matches = str.match(TIME); + if (!matches) + return false; + const hour = +matches[1]; + const minute = +matches[2]; + const second = +matches[3]; + const timeZone = !!matches[5]; + return (((hour <= 23 && minute <= 59 && second <= 59) || + (hour == 23 && minute == 59 && second == 60)) && + (!full || timeZone)); +} +const DATE_TIME_SEPARATOR = /t|\s/i; +function date_time(str) { + const dateTime = str.split(DATE_TIME_SEPARATOR); + return dateTime.length == 2 && format_date(dateTime[0]) && format_time(true, dateTime[1]); +} +const NOT_URI_FRAGMENT = /\/|:/; +const URI_PATTERN = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; +function uri(str) { + return NOT_URI_FRAGMENT.test(str) && URI_PATTERN.test(str); +} +const Z_ANCHOR = /[^\\]\\Z/; +function regex(str) { + if (Z_ANCHOR.test(str)) + return false; + try { + new RegExp(str, 'u'); + return true; } - /** - * Internal method that handles batching and configuration for a runnable - * It takes a function, input values, and optional configuration, and - * returns a promise that resolves to the output values. - * @param func The function to be executed for each input value. - * @param input The input values to be processed. - * @param config Optional configuration for the function execution. - * @returns A promise that resolves to the output values. - */ - async _batchWithConfig(func, inputs, options, batchOptions) { - const optionsList = this._getOptionsList(options ?? {}, inputs.length); - const callbackManagers = await Promise.all(optionsList.map(getCallbackManagerForConfig)); - const runManagers = await Promise.all(callbackManagers.map(async (callbackManager, i) => { - const handleStartRes = await callbackManager?.handleChainStart(this.toJSON(), base_coerceToDict(inputs[i], "input"), optionsList[i].runId, optionsList[i].runType, undefined, undefined, optionsList[i].runName ?? this.getName()); - delete optionsList[i].runId; - return handleStartRes; - })); - let outputs; - try { - const promise = func.call(this, inputs, optionsList, runManagers, batchOptions); - outputs = await raceWithSignal(promise, optionsList?.[0]?.signal); - } - catch (e) { - await Promise.all(runManagers.map((runManager) => runManager?.handleChainError(e))); - throw e; - } - await Promise.all(runManagers.map((runManager) => runManager?.handleChainEnd(base_coerceToDict(outputs, "output")))); - return outputs; + catch (e) { + return false; } - /** - * Helper method to transform an Iterator of Input values into an Iterator of - * Output values, with callbacks. - * Use this to implement `stream()` or `transform()` in Runnable subclasses. - */ - async *_transformStreamWithConfig(inputGenerator, transformer, options) { - let finalInput; - let finalInputSupported = true; - let finalOutput; - let finalOutputSupported = true; - const config = ensureConfig(options); - const callbackManager_ = await getCallbackManagerForConfig(config); - async function* wrapInputForTracing() { - for await (const chunk of inputGenerator) { - if (finalInputSupported) { - if (finalInput === undefined) { - finalInput = chunk; - } - else { - try { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - finalInput = concat(finalInput, chunk); - } - catch { - finalInput = undefined; - finalInputSupported = false; - } - } +} + +;// CONCATENATED MODULE: ./node_modules/@cfworker/json-schema/dist/esm/types.js +var OutputFormat; +(function (OutputFormat) { + OutputFormat[OutputFormat["Flag"] = 1] = "Flag"; + OutputFormat[OutputFormat["Basic"] = 2] = "Basic"; + OutputFormat[OutputFormat["Detailed"] = 4] = "Detailed"; +})(OutputFormat || (OutputFormat = {})); + +;// CONCATENATED MODULE: ./node_modules/@cfworker/json-schema/dist/esm/validate.js + + + + + +function validate_validate(instance, schema, draft = '2019-09', lookup = dereference(schema), shortCircuit = true, recursiveAnchor = null, instanceLocation = '#', schemaLocation = '#', evaluated = Object.create(null)) { + if (schema === true) { + return { valid: true, errors: [] }; + } + if (schema === false) { + return { + valid: false, + errors: [ + { + instanceLocation, + keyword: 'false', + keywordLocation: instanceLocation, + error: 'False boolean schema.' } - yield chunk; + ] + }; + } + const rawInstanceType = typeof instance; + let instanceType; + switch (rawInstanceType) { + case 'boolean': + case 'number': + case 'string': + instanceType = rawInstanceType; + break; + case 'object': + if (instance === null) { + instanceType = 'null'; } - } - let runManager; - try { - const pipe = await pipeGeneratorWithSetup(transformer.bind(this), wrapInputForTracing(), async () => callbackManager_?.handleChainStart(this.toJSON(), { input: "" }, config.runId, config.runType, undefined, undefined, config.runName ?? this.getName()), options?.signal, config); - delete config.runId; - runManager = pipe.setup; - const streamEventsHandler = runManager?.handlers.find(isStreamEventsHandler); - let iterator = pipe.output; - if (streamEventsHandler !== undefined && runManager !== undefined) { - iterator = streamEventsHandler.tapOutputIterable(runManager.runId, iterator); + else if (Array.isArray(instance)) { + instanceType = 'array'; } - const streamLogHandler = runManager?.handlers.find(isLogStreamHandler); - if (streamLogHandler !== undefined && runManager !== undefined) { - iterator = streamLogHandler.tapOutputIterable(runManager.runId, iterator); + else { + instanceType = 'object'; } - for await (const chunk of iterator) { - yield chunk; - if (finalOutputSupported) { - if (finalOutput === undefined) { - finalOutput = chunk; - } - else { - try { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - finalOutput = concat(finalOutput, chunk); - } - catch { - finalOutput = undefined; - finalOutputSupported = false; - } - } - } + break; + default: + throw new Error(`Instances of "${rawInstanceType}" type are not supported.`); + } + const { $ref, $recursiveRef, $recursiveAnchor, type: $type, const: $const, enum: $enum, required: $required, not: $not, anyOf: $anyOf, allOf: $allOf, oneOf: $oneOf, if: $if, then: $then, else: $else, format: $format, properties: $properties, patternProperties: $patternProperties, additionalProperties: $additionalProperties, unevaluatedProperties: $unevaluatedProperties, minProperties: $minProperties, maxProperties: $maxProperties, propertyNames: $propertyNames, dependentRequired: $dependentRequired, dependentSchemas: $dependentSchemas, dependencies: $dependencies, prefixItems: $prefixItems, items: $items, additionalItems: $additionalItems, unevaluatedItems: $unevaluatedItems, contains: $contains, minContains: $minContains, maxContains: $maxContains, minItems: $minItems, maxItems: $maxItems, uniqueItems: $uniqueItems, minimum: $minimum, maximum: $maximum, exclusiveMinimum: $exclusiveMinimum, exclusiveMaximum: $exclusiveMaximum, multipleOf: $multipleOf, minLength: $minLength, maxLength: $maxLength, pattern: $pattern, __absolute_ref__, __absolute_recursive_ref__ } = schema; + const errors = []; + if ($recursiveAnchor === true && recursiveAnchor === null) { + recursiveAnchor = schema; + } + if ($recursiveRef === '#') { + const refSchema = recursiveAnchor === null + ? lookup[__absolute_recursive_ref__] + : recursiveAnchor; + const keywordLocation = `${schemaLocation}/$recursiveRef`; + const result = validate_validate(instance, recursiveAnchor === null ? schema : recursiveAnchor, draft, lookup, shortCircuit, refSchema, instanceLocation, keywordLocation, evaluated); + if (!result.valid) { + errors.push({ + instanceLocation, + keyword: '$recursiveRef', + keywordLocation, + error: 'A subschema had errors.' + }, ...result.errors); + } + } + if ($ref !== undefined) { + const uri = __absolute_ref__ || $ref; + const refSchema = lookup[uri]; + if (refSchema === undefined) { + let message = `Unresolved $ref "${$ref}".`; + if (__absolute_ref__ && __absolute_ref__ !== $ref) { + message += ` Absolute URI "${__absolute_ref__}".`; } + message += `\nKnown schemas:\n- ${Object.keys(lookup).join('\n- ')}`; + throw new Error(message); } - catch (e) { - await runManager?.handleChainError(e, undefined, undefined, undefined, { - inputs: base_coerceToDict(finalInput, "input"), + const keywordLocation = `${schemaLocation}/$ref`; + const result = validate_validate(instance, refSchema, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, keywordLocation, evaluated); + if (!result.valid) { + errors.push({ + instanceLocation, + keyword: '$ref', + keywordLocation, + error: 'A subschema had errors.' + }, ...result.errors); + } + if (draft === '4' || draft === '7') { + return { valid: errors.length === 0, errors }; + } + } + if (Array.isArray($type)) { + let length = $type.length; + let valid = false; + for (let i = 0; i < length; i++) { + if (instanceType === $type[i] || + ($type[i] === 'integer' && + instanceType === 'number' && + instance % 1 === 0 && + instance === instance)) { + valid = true; + break; + } + } + if (!valid) { + errors.push({ + instanceLocation, + keyword: 'type', + keywordLocation: `${schemaLocation}/type`, + error: `Instance type "${instanceType}" is invalid. Expected "${$type.join('", "')}".` }); - throw e; } - await runManager?.handleChainEnd(finalOutput ?? {}, undefined, undefined, undefined, { inputs: base_coerceToDict(finalInput, "input") }); } - getGraph(_) { - const graph = new Graph(); - // TODO: Add input schema for runnables - const inputNode = graph.addNode({ - name: `${this.getName()}Input`, - schema: z.any(), - }); - const runnableNode = graph.addNode(this); - // TODO: Add output schemas for runnables - const outputNode = graph.addNode({ - name: `${this.getName()}Output`, - schema: z.any(), - }); - graph.addEdge(inputNode, runnableNode); - graph.addEdge(runnableNode, outputNode); - return graph; + else if ($type === 'integer') { + if (instanceType !== 'number' || instance % 1 || instance !== instance) { + errors.push({ + instanceLocation, + keyword: 'type', + keywordLocation: `${schemaLocation}/type`, + error: `Instance type "${instanceType}" is invalid. Expected "${$type}".` + }); + } } - /** - * Create a new runnable sequence that runs each individual runnable in series, - * piping the output of one runnable into another runnable or runnable-like. - * @param coerceable A runnable, function, or object whose values are functions or runnables. - * @returns A new runnable sequence. - */ - pipe(coerceable) { - // eslint-disable-next-line @typescript-eslint/no-use-before-define - return new RunnableSequence({ - first: this, - last: _coerceToRunnable(coerceable), + else if ($type !== undefined && instanceType !== $type) { + errors.push({ + instanceLocation, + keyword: 'type', + keywordLocation: `${schemaLocation}/type`, + error: `Instance type "${instanceType}" is invalid. Expected "${$type}".` }); } - /** - * Pick keys from the dict output of this runnable. Returns a new runnable. - */ - pick(keys) { - // eslint-disable-next-line @typescript-eslint/no-use-before-define - return this.pipe(new RunnablePick(keys)); - } - /** - * Assigns new fields to the dict output of this runnable. Returns a new runnable. - */ - assign(mapping) { - return this.pipe( - // eslint-disable-next-line @typescript-eslint/no-use-before-define - new RunnableAssign( - // eslint-disable-next-line @typescript-eslint/no-use-before-define - new RunnableMap({ steps: mapping }))); - } - /** - * Default implementation of transform, which buffers input and then calls stream. - * Subclasses should override this method if they can start producing output while - * input is still being generated. - * @param generator - * @param options - */ - async *transform(generator, options) { - let finalChunk; - for await (const chunk of generator) { - if (finalChunk === undefined) { - finalChunk = chunk; + if ($const !== undefined) { + if (instanceType === 'object' || instanceType === 'array') { + if (!deepCompareStrict(instance, $const)) { + errors.push({ + instanceLocation, + keyword: 'const', + keywordLocation: `${schemaLocation}/const`, + error: `Instance does not match ${JSON.stringify($const)}.` + }); } - else { - // Make a best effort to gather, for any type that supports concat. - // This method should throw an error if gathering fails. - // eslint-disable-next-line @typescript-eslint/no-explicit-any - finalChunk = concat(finalChunk, chunk); + } + else if (instance !== $const) { + errors.push({ + instanceLocation, + keyword: 'const', + keywordLocation: `${schemaLocation}/const`, + error: `Instance does not match ${JSON.stringify($const)}.` + }); + } + } + if ($enum !== undefined) { + if (instanceType === 'object' || instanceType === 'array') { + if (!$enum.some(value => deepCompareStrict(instance, value))) { + errors.push({ + instanceLocation, + keyword: 'enum', + keywordLocation: `${schemaLocation}/enum`, + error: `Instance does not match any of ${JSON.stringify($enum)}.` + }); } } - yield* this._streamIterator(finalChunk, ensureConfig(options)); + else if (!$enum.some(value => instance === value)) { + errors.push({ + instanceLocation, + keyword: 'enum', + keywordLocation: `${schemaLocation}/enum`, + error: `Instance does not match any of ${JSON.stringify($enum)}.` + }); + } } - /** - * Stream all output from a runnable, as reported to the callback system. - * This includes all inner runs of LLMs, Retrievers, Tools, etc. - * Output is streamed as Log objects, which include a list of - * jsonpatch ops that describe how the state of the run has changed in each - * step, and the final state of the run. - * The jsonpatch ops can be applied in order to construct state. - * @param input - * @param options - * @param streamOptions - */ - async *streamLog(input, options, streamOptions) { - const logStreamCallbackHandler = new LogStreamCallbackHandler({ - ...streamOptions, - autoClose: false, - _schemaFormat: "original", - }); - const config = ensureConfig(options); - yield* this._streamLog(input, logStreamCallbackHandler, config); + if ($not !== undefined) { + const keywordLocation = `${schemaLocation}/not`; + const result = validate_validate(instance, $not, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, keywordLocation); + if (result.valid) { + errors.push({ + instanceLocation, + keyword: 'not', + keywordLocation, + error: 'Instance matched "not" schema.' + }); + } } - async *_streamLog(input, logStreamCallbackHandler, config) { - const { callbacks } = config; - if (callbacks === undefined) { - // eslint-disable-next-line no-param-reassign - config.callbacks = [logStreamCallbackHandler]; + let subEvaluateds = []; + if ($anyOf !== undefined) { + const keywordLocation = `${schemaLocation}/anyOf`; + const errorsLength = errors.length; + let anyValid = false; + for (let i = 0; i < $anyOf.length; i++) { + const subSchema = $anyOf[i]; + const subEvaluated = Object.create(evaluated); + const result = validate_validate(instance, subSchema, draft, lookup, shortCircuit, $recursiveAnchor === true ? recursiveAnchor : null, instanceLocation, `${keywordLocation}/${i}`, subEvaluated); + errors.push(...result.errors); + anyValid = anyValid || result.valid; + if (result.valid) { + subEvaluateds.push(subEvaluated); + } } - else if (Array.isArray(callbacks)) { - // eslint-disable-next-line no-param-reassign - config.callbacks = callbacks.concat([logStreamCallbackHandler]); + if (anyValid) { + errors.length = errorsLength; } else { - const copiedCallbacks = callbacks.copy(); - copiedCallbacks.addHandler(logStreamCallbackHandler, true); - // eslint-disable-next-line no-param-reassign - config.callbacks = copiedCallbacks; + errors.splice(errorsLength, 0, { + instanceLocation, + keyword: 'anyOf', + keywordLocation, + error: 'Instance does not match any subschemas.' + }); } - const runnableStreamPromise = this.stream(input, config); - async function consumeRunnableStream() { - try { - const runnableStream = await runnableStreamPromise; - for await (const chunk of runnableStream) { - const patch = new RunLogPatch({ - ops: [ - { - op: "add", - path: "/streamed_output/-", - value: chunk, - }, - ], - }); - await logStreamCallbackHandler.writer.write(patch); - } + } + if ($allOf !== undefined) { + const keywordLocation = `${schemaLocation}/allOf`; + const errorsLength = errors.length; + let allValid = true; + for (let i = 0; i < $allOf.length; i++) { + const subSchema = $allOf[i]; + const subEvaluated = Object.create(evaluated); + const result = validate_validate(instance, subSchema, draft, lookup, shortCircuit, $recursiveAnchor === true ? recursiveAnchor : null, instanceLocation, `${keywordLocation}/${i}`, subEvaluated); + errors.push(...result.errors); + allValid = allValid && result.valid; + if (result.valid) { + subEvaluateds.push(subEvaluated); } - finally { - await logStreamCallbackHandler.writer.close(); + } + if (allValid) { + errors.length = errorsLength; + } + else { + errors.splice(errorsLength, 0, { + instanceLocation, + keyword: 'allOf', + keywordLocation, + error: `Instance does not match every subschema.` + }); + } + } + if ($oneOf !== undefined) { + const keywordLocation = `${schemaLocation}/oneOf`; + const errorsLength = errors.length; + const matches = $oneOf.filter((subSchema, i) => { + const subEvaluated = Object.create(evaluated); + const result = validate_validate(instance, subSchema, draft, lookup, shortCircuit, $recursiveAnchor === true ? recursiveAnchor : null, instanceLocation, `${keywordLocation}/${i}`, subEvaluated); + errors.push(...result.errors); + if (result.valid) { + subEvaluateds.push(subEvaluated); } + return result.valid; + }).length; + if (matches === 1) { + errors.length = errorsLength; } - const runnableStreamConsumePromise = consumeRunnableStream(); - try { - for await (const log of logStreamCallbackHandler) { - yield log; + else { + errors.splice(errorsLength, 0, { + instanceLocation, + keyword: 'oneOf', + keywordLocation, + error: `Instance does not match exactly one subschema (${matches} matches).` + }); + } + } + if (instanceType === 'object' || instanceType === 'array') { + Object.assign(evaluated, ...subEvaluateds); + } + if ($if !== undefined) { + const keywordLocation = `${schemaLocation}/if`; + const conditionResult = validate_validate(instance, $if, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, keywordLocation, evaluated).valid; + if (conditionResult) { + if ($then !== undefined) { + const thenResult = validate_validate(instance, $then, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, `${schemaLocation}/then`, evaluated); + if (!thenResult.valid) { + errors.push({ + instanceLocation, + keyword: 'if', + keywordLocation, + error: `Instance does not match "then" schema.` + }, ...thenResult.errors); + } } } - finally { - await runnableStreamConsumePromise; + else if ($else !== undefined) { + const elseResult = validate_validate(instance, $else, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, `${schemaLocation}/else`, evaluated); + if (!elseResult.valid) { + errors.push({ + instanceLocation, + keyword: 'if', + keywordLocation, + error: `Instance does not match "else" schema.` + }, ...elseResult.errors); + } } } - streamEvents(input, options, streamOptions) { - let stream; - if (options.version === "v1") { - stream = this._streamEventsV1(input, options, streamOptions); + if (instanceType === 'object') { + if ($required !== undefined) { + for (const key of $required) { + if (!(key in instance)) { + errors.push({ + instanceLocation, + keyword: 'required', + keywordLocation: `${schemaLocation}/required`, + error: `Instance does not have required property "${key}".` + }); + } + } } - else if (options.version === "v2") { - stream = this._streamEventsV2(input, options, streamOptions); + const keys = Object.keys(instance); + if ($minProperties !== undefined && keys.length < $minProperties) { + errors.push({ + instanceLocation, + keyword: 'minProperties', + keywordLocation: `${schemaLocation}/minProperties`, + error: `Instance does not have at least ${$minProperties} properties.` + }); } - else { - throw new Error(`Only versions "v1" and "v2" of the schema are currently supported.`); + if ($maxProperties !== undefined && keys.length > $maxProperties) { + errors.push({ + instanceLocation, + keyword: 'maxProperties', + keywordLocation: `${schemaLocation}/maxProperties`, + error: `Instance does not have at least ${$maxProperties} properties.` + }); } - if (options.encoding === "text/event-stream") { - return convertToHttpEventStream(stream); + if ($propertyNames !== undefined) { + const keywordLocation = `${schemaLocation}/propertyNames`; + for (const key in instance) { + const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`; + const result = validate_validate(key, $propertyNames, draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, keywordLocation); + if (!result.valid) { + errors.push({ + instanceLocation, + keyword: 'propertyNames', + keywordLocation, + error: `Property name "${key}" does not match schema.` + }, ...result.errors); + } + } } - else { - return IterableReadableStream.fromAsyncGenerator(stream); + if ($dependentRequired !== undefined) { + const keywordLocation = `${schemaLocation}/dependantRequired`; + for (const key in $dependentRequired) { + if (key in instance) { + const required = $dependentRequired[key]; + for (const dependantKey of required) { + if (!(dependantKey in instance)) { + errors.push({ + instanceLocation, + keyword: 'dependentRequired', + keywordLocation, + error: `Instance has "${key}" but does not have "${dependantKey}".` + }); + } + } + } + } } - } - async *_streamEventsV2(input, options, streamOptions) { - const eventStreamer = new EventStreamCallbackHandler({ - ...streamOptions, - autoClose: false, - }); - const config = ensureConfig(options); - const runId = config.runId ?? v4(); - config.runId = runId; - const callbacks = config.callbacks; - if (callbacks === undefined) { - config.callbacks = [eventStreamer]; + if ($dependentSchemas !== undefined) { + for (const key in $dependentSchemas) { + const keywordLocation = `${schemaLocation}/dependentSchemas`; + if (key in instance) { + const result = validate_validate(instance, $dependentSchemas[key], draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, `${keywordLocation}/${encodePointer(key)}`, evaluated); + if (!result.valid) { + errors.push({ + instanceLocation, + keyword: 'dependentSchemas', + keywordLocation, + error: `Instance has "${key}" but does not match dependant schema.` + }, ...result.errors); + } + } + } } - else if (Array.isArray(callbacks)) { - config.callbacks = callbacks.concat(eventStreamer); + if ($dependencies !== undefined) { + const keywordLocation = `${schemaLocation}/dependencies`; + for (const key in $dependencies) { + if (key in instance) { + const propsOrSchema = $dependencies[key]; + if (Array.isArray(propsOrSchema)) { + for (const dependantKey of propsOrSchema) { + if (!(dependantKey in instance)) { + errors.push({ + instanceLocation, + keyword: 'dependencies', + keywordLocation, + error: `Instance has "${key}" but does not have "${dependantKey}".` + }); + } + } + } + else { + const result = validate_validate(instance, propsOrSchema, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, `${keywordLocation}/${encodePointer(key)}`); + if (!result.valid) { + errors.push({ + instanceLocation, + keyword: 'dependencies', + keywordLocation, + error: `Instance has "${key}" but does not match dependant schema.` + }, ...result.errors); + } + } + } + } } - else { - const copiedCallbacks = callbacks.copy(); - copiedCallbacks.addHandler(eventStreamer, true); - // eslint-disable-next-line no-param-reassign - config.callbacks = copiedCallbacks; + const thisEvaluated = Object.create(null); + let stop = false; + if ($properties !== undefined) { + const keywordLocation = `${schemaLocation}/properties`; + for (const key in $properties) { + if (!(key in instance)) { + continue; + } + const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`; + const result = validate_validate(instance[key], $properties[key], draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, `${keywordLocation}/${encodePointer(key)}`); + if (result.valid) { + evaluated[key] = thisEvaluated[key] = true; + } + else { + stop = shortCircuit; + errors.push({ + instanceLocation, + keyword: 'properties', + keywordLocation, + error: `Property "${key}" does not match schema.` + }, ...result.errors); + if (stop) + break; + } + } } - const abortController = new AbortController(); - // Call the runnable in streaming mode, - // add each chunk to the output stream - const outerThis = this; - async function consumeRunnableStream() { - try { - let signal; - if (options?.signal) { - if ("any" in AbortSignal) { - // Use native AbortSignal.any() if available (Node 19+) - // eslint-disable-next-line @typescript-eslint/no-explicit-any - signal = AbortSignal.any([ - abortController.signal, - options.signal, - ]); + if (!stop && $patternProperties !== undefined) { + const keywordLocation = `${schemaLocation}/patternProperties`; + for (const pattern in $patternProperties) { + const regex = new RegExp(pattern, 'u'); + const subSchema = $patternProperties[pattern]; + for (const key in instance) { + if (!regex.test(key)) { + continue; + } + const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`; + const result = validate_validate(instance[key], subSchema, draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, `${keywordLocation}/${encodePointer(pattern)}`); + if (result.valid) { + evaluated[key] = thisEvaluated[key] = true; } else { - // Fallback for Node 18 and below - just use the provided signal - signal = options.signal; - // Ensure we still abort our controller when the parent signal aborts - options.signal.addEventListener("abort", () => { - abortController.abort(); - }, { once: true }); + stop = shortCircuit; + errors.push({ + instanceLocation, + keyword: 'patternProperties', + keywordLocation, + error: `Property "${key}" matches pattern "${pattern}" but does not match associated schema.` + }, ...result.errors); } } - else { - signal = abortController.signal; - } - const runnableStream = await outerThis.stream(input, { - ...config, - signal, - }); - const tappedStream = eventStreamer.tapOutputIterable(runId, runnableStream); - // eslint-disable-next-line @typescript-eslint/no-unused-vars - for await (const _ of tappedStream) { - // Just iterate so that the callback handler picks up events - if (abortController.signal.aborted) - break; - } - } - finally { - await eventStreamer.finish(); } } - const runnableStreamConsumePromise = consumeRunnableStream(); - let firstEventSent = false; - let firstEventRunId; - try { - for await (const event of eventStreamer) { - // This is a work-around an issue where the inputs into the - // chain are not available until the entire input is consumed. - // As a temporary solution, we'll modify the input to be the input - // that was passed into the chain. - if (!firstEventSent) { - event.data.input = input; - firstEventSent = true; - firstEventRunId = event.run_id; - yield event; + if (!stop && $additionalProperties !== undefined) { + const keywordLocation = `${schemaLocation}/additionalProperties`; + for (const key in instance) { + if (thisEvaluated[key]) { continue; } - if (event.run_id === firstEventRunId && event.event.endsWith("_end")) { - // If it's the end event corresponding to the root runnable - // we dont include the input in the event since it's guaranteed - // to be included in the first event. - if (event.data?.input) { - delete event.data.input; - } + const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`; + const result = validate_validate(instance[key], $additionalProperties, draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, keywordLocation); + if (result.valid) { + evaluated[key] = true; + } + else { + stop = shortCircuit; + errors.push({ + instanceLocation, + keyword: 'additionalProperties', + keywordLocation, + error: `Property "${key}" does not match additional properties schema.` + }, ...result.errors); } - yield event; } } - finally { - abortController.abort(); - await runnableStreamConsumePromise; + else if (!stop && $unevaluatedProperties !== undefined) { + const keywordLocation = `${schemaLocation}/unevaluatedProperties`; + for (const key in instance) { + if (!evaluated[key]) { + const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`; + const result = validate_validate(instance[key], $unevaluatedProperties, draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, keywordLocation); + if (result.valid) { + evaluated[key] = true; + } + else { + errors.push({ + instanceLocation, + keyword: 'unevaluatedProperties', + keywordLocation, + error: `Property "${key}" does not match unevaluated properties schema.` + }, ...result.errors); + } + } + } } } - async *_streamEventsV1(input, options, streamOptions) { - let runLog; - let hasEncounteredStartEvent = false; - const config = ensureConfig(options); - const rootTags = config.tags ?? []; - const rootMetadata = config.metadata ?? {}; - const rootName = config.runName ?? this.getName(); - const logStreamCallbackHandler = new LogStreamCallbackHandler({ - ...streamOptions, - autoClose: false, - _schemaFormat: "streaming_events", - }); - const rootEventFilter = new _RootEventFilter({ - ...streamOptions, - }); - const logStream = this._streamLog(input, logStreamCallbackHandler, config); - for await (const log of logStream) { - if (!runLog) { - runLog = RunLog.fromRunLogPatch(log); + else if (instanceType === 'array') { + if ($maxItems !== undefined && instance.length > $maxItems) { + errors.push({ + instanceLocation, + keyword: 'maxItems', + keywordLocation: `${schemaLocation}/maxItems`, + error: `Array has too many items (${instance.length} > ${$maxItems}).` + }); + } + if ($minItems !== undefined && instance.length < $minItems) { + errors.push({ + instanceLocation, + keyword: 'minItems', + keywordLocation: `${schemaLocation}/minItems`, + error: `Array has too few items (${instance.length} < ${$minItems}).` + }); + } + const length = instance.length; + let i = 0; + let stop = false; + if ($prefixItems !== undefined) { + const keywordLocation = `${schemaLocation}/prefixItems`; + const length2 = Math.min($prefixItems.length, length); + for (; i < length2; i++) { + const result = validate_validate(instance[i], $prefixItems[i], draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, `${keywordLocation}/${i}`); + evaluated[i] = true; + if (!result.valid) { + stop = shortCircuit; + errors.push({ + instanceLocation, + keyword: 'prefixItems', + keywordLocation, + error: `Items did not match schema.` + }, ...result.errors); + if (stop) + break; + } } - else { - runLog = runLog.concat(log); + } + if ($items !== undefined) { + const keywordLocation = `${schemaLocation}/items`; + if (Array.isArray($items)) { + const length2 = Math.min($items.length, length); + for (; i < length2; i++) { + const result = validate_validate(instance[i], $items[i], draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, `${keywordLocation}/${i}`); + evaluated[i] = true; + if (!result.valid) { + stop = shortCircuit; + errors.push({ + instanceLocation, + keyword: 'items', + keywordLocation, + error: `Items did not match schema.` + }, ...result.errors); + if (stop) + break; + } + } } - if (runLog.state === undefined) { - throw new Error(`Internal error: "streamEvents" state is missing. Please open a bug report.`); + else { + for (; i < length; i++) { + const result = validate_validate(instance[i], $items, draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, keywordLocation); + evaluated[i] = true; + if (!result.valid) { + stop = shortCircuit; + errors.push({ + instanceLocation, + keyword: 'items', + keywordLocation, + error: `Items did not match schema.` + }, ...result.errors); + if (stop) + break; + } + } } - // Yield the start event for the root runnable if it hasn't been seen. - // The root run is never filtered out - if (!hasEncounteredStartEvent) { - hasEncounteredStartEvent = true; - const state = { ...runLog.state }; - const event = { - run_id: state.id, - event: `on_${state.type}_start`, - name: rootName, - tags: rootTags, - metadata: rootMetadata, - data: { - input, - }, - }; - if (rootEventFilter.includeEvent(event, state.type)) { - yield event; + if (!stop && $additionalItems !== undefined) { + const keywordLocation = `${schemaLocation}/additionalItems`; + for (; i < length; i++) { + const result = validate_validate(instance[i], $additionalItems, draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, keywordLocation); + evaluated[i] = true; + if (!result.valid) { + stop = shortCircuit; + errors.push({ + instanceLocation, + keyword: 'additionalItems', + keywordLocation, + error: `Items did not match additional items schema.` + }, ...result.errors); + } } } - const paths = log.ops - .filter((op) => op.path.startsWith("/logs/")) - .map((op) => op.path.split("/")[2]); - const dedupedPaths = [...new Set(paths)]; - for (const path of dedupedPaths) { - let eventType; - let data = {}; - const logEntry = runLog.state.logs[path]; - if (logEntry.end_time === undefined) { - if (logEntry.streamed_output.length > 0) { - eventType = "stream"; + } + if ($contains !== undefined) { + if (length === 0 && $minContains === undefined) { + errors.push({ + instanceLocation, + keyword: 'contains', + keywordLocation: `${schemaLocation}/contains`, + error: `Array is empty. It must contain at least one item matching the schema.` + }); + } + else if ($minContains !== undefined && length < $minContains) { + errors.push({ + instanceLocation, + keyword: 'minContains', + keywordLocation: `${schemaLocation}/minContains`, + error: `Array has less items (${length}) than minContains (${$minContains}).` + }); + } + else { + const keywordLocation = `${schemaLocation}/contains`; + const errorsLength = errors.length; + let contained = 0; + for (let j = 0; j < length; j++) { + const result = validate_validate(instance[j], $contains, draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${j}`, keywordLocation); + if (result.valid) { + evaluated[j] = true; + contained++; } else { - eventType = "start"; + errors.push(...result.errors); } } - else { - eventType = "end"; + if (contained >= ($minContains || 0)) { + errors.length = errorsLength; } - if (eventType === "start") { - // Include the inputs with the start event if they are available. - // Usually they will NOT be available for components that operate - // on streams, since those components stream the input and - // don't know its final value until the end of the stream. - if (logEntry.inputs !== undefined) { - data.input = logEntry.inputs; - } + if ($minContains === undefined && + $maxContains === undefined && + contained === 0) { + errors.splice(errorsLength, 0, { + instanceLocation, + keyword: 'contains', + keywordLocation, + error: `Array does not contain item matching schema.` + }); } - else if (eventType === "end") { - if (logEntry.inputs !== undefined) { - data.input = logEntry.inputs; - } - data.output = logEntry.final_output; + else if ($minContains !== undefined && contained < $minContains) { + errors.push({ + instanceLocation, + keyword: 'minContains', + keywordLocation: `${schemaLocation}/minContains`, + error: `Array must contain at least ${$minContains} items matching schema. Only ${contained} items were found.` + }); } - else if (eventType === "stream") { - const chunkCount = logEntry.streamed_output.length; - if (chunkCount !== 1) { - throw new Error(`Expected exactly one chunk of streamed output, got ${chunkCount} instead. Encountered in: "${logEntry.name}"`); - } - data = { chunk: logEntry.streamed_output[0] }; - // Clean up the stream, we don't need it anymore. - // And this avoids duplicates as well! - logEntry.streamed_output = []; + else if ($maxContains !== undefined && contained > $maxContains) { + errors.push({ + instanceLocation, + keyword: 'maxContains', + keywordLocation: `${schemaLocation}/maxContains`, + error: `Array may contain at most ${$maxContains} items matching schema. ${contained} items were found.` + }); } - yield { - event: `on_${logEntry.type}_${eventType}`, - name: logEntry.name, - run_id: logEntry.id, - tags: logEntry.tags, - metadata: logEntry.metadata, - data, - }; } - // Finally, we take care of the streaming output from the root chain - // if there is any. - const { state } = runLog; - if (state.streamed_output.length > 0) { - const chunkCount = state.streamed_output.length; - if (chunkCount !== 1) { - throw new Error(`Expected exactly one chunk of streamed output, got ${chunkCount} instead. Encountered in: "${state.name}"`); + } + if (!stop && $unevaluatedItems !== undefined) { + const keywordLocation = `${schemaLocation}/unevaluatedItems`; + for (i; i < length; i++) { + if (evaluated[i]) { + continue; } - const data = { chunk: state.streamed_output[0] }; - // Clean up the stream, we don't need it anymore. - state.streamed_output = []; - const event = { - event: `on_${state.type}_stream`, - run_id: state.id, - tags: rootTags, - metadata: rootMetadata, - name: rootName, - data, - }; - if (rootEventFilter.includeEvent(event, state.type)) { - yield event; + const result = validate_validate(instance[i], $unevaluatedItems, draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, keywordLocation); + evaluated[i] = true; + if (!result.valid) { + errors.push({ + instanceLocation, + keyword: 'unevaluatedItems', + keywordLocation, + error: `Items did not match unevaluated items schema.` + }, ...result.errors); } } } - const state = runLog?.state; - if (state !== undefined) { - // Finally, yield the end event for the root runnable. - const event = { - event: `on_${state.type}_end`, - name: rootName, - run_id: state.id, - tags: rootTags, - metadata: rootMetadata, - data: { - output: state.final_output, - }, - }; - if (rootEventFilter.includeEvent(event, state.type)) - yield event; + if ($uniqueItems) { + for (let j = 0; j < length; j++) { + const a = instance[j]; + const ao = typeof a === 'object' && a !== null; + for (let k = 0; k < length; k++) { + if (j === k) { + continue; + } + const b = instance[k]; + const bo = typeof b === 'object' && b !== null; + if (a === b || (ao && bo && deepCompareStrict(a, b))) { + errors.push({ + instanceLocation, + keyword: 'uniqueItems', + keywordLocation: `${schemaLocation}/uniqueItems`, + error: `Duplicate items at indexes ${j} and ${k}.` + }); + j = Number.MAX_SAFE_INTEGER; + k = Number.MAX_SAFE_INTEGER; + } + } + } + } + } + else if (instanceType === 'number') { + if (draft === '4') { + if ($minimum !== undefined && + (($exclusiveMinimum === true && instance <= $minimum) || + instance < $minimum)) { + errors.push({ + instanceLocation, + keyword: 'minimum', + keywordLocation: `${schemaLocation}/minimum`, + error: `${instance} is less than ${$exclusiveMinimum ? 'or equal to ' : ''} ${$minimum}.` + }); + } + if ($maximum !== undefined && + (($exclusiveMaximum === true && instance >= $maximum) || + instance > $maximum)) { + errors.push({ + instanceLocation, + keyword: 'maximum', + keywordLocation: `${schemaLocation}/maximum`, + error: `${instance} is greater than ${$exclusiveMaximum ? 'or equal to ' : ''} ${$maximum}.` + }); + } + } + else { + if ($minimum !== undefined && instance < $minimum) { + errors.push({ + instanceLocation, + keyword: 'minimum', + keywordLocation: `${schemaLocation}/minimum`, + error: `${instance} is less than ${$minimum}.` + }); + } + if ($maximum !== undefined && instance > $maximum) { + errors.push({ + instanceLocation, + keyword: 'maximum', + keywordLocation: `${schemaLocation}/maximum`, + error: `${instance} is greater than ${$maximum}.` + }); + } + if ($exclusiveMinimum !== undefined && instance <= $exclusiveMinimum) { + errors.push({ + instanceLocation, + keyword: 'exclusiveMinimum', + keywordLocation: `${schemaLocation}/exclusiveMinimum`, + error: `${instance} is less than ${$exclusiveMinimum}.` + }); + } + if ($exclusiveMaximum !== undefined && instance >= $exclusiveMaximum) { + errors.push({ + instanceLocation, + keyword: 'exclusiveMaximum', + keywordLocation: `${schemaLocation}/exclusiveMaximum`, + error: `${instance} is greater than or equal to ${$exclusiveMaximum}.` + }); + } + } + if ($multipleOf !== undefined) { + const remainder = instance % $multipleOf; + if (Math.abs(0 - remainder) >= 1.1920929e-7 && + Math.abs($multipleOf - remainder) >= 1.1920929e-7) { + errors.push({ + instanceLocation, + keyword: 'multipleOf', + keywordLocation: `${schemaLocation}/multipleOf`, + error: `${instance} is not a multiple of ${$multipleOf}.` + }); + } + } + } + else if (instanceType === 'string') { + const length = $minLength === undefined && $maxLength === undefined + ? 0 + : ucs2length(instance); + if ($minLength !== undefined && length < $minLength) { + errors.push({ + instanceLocation, + keyword: 'minLength', + keywordLocation: `${schemaLocation}/minLength`, + error: `String is too short (${length} < ${$minLength}).` + }); + } + if ($maxLength !== undefined && length > $maxLength) { + errors.push({ + instanceLocation, + keyword: 'maxLength', + keywordLocation: `${schemaLocation}/maxLength`, + error: `String is too long (${length} > ${$maxLength}).` + }); + } + if ($pattern !== undefined && !new RegExp($pattern, 'u').test(instance)) { + errors.push({ + instanceLocation, + keyword: 'pattern', + keywordLocation: `${schemaLocation}/pattern`, + error: `String does not match pattern.` + }); + } + if ($format !== undefined && + fastFormat[$format] && + !fastFormat[$format](instance)) { + errors.push({ + instanceLocation, + keyword: 'format', + keywordLocation: `${schemaLocation}/format`, + error: `String does not match format "${$format}".` + }); + } + } + return { valid: errors.length === 0, errors }; +} + +;// CONCATENATED MODULE: ./node_modules/@cfworker/json-schema/dist/esm/validator.js + + +class Validator { + schema; + draft; + shortCircuit; + lookup; + constructor(schema, draft = '2019-09', shortCircuit = true) { + this.schema = schema; + this.draft = draft; + this.shortCircuit = shortCircuit; + this.lookup = dereference(schema); + } + validate(instance) { + return validate(instance, this.schema, this.draft, this.lookup, this.shortCircuit); + } + addSchema(schema, id) { + if (id) { + schema = { ...schema, $id: id }; } + dereference(schema, this.lookup); + } +} + +;// CONCATENATED MODULE: ./node_modules/@cfworker/json-schema/dist/esm/index.js + + + + + + + + + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/types/zod.js + +function isZodSchemaV4(schema) { + if (typeof schema !== "object" || schema === null) { + return false; } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - static isRunnable(thing) { - return isRunnableInterface(thing); + const obj = schema; + if (!("_zod" in obj)) { + return false; } - /** - * Bind lifecycle listeners to a Runnable, returning a new Runnable. - * The Run object contains information about the run, including its id, - * type, input, output, error, startTime, endTime, and any tags or metadata - * added to the run. - * - * @param {Object} params - The object containing the callback functions. - * @param {(run: Run) => void} params.onStart - Called before the runnable starts running, with the Run object. - * @param {(run: Run) => void} params.onEnd - Called after the runnable finishes running, with the Run object. - * @param {(run: Run) => void} params.onError - Called if the runnable throws an error, with the Run object. - */ - withListeners({ onStart, onEnd, onError, }) { - // eslint-disable-next-line @typescript-eslint/no-use-before-define - return new RunnableBinding({ - bound: this, - config: {}, - configFactories: [ - (config) => ({ - callbacks: [ - new RootListenersTracer({ - config, - onStart, - onEnd, - onError, - }), - ], - }), - ], - }); + const zod = obj._zod; + return (typeof zod === "object" && + zod !== null && + "def" in zod); +} +function isZodSchemaV3(schema) { + if (typeof schema !== "object" || schema === null) { + return false; } - /** - * Convert a runnable to a tool. Return a new instance of `RunnableToolLike` - * which contains the runnable, name, description and schema. - * - * @template {T extends RunInput = RunInput} RunInput - The input type of the runnable. Should be the same as the `RunInput` type of the runnable. - * - * @param fields - * @param {string | undefined} [fields.name] The name of the tool. If not provided, it will default to the name of the runnable. - * @param {string | undefined} [fields.description] The description of the tool. Falls back to the description on the Zod schema if not provided, or undefined if neither are provided. - * @param {z.ZodType} [fields.schema] The Zod schema for the input of the tool. Infers the Zod type from the input type of the runnable. - * @returns {RunnableToolLike, RunOutput>} An instance of `RunnableToolLike` which is a runnable that can be used as a tool. - */ - asTool(fields) { - return convertRunnableToTool(this, fields); + const obj = schema; + if (!("_def" in obj) || "_zod" in obj) { + return false; + } + const def = obj._def; + return (typeof def === "object" && + def != null && + "typeName" in def); +} +/** Backward compatible isZodSchema for Zod 3 */ +function isZodSchema(schema) { + if (isZodSchemaV4(schema)) { + console.warn("[WARNING] Attempting to use Zod 4 schema in a context where Zod 3 schema is expected. This may cause unexpected behavior."); } + return isZodSchemaV3(schema); } /** - * A runnable that delegates calls to another runnable with a set of kwargs. - * @example - * ```typescript - * import { - * type RunnableConfig, - * RunnableLambda, - * } from "@langchain/core/runnables"; - * - * const enhanceProfile = ( - * profile: Record, - * config?: RunnableConfig - * ) => { - * if (config?.configurable?.role) { - * return { ...profile, role: config.configurable.role }; - * } - * return profile; - * }; - * - * const runnable = RunnableLambda.from(enhanceProfile); - * - * // Bind configuration to the runnable to set the user's role dynamically - * const adminRunnable = runnable.bind({ configurable: { role: "Admin" } }); - * const userRunnable = runnable.bind({ configurable: { role: "User" } }); - * - * const result1 = await adminRunnable.invoke({ - * name: "Alice", - * email: "alice@example.com" - * }); - * - * // { name: "Alice", email: "alice@example.com", role: "Admin" } - * - * const result2 = await userRunnable.invoke({ - * name: "Bob", - * email: "bob@example.com" - * }); + * Given either a Zod schema, or plain object, determine if the input is a Zod schema. * - * // { name: "Bob", email: "bob@example.com", role: "User" } - * ``` + * @param {unknown} input + * @returns {boolean} Whether or not the provided input is a Zod schema. */ -class RunnableBinding extends Runnable { - static lc_name() { - return "RunnableBinding"; +function isInteropZodSchema(input) { + if (!input) { + return false; } - constructor(fields) { - super(fields); - Object.defineProperty(this, "lc_namespace", { - enumerable: true, - configurable: true, - writable: true, - value: ["langchain_core", "runnables"] - }); - Object.defineProperty(this, "lc_serializable", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - Object.defineProperty(this, "bound", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "config", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "kwargs", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "configFactories", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.bound = fields.bound; - this.kwargs = fields.kwargs; - this.config = fields.config; - this.configFactories = fields.configFactories; + if (typeof input !== "object") { + return false; } - getName(suffix) { - return this.bound.getName(suffix); + if (Array.isArray(input)) { + return false; } - async _mergeConfig(...options) { - const config = mergeConfigs(this.config, ...options); - return mergeConfigs(config, ...(this.configFactories - ? await Promise.all(this.configFactories.map(async (configFactory) => await configFactory(config))) - : [])); + if (isZodSchemaV4(input) || + isZodSchemaV3(input)) { + return true; } - bind(kwargs) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - return new this.constructor({ - bound: this.bound, - kwargs: { ...this.kwargs, ...kwargs }, - config: this.config, - }); + return false; +} +/** + * Asynchronously parses the input using the provided Zod schema (v3 or v4) and returns a safe parse result. + * This function handles both Zod v3 and v4 schemas, returning a result object indicating success or failure. + * + * @template T - The expected output type of the schema. + * @param {InteropZodType} schema - The Zod schema (v3 or v4) to use for parsing. + * @param {unknown} input - The input value to parse. + * @returns {Promise>} A promise that resolves to a safe parse result object. + * @throws {Error} If the schema is not a recognized Zod v3 or v4 schema. + */ +async function interopSafeParseAsync(schema, input) { + if (isZodSchemaV4(schema)) { + try { + const data = await parse_parseAsync(schema, input); + return { + success: true, + data, + }; + } + catch (error) { + return { + success: false, + error: error, + }; + } } - withConfig(config) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - return new this.constructor({ - bound: this.bound, - kwargs: this.kwargs, - config: { ...this.config, ...config }, - }); + if (isZodSchemaV3(schema)) { + return schema.safeParse(input); } - withRetry(fields) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - return new this.constructor({ - bound: this.bound.withRetry(fields), - kwargs: this.kwargs, - config: this.config, - }); + throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType"); +} +/** + * Asynchronously parses the input using the provided Zod schema (v3 or v4) and returns the parsed value. + * Throws an error if parsing fails or if the schema is not a recognized Zod v3 or v4 schema. + * + * @template T - The expected output type of the schema. + * @param {InteropZodType} schema - The Zod schema (v3 or v4) to use for parsing. + * @param {unknown} input - The input value to parse. + * @returns {Promise} A promise that resolves to the parsed value. + * @throws {Error} If parsing fails or the schema is not a recognized Zod v3 or v4 schema. + */ +async function interopParseAsync(schema, input) { + if (isZodSchemaV4(schema)) { + return parse_parse(schema, input); } - async invoke(input, options) { - return this.bound.invoke(input, await this._mergeConfig(ensureConfig(options), this.kwargs)); + if (isZodSchemaV3(schema)) { + return schema.parse(input); } - async batch(inputs, options, batchOptions) { - const mergedOptions = Array.isArray(options) - ? await Promise.all(options.map(async (individualOption) => this._mergeConfig(ensureConfig(individualOption), this.kwargs))) - : await this._mergeConfig(ensureConfig(options), this.kwargs); - return this.bound.batch(inputs, mergedOptions, batchOptions); + throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType"); +} +/** + * Safely parses the input using the provided Zod schema (v3 or v4) and returns a result object + * indicating success or failure. This function is compatible with both Zod v3 and v4 schemas. + * + * @template T - The expected output type of the schema. + * @param {InteropZodType} schema - The Zod schema (v3 or v4) to use for parsing. + * @param {unknown} input - The input value to parse. + * @returns {InteropZodSafeParseResult} An object with either the parsed data (on success) + * or the error (on failure). + * @throws {Error} If the schema is not a recognized Zod v3 or v4 schema. + */ +function interopSafeParse(schema, input) { + if (isZodSchemaV4(schema)) { + try { + const data = parse(schema, input); + return { + success: true, + data, + }; + } + catch (error) { + return { + success: false, + error: error, + }; + } } - async *_streamIterator(input, options) { - yield* this.bound._streamIterator(input, await this._mergeConfig(ensureConfig(options), this.kwargs)); + if (isZodSchemaV3(schema)) { + return schema.safeParse(input); } - async stream(input, options) { - return this.bound.stream(input, await this._mergeConfig(ensureConfig(options), this.kwargs)); + throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType"); +} +/** + * Parses the input using the provided Zod schema (v3 or v4) and returns the parsed value. + * Throws an error if parsing fails or if the schema is not a recognized Zod v3 or v4 schema. + * + * @template T - The expected output type of the schema. + * @param {InteropZodType} schema - The Zod schema (v3 or v4) to use for parsing. + * @param {unknown} input - The input value to parse. + * @returns {T} The parsed value. + * @throws {Error} If parsing fails or the schema is not a recognized Zod v3 or v4 schema. + */ +function interopParse(schema, input) { + if (isZodSchemaV4(schema)) { + return parse(schema, input); } - async *transform(generator, options) { - yield* this.bound.transform(generator, await this._mergeConfig(ensureConfig(options), this.kwargs)); + if (isZodSchemaV3(schema)) { + return schema.parse(input); } - streamEvents(input, options, streamOptions) { - // eslint-disable-next-line @typescript-eslint/no-this-alias - const outerThis = this; - const generator = async function* () { - yield* outerThis.bound.streamEvents(input, { - ...(await outerThis._mergeConfig(ensureConfig(options), outerThis.kwargs)), - version: options.version, - }, streamOptions); - }; - return IterableReadableStream.fromAsyncGenerator(generator()); + throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType"); +} +/** + * Retrieves the description from a schema definition (v3, v4, or plain object), if available. + * + * @param {unknown} schema - The schema to extract the description from. + * @returns {string | undefined} The description of the schema, or undefined if not present. + */ +function getSchemaDescription(schema) { + if (isZodSchemaV4(schema)) { + return registries_globalRegistry.get(schema)?.description; } - static isRunnableBinding( - // eslint-disable-next-line @typescript-eslint/no-explicit-any - thing - // eslint-disable-next-line @typescript-eslint/no-explicit-any - ) { - return thing.bound && Runnable.isRunnable(thing.bound); + if (isZodSchemaV3(schema)) { + return schema.description; } - /** - * Bind lifecycle listeners to a Runnable, returning a new Runnable. - * The Run object contains information about the run, including its id, - * type, input, output, error, startTime, endTime, and any tags or metadata - * added to the run. - * - * @param {Object} params - The object containing the callback functions. - * @param {(run: Run) => void} params.onStart - Called before the runnable starts running, with the Run object. - * @param {(run: Run) => void} params.onEnd - Called after the runnable finishes running, with the Run object. - * @param {(run: Run) => void} params.onError - Called if the runnable throws an error, with the Run object. - */ - withListeners({ onStart, onEnd, onError, }) { - return new RunnableBinding({ - bound: this.bound, - kwargs: this.kwargs, - config: this.config, - configFactories: [ - (config) => ({ - callbacks: [ - new RootListenersTracer({ - config, - onStart, - onEnd, - onError, - }), - ], - }), - ], - }); + if ("description" in schema && typeof schema.description === "string") { + return schema.description; } + return undefined; } /** - * A runnable that delegates calls to another runnable - * with each element of the input sequence. - * @example - * ```typescript - * import { RunnableEach, RunnableLambda } from "@langchain/core/runnables"; + * Determines if the provided Zod schema is "shapeless". + * A shapeless schema is one that does not define any object shape, + * such as ZodString, ZodNumber, ZodBoolean, ZodAny, etc. + * For ZodObject, it must have no shape keys to be considered shapeless. + * ZodRecord schemas are considered shapeless since they define dynamic + * key-value mappings without fixed keys. * - * const toUpperCase = (input: string): string => input.toUpperCase(); - * const addGreeting = (input: string): string => `Hello, ${input}!`; - * - * const upperCaseLambda = RunnableLambda.from(toUpperCase); - * const greetingLambda = RunnableLambda.from(addGreeting); + * @param schema The Zod schema to check. + * @returns {boolean} True if the schema is shapeless, false otherwise. + */ +function isShapelessZodSchema(schema) { + if (!isInteropZodSchema(schema)) { + return false; + } + // Check for v3 schemas + if (isZodSchemaV3(schema)) { + // @ts-expect-error - zod v3 types are not compatible with zod v4 types + const def = schema._def; + // ZodObject is only shaped if it has actual shape keys + if (def.typeName === "ZodObject") { + const obj = schema; + return !obj.shape || Object.keys(obj.shape).length === 0; + } + // ZodRecord is shapeless (dynamic key-value mapping) + if (def.typeName === "ZodRecord") { + return true; + } + } + // Check for v4 schemas + if (isZodSchemaV4(schema)) { + const def = schema._zod.def; + // Object type is only shaped if it has actual shape keys + if (def.type === "object") { + const obj = schema; + return !obj.shape || Object.keys(obj.shape).length === 0; + } + // Record type is shapeless (dynamic key-value mapping) + if (def.type === "record") { + return true; + } + } + // For other schemas, check if they have a `shape` property + // If they don't have shape, they're likely shapeless + if (typeof schema === "object" && schema !== null && !("shape" in schema)) { + return true; + } + return false; +} +/** + * Determines if the provided Zod schema should be treated as a simple string schema + * that maps to DynamicTool. This aligns with the type-level constraint of + * InteropZodType which only matches basic string schemas. + * If the provided schema is just z.string(), we can make the determination that + * the tool is just a generic string tool that doesn't require any input validation. * - * const chain = new RunnableEach({ - * bound: upperCaseLambda.pipe(greetingLambda), - * }); + * This function only returns true for basic ZodString schemas, including: + * - Basic string schemas (z.string()) + * - String schemas with validations (z.string().min(1), z.string().email(), etc.) * - * const result = await chain.invoke(["alice", "bob", "carol"]) + * This function returns false for everything else, including: + * - String schemas with defaults (z.string().default("value")) + * - Branded string schemas (z.string().brand<"UserId">()) + * - String schemas with catch operations (z.string().catch("default")) + * - Optional/nullable string schemas (z.string().optional()) + * - Transformed schemas (z.string().transform() or z.object().transform()) + * - Object or record schemas, even if they're empty + * - Any other schema type * - * // ["Hello, ALICE!", "Hello, BOB!", "Hello, CAROL!"] - * ``` + * @param schema The Zod schema to check. + * @returns {boolean} True if the schema is a basic ZodString, false otherwise. */ -class RunnableEach extends Runnable { - static lc_name() { - return "RunnableEach"; +function isSimpleStringZodSchema(schema) { + if (!isInteropZodSchema(schema)) { + return false; } - constructor(fields) { - super(fields); - Object.defineProperty(this, "lc_serializable", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - Object.defineProperty(this, "lc_namespace", { - enumerable: true, - configurable: true, - writable: true, - value: ["langchain_core", "runnables"] - }); - Object.defineProperty(this, "bound", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.bound = fields.bound; + // For v3 schemas + if (isZodSchemaV3(schema)) { + // @ts-expect-error - zod v3 types are not compatible with zod v4 types + const def = schema._def; + // Only accept basic ZodString + return def.typeName === "ZodString"; } - /** - * Binds the runnable with the specified arguments. - * @param kwargs The arguments to bind the runnable with. - * @returns A new instance of the `RunnableEach` class that is bound with the specified arguments. - */ - bind(kwargs) { - return new RunnableEach({ - bound: this.bound.bind(kwargs), - }); + // For v4 schemas + if (isZodSchemaV4(schema)) { + const def = schema._zod.def; + // Only accept basic string type + return def.type === "string"; } - /** - * Invokes the runnable with the specified input and configuration. - * @param input The input to invoke the runnable with. - * @param config The configuration to invoke the runnable with. - * @returns A promise that resolves to the output of the runnable. - */ - async invoke(inputs, config) { - return this._callWithConfig(this._invoke.bind(this), inputs, config); + return false; +} +function isZodObjectV3(obj) { + // Zod v3 object schemas have _def.typeName === "ZodObject" + if (typeof obj === "object" && + obj !== null && + "_def" in obj && + typeof obj._def === "object" && + obj._def !== null && + "typeName" in obj._def && + obj._def.typeName === "ZodObject") { + return true; } - /** - * A helper method that is used to invoke the runnable with the specified input and configuration. - * @param input The input to invoke the runnable with. - * @param config The configuration to invoke the runnable with. - * @returns A promise that resolves to the output of the runnable. - */ - async _invoke(inputs, config, runManager) { - return this.bound.batch(inputs, patchConfig(config, { callbacks: runManager?.getChild() })); + return false; +} +function isZodObjectV4(obj) { + if (!isZodSchemaV4(obj)) + return false; + // Zod v4 object schemas have _zod.def.type === "object" + if (typeof obj === "object" && + obj !== null && + "_zod" in obj && + typeof obj._zod === "object" && + obj._zod !== null && + "def" in obj._zod && + typeof obj._zod.def === "object" && + obj._zod.def !== null && + "type" in obj._zod.def && + obj._zod.def.type === "object") { + return true; } - /** - * Bind lifecycle listeners to a Runnable, returning a new Runnable. - * The Run object contains information about the run, including its id, - * type, input, output, error, startTime, endTime, and any tags or metadata - * added to the run. - * - * @param {Object} params - The object containing the callback functions. - * @param {(run: Run) => void} params.onStart - Called before the runnable starts running, with the Run object. - * @param {(run: Run) => void} params.onEnd - Called after the runnable finishes running, with the Run object. - * @param {(run: Run) => void} params.onError - Called if the runnable throws an error, with the Run object. - */ - withListeners({ onStart, onEnd, onError, }) { - return new RunnableEach({ - bound: this.bound.withListeners({ onStart, onEnd, onError }), - }); + return false; +} +function isZodArrayV4(obj) { + if (!isZodSchemaV4(obj)) + return false; + // Zod v4 array schemas have _zod.def.type === "array" + if (typeof obj === "object" && + obj !== null && + "_zod" in obj && + typeof obj._zod === "object" && + obj._zod !== null && + "def" in obj._zod && + typeof obj._zod.def === "object" && + obj._zod.def !== null && + "type" in obj._zod.def && + obj._zod.def.type === "array") { + return true; } + return false; } /** - * Base class for runnables that can be retried a - * specified number of times. - * @example - * ```typescript - * import { - * RunnableLambda, - * RunnableRetry, - * } from "@langchain/core/runnables"; - * - * // Simulate an API call that fails - * const simulateApiCall = (input: string): string => { - * console.log(`Attempting API call with input: ${input}`); - * throw new Error("API call failed due to network issue"); - * }; + * Determines if the provided value is an InteropZodObject (Zod v3 or v4 object schema). * - * const apiCallLambda = RunnableLambda.from(simulateApiCall); - * - * // Apply retry logic using the .withRetry() method - * const apiCallWithRetry = apiCallLambda.withRetry({ stopAfterAttempt: 3 }); - * - * // Alternatively, create a RunnableRetry instance manually - * const manualRetry = new RunnableRetry({ - * bound: apiCallLambda, - * maxAttemptNumber: 3, - * config: {}, - * }); - * - * // Example invocation using the .withRetry() method - * const res = await apiCallWithRetry - * .invoke("Request 1") - * .catch((error) => { - * console.error("Failed after multiple retries:", error.message); - * }); + * @param obj The value to check. + * @returns {boolean} True if the value is a Zod v3 or v4 object schema, false otherwise. + */ +function isInteropZodObject(obj) { + if (isZodObjectV3(obj)) + return true; + if (isZodObjectV4(obj)) + return true; + return false; +} +/** + * Retrieves the shape (fields) of a Zod object schema, supporting both Zod v3 and v4. * - * // Example invocation using the manual retry instance - * const res2 = await manualRetry - * .invoke("Request 2") - * .catch((error) => { - * console.error("Failed after multiple retries:", error.message); - * }); - * ``` + * @template T - The type of the Zod object schema. + * @param {T} schema - The Zod object schema instance (either v3 or v4). + * @returns {InteropZodObjectShape} The shape of the object schema. + * @throws {Error} If the schema is not a Zod v3 or v4 object. */ -class RunnableRetry extends RunnableBinding { - static lc_name() { - return "RunnableRetry"; - } - constructor(fields) { - super(fields); - Object.defineProperty(this, "lc_namespace", { - enumerable: true, - configurable: true, - writable: true, - value: ["langchain_core", "runnables"] - }); - Object.defineProperty(this, "maxAttemptNumber", { - enumerable: true, - configurable: true, - writable: true, - value: 3 - }); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - Object.defineProperty(this, "onFailedAttempt", { - enumerable: true, - configurable: true, - writable: true, - value: () => { } - }); - this.maxAttemptNumber = fields.maxAttemptNumber ?? this.maxAttemptNumber; - this.onFailedAttempt = fields.onFailedAttempt ?? this.onFailedAttempt; - } - _patchConfigForRetry(attempt, config, runManager) { - const tag = attempt > 1 ? `retry:attempt:${attempt}` : undefined; - return patchConfig(config, { callbacks: runManager?.getChild(tag) }); - } - async _invoke(input, config, runManager) { - return p_retry((attemptNumber) => super.invoke(input, this._patchConfigForRetry(attemptNumber, config, runManager)), { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - onFailedAttempt: (error) => this.onFailedAttempt(error, input), - retries: Math.max(this.maxAttemptNumber - 1, 0), - randomize: true, - }); +function getInteropZodObjectShape(schema) { + if (isZodSchemaV3(schema)) { + return schema.shape; } - /** - * Method that invokes the runnable with the specified input, run manager, - * and config. It handles the retry logic by catching any errors and - * recursively invoking itself with the updated config for the next retry - * attempt. - * @param input The input for the runnable. - * @param runManager The run manager for the runnable. - * @param config The config for the runnable. - * @returns A promise that resolves to the output of the runnable. - */ - async invoke(input, config) { - return this._callWithConfig(this._invoke.bind(this), input, config); + if (isZodSchemaV4(schema)) { + return schema._zod.def.shape; } - async _batch(inputs, configs, runManagers, batchOptions) { - const resultsMap = {}; - try { - await p_retry(async (attemptNumber) => { - const remainingIndexes = inputs - .map((_, i) => i) - .filter((i) => resultsMap[i.toString()] === undefined || - // eslint-disable-next-line no-instanceof/no-instanceof - resultsMap[i.toString()] instanceof Error); - const remainingInputs = remainingIndexes.map((i) => inputs[i]); - const patchedConfigs = remainingIndexes.map((i) => this._patchConfigForRetry(attemptNumber, configs?.[i], runManagers?.[i])); - const results = await super.batch(remainingInputs, patchedConfigs, { - ...batchOptions, - returnExceptions: true, - }); - let firstException; - for (let i = 0; i < results.length; i += 1) { - const result = results[i]; - const resultMapIndex = remainingIndexes[i]; - // eslint-disable-next-line no-instanceof/no-instanceof - if (result instanceof Error) { - if (firstException === undefined) { - firstException = result; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - firstException.input = remainingInputs[i]; - } + throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject"); +} +/** + * Extends a Zod object schema with additional fields, supporting both Zod v3 and v4. + * + * @template T - The type of the Zod object schema. + * @param {T} schema - The Zod object schema instance (either v3 or v4). + * @param {InteropZodObjectShape} extension - The fields to add to the schema. + * @returns {InteropZodObject} The extended Zod object schema. + * @throws {Error} If the schema is not a Zod v3 or v4 object. + */ +function extendInteropZodObject(schema, extension) { + if (isZodSchemaV3(schema)) { + return schema.extend(extension); + } + if (isZodSchemaV4(schema)) { + return util.extend(schema, extension); + } + throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject"); +} +/** + * Returns a partial version of a Zod object schema, making all fields optional. + * Supports both Zod v3 and v4. + * + * @template T - The type of the Zod object schema. + * @param {T} schema - The Zod object schema instance (either v3 or v4). + * @returns {InteropZodObject} The partial Zod object schema. + * @throws {Error} If the schema is not a Zod v3 or v4 object. + */ +function interopZodObjectPartial(schema) { + if (isZodSchemaV3(schema)) { + // z3: .partial() exists and works as expected + return schema.partial(); + } + if (isZodSchemaV4(schema)) { + // z4: util.partial exists and works as expected + return util.partial($ZodOptional, schema, undefined); + } + throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject"); +} +/** + * Returns a strict version of a Zod object schema, disallowing unknown keys. + * Supports both Zod v3 and v4 object schemas. If `recursive` is true, applies strictness + * recursively to all nested object schemas and arrays of object schemas. + * + * @template T - The type of the Zod object schema. + * @param {T} schema - The Zod object schema instance (either v3 or v4). + * @param {boolean} [recursive=false] - Whether to apply strictness recursively to nested objects/arrays. + * @returns {InteropZodObject} The strict Zod object schema. + * @throws {Error} If the schema is not a Zod v3 or v4 object. + */ +function interopZodObjectStrict(schema, recursive = false) { + if (isZodSchemaV3(schema)) { + // TODO: v3 schemas aren't recursively handled here + // (currently not necessary since zodToJsonSchema handles this) + return schema.strict(); + } + if (isZodObjectV4(schema)) { + const outputShape = schema._zod.def.shape; + if (recursive) { + for (const [key, keySchema] of Object.entries(schema._zod.def.shape)) { + // If the shape key is a v4 object schema, we need to make it strict + if (isZodObjectV4(keySchema)) { + const outputSchema = interopZodObjectStrict(keySchema, recursive); + outputShape[key] = outputSchema; + } + // If the shape key is a v4 array schema, we need to make the element + // schema strict if it's an object schema + else if (isZodArrayV4(keySchema)) { + let elementSchema = keySchema._zod.def.element; + if (isZodObjectV4(elementSchema)) { + elementSchema = interopZodObjectStrict(elementSchema, recursive); } - resultsMap[resultMapIndex.toString()] = result; + outputShape[key] = util_clone(keySchema, { + ...keySchema._zod.def, + element: elementSchema, + }); } - if (firstException) { - throw firstException; + // Otherwise, just use the keySchema + else { + outputShape[key] = keySchema; } - return results; - }, { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - onFailedAttempt: (error) => this.onFailedAttempt(error, error.input), - retries: Math.max(this.maxAttemptNumber - 1, 0), - randomize: true, - }); + // Assign meta fields to the keySchema + const meta = registries_globalRegistry.get(keySchema); + if (meta) + registries_globalRegistry.add(outputShape[key], meta); + } } - catch (e) { - if (batchOptions?.returnExceptions !== true) { - throw e; + const modifiedSchema = util_clone(schema, { + ...schema._zod.def, + shape: outputShape, + catchall: _never($ZodNever), + }); + const meta = registries_globalRegistry.get(schema); + if (meta) + registries_globalRegistry.add(modifiedSchema, meta); + return modifiedSchema; + } + throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject"); +} +/** + * Returns a passthrough version of a Zod object schema, allowing unknown keys. + * Supports both Zod v3 and v4 object schemas. If `recursive` is true, applies passthrough + * recursively to all nested object schemas and arrays of object schemas. + * + * @template T - The type of the Zod object schema. + * @param {T} schema - The Zod object schema instance (either v3 or v4). + * @param {boolean} [recursive=false] - Whether to apply passthrough recursively to nested objects/arrays. + * @returns {InteropZodObject} The passthrough Zod object schema. + * @throws {Error} If the schema is not a Zod v3 or v4 object. + */ +function interopZodObjectPassthrough(schema, recursive = false) { + if (isZodObjectV3(schema)) { + // TODO: v3 schemas aren't recursively handled here + // (currently not necessary since zodToJsonSchema handles this) + return schema.passthrough(); + } + if (isZodObjectV4(schema)) { + const outputShape = schema._zod.def.shape; + if (recursive) { + for (const [key, keySchema] of Object.entries(schema._zod.def.shape)) { + // If the shape key is a v4 object schema, we need to make it passthrough + if (isZodObjectV4(keySchema)) { + const outputSchema = interopZodObjectPassthrough(keySchema, recursive); + outputShape[key] = outputSchema; + } + // If the shape key is a v4 array schema, we need to make the element + // schema passthrough if it's an object schema + else if (isZodArrayV4(keySchema)) { + let elementSchema = keySchema._zod.def.element; + if (isZodObjectV4(elementSchema)) { + elementSchema = interopZodObjectPassthrough(elementSchema, recursive); + } + outputShape[key] = clone(keySchema, { + ...keySchema._zod.def, + element: elementSchema, + }); + } + // Otherwise, just use the keySchema + else { + outputShape[key] = keySchema; + } + // Assign meta fields to the keySchema + const meta = globalRegistry.get(keySchema); + if (meta) + globalRegistry.add(outputShape[key], meta); } } - return Object.keys(resultsMap) - .sort((a, b) => parseInt(a, 10) - parseInt(b, 10)) - .map((key) => resultsMap[parseInt(key, 10)]); + const modifiedSchema = clone(schema, { + ...schema._zod.def, + shape: outputShape, + catchall: _unknown($ZodUnknown), + }); + const meta = globalRegistry.get(schema); + if (meta) + globalRegistry.add(modifiedSchema, meta); + return modifiedSchema; } - async batch(inputs, options, batchOptions) { - return this._batchWithConfig(this._batch.bind(this), inputs, options, batchOptions); + throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject"); +} +/** + * Returns a getter function for the default value of a Zod schema, if one is defined. + * Supports both Zod v3 and v4 schemas. If the schema has a default value, + * the returned function will return that value when called. If no default is defined, + * returns undefined. + * + * @template T - The type of the Zod schema. + * @param {T} schema - The Zod schema instance (either v3 or v4). + * @returns {(() => InferInteropZodOutput) | undefined} A function that returns the default value, or undefined if no default is set. + */ +function getInteropZodDefaultGetter(schema) { + if (isZodSchemaV3(schema)) { + try { + const defaultValue = schema.parse(undefined); + return () => defaultValue; + } + catch { + return undefined; + } + } + if (isZodSchemaV4(schema)) { + try { + const defaultValue = parse(schema, undefined); + return () => defaultValue; + } + catch { + return undefined; + } } + return undefined; +} +function isZodTransformV3(schema) { + return (isZodSchemaV3(schema) && + "typeName" in schema._def && + schema._def.typeName === "ZodEffects"); +} +function isZodTransformV4(schema) { + return isZodSchemaV4(schema) && schema._zod.def.type === "pipe"; } /** - * A sequence of runnables, where the output of each is the input of the next. - * @example - * ```typescript - * const promptTemplate = PromptTemplate.fromTemplate( - * "Tell me a joke about {topic}", - * ); - * const chain = RunnableSequence.from([promptTemplate, new ChatOpenAI({})]); - * const result = await chain.invoke({ topic: "bears" }); - * ``` + * Returns the input type of a Zod transform schema, for both v3 and v4. + * If the schema is not a transform, returns undefined. If `recursive` is true, + * recursively processes nested object schemas and arrays of object schemas. + * + * @param schema - The Zod schema instance (v3 or v4) + * @param {boolean} [recursive=false] - Whether to recursively process nested objects/arrays. + * @returns The input Zod schema of the transform, or undefined if not a transform + */ +function interopZodTransformInputSchema(schema, recursive = false) { + // Zod v3: ._def.schema is the input schema for ZodEffects (transform) + if (isZodSchemaV3(schema)) { + if (isZodTransformV3(schema)) { + return interopZodTransformInputSchema(schema._def.schema, recursive); + } + // TODO: v3 schemas aren't recursively handled here + // (currently not necessary since zodToJsonSchema handles this) + return schema; + } + // Zod v4: _def.type is the input schema for ZodEffects (transform) + if (isZodSchemaV4(schema)) { + let outputSchema = schema; + if (isZodTransformV4(schema)) { + outputSchema = interopZodTransformInputSchema(schema._zod.def.in, recursive); + } + if (recursive) { + // Handle nested object schemas + if (isZodObjectV4(outputSchema)) { + const outputShape = outputSchema._zod.def.shape; + for (const [key, keySchema] of Object.entries(outputSchema._zod.def.shape)) { + outputShape[key] = interopZodTransformInputSchema(keySchema, recursive); + } + outputSchema = util_clone(outputSchema, { + ...outputSchema._zod.def, + shape: outputShape, + }); + } + // Handle nested array schemas + else if (isZodArrayV4(outputSchema)) { + const elementSchema = interopZodTransformInputSchema(outputSchema._zod.def.element, recursive); + outputSchema = util_clone(outputSchema, { + ...outputSchema._zod.def, + element: elementSchema, + }); + } + } + const meta = registries_globalRegistry.get(schema); + if (meta) + registries_globalRegistry.add(outputSchema, meta); + return outputSchema; + } + throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType"); +} + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/json_schema.js + + + + + +/** + * Converts a Zod schema or JSON schema to a JSON schema. + * @param schema - The schema to convert. + * @returns The converted schema. */ -class RunnableSequence extends Runnable { - static lc_name() { - return "RunnableSequence"; +function json_schema_toJsonSchema(schema) { + if (isZodSchemaV4(schema)) { + const inputSchema = interopZodTransformInputSchema(schema, true); + if (isZodObjectV4(inputSchema)) { + const strictSchema = interopZodObjectStrict(inputSchema, true); + return toJSONSchema(strictSchema); + } + else { + return toJSONSchema(schema); + } } - constructor(fields) { - super(fields); - Object.defineProperty(this, "first", { + if (isZodSchemaV3(schema)) { + return zodToJsonSchema_zodToJsonSchema(schema); + } + return schema; +} +/** + * Validates if a JSON schema validates only strings. May return false negatives in some edge cases + * (like recursive or unresolvable refs). + * + * @param schema - The schema to validate. + * @returns `true` if the schema validates only strings, `false` otherwise. + */ +function validatesOnlyStrings(schema) { + // Null, undefined, or empty schema + if (!schema || + typeof schema !== "object" || + Object.keys(schema).length === 0 || + Array.isArray(schema)) { + return false; // Validates anything, not just strings + } + // Explicit type constraint + if ("type" in schema) { + if (typeof schema.type === "string") { + return schema.type === "string"; + } + if (Array.isArray(schema.type)) { + // not sure why someone would do `"type": ["string"]` or especially `"type": ["string", + // "string", "string", ...]` but we're not here to judge + return schema.type.every((t) => t === "string"); + } + return false; // Invalid or non-string type + } + // Enum with only string values + if ("enum" in schema) { + return (Array.isArray(schema.enum) && + schema.enum.length > 0 && + schema.enum.every((val) => typeof val === "string")); + } + // String constant + if ("const" in schema) { + return typeof schema.const === "string"; + } + // Schema combinations + if ("allOf" in schema && Array.isArray(schema.allOf)) { + // If any subschema validates only strings, then the overall schema validates only strings + return schema.allOf.some((subschema) => validatesOnlyStrings(subschema)); + } + if (("anyOf" in schema && Array.isArray(schema.anyOf)) || + ("oneOf" in schema && Array.isArray(schema.oneOf))) { + const subschemas = ("anyOf" in schema ? schema.anyOf : schema.oneOf); + // All subschemas must validate only strings + return (subschemas.length > 0 && + subschemas.every((subschema) => validatesOnlyStrings(subschema))); + } + // 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. + if ("not" in schema) { + return false; // The not case can validate non-strings + } + if ("$ref" in schema && typeof schema.$ref === "string") { + const ref = schema.$ref; + const resolved = dereference(schema); + if (resolved[ref]) { + return validatesOnlyStrings(resolved[ref]); + } + return false; + } + // ignore recursive refs and other cases where type is omitted for now + // ignore other cases for now where type is omitted + return false; +} + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/graph.js + + + + +function nodeDataStr(id, data) { + if (id !== undefined && !wrapper_validate(id)) { + return id; + } + else if (isRunnableInterface(data)) { + try { + let dataStr = data.getName(); + dataStr = dataStr.startsWith("Runnable") + ? dataStr.slice("Runnable".length) + : dataStr; + return dataStr; + } + catch (error) { + return data.getName(); + } + } + else { + return data.name ?? "UnknownSchema"; + } +} +function nodeDataJson(node) { + // if node.data implements Runnable + if (isRunnableInterface(node.data)) { + return { + type: "runnable", + data: { + id: node.data.lc_id, + name: node.data.getName(), + }, + }; + } + else { + return { + type: "schema", + data: { ...json_schema_toJsonSchema(node.data.schema), title: node.data.name }, + }; + } +} +class Graph { + constructor(params) { + Object.defineProperty(this, "nodes", { enumerable: true, configurable: true, writable: true, - value: void 0 + value: {} }); - Object.defineProperty(this, "middle", { + Object.defineProperty(this, "edges", { enumerable: true, configurable: true, writable: true, value: [] }); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - Object.defineProperty(this, "last", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "omitSequenceTags", { - enumerable: true, - configurable: true, - writable: true, - value: false - }); - Object.defineProperty(this, "lc_serializable", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - Object.defineProperty(this, "lc_namespace", { - enumerable: true, - configurable: true, - writable: true, - value: ["langchain_core", "runnables"] - }); - this.first = fields.first; - this.middle = fields.middle ?? this.middle; - this.last = fields.last; - this.name = fields.name; - this.omitSequenceTags = fields.omitSequenceTags ?? this.omitSequenceTags; + this.nodes = params?.nodes ?? this.nodes; + this.edges = params?.edges ?? this.edges; } - get steps() { - return [this.first, ...this.middle, this.last]; + // Convert the graph to a JSON-serializable format. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + toJSON() { + const stableNodeIds = {}; + Object.values(this.nodes).forEach((node, i) => { + stableNodeIds[node.id] = wrapper_validate(node.id) ? i : node.id; + }); + return { + nodes: Object.values(this.nodes).map((node) => ({ + id: stableNodeIds[node.id], + ...nodeDataJson(node), + })), + edges: this.edges.map((edge) => { + const item = { + source: stableNodeIds[edge.source], + target: stableNodeIds[edge.target], + }; + if (typeof edge.data !== "undefined") { + item.data = edge.data; + } + if (typeof edge.conditional !== "undefined") { + item.conditional = edge.conditional; + } + return item; + }), + }; } - async invoke(input, options) { - const config = ensureConfig(options); - const callbackManager_ = await getCallbackManagerForConfig(config); - const runManager = await callbackManager_?.handleChainStart(this.toJSON(), base_coerceToDict(input, "input"), config.runId, undefined, undefined, undefined, config?.runName); - delete config.runId; - let nextStepInput = input; - let finalOutput; - try { - const initialSteps = [this.first, ...this.middle]; - for (let i = 0; i < initialSteps.length; i += 1) { - const step = initialSteps[i]; - const promise = step.invoke(nextStepInput, patchConfig(config, { - callbacks: runManager?.getChild(this.omitSequenceTags ? undefined : `seq:step:${i + 1}`), - })); - nextStepInput = await raceWithSignal(promise, options?.signal); - } - // TypeScript can't detect that the last output of the sequence returns RunOutput, so call it out of the loop here - if (options?.signal?.aborted) { - throw new Error("Aborted"); - } - finalOutput = await this.last.invoke(nextStepInput, patchConfig(config, { - callbacks: runManager?.getChild(this.omitSequenceTags ? undefined : `seq:step:${this.steps.length}`), - })); - } - catch (e) { - await runManager?.handleChainError(e); - throw e; + addNode(data, id, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + metadata) { + if (id !== undefined && this.nodes[id] !== undefined) { + throw new Error(`Node with id ${id} already exists`); } - await runManager?.handleChainEnd(base_coerceToDict(finalOutput, "output")); - return finalOutput; + const nodeId = id ?? v4(); + const node = { + id: nodeId, + data, + name: nodeDataStr(id, data), + metadata, + }; + this.nodes[nodeId] = node; + return node; } - async batch(inputs, options, batchOptions) { - const configList = this._getOptionsList(options ?? {}, inputs.length); - const callbackManagers = await Promise.all(configList.map(getCallbackManagerForConfig)); - const runManagers = await Promise.all(callbackManagers.map(async (callbackManager, i) => { - const handleStartRes = await callbackManager?.handleChainStart(this.toJSON(), base_coerceToDict(inputs[i], "input"), configList[i].runId, undefined, undefined, undefined, configList[i].runName); - delete configList[i].runId; - return handleStartRes; - })); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - let nextStepInputs = inputs; - try { - for (let i = 0; i < this.steps.length; i += 1) { - const step = this.steps[i]; - const promise = step.batch(nextStepInputs, runManagers.map((runManager, j) => { - const childRunManager = runManager?.getChild(this.omitSequenceTags ? undefined : `seq:step:${i + 1}`); - return patchConfig(configList[j], { callbacks: childRunManager }); - }), batchOptions); - nextStepInputs = await raceWithSignal(promise, configList[0]?.signal); - } + removeNode(node) { + // Remove the node from the nodes map + delete this.nodes[node.id]; + // Filter out edges connected to the node + this.edges = this.edges.filter((edge) => edge.source !== node.id && edge.target !== node.id); + } + addEdge(source, target, data, conditional) { + if (this.nodes[source.id] === undefined) { + throw new Error(`Source node ${source.id} not in graph`); } - catch (e) { - await Promise.all(runManagers.map((runManager) => runManager?.handleChainError(e))); - throw e; + if (this.nodes[target.id] === undefined) { + throw new Error(`Target node ${target.id} not in graph`); } - await Promise.all(runManagers.map((runManager) => runManager?.handleChainEnd(base_coerceToDict(nextStepInputs, "output")))); - return nextStepInputs; + const edge = { + source: source.id, + target: target.id, + data, + conditional, + }; + this.edges.push(edge); + return edge; } - async *_streamIterator(input, options) { - const callbackManager_ = await getCallbackManagerForConfig(options); - const { runId, ...otherOptions } = options ?? {}; - const runManager = await callbackManager_?.handleChainStart(this.toJSON(), base_coerceToDict(input, "input"), runId, undefined, undefined, undefined, otherOptions?.runName); - const steps = [this.first, ...this.middle, this.last]; - let concatSupported = true; - let finalOutput; - async function* inputGenerator() { - yield input; + firstNode() { + return _firstNode(this); + } + lastNode() { + return _lastNode(this); + } + /** + * Add all nodes and edges from another graph. + * Note this doesn't check for duplicates, nor does it connect the graphs. + */ + extend(graph, prefix = "") { + let finalPrefix = prefix; + const nodeIds = Object.values(graph.nodes).map((node) => node.id); + if (nodeIds.every(wrapper_validate)) { + finalPrefix = ""; } - try { - let finalGenerator = steps[0].transform(inputGenerator(), patchConfig(otherOptions, { - callbacks: runManager?.getChild(this.omitSequenceTags ? undefined : `seq:step:1`), - })); - for (let i = 1; i < steps.length; i += 1) { - const step = steps[i]; - finalGenerator = await step.transform(finalGenerator, patchConfig(otherOptions, { - callbacks: runManager?.getChild(this.omitSequenceTags ? undefined : `seq:step:${i + 1}`), - })); - } - for await (const chunk of finalGenerator) { - options?.signal?.throwIfAborted(); - yield chunk; - if (concatSupported) { - if (finalOutput === undefined) { - finalOutput = chunk; - } - else { - try { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - finalOutput = concat(finalOutput, chunk); - } - catch (e) { - finalOutput = undefined; - concatSupported = false; - } - } - } - } + const prefixed = (id) => { + return finalPrefix ? `${finalPrefix}:${id}` : id; + }; + Object.entries(graph.nodes).forEach(([key, value]) => { + this.nodes[prefixed(key)] = { ...value, id: prefixed(key) }; + }); + const newEdges = graph.edges.map((edge) => { + return { + ...edge, + source: prefixed(edge.source), + target: prefixed(edge.target), + }; + }); + // Add all edges from the other graph + this.edges = [...this.edges, ...newEdges]; + const first = graph.firstNode(); + const last = graph.lastNode(); + return [ + first ? { id: prefixed(first.id), data: first.data } : undefined, + last ? { id: prefixed(last.id), data: last.data } : undefined, + ]; + } + trimFirstNode() { + const firstNode = this.firstNode(); + if (firstNode && _firstNode(this, [firstNode.id])) { + this.removeNode(firstNode); } - catch (e) { - await runManager?.handleChainError(e); - throw e; + } + trimLastNode() { + const lastNode = this.lastNode(); + if (lastNode && _lastNode(this, [lastNode.id])) { + this.removeNode(lastNode); } - await runManager?.handleChainEnd(base_coerceToDict(finalOutput, "output")); } - getGraph(config) { - const graph = new Graph(); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - let currentLastNode = null; - this.steps.forEach((step, index) => { - const stepGraph = step.getGraph(config); - if (index !== 0) { - stepGraph.trimFirstNode(); - } - if (index !== this.steps.length - 1) { - stepGraph.trimLastNode(); - } - graph.extend(stepGraph); - const stepFirstNode = stepGraph.firstNode(); - if (!stepFirstNode) { - throw new Error(`Runnable ${step} has no first node`); + /** + * Return a new graph with all nodes re-identified, + * using their unique, readable names where possible. + */ + reid() { + const nodeLabels = Object.fromEntries(Object.values(this.nodes).map((node) => [node.id, node.name])); + const nodeLabelCounts = new Map(); + Object.values(nodeLabels).forEach((label) => { + nodeLabelCounts.set(label, (nodeLabelCounts.get(label) || 0) + 1); + }); + const getNodeId = (nodeId) => { + const label = nodeLabels[nodeId]; + if (wrapper_validate(nodeId) && nodeLabelCounts.get(label) === 1) { + return label; } - if (currentLastNode) { - graph.addEdge(currentLastNode, stepFirstNode); + else { + return nodeId; } - currentLastNode = stepGraph.lastNode(); + }; + return new Graph({ + nodes: Object.fromEntries(Object.entries(this.nodes).map(([id, node]) => [ + getNodeId(id), + { ...node, id: getNodeId(id) }, + ])), + edges: this.edges.map((edge) => ({ + ...edge, + source: getNodeId(edge.source), + target: getNodeId(edge.target), + })), }); - return graph; } - pipe(coerceable) { - if (RunnableSequence.isRunnableSequence(coerceable)) { - return new RunnableSequence({ - first: this.first, - middle: this.middle.concat([ - this.last, - coerceable.first, - ...coerceable.middle, - ]), - last: coerceable.last, - name: this.name ?? coerceable.name, - }); + drawMermaid(params) { + const { withStyles, curveStyle, nodeColors = { + default: "fill:#f2f0ff,line-height:1.2", + first: "fill-opacity:0", + last: "fill:#bfb6fc", + }, wrapLabelNWords, } = params ?? {}; + const graph = this.reid(); + const firstNode = graph.firstNode(); + const lastNode = graph.lastNode(); + return drawMermaid(graph.nodes, graph.edges, { + firstNode: firstNode?.id, + lastNode: lastNode?.id, + withStyles, + curveStyle, + nodeColors, + wrapLabelNWords, + }); + } + async drawMermaidPng(params) { + const mermaidSyntax = this.drawMermaid(params); + return drawMermaidPng(mermaidSyntax, { + backgroundColor: params?.backgroundColor, + }); + } +} +/** + * Find the single node that is not a target of any edge. + * Exclude nodes/sources with ids in the exclude list. + * If there is no such node, or there are multiple, return undefined. + * When drawing the graph, this node would be the origin. + */ +function _firstNode(graph, exclude = []) { + const targets = new Set(graph.edges + .filter((edge) => !exclude.includes(edge.source)) + .map((edge) => edge.target)); + const found = []; + for (const node of Object.values(graph.nodes)) { + if (!exclude.includes(node.id) && !targets.has(node.id)) { + found.push(node); + } + } + return found.length === 1 ? found[0] : undefined; +} +/** + * Find the single node that is not a source of any edge. + * Exclude nodes/targets with ids in the exclude list. + * If there is no such node, or there are multiple, return undefined. + * When drawing the graph, this node would be the destination. + */ +function _lastNode(graph, exclude = []) { + const sources = new Set(graph.edges + .filter((edge) => !exclude.includes(edge.target)) + .map((edge) => edge.source)); + const found = []; + for (const node of Object.values(graph.nodes)) { + if (!exclude.includes(node.id) && !sources.has(node.id)) { + found.push(node); + } + } + return found.length === 1 ? found[0] : undefined; +} + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/wrappers.js + +function convertToHttpEventStream(stream) { + const encoder = new TextEncoder(); + const finalStream = new ReadableStream({ + async start(controller) { + for await (const chunk of stream) { + controller.enqueue(encoder.encode(`event: data\ndata: ${JSON.stringify(chunk)}\n\n`)); + } + controller.enqueue(encoder.encode("event: end\n\n")); + controller.close(); + }, + }); + return IterableReadableStream.fromReadableStream(finalStream); +} + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/iter.js + + +function isIterableIterator(thing) { + return (typeof thing === "object" && + thing !== null && + typeof thing[Symbol.iterator] === "function" && + // avoid detecting array/set as iterator + typeof thing.next === "function"); +} +const isIterator = (x) => x != null && + typeof x === "object" && + "next" in x && + typeof x.next === "function"; +function iter_isAsyncIterable(thing) { + return (typeof thing === "object" && + thing !== null && + typeof thing[Symbol.asyncIterator] === + "function"); +} +function* consumeIteratorInContext(context, iter) { + while (true) { + const { value, done } = async_local_storage_AsyncLocalStorageProviderSingleton.runWithConfig(pickRunnableConfigKeys(context), iter.next.bind(iter), true); + if (done) { + break; } else { - return new RunnableSequence({ - first: this.first, - middle: [...this.middle, this.last], - last: _coerceToRunnable(coerceable), - name: this.name, - }); + yield value; } } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - static isRunnableSequence(thing) { - return Array.isArray(thing.middle) && Runnable.isRunnable(thing); - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - static from([first, ...runnables], nameOrFields) { - let extra = {}; - if (typeof nameOrFields === "string") { - extra.name = nameOrFields; +} +async function* consumeAsyncIterableInContext(context, iter) { + const iterator = iter[Symbol.asyncIterator](); + while (true) { + const { value, done } = await async_local_storage_AsyncLocalStorageProviderSingleton.runWithConfig(pickRunnableConfigKeys(context), iterator.next.bind(iter), true); + if (done) { + break; } - else if (nameOrFields !== undefined) { - extra = nameOrFields; + else { + yield value; } - return new RunnableSequence({ - ...extra, - first: _coerceToRunnable(first), - middle: runnables.slice(0, -1).map(_coerceToRunnable), - last: _coerceToRunnable(runnables[runnables.length - 1]), - }); } } + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/base.js + + + + + + + + + + + + + + + + + + + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function base_coerceToDict(value, defaultKey) { + return value && + !Array.isArray(value) && + // eslint-disable-next-line no-instanceof/no-instanceof + !(value instanceof Date) && + typeof value === "object" + ? value + : { [defaultKey]: value }; +} /** - * A runnable that runs a mapping of runnables in parallel, - * and returns a mapping of their outputs. - * @example - * ```typescript - * const mapChain = RunnableMap.from({ - * joke: PromptTemplate.fromTemplate("Tell me a joke about {topic}").pipe( - * new ChatAnthropic({}), - * ), - * poem: PromptTemplate.fromTemplate("write a 2-line poem about {topic}").pipe( - * new ChatAnthropic({}), - * ), - * }); - * const result = await mapChain.invoke({ topic: "bear" }); - * ``` + * A Runnable is a generic unit of work that can be invoked, batched, streamed, and/or + * transformed. */ -class RunnableMap extends Runnable { - static lc_name() { - return "RunnableMap"; - } - getStepsKeys() { - return Object.keys(this.steps); - } - constructor(fields) { - super(fields); - Object.defineProperty(this, "lc_namespace", { - enumerable: true, - configurable: true, - writable: true, - value: ["langchain_core", "runnables"] - }); - Object.defineProperty(this, "lc_serializable", { +class Runnable extends Serializable { + constructor() { + super(...arguments); + Object.defineProperty(this, "lc_runnable", { enumerable: true, configurable: true, writable: true, value: true }); - Object.defineProperty(this, "steps", { + Object.defineProperty(this, "name", { enumerable: true, configurable: true, writable: true, value: void 0 }); - this.steps = {}; - for (const [key, value] of Object.entries(fields.steps)) { - this.steps[key] = _coerceToRunnable(value); - } - } - static from(steps) { - return new RunnableMap({ steps }); } - async invoke(input, options) { - const config = ensureConfig(options); - const callbackManager_ = await getCallbackManagerForConfig(config); - const runManager = await callbackManager_?.handleChainStart(this.toJSON(), { - input, - }, config.runId, undefined, undefined, undefined, config?.runName); - delete config.runId; + getName(suffix) { + const name = // eslint-disable-next-line @typescript-eslint/no-explicit-any - const output = {}; - try { - const promises = Object.entries(this.steps).map(async ([key, runnable]) => { - output[key] = await runnable.invoke(input, patchConfig(config, { - callbacks: runManager?.getChild(`map:key:${key}`), - })); - }); - await raceWithSignal(Promise.all(promises), options?.signal); + this.name ?? this.constructor.lc_name() ?? this.constructor.name; + return suffix ? `${name}${suffix}` : name; + } + /** + * Bind arguments to a Runnable, returning a new Runnable. + * @param kwargs + * @returns A new RunnableBinding that, when invoked, will apply the bound args. + * + * @deprecated Use {@link withConfig} instead. This will be removed in the next breaking release. + */ + bind(kwargs) { + // eslint-disable-next-line @typescript-eslint/no-use-before-define + return new RunnableBinding({ bound: this, kwargs, config: {} }); + } + /** + * Return a new Runnable that maps a list of inputs to a list of outputs, + * by calling invoke() with each input. + * + * @deprecated This will be removed in the next breaking release. + */ + map() { + // eslint-disable-next-line @typescript-eslint/no-use-before-define + return new RunnableEach({ bound: this }); + } + /** + * Add retry logic to an existing runnable. + * @param fields.stopAfterAttempt The number of attempts to retry. + * @param fields.onFailedAttempt A function that is called when a retry fails. + * @returns A new RunnableRetry that, when invoked, will retry according to the parameters. + */ + withRetry(fields) { + // eslint-disable-next-line @typescript-eslint/no-use-before-define + return new RunnableRetry({ + bound: this, + kwargs: {}, + config: {}, + maxAttemptNumber: fields?.stopAfterAttempt, + ...fields, + }); + } + /** + * Bind config to a Runnable, returning a new Runnable. + * @param config New configuration parameters to attach to the new runnable. + * @returns A new RunnableBinding with a config matching what's passed. + */ + withConfig(config) { + // eslint-disable-next-line @typescript-eslint/no-use-before-define + return new RunnableBinding({ + bound: this, + config, + kwargs: {}, + }); + } + /** + * Create a new runnable from the current one that will try invoking + * other passed fallback runnables if the initial invocation fails. + * @param fields.fallbacks Other runnables to call if the runnable errors. + * @returns A new RunnableWithFallbacks. + */ + withFallbacks(fields) { + const fallbacks = Array.isArray(fields) ? fields : fields.fallbacks; + // eslint-disable-next-line @typescript-eslint/no-use-before-define + return new RunnableWithFallbacks({ + runnable: this, + fallbacks, + }); + } + _getOptionsList(options, length = 0) { + if (Array.isArray(options) && options.length !== length) { + throw new Error(`Passed "options" must be an array with the same length as the inputs, but got ${options.length} options for ${length} inputs`); } - catch (e) { - await runManager?.handleChainError(e); - throw e; + if (Array.isArray(options)) { + return options.map(ensureConfig); } - await runManager?.handleChainEnd(output); - return output; + if (length > 1 && !Array.isArray(options) && options.runId) { + console.warn("Provided runId will be used only for the first element of the batch."); + const subsequent = Object.fromEntries(Object.entries(options).filter(([key]) => key !== "runId")); + return Array.from({ length }, (_, i) => ensureConfig(i === 0 ? options : subsequent)); + } + return Array.from({ length }, () => ensureConfig(options)); } - async *_transform(generator, runManager, options) { - // shallow copy steps to ignore changes while iterating - const steps = { ...this.steps }; - // each step gets a copy of the input iterator - const inputCopies = atee(generator, Object.keys(steps).length); - // start the first iteration of each output iterator - const tasks = new Map(Object.entries(steps).map(([key, runnable], i) => { - const gen = runnable.transform(inputCopies[i], patchConfig(options, { - callbacks: runManager?.getChild(`map:key:${key}`), - })); - return [key, gen.next().then((result) => ({ key, gen, result }))]; - })); - // yield chunks as they become available, - // starting new iterations as needed, - // until all iterators are done - while (tasks.size) { - const promise = Promise.race(tasks.values()); - const { key, result, gen } = await raceWithSignal(promise, options?.signal); - tasks.delete(key); - if (!result.done) { - yield { [key]: result.value }; - tasks.set(key, gen.next().then((result) => ({ key, gen, result }))); + async batch(inputs, options, batchOptions) { + const configList = this._getOptionsList(options ?? {}, inputs.length); + const maxConcurrency = configList[0]?.maxConcurrency ?? batchOptions?.maxConcurrency; + const caller = new async_caller_AsyncCaller({ + maxConcurrency, + onFailedAttempt: (e) => { + throw e; + }, + }); + const batchCalls = inputs.map((input, i) => caller.call(async () => { + try { + const result = await this.invoke(input, configList[i]); + return result; } - } + catch (e) { + if (batchOptions?.returnExceptions) { + return e; + } + throw e; + } + })); + return Promise.all(batchCalls); } - transform(generator, options) { - return this._transformStreamWithConfig(generator, this._transform.bind(this), options); + /** + * Default streaming implementation. + * Subclasses should override this method if they support streaming output. + * @param input + * @param options + */ + async *_streamIterator(input, options) { + yield this.invoke(input, options); } + /** + * Stream output in chunks. + * @param input + * @param options + * @returns A readable stream that is also an iterable. + */ async stream(input, options) { - async function* generator() { - yield input; - } + // Buffer the first streamed chunk to allow for initial errors + // to surface immediately. const config = ensureConfig(options); const wrappedGenerator = new AsyncGeneratorWithSetup({ - generator: this.transform(generator(), config), + generator: this._streamIterator(input, config), config, }); await wrappedGenerator.setup; return IterableReadableStream.fromAsyncGenerator(wrappedGenerator); } -} -/** - * A runnable that wraps a traced LangSmith function. - */ -class RunnableTraceable extends Runnable { - constructor(fields) { - super(fields); - Object.defineProperty(this, "lc_serializable", { - enumerable: true, - configurable: true, - writable: true, - value: false - }); - Object.defineProperty(this, "lc_namespace", { - enumerable: true, - configurable: true, - writable: true, - value: ["langchain_core", "runnables"] - }); - Object.defineProperty(this, "func", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - if (!isTraceableFunction(fields.func)) { - throw new Error("RunnableTraceable requires a function that is wrapped in traceable higher-order function"); + _separateRunnableConfigFromCallOptions(options) { + let runnableConfig; + if (options === undefined) { + runnableConfig = ensureConfig(options); } - this.func = fields.func; - } - async invoke(input, options) { - const [config] = this._getOptionsList(options ?? {}, 1); - const callbacks = await getCallbackManagerForConfig(config); - const promise = this.func(patchConfig(config, { callbacks }), input); - return raceWithSignal(promise, config?.signal); + else { + runnableConfig = ensureConfig({ + callbacks: options.callbacks, + tags: options.tags, + metadata: options.metadata, + runName: options.runName, + configurable: options.configurable, + recursionLimit: options.recursionLimit, + maxConcurrency: options.maxConcurrency, + runId: options.runId, + timeout: options.timeout, + signal: options.signal, + }); + } + const callOptions = { ...options }; + delete callOptions.callbacks; + delete callOptions.tags; + delete callOptions.metadata; + delete callOptions.runName; + delete callOptions.configurable; + delete callOptions.recursionLimit; + delete callOptions.maxConcurrency; + delete callOptions.runId; + delete callOptions.timeout; + delete callOptions.signal; + return [runnableConfig, callOptions]; } - async *_streamIterator(input, options) { - const [config] = this._getOptionsList(options ?? {}, 1); - const result = await this.invoke(input, options); - if (iter_isAsyncIterable(result)) { - for await (const item of result) { - config?.signal?.throwIfAborted(); - yield item; - } - return; + async _callWithConfig(func, input, options) { + const config = ensureConfig(options); + const callbackManager_ = await getCallbackManagerForConfig(config); + const runManager = await callbackManager_?.handleChainStart(this.toJSON(), base_coerceToDict(input, "input"), config.runId, config?.runType, undefined, undefined, config?.runName ?? this.getName()); + delete config.runId; + let output; + try { + const promise = func.call(this, input, config, runManager); + output = await raceWithSignal(promise, options?.signal); } - if (isIterator(result)) { - while (true) { - config?.signal?.throwIfAborted(); - const state = result.next(); - if (state.done) - break; - yield state.value; - } - return; + catch (e) { + await runManager?.handleChainError(e); + throw e; } - yield result; - } - static from(func) { - return new RunnableTraceable({ func }); - } -} -function assertNonTraceableFunction(func) { - if (isTraceableFunction(func)) { - throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen."); - } -} -/** - * A runnable that wraps an arbitrary function that takes a single argument. - * @example - * ```typescript - * import { RunnableLambda } from "@langchain/core/runnables"; - * - * const add = (input: { x: number; y: number }) => input.x + input.y; - * - * const multiply = (input: { value: number; multiplier: number }) => - * input.value * input.multiplier; - * - * // Create runnables for the functions - * const addLambda = RunnableLambda.from(add); - * const multiplyLambda = RunnableLambda.from(multiply); - * - * // Chain the lambdas for a mathematical operation - * const chainedLambda = addLambda.pipe((result) => - * multiplyLambda.invoke({ value: result, multiplier: 2 }) - * ); - * - * // Example invocation of the chainedLambda - * const result = await chainedLambda.invoke({ x: 2, y: 3 }); - * - * // Will log "10" (since (2 + 3) * 2 = 10) - * ``` - */ -class base_RunnableLambda extends Runnable { - static lc_name() { - return "RunnableLambda"; + await runManager?.handleChainEnd(base_coerceToDict(output, "output")); + return output; } - constructor(fields) { - if (isTraceableFunction(fields.func)) { - // eslint-disable-next-line no-constructor-return - return RunnableTraceable.from(fields.func); + /** + * Internal method that handles batching and configuration for a runnable + * It takes a function, input values, and optional configuration, and + * returns a promise that resolves to the output values. + * @param func The function to be executed for each input value. + * @param input The input values to be processed. + * @param config Optional configuration for the function execution. + * @returns A promise that resolves to the output values. + */ + async _batchWithConfig(func, inputs, options, batchOptions) { + const optionsList = this._getOptionsList(options ?? {}, inputs.length); + const callbackManagers = await Promise.all(optionsList.map(getCallbackManagerForConfig)); + const runManagers = await Promise.all(callbackManagers.map(async (callbackManager, i) => { + const handleStartRes = await callbackManager?.handleChainStart(this.toJSON(), base_coerceToDict(inputs[i], "input"), optionsList[i].runId, optionsList[i].runType, undefined, undefined, optionsList[i].runName ?? this.getName()); + delete optionsList[i].runId; + return handleStartRes; + })); + let outputs; + try { + const promise = func.call(this, inputs, optionsList, runManagers, batchOptions); + outputs = await raceWithSignal(promise, optionsList?.[0]?.signal); } - super(fields); - Object.defineProperty(this, "lc_namespace", { - enumerable: true, - configurable: true, - writable: true, - value: ["langchain_core", "runnables"] - }); - Object.defineProperty(this, "func", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - assertNonTraceableFunction(fields.func); - this.func = fields.func; - } - static from(func) { - return new base_RunnableLambda({ - func, - }); - } - async _invoke(input, config, runManager) { - return new Promise((resolve, reject) => { - const childConfig = patchConfig(config, { - callbacks: runManager?.getChild(), - recursionLimit: (config?.recursionLimit ?? DEFAULT_RECURSION_LIMIT) - 1, - }); - void async_local_storage_AsyncLocalStorageProviderSingleton.runWithConfig(pickRunnableConfigKeys(childConfig), async () => { - try { - let output = await this.func(input, { - ...childConfig, - }); - if (output && Runnable.isRunnable(output)) { - if (config?.recursionLimit === 0) { - throw new Error("Recursion limit reached."); - } - output = await output.invoke(input, { - ...childConfig, - recursionLimit: (childConfig.recursionLimit ?? DEFAULT_RECURSION_LIMIT) - 1, - }); + catch (e) { + await Promise.all(runManagers.map((runManager) => runManager?.handleChainError(e))); + throw e; + } + await Promise.all(runManagers.map((runManager) => runManager?.handleChainEnd(base_coerceToDict(outputs, "output")))); + return outputs; + } + /** + * Helper method to transform an Iterator of Input values into an Iterator of + * Output values, with callbacks. + * Use this to implement `stream()` or `transform()` in Runnable subclasses. + */ + async *_transformStreamWithConfig(inputGenerator, transformer, options) { + let finalInput; + let finalInputSupported = true; + let finalOutput; + let finalOutputSupported = true; + const config = ensureConfig(options); + const callbackManager_ = await getCallbackManagerForConfig(config); + async function* wrapInputForTracing() { + for await (const chunk of inputGenerator) { + if (finalInputSupported) { + if (finalInput === undefined) { + finalInput = chunk; } - else if (iter_isAsyncIterable(output)) { - let finalOutput; - for await (const chunk of consumeAsyncIterableInContext(childConfig, output)) { - config?.signal?.throwIfAborted(); - if (finalOutput === undefined) { - finalOutput = chunk; - } - else { - // Make a best effort to gather, for any type that supports concat. - try { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - finalOutput = concat(finalOutput, chunk); - } - catch (e) { - finalOutput = chunk; - } - } + else { + try { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + finalInput = concat(finalInput, chunk); } - output = finalOutput; - } - else if (isIterableIterator(output)) { - let finalOutput; - for (const chunk of consumeIteratorInContext(childConfig, output)) { - config?.signal?.throwIfAborted(); - if (finalOutput === undefined) { - finalOutput = chunk; - } - else { - // Make a best effort to gather, for any type that supports concat. - try { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - finalOutput = concat(finalOutput, chunk); - } - catch (e) { - finalOutput = chunk; - } - } + catch { + finalInput = undefined; + finalInputSupported = false; } - output = finalOutput; } - resolve(output); } - catch (e) { - reject(e); + yield chunk; + } + } + let runManager; + try { + const pipe = await pipeGeneratorWithSetup(transformer.bind(this), wrapInputForTracing(), async () => callbackManager_?.handleChainStart(this.toJSON(), { input: "" }, config.runId, config.runType, undefined, undefined, config.runName ?? this.getName()), options?.signal, config); + delete config.runId; + runManager = pipe.setup; + const streamEventsHandler = runManager?.handlers.find(isStreamEventsHandler); + let iterator = pipe.output; + if (streamEventsHandler !== undefined && runManager !== undefined) { + iterator = streamEventsHandler.tapOutputIterable(runManager.runId, iterator); + } + const streamLogHandler = runManager?.handlers.find(isLogStreamHandler); + if (streamLogHandler !== undefined && runManager !== undefined) { + iterator = streamLogHandler.tapOutputIterable(runManager.runId, iterator); + } + for await (const chunk of iterator) { + yield chunk; + if (finalOutputSupported) { + if (finalOutput === undefined) { + finalOutput = chunk; + } + else { + try { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + finalOutput = concat(finalOutput, chunk); + } + catch { + finalOutput = undefined; + finalOutputSupported = false; + } + } } + } + } + catch (e) { + await runManager?.handleChainError(e, undefined, undefined, undefined, { + inputs: base_coerceToDict(finalInput, "input"), }); + throw e; + } + await runManager?.handleChainEnd(finalOutput ?? {}, undefined, undefined, undefined, { inputs: base_coerceToDict(finalInput, "input") }); + } + getGraph(_) { + const graph = new Graph(); + // TODO: Add input schema for runnables + const inputNode = graph.addNode({ + name: `${this.getName()}Input`, + schema: anyType(), + }); + const runnableNode = graph.addNode(this); + // TODO: Add output schemas for runnables + const outputNode = graph.addNode({ + name: `${this.getName()}Output`, + schema: anyType(), }); + graph.addEdge(inputNode, runnableNode); + graph.addEdge(runnableNode, outputNode); + return graph; } - async invoke(input, options) { - return this._callWithConfig(this._invoke.bind(this), input, options); + /** + * Create a new runnable sequence that runs each individual runnable in series, + * piping the output of one runnable into another runnable or runnable-like. + * @param coerceable A runnable, function, or object whose values are functions or runnables. + * @returns A new runnable sequence. + */ + pipe(coerceable) { + // eslint-disable-next-line @typescript-eslint/no-use-before-define + return new RunnableSequence({ + first: this, + last: _coerceToRunnable(coerceable), + }); } - async *_transform(generator, runManager, config) { + /** + * Pick keys from the dict output of this runnable. Returns a new runnable. + */ + pick(keys) { + // eslint-disable-next-line @typescript-eslint/no-use-before-define + return this.pipe(new RunnablePick(keys)); + } + /** + * Assigns new fields to the dict output of this runnable. Returns a new runnable. + */ + assign(mapping) { + return this.pipe( + // eslint-disable-next-line @typescript-eslint/no-use-before-define + new RunnableAssign( + // eslint-disable-next-line @typescript-eslint/no-use-before-define + new RunnableMap({ steps: mapping }))); + } + /** + * Default implementation of transform, which buffers input and then calls stream. + * Subclasses should override this method if they can start producing output while + * input is still being generated. + * @param generator + * @param options + */ + async *transform(generator, options) { let finalChunk; for await (const chunk of generator) { if (finalChunk === undefined) { @@ -100029,492 +105669,435 @@ class base_RunnableLambda extends Runnable { } else { // Make a best effort to gather, for any type that supports concat. - try { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - finalChunk = concat(finalChunk, chunk); - } - catch (e) { - finalChunk = chunk; - } + // This method should throw an error if gathering fails. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + finalChunk = concat(finalChunk, chunk); } } - const childConfig = patchConfig(config, { - callbacks: runManager?.getChild(), - recursionLimit: (config?.recursionLimit ?? DEFAULT_RECURSION_LIMIT) - 1, + yield* this._streamIterator(finalChunk, ensureConfig(options)); + } + /** + * Stream all output from a runnable, as reported to the callback system. + * This includes all inner runs of LLMs, Retrievers, Tools, etc. + * Output is streamed as Log objects, which include a list of + * jsonpatch ops that describe how the state of the run has changed in each + * step, and the final state of the run. + * The jsonpatch ops can be applied in order to construct state. + * @param input + * @param options + * @param streamOptions + */ + async *streamLog(input, options, streamOptions) { + const logStreamCallbackHandler = new LogStreamCallbackHandler({ + ...streamOptions, + autoClose: false, + _schemaFormat: "original", }); - const output = await new Promise((resolve, reject) => { - void async_local_storage_AsyncLocalStorageProviderSingleton.runWithConfig(pickRunnableConfigKeys(childConfig), async () => { - try { - const res = await this.func(finalChunk, { - ...childConfig, - config: childConfig, + const config = ensureConfig(options); + yield* this._streamLog(input, logStreamCallbackHandler, config); + } + async *_streamLog(input, logStreamCallbackHandler, config) { + const { callbacks } = config; + if (callbacks === undefined) { + // eslint-disable-next-line no-param-reassign + config.callbacks = [logStreamCallbackHandler]; + } + else if (Array.isArray(callbacks)) { + // eslint-disable-next-line no-param-reassign + config.callbacks = callbacks.concat([logStreamCallbackHandler]); + } + else { + const copiedCallbacks = callbacks.copy(); + copiedCallbacks.addHandler(logStreamCallbackHandler, true); + // eslint-disable-next-line no-param-reassign + config.callbacks = copiedCallbacks; + } + const runnableStreamPromise = this.stream(input, config); + async function consumeRunnableStream() { + try { + const runnableStream = await runnableStreamPromise; + for await (const chunk of runnableStream) { + const patch = new RunLogPatch({ + ops: [ + { + op: "add", + path: "/streamed_output/-", + value: chunk, + }, + ], }); - resolve(res); - } - catch (e) { - reject(e); + await logStreamCallbackHandler.writer.write(patch); } - }); - }); - if (output && Runnable.isRunnable(output)) { - if (config?.recursionLimit === 0) { - throw new Error("Recursion limit reached."); } - const stream = await output.stream(finalChunk, childConfig); - for await (const chunk of stream) { - yield chunk; + finally { + await logStreamCallbackHandler.writer.close(); } } - else if (iter_isAsyncIterable(output)) { - for await (const chunk of consumeAsyncIterableInContext(childConfig, output)) { - config?.signal?.throwIfAborted(); - yield chunk; + const runnableStreamConsumePromise = consumeRunnableStream(); + try { + for await (const log of logStreamCallbackHandler) { + yield log; } } - else if (isIterableIterator(output)) { - for (const chunk of consumeIteratorInContext(childConfig, output)) { - config?.signal?.throwIfAborted(); - yield chunk; - } + finally { + await runnableStreamConsumePromise; + } + } + streamEvents(input, options, streamOptions) { + let stream; + if (options.version === "v1") { + stream = this._streamEventsV1(input, options, streamOptions); + } + else if (options.version === "v2") { + stream = this._streamEventsV2(input, options, streamOptions); } else { - yield output; + throw new Error(`Only versions "v1" and "v2" of the schema are currently supported.`); } - } - transform(generator, options) { - return this._transformStreamWithConfig(generator, this._transform.bind(this), options); - } - async stream(input, options) { - async function* generator() { - yield input; + if (options.encoding === "text/event-stream") { + return convertToHttpEventStream(stream); } - const config = ensureConfig(options); - const wrappedGenerator = new AsyncGeneratorWithSetup({ - generator: this.transform(generator(), config), - config, - }); - await wrappedGenerator.setup; - return IterableReadableStream.fromAsyncGenerator(wrappedGenerator); - } -} -/** - * A runnable that runs a mapping of runnables in parallel, - * and returns a mapping of their outputs. - * @example - * ```typescript - * import { - * RunnableLambda, - * RunnableParallel, - * } from "@langchain/core/runnables"; - * - * const addYears = (age: number): number => age + 5; - * const yearsToFifty = (age: number): number => 50 - age; - * const yearsToHundred = (age: number): number => 100 - age; - * - * const addYearsLambda = RunnableLambda.from(addYears); - * const milestoneFiftyLambda = RunnableLambda.from(yearsToFifty); - * const milestoneHundredLambda = RunnableLambda.from(yearsToHundred); - * - * // Pipe will coerce objects into RunnableParallel by default, but we - * // explicitly instantiate one here to demonstrate - * const sequence = addYearsLambda.pipe( - * RunnableParallel.from({ - * years_to_fifty: milestoneFiftyLambda, - * years_to_hundred: milestoneHundredLambda, - * }) - * ); - * - * // Invoke the sequence with a single age input - * const res = sequence.invoke(25); - * - * // { years_to_fifty: 25, years_to_hundred: 75 } - * ``` - */ -class RunnableParallel extends (/* unused pure expression or super */ null && (RunnableMap)) { -} -/** - * A Runnable that can fallback to other Runnables if it fails. - * External APIs (e.g., APIs for a language model) may at times experience - * degraded performance or even downtime. - * - * In these cases, it can be useful to have a fallback Runnable that can be - * used in place of the original Runnable (e.g., fallback to another LLM provider). - * - * Fallbacks can be defined at the level of a single Runnable, or at the level - * of a chain of Runnables. Fallbacks are tried in order until one succeeds or - * all fail. - * - * While you can instantiate a `RunnableWithFallbacks` directly, it is usually - * more convenient to use the `withFallbacks` method on an existing Runnable. - * - * When streaming, fallbacks will only be called on failures during the initial - * stream creation. Errors that occur after a stream starts will not fallback - * to the next Runnable. - * - * @example - * ```typescript - * import { - * RunnableLambda, - * RunnableWithFallbacks, - * } from "@langchain/core/runnables"; - * - * const primaryOperation = (input: string): string => { - * if (input !== "safe") { - * throw new Error("Primary operation failed due to unsafe input"); - * } - * return `Processed: ${input}`; - * }; - * - * // Define a fallback operation that processes the input differently - * const fallbackOperation = (input: string): string => - * `Fallback processed: ${input}`; - * - * const primaryRunnable = RunnableLambda.from(primaryOperation); - * const fallbackRunnable = RunnableLambda.from(fallbackOperation); - * - * // Apply the fallback logic using the .withFallbacks() method - * const runnableWithFallback = primaryRunnable.withFallbacks([fallbackRunnable]); - * - * // Alternatively, create a RunnableWithFallbacks instance manually - * const manualFallbackChain = new RunnableWithFallbacks({ - * runnable: primaryRunnable, - * fallbacks: [fallbackRunnable], - * }); - * - * // Example invocation using .withFallbacks() - * const res = await runnableWithFallback - * .invoke("unsafe input") - * .catch((error) => { - * console.error("Failed after all attempts:", error.message); - * }); - * - * // "Fallback processed: unsafe input" - * - * // Example invocation using manual instantiation - * const res = await manualFallbackChain - * .invoke("safe") - * .catch((error) => { - * console.error("Failed after all attempts:", error.message); - * }); - * - * // "Processed: safe" - * ``` - */ -class RunnableWithFallbacks extends Runnable { - static lc_name() { - return "RunnableWithFallbacks"; - } - constructor(fields) { - super(fields); - Object.defineProperty(this, "lc_namespace", { - enumerable: true, - configurable: true, - writable: true, - value: ["langchain_core", "runnables"] - }); - Object.defineProperty(this, "lc_serializable", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - Object.defineProperty(this, "runnable", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "fallbacks", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.runnable = fields.runnable; - this.fallbacks = fields.fallbacks; - } - *runnables() { - yield this.runnable; - for (const fallback of this.fallbacks) { - yield fallback; + else { + return IterableReadableStream.fromAsyncGenerator(stream); } } - async invoke(input, options) { - const config = ensureConfig(options); - const callbackManager_ = await getCallbackManagerForConfig(config); - const { runId, ...otherConfigFields } = config; - const runManager = await callbackManager_?.handleChainStart(this.toJSON(), base_coerceToDict(input, "input"), runId, undefined, undefined, undefined, otherConfigFields?.runName); - const childConfig = patchConfig(otherConfigFields, { - callbacks: runManager?.getChild(), - }); - const res = await async_local_storage_AsyncLocalStorageProviderSingleton.runWithConfig(childConfig, async () => { - let firstError; - for (const runnable of this.runnables()) { - config?.signal?.throwIfAborted(); - try { - const output = await runnable.invoke(input, childConfig); - await runManager?.handleChainEnd(base_coerceToDict(output, "output")); - return output; - } - catch (e) { - if (firstError === undefined) { - firstError = e; - } - } - } - if (firstError === undefined) { - throw new Error("No error stored at end of fallback."); - } - await runManager?.handleChainError(firstError); - throw firstError; + async *_streamEventsV2(input, options, streamOptions) { + const eventStreamer = new EventStreamCallbackHandler({ + ...streamOptions, + autoClose: false, }); - return res; - } - async *_streamIterator(input, options) { const config = ensureConfig(options); - const callbackManager_ = await getCallbackManagerForConfig(config); - const { runId, ...otherConfigFields } = config; - const runManager = await callbackManager_?.handleChainStart(this.toJSON(), base_coerceToDict(input, "input"), runId, undefined, undefined, undefined, otherConfigFields?.runName); - let firstError; - let stream; - for (const runnable of this.runnables()) { - config?.signal?.throwIfAborted(); - const childConfig = patchConfig(otherConfigFields, { - callbacks: runManager?.getChild(), - }); + const runId = config.runId ?? v4(); + config.runId = runId; + const callbacks = config.callbacks; + if (callbacks === undefined) { + config.callbacks = [eventStreamer]; + } + else if (Array.isArray(callbacks)) { + config.callbacks = callbacks.concat(eventStreamer); + } + else { + const copiedCallbacks = callbacks.copy(); + copiedCallbacks.addHandler(eventStreamer, true); + // eslint-disable-next-line no-param-reassign + config.callbacks = copiedCallbacks; + } + const abortController = new AbortController(); + // Call the runnable in streaming mode, + // add each chunk to the output stream + const outerThis = this; + async function consumeRunnableStream() { + let signal; + let listener = null; try { - const originalStream = await runnable.stream(input, childConfig); - stream = consumeAsyncIterableInContext(childConfig, originalStream); - break; + if (options?.signal) { + if ("any" in AbortSignal) { + // Use native AbortSignal.any() if available (Node 19+) + // eslint-disable-next-line @typescript-eslint/no-explicit-any + signal = AbortSignal.any([ + abortController.signal, + options.signal, + ]); + } + else { + // Fallback for Node 18 and below - just use the provided signal + signal = options.signal; + // Ensure we still abort our controller when the parent signal aborts + listener = () => { + abortController.abort(); + }; + options.signal.addEventListener("abort", listener, { once: true }); + } + } + else { + signal = abortController.signal; + } + const runnableStream = await outerThis.stream(input, { + ...config, + signal, + }); + const tappedStream = eventStreamer.tapOutputIterable(runId, runnableStream); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + for await (const _ of tappedStream) { + // Just iterate so that the callback handler picks up events + if (abortController.signal.aborted) + break; + } } - catch (e) { - if (firstError === undefined) { - firstError = e; + finally { + await eventStreamer.finish(); + if (signal && listener) { + signal.removeEventListener("abort", listener); } } } - if (stream === undefined) { - const error = firstError ?? new Error("No error stored at end of fallback."); - await runManager?.handleChainError(error); - throw error; - } - let output; + const runnableStreamConsumePromise = consumeRunnableStream(); + let firstEventSent = false; + let firstEventRunId; try { - for await (const chunk of stream) { - yield chunk; - try { - output = output === undefined ? output : concat(output, chunk); + for await (const event of eventStreamer) { + // This is a work-around an issue where the inputs into the + // chain are not available until the entire input is consumed. + // As a temporary solution, we'll modify the input to be the input + // that was passed into the chain. + if (!firstEventSent) { + event.data.input = input; + firstEventSent = true; + firstEventRunId = event.run_id; + yield event; + continue; } - catch (e) { - output = undefined; + if (event.run_id === firstEventRunId && event.event.endsWith("_end")) { + // If it's the end event corresponding to the root runnable + // we dont include the input in the event since it's guaranteed + // to be included in the first event. + if (event.data?.input) { + delete event.data.input; + } } + yield event; } } - catch (e) { - await runManager?.handleChainError(e); - throw e; + finally { + abortController.abort(); + await runnableStreamConsumePromise; } - await runManager?.handleChainEnd(base_coerceToDict(output, "output")); } - async batch(inputs, options, batchOptions) { - if (batchOptions?.returnExceptions) { - throw new Error("Not implemented."); - } - const configList = this._getOptionsList(options ?? {}, inputs.length); - const callbackManagers = await Promise.all(configList.map((config) => getCallbackManagerForConfig(config))); - const runManagers = await Promise.all(callbackManagers.map(async (callbackManager, i) => { - const handleStartRes = await callbackManager?.handleChainStart(this.toJSON(), base_coerceToDict(inputs[i], "input"), configList[i].runId, undefined, undefined, undefined, configList[i].runName); - delete configList[i].runId; - return handleStartRes; - })); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - let firstError; - for (const runnable of this.runnables()) { - configList[0].signal?.throwIfAborted(); - try { - const outputs = await runnable.batch(inputs, runManagers.map((runManager, j) => patchConfig(configList[j], { - callbacks: runManager?.getChild(), - })), batchOptions); - await Promise.all(runManagers.map((runManager, i) => runManager?.handleChainEnd(base_coerceToDict(outputs[i], "output")))); - return outputs; + async *_streamEventsV1(input, options, streamOptions) { + let runLog; + let hasEncounteredStartEvent = false; + const config = ensureConfig(options); + const rootTags = config.tags ?? []; + const rootMetadata = config.metadata ?? {}; + const rootName = config.runName ?? this.getName(); + const logStreamCallbackHandler = new LogStreamCallbackHandler({ + ...streamOptions, + autoClose: false, + _schemaFormat: "streaming_events", + }); + const rootEventFilter = new _RootEventFilter({ + ...streamOptions, + }); + const logStream = this._streamLog(input, logStreamCallbackHandler, config); + for await (const log of logStream) { + if (!runLog) { + runLog = RunLog.fromRunLogPatch(log); } - catch (e) { - if (firstError === undefined) { - firstError = e; + else { + runLog = runLog.concat(log); + } + if (runLog.state === undefined) { + throw new Error(`Internal error: "streamEvents" state is missing. Please open a bug report.`); + } + // Yield the start event for the root runnable if it hasn't been seen. + // The root run is never filtered out + if (!hasEncounteredStartEvent) { + hasEncounteredStartEvent = true; + const state = { ...runLog.state }; + const event = { + run_id: state.id, + event: `on_${state.type}_start`, + name: rootName, + tags: rootTags, + metadata: rootMetadata, + data: { + input, + }, + }; + if (rootEventFilter.includeEvent(event, state.type)) { + yield event; + } + } + const paths = log.ops + .filter((op) => op.path.startsWith("/logs/")) + .map((op) => op.path.split("/")[2]); + const dedupedPaths = [...new Set(paths)]; + for (const path of dedupedPaths) { + let eventType; + let data = {}; + const logEntry = runLog.state.logs[path]; + if (logEntry.end_time === undefined) { + if (logEntry.streamed_output.length > 0) { + eventType = "stream"; + } + else { + eventType = "start"; + } + } + else { + eventType = "end"; + } + if (eventType === "start") { + // Include the inputs with the start event if they are available. + // Usually they will NOT be available for components that operate + // on streams, since those components stream the input and + // don't know its final value until the end of the stream. + if (logEntry.inputs !== undefined) { + data.input = logEntry.inputs; + } + } + else if (eventType === "end") { + if (logEntry.inputs !== undefined) { + data.input = logEntry.inputs; + } + data.output = logEntry.final_output; + } + else if (eventType === "stream") { + const chunkCount = logEntry.streamed_output.length; + if (chunkCount !== 1) { + throw new Error(`Expected exactly one chunk of streamed output, got ${chunkCount} instead. Encountered in: "${logEntry.name}"`); + } + data = { chunk: logEntry.streamed_output[0] }; + // Clean up the stream, we don't need it anymore. + // And this avoids duplicates as well! + logEntry.streamed_output = []; + } + yield { + event: `on_${logEntry.type}_${eventType}`, + name: logEntry.name, + run_id: logEntry.id, + tags: logEntry.tags, + metadata: logEntry.metadata, + data, + }; + } + // Finally, we take care of the streaming output from the root chain + // if there is any. + const { state } = runLog; + if (state.streamed_output.length > 0) { + const chunkCount = state.streamed_output.length; + if (chunkCount !== 1) { + throw new Error(`Expected exactly one chunk of streamed output, got ${chunkCount} instead. Encountered in: "${state.name}"`); + } + const data = { chunk: state.streamed_output[0] }; + // Clean up the stream, we don't need it anymore. + state.streamed_output = []; + const event = { + event: `on_${state.type}_stream`, + run_id: state.id, + tags: rootTags, + metadata: rootMetadata, + name: rootName, + data, + }; + if (rootEventFilter.includeEvent(event, state.type)) { + yield event; } } } - if (!firstError) { - throw new Error("No error stored at end of fallbacks."); + const state = runLog?.state; + if (state !== undefined) { + // Finally, yield the end event for the root runnable. + const event = { + event: `on_${state.type}_end`, + name: rootName, + run_id: state.id, + tags: rootTags, + metadata: rootMetadata, + data: { + output: state.final_output, + }, + }; + if (rootEventFilter.includeEvent(event, state.type)) + yield event; } - await Promise.all(runManagers.map((runManager) => runManager?.handleChainError(firstError))); - throw firstError; - } -} -// TODO: Figure out why the compiler needs help eliminating Error as a RunOutput type -function _coerceToRunnable(coerceable) { - if (typeof coerceable === "function") { - return new base_RunnableLambda({ func: coerceable }); } - else if (Runnable.isRunnable(coerceable)) { - return coerceable; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + static isRunnable(thing) { + return isRunnableInterface(thing); } - else if (!Array.isArray(coerceable) && typeof coerceable === "object") { - const runnables = {}; - for (const [key, value] of Object.entries(coerceable)) { - runnables[key] = _coerceToRunnable(value); - } - return new RunnableMap({ - steps: runnables, + /** + * Bind lifecycle listeners to a Runnable, returning a new Runnable. + * The Run object contains information about the run, including its id, + * type, input, output, error, startTime, endTime, and any tags or metadata + * added to the run. + * + * @param {Object} params - The object containing the callback functions. + * @param {(run: Run) => void} params.onStart - Called before the runnable starts running, with the Run object. + * @param {(run: Run) => void} params.onEnd - Called after the runnable finishes running, with the Run object. + * @param {(run: Run) => void} params.onError - Called if the runnable throws an error, with the Run object. + */ + withListeners({ onStart, onEnd, onError, }) { + // eslint-disable-next-line @typescript-eslint/no-use-before-define + return new RunnableBinding({ + bound: this, + config: {}, + configFactories: [ + (config) => ({ + callbacks: [ + new RootListenersTracer({ + config, + onStart, + onEnd, + onError, + }), + ], + }), + ], }); } - else { - throw new Error(`Expected a Runnable, function or object.\nInstead got an unsupported type.`); + /** + * Convert a runnable to a tool. Return a new instance of `RunnableToolLike` + * which contains the runnable, name, description and schema. + * + * @template {T extends RunInput = RunInput} RunInput - The input type of the runnable. Should be the same as the `RunInput` type of the runnable. + * + * @param fields + * @param {string | undefined} [fields.name] The name of the tool. If not provided, it will default to the name of the runnable. + * @param {string | undefined} [fields.description] The description of the tool. Falls back to the description on the Zod schema if not provided, or undefined if neither are provided. + * @param {z.ZodType} [fields.schema] The Zod schema for the input of the tool. Infers the Zod type from the input type of the runnable. + * @returns {RunnableToolLike, RunOutput>} An instance of `RunnableToolLike` which is a runnable that can be used as a tool. + */ + asTool(fields) { + return convertRunnableToTool(this, fields); } } /** - * A runnable that assigns key-value pairs to inputs of type `Record`. + * Wraps a runnable and applies partial config upon invocation. + * * @example * ```typescript * import { - * RunnableAssign, + * type RunnableConfig, * RunnableLambda, - * RunnableParallel, * } from "@langchain/core/runnables"; * - * const calculateAge = (x: { birthYear: number }): { age: number } => { - * const currentYear = new Date().getFullYear(); - * return { age: currentYear - x.birthYear }; - * }; - * - * const createGreeting = (x: { name: string }): { greeting: string } => { - * return { greeting: `Hello, ${x.name}!` }; + * const enhanceProfile = ( + * profile: Record, + * config?: RunnableConfig + * ) => { + * if (config?.configurable?.role) { + * return { ...profile, role: config.configurable.role }; + * } + * return profile; * }; * - * const mapper = RunnableParallel.from({ - * age_step: RunnableLambda.from(calculateAge), - * greeting_step: RunnableLambda.from(createGreeting), - * }); - * - * const runnableAssign = new RunnableAssign({ mapper }); - * - * const res = await runnableAssign.invoke({ name: "Alice", birthYear: 1990 }); + * const runnable = RunnableLambda.from(enhanceProfile); * - * // { name: "Alice", birthYear: 1990, age_step: { age: 34 }, greeting_step: { greeting: "Hello, Alice!" } } - * ``` - */ -class RunnableAssign extends Runnable { - static lc_name() { - return "RunnableAssign"; - } - constructor(fields) { - // eslint-disable-next-line no-instanceof/no-instanceof - if (fields instanceof RunnableMap) { - // eslint-disable-next-line no-param-reassign - fields = { mapper: fields }; - } - super(fields); - Object.defineProperty(this, "lc_namespace", { - enumerable: true, - configurable: true, - writable: true, - value: ["langchain_core", "runnables"] - }); - Object.defineProperty(this, "lc_serializable", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - Object.defineProperty(this, "mapper", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.mapper = fields.mapper; - } - async invoke(input, options) { - const mapperResult = await this.mapper.invoke(input, options); - return { - ...input, - ...mapperResult, - }; - } - async *_transform(generator, runManager, options) { - // collect mapper keys - const mapperKeys = this.mapper.getStepsKeys(); - // create two input gens, one for the mapper, one for the input - const [forPassthrough, forMapper] = atee(generator); - // create mapper output gen - const mapperOutput = this.mapper.transform(forMapper, patchConfig(options, { callbacks: runManager?.getChild() })); - // start the mapper - const firstMapperChunkPromise = mapperOutput.next(); - // yield the passthrough - for await (const chunk of forPassthrough) { - if (typeof chunk !== "object" || Array.isArray(chunk)) { - throw new Error(`RunnableAssign can only be used with objects as input, got ${typeof chunk}`); - } - const filtered = Object.fromEntries(Object.entries(chunk).filter(([key]) => !mapperKeys.includes(key))); - if (Object.keys(filtered).length > 0) { - yield filtered; - } - } - // yield the mapper output - yield (await firstMapperChunkPromise).value; - for await (const chunk of mapperOutput) { - yield chunk; - } - } - transform(generator, options) { - return this._transformStreamWithConfig(generator, this._transform.bind(this), options); - } - async stream(input, options) { - async function* generator() { - yield input; - } - const config = ensureConfig(options); - const wrappedGenerator = new AsyncGeneratorWithSetup({ - generator: this.transform(generator(), config), - config, - }); - await wrappedGenerator.setup; - return IterableReadableStream.fromAsyncGenerator(wrappedGenerator); - } -} -/** - * A runnable that assigns key-value pairs to inputs of type `Record`. - * Useful for streaming, can be automatically created and chained by calling `runnable.pick();`. - * @example - * ```typescript - * import { RunnablePick } from "@langchain/core/runnables"; + * // Bind configuration to the runnable to set the user's role dynamically + * const adminRunnable = runnable.bind({ configurable: { role: "Admin" } }); + * const userRunnable = runnable.bind({ configurable: { role: "User" } }); * - * const inputData = { - * name: "John", - * age: 30, - * city: "New York", - * country: "USA", - * email: "john.doe@example.com", - * phone: "+1234567890", - * }; + * const result1 = await adminRunnable.invoke({ + * name: "Alice", + * email: "alice@example.com" + * }); * - * const basicInfoRunnable = new RunnablePick(["name", "city"]); + * // { name: "Alice", email: "alice@example.com", role: "Admin" } * - * // Example invocation - * const res = await basicInfoRunnable.invoke(inputData); + * const result2 = await userRunnable.invoke({ + * name: "Bob", + * email: "bob@example.com" + * }); * - * // { name: 'John', city: 'New York' } + * // { name: "Bob", email: "bob@example.com", role: "User" } * ``` */ -class RunnablePick extends Runnable { +class RunnableBinding extends Runnable { static lc_name() { - return "RunnablePick"; + return "RunnableBinding"; } constructor(fields) { - if (typeof fields === "string" || Array.isArray(fields)) { - // eslint-disable-next-line no-param-reassign - fields = { keys: fields }; - } super(fields); Object.defineProperty(this, "lc_namespace", { enumerable: true, @@ -100523,1114 +106106,1126 @@ class RunnablePick extends Runnable { value: ["langchain_core", "runnables"] }); Object.defineProperty(this, "lc_serializable", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - Object.defineProperty(this, "keys", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.keys = fields.keys; - } - async _pick(input) { - if (typeof this.keys === "string") { - return input[this.keys]; - } - else { - const picked = this.keys - .map((key) => [key, input[key]]) - .filter((v) => v[1] !== undefined); - return picked.length === 0 ? undefined : Object.fromEntries(picked); - } - } - async invoke(input, options) { - return this._callWithConfig(this._pick.bind(this), input, options); - } - async *_transform(generator) { - for await (const chunk of generator) { - const picked = await this._pick(chunk); - if (picked !== undefined) { - yield picked; - } - } - } - transform(generator, options) { - return this._transformStreamWithConfig(generator, this._transform.bind(this), options); - } - async stream(input, options) { - async function* generator() { - yield input; - } - const config = ensureConfig(options); - const wrappedGenerator = new AsyncGeneratorWithSetup({ - generator: this.transform(generator(), config), - config, - }); - await wrappedGenerator.setup; - return IterableReadableStream.fromAsyncGenerator(wrappedGenerator); - } -} -class RunnableToolLike extends RunnableBinding { - constructor(fields) { - const sequence = RunnableSequence.from([ - base_RunnableLambda.from(async (input) => { - let toolInput; - if (_isToolCall(input)) { - try { - toolInput = await this.schema.parseAsync(input.args); - } - catch (e) { - throw new ToolInputParsingException(`Received tool input did not match expected schema`, JSON.stringify(input.args)); - } - } - else { - toolInput = input; - } - return toolInput; - }).withConfig({ runName: `${fields.name}:parse_input` }), - fields.bound, - ]).withConfig({ runName: fields.name }); - super({ - bound: sequence, - config: fields.config ?? {}, + enumerable: true, + configurable: true, + writable: true, + value: true }); - Object.defineProperty(this, "name", { + Object.defineProperty(this, "bound", { enumerable: true, configurable: true, writable: true, value: void 0 }); - Object.defineProperty(this, "description", { + Object.defineProperty(this, "config", { enumerable: true, configurable: true, writable: true, value: void 0 }); - Object.defineProperty(this, "schema", { + Object.defineProperty(this, "kwargs", { enumerable: true, configurable: true, writable: true, value: void 0 }); - this.name = fields.name; - this.description = fields.description; - this.schema = fields.schema; - } - static lc_name() { - return "RunnableToolLike"; - } -} -/** - * Given a runnable and a Zod schema, convert the runnable to a tool. - * - * @template RunInput The input type for the runnable. - * @template RunOutput The output type for the runnable. - * - * @param {Runnable} runnable The runnable to convert to a tool. - * @param fields - * @param {string | undefined} [fields.name] The name of the tool. If not provided, it will default to the name of the runnable. - * @param {string | undefined} [fields.description] The description of the tool. Falls back to the description on the Zod schema if not provided, or undefined if neither are provided. - * @param {z.ZodType} [fields.schema] The Zod schema for the input of the tool. Infers the Zod type from the input type of the runnable. - * @returns {RunnableToolLike, RunOutput>} An instance of `RunnableToolLike` which is a runnable that can be used as a tool. - */ -function convertRunnableToTool(runnable, fields) { - const name = fields.name ?? runnable.getName(); - const description = fields.description ?? fields.schema?.description; - if (fields.schema.constructor === z.ZodString) { - return new RunnableToolLike({ - name, - description, - schema: z - .object({ - input: z.string(), - }) - .transform((input) => input.input), - bound: runnable, - }); - } - return new RunnableToolLike({ - name, - description, - schema: fields.schema, - bound: runnable, - }); -} - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/modifier.js - -/** - * Message responsible for deleting other messages. - */ -class RemoveMessage extends BaseMessage { - constructor(fields) { - super({ - ...fields, - content: "", - }); - /** - * The ID of the message to remove. - */ - Object.defineProperty(this, "id", { + Object.defineProperty(this, "configFactories", { enumerable: true, configurable: true, writable: true, value: void 0 }); - this.id = fields.id; - } - _getType() { - return "remove"; + this.bound = fields.bound; + this.kwargs = fields.kwargs; + this.config = fields.config; + this.configFactories = fields.configFactories; } - get _printableFields() { - return { - ...super._printableFields, - id: this.id, - }; + getName(suffix) { + return this.bound.getName(suffix); } -} - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/transformers.js - - - - - - - - - - -const _isMessageType = (msg, types) => { - const typesAsStrings = [ - ...new Set(types?.map((t) => { - if (typeof t === "string") { - return t; - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const instantiatedMsgClass = new t({}); - if (!("getType" in instantiatedMsgClass) || - typeof instantiatedMsgClass.getType !== "function") { - throw new Error("Invalid type provided."); - } - return instantiatedMsgClass.getType(); - })), - ]; - const msgType = msg.getType(); - return typesAsStrings.some((t) => t === msgType); -}; -function filterMessages(messagesOrOptions, options) { - if (Array.isArray(messagesOrOptions)) { - return _filterMessages(messagesOrOptions, options); + async _mergeConfig(...options) { + const config = mergeConfigs(this.config, ...options); + return mergeConfigs(config, ...(this.configFactories + ? await Promise.all(this.configFactories.map(async (configFactory) => await configFactory(config))) + : [])); } - return RunnableLambda.from((input) => { - return _filterMessages(input, messagesOrOptions); - }); -} -function _filterMessages(messages, options = {}) { - const { includeNames, excludeNames, includeTypes, excludeTypes, includeIds, excludeIds, } = options; - const filtered = []; - for (const msg of messages) { - if (excludeNames && msg.name && excludeNames.includes(msg.name)) { - continue; - } - else if (excludeTypes && _isMessageType(msg, excludeTypes)) { - continue; - } - else if (excludeIds && msg.id && excludeIds.includes(msg.id)) { - continue; - } - // default to inclusion when no inclusion criteria given. - if (!(includeTypes || includeIds || includeNames)) { - filtered.push(msg); - } - else if (includeNames && - msg.name && - includeNames.some((iName) => iName === msg.name)) { - filtered.push(msg); - } - else if (includeTypes && _isMessageType(msg, includeTypes)) { - filtered.push(msg); - } - else if (includeIds && msg.id && includeIds.some((id) => id === msg.id)) { - filtered.push(msg); - } + /** + * Binds the runnable with the specified arguments. + * @param kwargs The arguments to bind the runnable with. + * @returns A new instance of the `RunnableBinding` class that is bound with the specified arguments. + * + * @deprecated Use {@link withConfig} instead. This will be removed in the next breaking release. + */ + bind(kwargs) { + return new this.constructor({ + bound: this.bound, + kwargs: { ...this.kwargs, ...kwargs }, + config: this.config, + }); } - return filtered; -} -function mergeMessageRuns(messages) { - if (Array.isArray(messages)) { - return _mergeMessageRuns(messages); + withConfig(config) { + return new this.constructor({ + bound: this.bound, + kwargs: this.kwargs, + config: { ...this.config, ...config }, + }); } - return RunnableLambda.from(_mergeMessageRuns); -} -function _mergeMessageRuns(messages) { - if (!messages.length) { - return []; + withRetry(fields) { + // eslint-disable-next-line @typescript-eslint/no-use-before-define + return new RunnableRetry({ + bound: this.bound, + kwargs: this.kwargs, + config: this.config, + maxAttemptNumber: fields?.stopAfterAttempt, + ...fields, + }); } - const merged = []; - for (const msg of messages) { - const curr = msg; - const last = merged.pop(); - if (!last) { - merged.push(curr); - } - else if (curr.getType() === "tool" || - !(curr.getType() === last.getType())) { - merged.push(last, curr); - } - else { - const lastChunk = convertToChunk(last); - const currChunk = convertToChunk(curr); - const mergedChunks = lastChunk.concat(currChunk); - if (typeof lastChunk.content === "string" && - typeof currChunk.content === "string") { - mergedChunks.content = `${lastChunk.content}\n${currChunk.content}`; - } - merged.push(_chunkToMsg(mergedChunks)); - } + async invoke(input, options) { + return this.bound.invoke(input, await this._mergeConfig(ensureConfig(options), this.kwargs)); } - return merged; -} -function trimMessages(messagesOrOptions, options) { - if (Array.isArray(messagesOrOptions)) { - const messages = messagesOrOptions; - if (!options) { - throw new Error("Options parameter is required when providing messages."); - } - return _trimMessagesHelper(messages, options); + async batch(inputs, options, batchOptions) { + const mergedOptions = Array.isArray(options) + ? await Promise.all(options.map(async (individualOption) => this._mergeConfig(ensureConfig(individualOption), this.kwargs))) + : await this._mergeConfig(ensureConfig(options), this.kwargs); + return this.bound.batch(inputs, mergedOptions, batchOptions); } - else { - const trimmerOptions = messagesOrOptions; - return RunnableLambda.from((input) => _trimMessagesHelper(input, trimmerOptions)).withConfig({ - runName: "trim_messages", - }); + async *_streamIterator(input, options) { + yield* this.bound._streamIterator(input, await this._mergeConfig(ensureConfig(options), this.kwargs)); } -} -async function _trimMessagesHelper(messages, options) { - const { maxTokens, tokenCounter, strategy = "last", allowPartial = false, endOn, startOn, includeSystem = false, textSplitter, } = options; - if (startOn && strategy === "first") { - throw new Error("`startOn` should only be specified if `strategy` is 'last'."); + async stream(input, options) { + return this.bound.stream(input, await this._mergeConfig(ensureConfig(options), this.kwargs)); } - if (includeSystem && strategy === "first") { - throw new Error("`includeSystem` should only be specified if `strategy` is 'last'."); + async *transform(generator, options) { + yield* this.bound.transform(generator, await this._mergeConfig(ensureConfig(options), this.kwargs)); } - let listTokenCounter; - if ("getNumTokens" in tokenCounter) { - listTokenCounter = async (msgs) => { - const tokenCounts = await Promise.all(msgs.map((msg) => tokenCounter.getNumTokens(msg.content))); - return tokenCounts.reduce((sum, count) => sum + count, 0); + streamEvents(input, options, streamOptions) { + // eslint-disable-next-line @typescript-eslint/no-this-alias + const outerThis = this; + const generator = async function* () { + yield* outerThis.bound.streamEvents(input, { + ...(await outerThis._mergeConfig(ensureConfig(options), outerThis.kwargs)), + version: options.version, + }, streamOptions); }; + return IterableReadableStream.fromAsyncGenerator(generator()); } - else { - listTokenCounter = async (msgs) => tokenCounter(msgs); + static isRunnableBinding( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + thing + // eslint-disable-next-line @typescript-eslint/no-explicit-any + ) { + return thing.bound && Runnable.isRunnable(thing.bound); } - let textSplitterFunc = defaultTextSplitter; - if (textSplitter) { - if ("splitText" in textSplitter) { - textSplitterFunc = textSplitter.splitText; - } - else { - textSplitterFunc = async (text) => textSplitter(text); - } + /** + * Bind lifecycle listeners to a Runnable, returning a new Runnable. + * The Run object contains information about the run, including its id, + * type, input, output, error, startTime, endTime, and any tags or metadata + * added to the run. + * + * @param {Object} params - The object containing the callback functions. + * @param {(run: Run) => void} params.onStart - Called before the runnable starts running, with the Run object. + * @param {(run: Run) => void} params.onEnd - Called after the runnable finishes running, with the Run object. + * @param {(run: Run) => void} params.onError - Called if the runnable throws an error, with the Run object. + */ + withListeners({ onStart, onEnd, onError, }) { + return new RunnableBinding({ + bound: this.bound, + kwargs: this.kwargs, + config: this.config, + configFactories: [ + (config) => ({ + callbacks: [ + new RootListenersTracer({ + config, + onStart, + onEnd, + onError, + }), + ], + }), + ], + }); } - if (strategy === "first") { - return _firstMaxTokens(messages, { - maxTokens, - tokenCounter: listTokenCounter, - textSplitter: textSplitterFunc, - partialStrategy: allowPartial ? "first" : undefined, - endOn, +} +/** + * A runnable that delegates calls to another runnable + * with each element of the input sequence. + * @example + * ```typescript + * import { RunnableEach, RunnableLambda } from "@langchain/core/runnables"; + * + * const toUpperCase = (input: string): string => input.toUpperCase(); + * const addGreeting = (input: string): string => `Hello, ${input}!`; + * + * const upperCaseLambda = RunnableLambda.from(toUpperCase); + * const greetingLambda = RunnableLambda.from(addGreeting); + * + * const chain = new RunnableEach({ + * bound: upperCaseLambda.pipe(greetingLambda), + * }); + * + * const result = await chain.invoke(["alice", "bob", "carol"]) + * + * // ["Hello, ALICE!", "Hello, BOB!", "Hello, CAROL!"] + * ``` + * + * @deprecated This will be removed in the next breaking release. + */ +class RunnableEach extends Runnable { + static lc_name() { + return "RunnableEach"; + } + constructor(fields) { + super(fields); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain_core", "runnables"] + }); + Object.defineProperty(this, "bound", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 }); + this.bound = fields.bound; } - else if (strategy === "last") { - return _lastMaxTokens(messages, { - maxTokens, - tokenCounter: listTokenCounter, - textSplitter: textSplitterFunc, - allowPartial, - includeSystem, - startOn, - endOn, + /** + * Binds the runnable with the specified arguments. + * @param kwargs The arguments to bind the runnable with. + * @returns A new instance of the `RunnableEach` class that is bound with the specified arguments. + * + * @deprecated Use {@link withConfig} instead. This will be removed in the next breaking release. + */ + bind(kwargs) { + return new RunnableEach({ + bound: this.bound.bind(kwargs), }); } - else { - throw new Error(`Unrecognized strategy: '${strategy}'. Must be one of 'first' or 'last'.`); + /** + * Invokes the runnable with the specified input and configuration. + * @param input The input to invoke the runnable with. + * @param config The configuration to invoke the runnable with. + * @returns A promise that resolves to the output of the runnable. + */ + async invoke(inputs, config) { + return this._callWithConfig(this._invoke.bind(this), inputs, config); } -} -async function _firstMaxTokens(messages, options) { - const { maxTokens, tokenCounter, textSplitter, partialStrategy, endOn } = options; - let messagesCopy = [...messages]; - let idx = 0; - for (let i = 0; i < messagesCopy.length; i += 1) { - const remainingMessages = i > 0 ? messagesCopy.slice(0, -i) : messagesCopy; - if ((await tokenCounter(remainingMessages)) <= maxTokens) { - idx = messagesCopy.length - i; - break; - } + /** + * A helper method that is used to invoke the runnable with the specified input and configuration. + * @param input The input to invoke the runnable with. + * @param config The configuration to invoke the runnable with. + * @returns A promise that resolves to the output of the runnable. + */ + async _invoke(inputs, config, runManager) { + return this.bound.batch(inputs, patchConfig(config, { callbacks: runManager?.getChild() })); } - if (idx < messagesCopy.length - 1 && partialStrategy) { - let includedPartial = false; - if (Array.isArray(messagesCopy[idx].content)) { - const excluded = messagesCopy[idx]; - if (typeof excluded.content === "string") { - throw new Error("Expected content to be an array."); - } - const numBlock = excluded.content.length; - const reversedContent = partialStrategy === "last" - ? [...excluded.content].reverse() - : excluded.content; - for (let i = 1; i <= numBlock; i += 1) { - const partialContent = partialStrategy === "first" - ? reversedContent.slice(0, i) - : reversedContent.slice(-i); - const fields = Object.fromEntries(Object.entries(excluded).filter(([k]) => k !== "type" && !k.startsWith("lc_"))); - const updatedMessage = _switchTypeToMessage(excluded.getType(), { - ...fields, - content: partialContent, - }); - const slicedMessages = [...messagesCopy.slice(0, idx), updatedMessage]; - if ((await tokenCounter(slicedMessages)) <= maxTokens) { - messagesCopy = slicedMessages; - idx += 1; - includedPartial = true; - } - else { - break; - } - } - if (includedPartial && partialStrategy === "last") { - excluded.content = [...reversedContent].reverse(); - } - } - if (!includedPartial) { - const excluded = messagesCopy[idx]; - let text; - if (Array.isArray(excluded.content) && - excluded.content.some((block) => typeof block === "string" || block.type === "text")) { - const textBlock = excluded.content.find((block) => block.type === "text" && block.text); - text = textBlock?.text; - } - else if (typeof excluded.content === "string") { - text = excluded.content; - } - if (text) { - const splitTexts = await textSplitter(text); - const numSplits = splitTexts.length; - if (partialStrategy === "last") { - splitTexts.reverse(); - } - for (let _ = 0; _ < numSplits - 1; _ += 1) { - splitTexts.pop(); - excluded.content = splitTexts.join(""); - if ((await tokenCounter([...messagesCopy.slice(0, idx), excluded])) <= - maxTokens) { - if (partialStrategy === "last") { - excluded.content = [...splitTexts].reverse().join(""); - } - messagesCopy = [...messagesCopy.slice(0, idx), excluded]; - idx += 1; - break; - } - } - } - } + /** + * Bind lifecycle listeners to a Runnable, returning a new Runnable. + * The Run object contains information about the run, including its id, + * type, input, output, error, startTime, endTime, and any tags or metadata + * added to the run. + * + * @param {Object} params - The object containing the callback functions. + * @param {(run: Run) => void} params.onStart - Called before the runnable starts running, with the Run object. + * @param {(run: Run) => void} params.onEnd - Called after the runnable finishes running, with the Run object. + * @param {(run: Run) => void} params.onError - Called if the runnable throws an error, with the Run object. + */ + withListeners({ onStart, onEnd, onError, }) { + return new RunnableEach({ + bound: this.bound.withListeners({ onStart, onEnd, onError }), + }); + } +} +/** + * Base class for runnables that can be retried a + * specified number of times. + * @example + * ```typescript + * import { + * RunnableLambda, + * RunnableRetry, + * } from "@langchain/core/runnables"; + * + * // Simulate an API call that fails + * const simulateApiCall = (input: string): string => { + * console.log(`Attempting API call with input: ${input}`); + * throw new Error("API call failed due to network issue"); + * }; + * + * const apiCallLambda = RunnableLambda.from(simulateApiCall); + * + * // Apply retry logic using the .withRetry() method + * const apiCallWithRetry = apiCallLambda.withRetry({ stopAfterAttempt: 3 }); + * + * // Alternatively, create a RunnableRetry instance manually + * const manualRetry = new RunnableRetry({ + * bound: apiCallLambda, + * maxAttemptNumber: 3, + * config: {}, + * }); + * + * // Example invocation using the .withRetry() method + * const res = await apiCallWithRetry + * .invoke("Request 1") + * .catch((error) => { + * console.error("Failed after multiple retries:", error.message); + * }); + * + * // Example invocation using the manual retry instance + * const res2 = await manualRetry + * .invoke("Request 2") + * .catch((error) => { + * console.error("Failed after multiple retries:", error.message); + * }); + * ``` + */ +class RunnableRetry extends RunnableBinding { + static lc_name() { + return "RunnableRetry"; } - if (endOn) { - const endOnArr = Array.isArray(endOn) ? endOn : [endOn]; - while (idx > 0 && !_isMessageType(messagesCopy[idx - 1], endOnArr)) { - idx -= 1; - } + constructor(fields) { + super(fields); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain_core", "runnables"] + }); + Object.defineProperty(this, "maxAttemptNumber", { + enumerable: true, + configurable: true, + writable: true, + value: 3 + }); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + Object.defineProperty(this, "onFailedAttempt", { + enumerable: true, + configurable: true, + writable: true, + value: () => { } + }); + this.maxAttemptNumber = fields.maxAttemptNumber ?? this.maxAttemptNumber; + this.onFailedAttempt = fields.onFailedAttempt ?? this.onFailedAttempt; } - return messagesCopy.slice(0, idx); -} -async function _lastMaxTokens(messages, options) { - const { allowPartial = false, includeSystem = false, endOn, startOn, ...rest } = options; - // Create a copy of messages to avoid mutation - let messagesCopy = messages.map((message) => { - const fields = Object.fromEntries(Object.entries(message).filter(([k]) => k !== "type" && !k.startsWith("lc_"))); - return _switchTypeToMessage(message.getType(), fields, isBaseMessageChunk(message)); - }); - if (endOn) { - const endOnArr = Array.isArray(endOn) ? endOn : [endOn]; - while (messagesCopy.length > 0 && - !_isMessageType(messagesCopy[messagesCopy.length - 1], endOnArr)) { - messagesCopy = messagesCopy.slice(0, -1); - } + _patchConfigForRetry(attempt, config, runManager) { + const tag = attempt > 1 ? `retry:attempt:${attempt}` : undefined; + return patchConfig(config, { callbacks: runManager?.getChild(tag) }); } - const swappedSystem = includeSystem && messagesCopy[0]?.getType() === "system"; - let reversed_ = swappedSystem - ? messagesCopy.slice(0, 1).concat(messagesCopy.slice(1).reverse()) - : messagesCopy.reverse(); - reversed_ = await _firstMaxTokens(reversed_, { - ...rest, - partialStrategy: allowPartial ? "last" : undefined, - endOn: startOn, - }); - if (swappedSystem) { - return [reversed_[0], ...reversed_.slice(1).reverse()]; + async _invoke(input, config, runManager) { + return p_retry((attemptNumber) => super.invoke(input, this._patchConfigForRetry(attemptNumber, config, runManager)), { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + onFailedAttempt: (error) => this.onFailedAttempt(error, input), + retries: Math.max(this.maxAttemptNumber - 1, 0), + randomize: true, + }); } - else { - return reversed_.reverse(); + /** + * Method that invokes the runnable with the specified input, run manager, + * and config. It handles the retry logic by catching any errors and + * recursively invoking itself with the updated config for the next retry + * attempt. + * @param input The input for the runnable. + * @param runManager The run manager for the runnable. + * @param config The config for the runnable. + * @returns A promise that resolves to the output of the runnable. + */ + async invoke(input, config) { + return this._callWithConfig(this._invoke.bind(this), input, config); } -} -const _MSG_CHUNK_MAP = { - human: { - message: human_HumanMessage, - messageChunk: human_HumanMessageChunk, - }, - ai: { - message: ai_AIMessage, - messageChunk: ai_AIMessageChunk, - }, - system: { - message: system_SystemMessage, - messageChunk: system_SystemMessageChunk, - }, - developer: { - message: system_SystemMessage, - messageChunk: system_SystemMessageChunk, - }, - tool: { - message: tool_ToolMessage, - messageChunk: tool_ToolMessageChunk, - }, - function: { - message: function_FunctionMessage, - messageChunk: function_FunctionMessageChunk, - }, - generic: { - message: chat_ChatMessage, - messageChunk: chat_ChatMessageChunk, - }, - remove: { - message: RemoveMessage, - messageChunk: RemoveMessage, // RemoveMessage does not have a chunk class. - }, -}; -function _switchTypeToMessage(messageType, fields, returnChunk) { - let chunk; - let msg; - switch (messageType) { - case "human": - if (returnChunk) { - chunk = new HumanMessageChunk(fields); - } - else { - msg = new HumanMessage(fields); - } - break; - case "ai": - if (returnChunk) { - let aiChunkFields = { - ...fields, - }; - if ("tool_calls" in aiChunkFields) { - aiChunkFields = { - ...aiChunkFields, - tool_call_chunks: aiChunkFields.tool_calls?.map((tc) => ({ - ...tc, - type: "tool_call_chunk", - index: undefined, - args: JSON.stringify(tc.args), - })), - }; - } - chunk = new AIMessageChunk(aiChunkFields); - } - else { - msg = new AIMessage(fields); - } - break; - case "system": - if (returnChunk) { - chunk = new SystemMessageChunk(fields); - } - else { - msg = new SystemMessage(fields); - } - break; - case "developer": - if (returnChunk) { - chunk = new SystemMessageChunk({ - ...fields, - additional_kwargs: { - ...fields.additional_kwargs, - __openai_role__: "developer", - }, - }); - } - else { - msg = new SystemMessage({ - ...fields, - additional_kwargs: { - ...fields.additional_kwargs, - __openai_role__: "developer", - }, + async _batch(inputs, configs, runManagers, batchOptions) { + const resultsMap = {}; + try { + await p_retry(async (attemptNumber) => { + const remainingIndexes = inputs + .map((_, i) => i) + .filter((i) => resultsMap[i.toString()] === undefined || + // eslint-disable-next-line no-instanceof/no-instanceof + resultsMap[i.toString()] instanceof Error); + const remainingInputs = remainingIndexes.map((i) => inputs[i]); + const patchedConfigs = remainingIndexes.map((i) => this._patchConfigForRetry(attemptNumber, configs?.[i], runManagers?.[i])); + const results = await super.batch(remainingInputs, patchedConfigs, { + ...batchOptions, + returnExceptions: true, }); - } - break; - case "tool": - if ("tool_call_id" in fields) { - if (returnChunk) { - chunk = new ToolMessageChunk(fields); - } - else { - msg = new ToolMessage(fields); - } - } - else { - throw new Error("Can not convert ToolMessage to ToolMessageChunk if 'tool_call_id' field is not defined."); - } - break; - case "function": - if (returnChunk) { - chunk = new FunctionMessageChunk(fields); - } - else { - if (!fields.name) { - throw new Error("FunctionMessage must have a 'name' field"); - } - msg = new FunctionMessage(fields); - } - break; - case "generic": - if ("role" in fields) { - if (returnChunk) { - chunk = new ChatMessageChunk(fields); + let firstException; + for (let i = 0; i < results.length; i += 1) { + const result = results[i]; + const resultMapIndex = remainingIndexes[i]; + // eslint-disable-next-line no-instanceof/no-instanceof + if (result instanceof Error) { + if (firstException === undefined) { + firstException = result; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + firstException.input = remainingInputs[i]; + } + } + resultsMap[resultMapIndex.toString()] = result; } - else { - msg = new ChatMessage(fields); + if (firstException) { + throw firstException; } + return results; + }, { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + onFailedAttempt: (error) => this.onFailedAttempt(error, error.input), + retries: Math.max(this.maxAttemptNumber - 1, 0), + randomize: true, + }); + } + catch (e) { + if (batchOptions?.returnExceptions !== true) { + throw e; } - else { - throw new Error("Can not convert ChatMessage to ChatMessageChunk if 'role' field is not defined."); - } - break; - default: - throw new Error(`Unrecognized message type ${messageType}`); - } - if (returnChunk && chunk) { - return chunk; - } - if (msg) { - return msg; - } - throw new Error(`Unrecognized message type ${messageType}`); -} -function _chunkToMsg(chunk) { - const chunkType = chunk.getType(); - let msg; - const fields = Object.fromEntries(Object.entries(chunk).filter(([k]) => !["type", "tool_call_chunks"].includes(k) && !k.startsWith("lc_"))); - if (chunkType in _MSG_CHUNK_MAP) { - msg = _switchTypeToMessage(chunkType, fields); + } + return Object.keys(resultsMap) + .sort((a, b) => parseInt(a, 10) - parseInt(b, 10)) + .map((key) => resultsMap[parseInt(key, 10)]); } - if (!msg) { - throw new Error(`Unrecognized message chunk class ${chunkType}. Supported classes are ${Object.keys(_MSG_CHUNK_MAP)}`); + async batch(inputs, options, batchOptions) { + return this._batchWithConfig(this._batch.bind(this), inputs, options, batchOptions); } - return msg; } /** - * The default text splitter function that splits text by newlines. - * - * @param {string} text - * @returns A promise that resolves to an array of strings split by newlines. - */ -function defaultTextSplitter(text) { - const splits = text.split("\n"); - return Promise.resolve([ - ...splits.slice(0, -1).map((s) => `${s}\n`), - splits[splits.length - 1], - ]); -} - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/index.js - - - - - - - - - - -// TODO: Use a star export when we deprecate the -// existing "ToolCall" type in "base.js". - - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/messages.js - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/js-sha1/hash.js -// @ts-nocheck -// Inlined to deal with portability issues with importing crypto module -/* - * [js-sha1]{@link https://github.com/emn178/js-sha1} - * - * @version 0.6.0 - * @author Chen, Yi-Cyuan [emn178@gmail.com] - * @copyright Chen, Yi-Cyuan 2014-2017 - * @license MIT + * A sequence of runnables, where the output of each is the input of the next. + * @example + * ```typescript + * const promptTemplate = PromptTemplate.fromTemplate( + * "Tell me a joke about {topic}", + * ); + * const chain = RunnableSequence.from([promptTemplate, new ChatOpenAI({ model: "gpt-4o-mini" })]); + * const result = await chain.invoke({ topic: "bears" }); + * ``` */ -/*jslint bitwise: true */ - -var root = typeof window === "object" ? window : {}; -var HEX_CHARS = "0123456789abcdef".split(""); -var EXTRA = [-2147483648, 8388608, 32768, 128]; -var SHIFT = [24, 16, 8, 0]; -var OUTPUT_TYPES = (/* unused pure expression or super */ null && (["hex", "array", "digest", "arrayBuffer"])); -var blocks = []; -function Sha1(sharedMemory) { - if (sharedMemory) { - blocks[0] = - blocks[16] = - blocks[1] = - blocks[2] = - blocks[3] = - blocks[4] = - blocks[5] = - blocks[6] = - blocks[7] = - blocks[8] = - blocks[9] = - blocks[10] = - blocks[11] = - blocks[12] = - blocks[13] = - blocks[14] = - blocks[15] = - 0; - this.blocks = blocks; +class RunnableSequence extends Runnable { + static lc_name() { + return "RunnableSequence"; } - else { - this.blocks = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + constructor(fields) { + super(fields); + Object.defineProperty(this, "first", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "middle", { + enumerable: true, + configurable: true, + writable: true, + value: [] + }); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + Object.defineProperty(this, "last", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "omitSequenceTags", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain_core", "runnables"] + }); + this.first = fields.first; + this.middle = fields.middle ?? this.middle; + this.last = fields.last; + this.name = fields.name; + this.omitSequenceTags = fields.omitSequenceTags ?? this.omitSequenceTags; } - this.h0 = 0x67452301; - this.h1 = 0xefcdab89; - this.h2 = 0x98badcfe; - this.h3 = 0x10325476; - this.h4 = 0xc3d2e1f0; - this.block = this.start = this.bytes = this.hBytes = 0; - this.finalized = this.hashed = false; - this.first = true; -} -Sha1.prototype.update = function (message) { - if (this.finalized) { - return; + get steps() { + return [this.first, ...this.middle, this.last]; } - var notString = typeof message !== "string"; - if (notString && message.constructor === root.ArrayBuffer) { - message = new Uint8Array(message); + async invoke(input, options) { + const config = ensureConfig(options); + const callbackManager_ = await getCallbackManagerForConfig(config); + const runManager = await callbackManager_?.handleChainStart(this.toJSON(), base_coerceToDict(input, "input"), config.runId, undefined, undefined, undefined, config?.runName); + delete config.runId; + let nextStepInput = input; + let finalOutput; + try { + const initialSteps = [this.first, ...this.middle]; + for (let i = 0; i < initialSteps.length; i += 1) { + const step = initialSteps[i]; + const promise = step.invoke(nextStepInput, patchConfig(config, { + callbacks: runManager?.getChild(this.omitSequenceTags ? undefined : `seq:step:${i + 1}`), + })); + nextStepInput = await raceWithSignal(promise, options?.signal); + } + // TypeScript can't detect that the last output of the sequence returns RunOutput, so call it out of the loop here + if (options?.signal?.aborted) { + throw new Error("Aborted"); + } + finalOutput = await this.last.invoke(nextStepInput, patchConfig(config, { + callbacks: runManager?.getChild(this.omitSequenceTags ? undefined : `seq:step:${this.steps.length}`), + })); + } + catch (e) { + await runManager?.handleChainError(e); + throw e; + } + await runManager?.handleChainEnd(base_coerceToDict(finalOutput, "output")); + return finalOutput; } - var code, index = 0, i, length = message.length || 0, blocks = this.blocks; - while (index < length) { - if (this.hashed) { - this.hashed = false; - blocks[0] = this.block; - blocks[16] = - blocks[1] = - blocks[2] = - blocks[3] = - blocks[4] = - blocks[5] = - blocks[6] = - blocks[7] = - blocks[8] = - blocks[9] = - blocks[10] = - blocks[11] = - blocks[12] = - blocks[13] = - blocks[14] = - blocks[15] = - 0; + async batch(inputs, options, batchOptions) { + const configList = this._getOptionsList(options ?? {}, inputs.length); + const callbackManagers = await Promise.all(configList.map(getCallbackManagerForConfig)); + const runManagers = await Promise.all(callbackManagers.map(async (callbackManager, i) => { + const handleStartRes = await callbackManager?.handleChainStart(this.toJSON(), base_coerceToDict(inputs[i], "input"), configList[i].runId, undefined, undefined, undefined, configList[i].runName); + delete configList[i].runId; + return handleStartRes; + })); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let nextStepInputs = inputs; + try { + for (let i = 0; i < this.steps.length; i += 1) { + const step = this.steps[i]; + const promise = step.batch(nextStepInputs, runManagers.map((runManager, j) => { + const childRunManager = runManager?.getChild(this.omitSequenceTags ? undefined : `seq:step:${i + 1}`); + return patchConfig(configList[j], { callbacks: childRunManager }); + }), batchOptions); + nextStepInputs = await raceWithSignal(promise, configList[0]?.signal); + } + } + catch (e) { + await Promise.all(runManagers.map((runManager) => runManager?.handleChainError(e))); + throw e; + } + await Promise.all(runManagers.map((runManager) => runManager?.handleChainEnd(base_coerceToDict(nextStepInputs, "output")))); + return nextStepInputs; + } + async *_streamIterator(input, options) { + const callbackManager_ = await getCallbackManagerForConfig(options); + const { runId, ...otherOptions } = options ?? {}; + const runManager = await callbackManager_?.handleChainStart(this.toJSON(), base_coerceToDict(input, "input"), runId, undefined, undefined, undefined, otherOptions?.runName); + const steps = [this.first, ...this.middle, this.last]; + let concatSupported = true; + let finalOutput; + async function* inputGenerator() { + yield input; } - if (notString) { - for (i = this.start; index < length && i < 64; ++index) { - blocks[i >> 2] |= message[index] << SHIFT[i++ & 3]; + try { + let finalGenerator = steps[0].transform(inputGenerator(), patchConfig(otherOptions, { + callbacks: runManager?.getChild(this.omitSequenceTags ? undefined : `seq:step:1`), + })); + for (let i = 1; i < steps.length; i += 1) { + const step = steps[i]; + finalGenerator = await step.transform(finalGenerator, patchConfig(otherOptions, { + callbacks: runManager?.getChild(this.omitSequenceTags ? undefined : `seq:step:${i + 1}`), + })); } - } - else { - for (i = this.start; index < length && i < 64; ++index) { - code = message.charCodeAt(index); - if (code < 0x80) { - blocks[i >> 2] |= code << SHIFT[i++ & 3]; - } - else if (code < 0x800) { - blocks[i >> 2] |= (0xc0 | (code >> 6)) << SHIFT[i++ & 3]; - blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; - } - else if (code < 0xd800 || code >= 0xe000) { - blocks[i >> 2] |= (0xe0 | (code >> 12)) << SHIFT[i++ & 3]; - blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3]; - blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; - } - else { - code = - 0x10000 + - (((code & 0x3ff) << 10) | (message.charCodeAt(++index) & 0x3ff)); - blocks[i >> 2] |= (0xf0 | (code >> 18)) << SHIFT[i++ & 3]; - blocks[i >> 2] |= (0x80 | ((code >> 12) & 0x3f)) << SHIFT[i++ & 3]; - blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3]; - blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; + for await (const chunk of finalGenerator) { + options?.signal?.throwIfAborted(); + yield chunk; + if (concatSupported) { + if (finalOutput === undefined) { + finalOutput = chunk; + } + else { + try { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + finalOutput = concat(finalOutput, chunk); + } + catch (e) { + finalOutput = undefined; + concatSupported = false; + } + } } } } - this.lastByteIndex = i; - this.bytes += i - this.start; - if (i >= 64) { - this.block = blocks[16]; - this.start = i - 64; - this.hash(); - this.hashed = true; + catch (e) { + await runManager?.handleChainError(e); + throw e; + } + await runManager?.handleChainEnd(base_coerceToDict(finalOutput, "output")); + } + getGraph(config) { + const graph = new Graph(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let currentLastNode = null; + this.steps.forEach((step, index) => { + const stepGraph = step.getGraph(config); + if (index !== 0) { + stepGraph.trimFirstNode(); + } + if (index !== this.steps.length - 1) { + stepGraph.trimLastNode(); + } + graph.extend(stepGraph); + const stepFirstNode = stepGraph.firstNode(); + if (!stepFirstNode) { + throw new Error(`Runnable ${step} has no first node`); + } + if (currentLastNode) { + graph.addEdge(currentLastNode, stepFirstNode); + } + currentLastNode = stepGraph.lastNode(); + }); + return graph; + } + pipe(coerceable) { + if (RunnableSequence.isRunnableSequence(coerceable)) { + return new RunnableSequence({ + first: this.first, + middle: this.middle.concat([ + this.last, + coerceable.first, + ...coerceable.middle, + ]), + last: coerceable.last, + name: this.name ?? coerceable.name, + }); } else { - this.start = i; + return new RunnableSequence({ + first: this.first, + middle: [...this.middle, this.last], + last: _coerceToRunnable(coerceable), + name: this.name, + }); } } - if (this.bytes > 4294967295) { - this.hBytes += (this.bytes / 4294967296) << 0; - this.bytes = this.bytes % 4294967296; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + static isRunnableSequence(thing) { + return Array.isArray(thing.middle) && Runnable.isRunnable(thing); } - return this; -}; -Sha1.prototype.finalize = function () { - if (this.finalized) { - return; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + static from([first, ...runnables], nameOrFields) { + let extra = {}; + if (typeof nameOrFields === "string") { + extra.name = nameOrFields; + } + else if (nameOrFields !== undefined) { + extra = nameOrFields; + } + return new RunnableSequence({ + ...extra, + first: _coerceToRunnable(first), + middle: runnables.slice(0, -1).map(_coerceToRunnable), + last: _coerceToRunnable(runnables[runnables.length - 1]), + }); } - this.finalized = true; - var blocks = this.blocks, i = this.lastByteIndex; - blocks[16] = this.block; - blocks[i >> 2] |= EXTRA[i & 3]; - this.block = blocks[16]; - if (i >= 56) { - if (!this.hashed) { - this.hash(); +} +/** + * A runnable that runs a mapping of runnables in parallel, + * and returns a mapping of their outputs. + * @example + * ```typescript + * const mapChain = RunnableMap.from({ + * joke: PromptTemplate.fromTemplate("Tell me a joke about {topic}").pipe( + * new ChatAnthropic({}), + * ), + * poem: PromptTemplate.fromTemplate("write a 2-line poem about {topic}").pipe( + * new ChatAnthropic({}), + * ), + * }); + * const result = await mapChain.invoke({ topic: "bear" }); + * ``` + */ +class RunnableMap extends Runnable { + static lc_name() { + return "RunnableMap"; + } + getStepsKeys() { + return Object.keys(this.steps); + } + constructor(fields) { + super(fields); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain_core", "runnables"] + }); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "steps", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.steps = {}; + for (const [key, value] of Object.entries(fields.steps)) { + this.steps[key] = _coerceToRunnable(value); } - blocks[0] = this.block; - blocks[16] = - blocks[1] = - blocks[2] = - blocks[3] = - blocks[4] = - blocks[5] = - blocks[6] = - blocks[7] = - blocks[8] = - blocks[9] = - blocks[10] = - blocks[11] = - blocks[12] = - blocks[13] = - blocks[14] = - blocks[15] = - 0; } - blocks[14] = (this.hBytes << 3) | (this.bytes >>> 29); - blocks[15] = this.bytes << 3; - this.hash(); -}; -Sha1.prototype.hash = function () { - var a = this.h0, b = this.h1, c = this.h2, d = this.h3, e = this.h4; - var f, j, t, blocks = this.blocks; - for (j = 16; j < 80; ++j) { - t = blocks[j - 3] ^ blocks[j - 8] ^ blocks[j - 14] ^ blocks[j - 16]; - blocks[j] = (t << 1) | (t >>> 31); + static from(steps) { + return new RunnableMap({ steps }); } - for (j = 0; j < 20; j += 5) { - f = (b & c) | (~b & d); - t = (a << 5) | (a >>> 27); - e = (t + f + e + 1518500249 + blocks[j]) << 0; - b = (b << 30) | (b >>> 2); - f = (a & b) | (~a & c); - t = (e << 5) | (e >>> 27); - d = (t + f + d + 1518500249 + blocks[j + 1]) << 0; - a = (a << 30) | (a >>> 2); - f = (e & a) | (~e & b); - t = (d << 5) | (d >>> 27); - c = (t + f + c + 1518500249 + blocks[j + 2]) << 0; - e = (e << 30) | (e >>> 2); - f = (d & e) | (~d & a); - t = (c << 5) | (c >>> 27); - b = (t + f + b + 1518500249 + blocks[j + 3]) << 0; - d = (d << 30) | (d >>> 2); - f = (c & d) | (~c & e); - t = (b << 5) | (b >>> 27); - a = (t + f + a + 1518500249 + blocks[j + 4]) << 0; - c = (c << 30) | (c >>> 2); + async invoke(input, options) { + const config = ensureConfig(options); + const callbackManager_ = await getCallbackManagerForConfig(config); + const runManager = await callbackManager_?.handleChainStart(this.toJSON(), { + input, + }, config.runId, undefined, undefined, undefined, config?.runName); + delete config.runId; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const output = {}; + try { + const promises = Object.entries(this.steps).map(async ([key, runnable]) => { + output[key] = await runnable.invoke(input, patchConfig(config, { + callbacks: runManager?.getChild(`map:key:${key}`), + })); + }); + await raceWithSignal(Promise.all(promises), options?.signal); + } + catch (e) { + await runManager?.handleChainError(e); + throw e; + } + await runManager?.handleChainEnd(output); + return output; } - for (; j < 40; j += 5) { - f = b ^ c ^ d; - t = (a << 5) | (a >>> 27); - e = (t + f + e + 1859775393 + blocks[j]) << 0; - b = (b << 30) | (b >>> 2); - f = a ^ b ^ c; - t = (e << 5) | (e >>> 27); - d = (t + f + d + 1859775393 + blocks[j + 1]) << 0; - a = (a << 30) | (a >>> 2); - f = e ^ a ^ b; - t = (d << 5) | (d >>> 27); - c = (t + f + c + 1859775393 + blocks[j + 2]) << 0; - e = (e << 30) | (e >>> 2); - f = d ^ e ^ a; - t = (c << 5) | (c >>> 27); - b = (t + f + b + 1859775393 + blocks[j + 3]) << 0; - d = (d << 30) | (d >>> 2); - f = c ^ d ^ e; - t = (b << 5) | (b >>> 27); - a = (t + f + a + 1859775393 + blocks[j + 4]) << 0; - c = (c << 30) | (c >>> 2); + async *_transform(generator, runManager, options) { + // shallow copy steps to ignore changes while iterating + const steps = { ...this.steps }; + // each step gets a copy of the input iterator + const inputCopies = atee(generator, Object.keys(steps).length); + // start the first iteration of each output iterator + const tasks = new Map(Object.entries(steps).map(([key, runnable], i) => { + const gen = runnable.transform(inputCopies[i], patchConfig(options, { + callbacks: runManager?.getChild(`map:key:${key}`), + })); + return [key, gen.next().then((result) => ({ key, gen, result }))]; + })); + // yield chunks as they become available, + // starting new iterations as needed, + // until all iterators are done + while (tasks.size) { + const promise = Promise.race(tasks.values()); + const { key, result, gen } = await raceWithSignal(promise, options?.signal); + tasks.delete(key); + if (!result.done) { + yield { [key]: result.value }; + tasks.set(key, gen.next().then((result) => ({ key, gen, result }))); + } + } } - for (; j < 60; j += 5) { - f = (b & c) | (b & d) | (c & d); - t = (a << 5) | (a >>> 27); - e = (t + f + e - 1894007588 + blocks[j]) << 0; - b = (b << 30) | (b >>> 2); - f = (a & b) | (a & c) | (b & c); - t = (e << 5) | (e >>> 27); - d = (t + f + d - 1894007588 + blocks[j + 1]) << 0; - a = (a << 30) | (a >>> 2); - f = (e & a) | (e & b) | (a & b); - t = (d << 5) | (d >>> 27); - c = (t + f + c - 1894007588 + blocks[j + 2]) << 0; - e = (e << 30) | (e >>> 2); - f = (d & e) | (d & a) | (e & a); - t = (c << 5) | (c >>> 27); - b = (t + f + b - 1894007588 + blocks[j + 3]) << 0; - d = (d << 30) | (d >>> 2); - f = (c & d) | (c & e) | (d & e); - t = (b << 5) | (b >>> 27); - a = (t + f + a - 1894007588 + blocks[j + 4]) << 0; - c = (c << 30) | (c >>> 2); + transform(generator, options) { + return this._transformStreamWithConfig(generator, this._transform.bind(this), options); } - for (; j < 80; j += 5) { - f = b ^ c ^ d; - t = (a << 5) | (a >>> 27); - e = (t + f + e - 899497514 + blocks[j]) << 0; - b = (b << 30) | (b >>> 2); - f = a ^ b ^ c; - t = (e << 5) | (e >>> 27); - d = (t + f + d - 899497514 + blocks[j + 1]) << 0; - a = (a << 30) | (a >>> 2); - f = e ^ a ^ b; - t = (d << 5) | (d >>> 27); - c = (t + f + c - 899497514 + blocks[j + 2]) << 0; - e = (e << 30) | (e >>> 2); - f = d ^ e ^ a; - t = (c << 5) | (c >>> 27); - b = (t + f + b - 899497514 + blocks[j + 3]) << 0; - d = (d << 30) | (d >>> 2); - f = c ^ d ^ e; - t = (b << 5) | (b >>> 27); - a = (t + f + a - 899497514 + blocks[j + 4]) << 0; - c = (c << 30) | (c >>> 2); + async stream(input, options) { + async function* generator() { + yield input; + } + const config = ensureConfig(options); + const wrappedGenerator = new AsyncGeneratorWithSetup({ + generator: this.transform(generator(), config), + config, + }); + await wrappedGenerator.setup; + return IterableReadableStream.fromAsyncGenerator(wrappedGenerator); } - this.h0 = (this.h0 + a) << 0; - this.h1 = (this.h1 + b) << 0; - this.h2 = (this.h2 + c) << 0; - this.h3 = (this.h3 + d) << 0; - this.h4 = (this.h4 + e) << 0; -}; -Sha1.prototype.hex = function () { - this.finalize(); - var h0 = this.h0, h1 = this.h1, h2 = this.h2, h3 = this.h3, h4 = this.h4; - return (HEX_CHARS[(h0 >> 28) & 0x0f] + - HEX_CHARS[(h0 >> 24) & 0x0f] + - HEX_CHARS[(h0 >> 20) & 0x0f] + - HEX_CHARS[(h0 >> 16) & 0x0f] + - HEX_CHARS[(h0 >> 12) & 0x0f] + - HEX_CHARS[(h0 >> 8) & 0x0f] + - HEX_CHARS[(h0 >> 4) & 0x0f] + - HEX_CHARS[h0 & 0x0f] + - HEX_CHARS[(h1 >> 28) & 0x0f] + - HEX_CHARS[(h1 >> 24) & 0x0f] + - HEX_CHARS[(h1 >> 20) & 0x0f] + - HEX_CHARS[(h1 >> 16) & 0x0f] + - HEX_CHARS[(h1 >> 12) & 0x0f] + - HEX_CHARS[(h1 >> 8) & 0x0f] + - HEX_CHARS[(h1 >> 4) & 0x0f] + - HEX_CHARS[h1 & 0x0f] + - HEX_CHARS[(h2 >> 28) & 0x0f] + - HEX_CHARS[(h2 >> 24) & 0x0f] + - HEX_CHARS[(h2 >> 20) & 0x0f] + - HEX_CHARS[(h2 >> 16) & 0x0f] + - HEX_CHARS[(h2 >> 12) & 0x0f] + - HEX_CHARS[(h2 >> 8) & 0x0f] + - HEX_CHARS[(h2 >> 4) & 0x0f] + - HEX_CHARS[h2 & 0x0f] + - HEX_CHARS[(h3 >> 28) & 0x0f] + - HEX_CHARS[(h3 >> 24) & 0x0f] + - HEX_CHARS[(h3 >> 20) & 0x0f] + - HEX_CHARS[(h3 >> 16) & 0x0f] + - HEX_CHARS[(h3 >> 12) & 0x0f] + - HEX_CHARS[(h3 >> 8) & 0x0f] + - HEX_CHARS[(h3 >> 4) & 0x0f] + - HEX_CHARS[h3 & 0x0f] + - HEX_CHARS[(h4 >> 28) & 0x0f] + - HEX_CHARS[(h4 >> 24) & 0x0f] + - HEX_CHARS[(h4 >> 20) & 0x0f] + - HEX_CHARS[(h4 >> 16) & 0x0f] + - HEX_CHARS[(h4 >> 12) & 0x0f] + - HEX_CHARS[(h4 >> 8) & 0x0f] + - HEX_CHARS[(h4 >> 4) & 0x0f] + - HEX_CHARS[h4 & 0x0f]); -}; -Sha1.prototype.toString = Sha1.prototype.hex; -Sha1.prototype.digest = function () { - this.finalize(); - var h0 = this.h0, h1 = this.h1, h2 = this.h2, h3 = this.h3, h4 = this.h4; - return [ - (h0 >> 24) & 0xff, - (h0 >> 16) & 0xff, - (h0 >> 8) & 0xff, - h0 & 0xff, - (h1 >> 24) & 0xff, - (h1 >> 16) & 0xff, - (h1 >> 8) & 0xff, - h1 & 0xff, - (h2 >> 24) & 0xff, - (h2 >> 16) & 0xff, - (h2 >> 8) & 0xff, - h2 & 0xff, - (h3 >> 24) & 0xff, - (h3 >> 16) & 0xff, - (h3 >> 8) & 0xff, - h3 & 0xff, - (h4 >> 24) & 0xff, - (h4 >> 16) & 0xff, - (h4 >> 8) & 0xff, - h4 & 0xff, - ]; -}; -Sha1.prototype.array = Sha1.prototype.digest; -Sha1.prototype.arrayBuffer = function () { - this.finalize(); - var buffer = new ArrayBuffer(20); - var dataView = new DataView(buffer); - dataView.setUint32(0, this.h0); - dataView.setUint32(4, this.h1); - dataView.setUint32(8, this.h2); - dataView.setUint32(12, this.h3); - dataView.setUint32(16, this.h4); - return buffer; -}; -const insecureHash = (message) => { - return new Sha1(true).update(message)["hex"](); -}; - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/hash.js - - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/caches/base.js - - +} /** - * This cache key should be consistent across all versions of LangChain. - * It is currently NOT consistent across versions of LangChain. - * - * A huge benefit of having a remote cache (like redis) is that you can - * access the cache from different processes/machines. The allows you to - * separate concerns and scale horizontally. - * - * TODO: Make cache key consistent across versions of LangChain. + * A runnable that wraps a traced LangSmith function. */ -const getCacheKey = (...strings) => insecureHash(strings.join("_")); -function deserializeStoredGeneration(storedGeneration) { - if (storedGeneration.message !== undefined) { - return { - text: storedGeneration.text, - message: mapStoredMessageToChatMessage(storedGeneration.message), - }; +class RunnableTraceable extends Runnable { + constructor(fields) { + super(fields); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain_core", "runnables"] + }); + Object.defineProperty(this, "func", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + if (!isTraceableFunction(fields.func)) { + throw new Error("RunnableTraceable requires a function that is wrapped in traceable higher-order function"); + } + this.func = fields.func; } - else { - return { text: storedGeneration.text }; + async invoke(input, options) { + const [config] = this._getOptionsList(options ?? {}, 1); + const callbacks = await getCallbackManagerForConfig(config); + const promise = this.func(patchConfig(config, { callbacks }), input); + return raceWithSignal(promise, config?.signal); } -} -function serializeGeneration(generation) { - const serializedValue = { - text: generation.text, - }; - if (generation.message !== undefined) { - serializedValue.message = generation.message.toDict(); + async *_streamIterator(input, options) { + const [config] = this._getOptionsList(options ?? {}, 1); + const result = await this.invoke(input, options); + if (iter_isAsyncIterable(result)) { + for await (const item of result) { + config?.signal?.throwIfAborted(); + yield item; + } + return; + } + if (isIterator(result)) { + while (true) { + config?.signal?.throwIfAborted(); + const state = result.next(); + if (state.done) + break; + yield state.value; + } + return; + } + yield result; + } + static from(func) { + return new RunnableTraceable({ func }); } - return serializedValue; } -/** - * Base class for all caches. All caches should extend this class. - */ -class BaseCache { +function assertNonTraceableFunction(func) { + if (isTraceableFunction(func)) { + throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen."); + } } -const GLOBAL_MAP = new Map(); /** - * A cache for storing LLM generations that stores data in memory. + * A runnable that wraps an arbitrary function that takes a single argument. + * @example + * ```typescript + * import { RunnableLambda } from "@langchain/core/runnables"; + * + * const add = (input: { x: number; y: number }) => input.x + input.y; + * + * const multiply = (input: { value: number; multiplier: number }) => + * input.value * input.multiplier; + * + * // Create runnables for the functions + * const addLambda = RunnableLambda.from(add); + * const multiplyLambda = RunnableLambda.from(multiply); + * + * // Chain the lambdas for a mathematical operation + * const chainedLambda = addLambda.pipe((result) => + * multiplyLambda.invoke({ value: result, multiplier: 2 }) + * ); + * + * // Example invocation of the chainedLambda + * const result = await chainedLambda.invoke({ x: 2, y: 3 }); + * + * // Will log "10" (since (2 + 3) * 2 = 10) + * ``` */ -class InMemoryCache extends BaseCache { - constructor(map) { - super(); - Object.defineProperty(this, "cache", { +class base_RunnableLambda extends Runnable { + static lc_name() { + return "RunnableLambda"; + } + constructor(fields) { + if (isTraceableFunction(fields.func)) { + // eslint-disable-next-line no-constructor-return + return RunnableTraceable.from(fields.func); + } + super(fields); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain_core", "runnables"] + }); + Object.defineProperty(this, "func", { enumerable: true, configurable: true, writable: true, value: void 0 }); - this.cache = map ?? new Map(); + assertNonTraceableFunction(fields.func); + this.func = fields.func; } - /** - * Retrieves data from the cache using a prompt and an LLM key. If the - * data is not found, it returns null. - * @param prompt The prompt used to find the data. - * @param llmKey The LLM key used to find the data. - * @returns The data corresponding to the prompt and LLM key, or null if not found. - */ - lookup(prompt, llmKey) { - return Promise.resolve(this.cache.get(getCacheKey(prompt, llmKey)) ?? null); + static from(func) { + return new base_RunnableLambda({ + func, + }); } - /** - * Updates the cache with new data using a prompt and an LLM key. - * @param prompt The prompt used to store the data. - * @param llmKey The LLM key used to store the data. - * @param value The data to be stored. - */ - async update(prompt, llmKey, value) { - this.cache.set(getCacheKey(prompt, llmKey), value); + async _invoke(input, config, runManager) { + return new Promise((resolve, reject) => { + const childConfig = patchConfig(config, { + callbacks: runManager?.getChild(), + recursionLimit: (config?.recursionLimit ?? DEFAULT_RECURSION_LIMIT) - 1, + }); + void async_local_storage_AsyncLocalStorageProviderSingleton.runWithConfig(pickRunnableConfigKeys(childConfig), async () => { + try { + let output = await this.func(input, { + ...childConfig, + }); + if (output && Runnable.isRunnable(output)) { + if (config?.recursionLimit === 0) { + throw new Error("Recursion limit reached."); + } + output = await output.invoke(input, { + ...childConfig, + recursionLimit: (childConfig.recursionLimit ?? DEFAULT_RECURSION_LIMIT) - 1, + }); + } + else if (iter_isAsyncIterable(output)) { + let finalOutput; + for await (const chunk of consumeAsyncIterableInContext(childConfig, output)) { + config?.signal?.throwIfAborted(); + if (finalOutput === undefined) { + finalOutput = chunk; + } + else { + // Make a best effort to gather, for any type that supports concat. + try { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + finalOutput = concat(finalOutput, chunk); + } + catch (e) { + finalOutput = chunk; + } + } + } + output = finalOutput; + } + else if (isIterableIterator(output)) { + let finalOutput; + for (const chunk of consumeIteratorInContext(childConfig, output)) { + config?.signal?.throwIfAborted(); + if (finalOutput === undefined) { + finalOutput = chunk; + } + else { + // Make a best effort to gather, for any type that supports concat. + try { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + finalOutput = concat(finalOutput, chunk); + } + catch (e) { + finalOutput = chunk; + } + } + } + output = finalOutput; + } + resolve(output); + } + catch (e) { + reject(e); + } + }); + }); } - /** - * Returns a global instance of InMemoryCache using a predefined global - * map as the initial cache. - * @returns A global instance of InMemoryCache. - */ - static global() { - return new InMemoryCache(GLOBAL_MAP); + async invoke(input, options) { + return this._callWithConfig(this._invoke.bind(this), input, options); + } + async *_transform(generator, runManager, config) { + let finalChunk; + for await (const chunk of generator) { + if (finalChunk === undefined) { + finalChunk = chunk; + } + else { + // Make a best effort to gather, for any type that supports concat. + try { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + finalChunk = concat(finalChunk, chunk); + } + catch (e) { + finalChunk = chunk; + } + } + } + const childConfig = patchConfig(config, { + callbacks: runManager?.getChild(), + recursionLimit: (config?.recursionLimit ?? DEFAULT_RECURSION_LIMIT) - 1, + }); + const output = await new Promise((resolve, reject) => { + void async_local_storage_AsyncLocalStorageProviderSingleton.runWithConfig(pickRunnableConfigKeys(childConfig), async () => { + try { + const res = await this.func(finalChunk, { + ...childConfig, + config: childConfig, + }); + resolve(res); + } + catch (e) { + reject(e); + } + }); + }); + if (output && Runnable.isRunnable(output)) { + if (config?.recursionLimit === 0) { + throw new Error("Recursion limit reached."); + } + const stream = await output.stream(finalChunk, childConfig); + for await (const chunk of stream) { + yield chunk; + } + } + else if (iter_isAsyncIterable(output)) { + for await (const chunk of consumeAsyncIterableInContext(childConfig, output)) { + config?.signal?.throwIfAborted(); + yield chunk; + } + } + else if (isIterableIterator(output)) { + for (const chunk of consumeIteratorInContext(childConfig, output)) { + config?.signal?.throwIfAborted(); + yield chunk; + } + } + else { + yield output; + } + } + transform(generator, options) { + return this._transformStreamWithConfig(generator, this._transform.bind(this), options); + } + async stream(input, options) { + async function* generator() { + yield input; + } + const config = ensureConfig(options); + const wrappedGenerator = new AsyncGeneratorWithSetup({ + generator: this.transform(generator(), config), + config, + }); + await wrappedGenerator.setup; + return IterableReadableStream.fromAsyncGenerator(wrappedGenerator); } } - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/prompt_values.js - - - /** - * Base PromptValue class. All prompt values should extend this class. + * A runnable that runs a mapping of runnables in parallel, + * and returns a mapping of their outputs. + * @example + * ```typescript + * import { + * RunnableLambda, + * RunnableParallel, + * } from "@langchain/core/runnables"; + * + * const addYears = (age: number): number => age + 5; + * const yearsToFifty = (age: number): number => 50 - age; + * const yearsToHundred = (age: number): number => 100 - age; + * + * const addYearsLambda = RunnableLambda.from(addYears); + * const milestoneFiftyLambda = RunnableLambda.from(yearsToFifty); + * const milestoneHundredLambda = RunnableLambda.from(yearsToHundred); + * + * // Pipe will coerce objects into RunnableParallel by default, but we + * // explicitly instantiate one here to demonstrate + * const sequence = addYearsLambda.pipe( + * RunnableParallel.from({ + * years_to_fifty: milestoneFiftyLambda, + * years_to_hundred: milestoneHundredLambda, + * }) + * ); + * + * // Invoke the sequence with a single age input + * const res = await sequence.invoke(25); + * + * // { years_to_fifty: 20, years_to_hundred: 70 } + * ``` */ -class BasePromptValue extends Serializable { +class RunnableParallel extends (/* unused pure expression or super */ null && (RunnableMap)) { } /** - * Represents a prompt value as a string. It extends the BasePromptValue - * class and overrides the toString and toChatMessages methods. + * A Runnable that can fallback to other Runnables if it fails. + * External APIs (e.g., APIs for a language model) may at times experience + * degraded performance or even downtime. + * + * In these cases, it can be useful to have a fallback Runnable that can be + * used in place of the original Runnable (e.g., fallback to another LLM provider). + * + * Fallbacks can be defined at the level of a single Runnable, or at the level + * of a chain of Runnables. Fallbacks are tried in order until one succeeds or + * all fail. + * + * While you can instantiate a `RunnableWithFallbacks` directly, it is usually + * more convenient to use the `withFallbacks` method on an existing Runnable. + * + * When streaming, fallbacks will only be called on failures during the initial + * stream creation. Errors that occur after a stream starts will not fallback + * to the next Runnable. + * + * @example + * ```typescript + * import { + * RunnableLambda, + * RunnableWithFallbacks, + * } from "@langchain/core/runnables"; + * + * const primaryOperation = (input: string): string => { + * if (input !== "safe") { + * throw new Error("Primary operation failed due to unsafe input"); + * } + * return `Processed: ${input}`; + * }; + * + * // Define a fallback operation that processes the input differently + * const fallbackOperation = (input: string): string => + * `Fallback processed: ${input}`; + * + * const primaryRunnable = RunnableLambda.from(primaryOperation); + * const fallbackRunnable = RunnableLambda.from(fallbackOperation); + * + * // Apply the fallback logic using the .withFallbacks() method + * const runnableWithFallback = primaryRunnable.withFallbacks([fallbackRunnable]); + * + * // Alternatively, create a RunnableWithFallbacks instance manually + * const manualFallbackChain = new RunnableWithFallbacks({ + * runnable: primaryRunnable, + * fallbacks: [fallbackRunnable], + * }); + * + * // Example invocation using .withFallbacks() + * const res = await runnableWithFallback + * .invoke("unsafe input") + * .catch((error) => { + * console.error("Failed after all attempts:", error.message); + * }); + * + * // "Fallback processed: unsafe input" + * + * // Example invocation using manual instantiation + * const res = await manualFallbackChain + * .invoke("safe") + * .catch((error) => { + * console.error("Failed after all attempts:", error.message); + * }); + * + * // "Processed: safe" + * ``` */ -class StringPromptValue extends BasePromptValue { +class RunnableWithFallbacks extends Runnable { static lc_name() { - return "StringPromptValue"; + return "RunnableWithFallbacks"; } - constructor(value) { - super({ value }); + constructor(fields) { + super(fields); Object.defineProperty(this, "lc_namespace", { enumerable: true, configurable: true, writable: true, - value: ["langchain_core", "prompt_values"] + value: ["langchain_core", "runnables"] }); Object.defineProperty(this, "lc_serializable", { enumerable: true, @@ -101638,81 +107233,207 @@ class StringPromptValue extends BasePromptValue { writable: true, value: true }); - Object.defineProperty(this, "value", { + Object.defineProperty(this, "runnable", { enumerable: true, configurable: true, writable: true, value: void 0 }); - this.value = value; + Object.defineProperty(this, "fallbacks", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.runnable = fields.runnable; + this.fallbacks = fields.fallbacks; } - toString() { - return this.value; + *runnables() { + yield this.runnable; + for (const fallback of this.fallbacks) { + yield fallback; + } } - toChatMessages() { - return [new human_HumanMessage(this.value)]; + async invoke(input, options) { + const config = ensureConfig(options); + const callbackManager_ = await getCallbackManagerForConfig(config); + const { runId, ...otherConfigFields } = config; + const runManager = await callbackManager_?.handleChainStart(this.toJSON(), base_coerceToDict(input, "input"), runId, undefined, undefined, undefined, otherConfigFields?.runName); + const childConfig = patchConfig(otherConfigFields, { + callbacks: runManager?.getChild(), + }); + const res = await async_local_storage_AsyncLocalStorageProviderSingleton.runWithConfig(childConfig, async () => { + let firstError; + for (const runnable of this.runnables()) { + config?.signal?.throwIfAborted(); + try { + const output = await runnable.invoke(input, childConfig); + await runManager?.handleChainEnd(base_coerceToDict(output, "output")); + return output; + } + catch (e) { + if (firstError === undefined) { + firstError = e; + } + } + } + if (firstError === undefined) { + throw new Error("No error stored at end of fallback."); + } + await runManager?.handleChainError(firstError); + throw firstError; + }); + return res; + } + async *_streamIterator(input, options) { + const config = ensureConfig(options); + const callbackManager_ = await getCallbackManagerForConfig(config); + const { runId, ...otherConfigFields } = config; + const runManager = await callbackManager_?.handleChainStart(this.toJSON(), base_coerceToDict(input, "input"), runId, undefined, undefined, undefined, otherConfigFields?.runName); + let firstError; + let stream; + for (const runnable of this.runnables()) { + config?.signal?.throwIfAborted(); + const childConfig = patchConfig(otherConfigFields, { + callbacks: runManager?.getChild(), + }); + try { + const originalStream = await runnable.stream(input, childConfig); + stream = consumeAsyncIterableInContext(childConfig, originalStream); + break; + } + catch (e) { + if (firstError === undefined) { + firstError = e; + } + } + } + if (stream === undefined) { + const error = firstError ?? new Error("No error stored at end of fallback."); + await runManager?.handleChainError(error); + throw error; + } + let output; + try { + for await (const chunk of stream) { + yield chunk; + try { + output = output === undefined ? output : concat(output, chunk); + } + catch (e) { + output = undefined; + } + } + } + catch (e) { + await runManager?.handleChainError(e); + throw e; + } + await runManager?.handleChainEnd(base_coerceToDict(output, "output")); + } + async batch(inputs, options, batchOptions) { + if (batchOptions?.returnExceptions) { + throw new Error("Not implemented."); + } + const configList = this._getOptionsList(options ?? {}, inputs.length); + const callbackManagers = await Promise.all(configList.map((config) => getCallbackManagerForConfig(config))); + const runManagers = await Promise.all(callbackManagers.map(async (callbackManager, i) => { + const handleStartRes = await callbackManager?.handleChainStart(this.toJSON(), base_coerceToDict(inputs[i], "input"), configList[i].runId, undefined, undefined, undefined, configList[i].runName); + delete configList[i].runId; + return handleStartRes; + })); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let firstError; + for (const runnable of this.runnables()) { + configList[0].signal?.throwIfAborted(); + try { + const outputs = await runnable.batch(inputs, runManagers.map((runManager, j) => patchConfig(configList[j], { + callbacks: runManager?.getChild(), + })), batchOptions); + await Promise.all(runManagers.map((runManager, i) => runManager?.handleChainEnd(base_coerceToDict(outputs[i], "output")))); + return outputs; + } + catch (e) { + if (firstError === undefined) { + firstError = e; + } + } + } + if (!firstError) { + throw new Error("No error stored at end of fallbacks."); + } + await Promise.all(runManagers.map((runManager) => runManager?.handleChainError(firstError))); + throw firstError; } } -/** - * Class that represents a chat prompt value. It extends the - * BasePromptValue and includes an array of BaseMessage instances. - */ -class ChatPromptValue extends BasePromptValue { - static lc_name() { - return "ChatPromptValue"; +// TODO: Figure out why the compiler needs help eliminating Error as a RunOutput type +function _coerceToRunnable(coerceable) { + if (typeof coerceable === "function") { + return new base_RunnableLambda({ func: coerceable }); } - constructor(fields) { - if (Array.isArray(fields)) { - // eslint-disable-next-line no-param-reassign - fields = { messages: fields }; + else if (Runnable.isRunnable(coerceable)) { + return coerceable; + } + else if (!Array.isArray(coerceable) && typeof coerceable === "object") { + const runnables = {}; + for (const [key, value] of Object.entries(coerceable)) { + runnables[key] = _coerceToRunnable(value); } - super(fields); - Object.defineProperty(this, "lc_namespace", { - enumerable: true, - configurable: true, - writable: true, - value: ["langchain_core", "prompt_values"] - }); - Object.defineProperty(this, "lc_serializable", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - Object.defineProperty(this, "messages", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 + return new RunnableMap({ + steps: runnables, }); - this.messages = fields.messages; - } - toString() { - return getBufferString(this.messages); } - toChatMessages() { - return this.messages; + else { + throw new Error(`Expected a Runnable, function or object.\nInstead got an unsupported type.`); } } /** - * Class that represents an image prompt value. It extends the - * BasePromptValue and includes an ImageURL instance. + * A runnable that assigns key-value pairs to inputs of type `Record`. + * @example + * ```typescript + * import { + * RunnableAssign, + * RunnableLambda, + * RunnableParallel, + * } from "@langchain/core/runnables"; + * + * const calculateAge = (x: { birthYear: number }): { age: number } => { + * const currentYear = new Date().getFullYear(); + * return { age: currentYear - x.birthYear }; + * }; + * + * const createGreeting = (x: { name: string }): { greeting: string } => { + * return { greeting: `Hello, ${x.name}!` }; + * }; + * + * const mapper = RunnableParallel.from({ + * age_step: RunnableLambda.from(calculateAge), + * greeting_step: RunnableLambda.from(createGreeting), + * }); + * + * const runnableAssign = new RunnableAssign({ mapper }); + * + * const res = await runnableAssign.invoke({ name: "Alice", birthYear: 1990 }); + * + * // { name: "Alice", birthYear: 1990, age_step: { age: 34 }, greeting_step: { greeting: "Hello, Alice!" } } + * ``` */ -class ImagePromptValue extends BasePromptValue { +class RunnableAssign extends Runnable { static lc_name() { - return "ImagePromptValue"; + return "RunnableAssign"; } constructor(fields) { - if (!("imageUrl" in fields)) { + // eslint-disable-next-line no-instanceof/no-instanceof + if (fields instanceof RunnableMap) { // eslint-disable-next-line no-param-reassign - fields = { imageUrl: fields }; + fields = { mapper: fields }; } super(fields); Object.defineProperty(this, "lc_namespace", { enumerable: true, configurable: true, writable: true, - value: ["langchain_core", "prompt_values"] + value: ["langchain_core", "runnables"] }); Object.defineProperty(this, "lc_serializable", { enumerable: true, @@ -101720,753 +107441,727 @@ class ImagePromptValue extends BasePromptValue { writable: true, value: true }); - Object.defineProperty(this, "imageUrl", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - /** @ignore */ - Object.defineProperty(this, "value", { + Object.defineProperty(this, "mapper", { enumerable: true, configurable: true, writable: true, value: void 0 }); - this.imageUrl = fields.imageUrl; - } - toString() { - return this.imageUrl.url; - } - toChatMessages() { - return [ - new human_HumanMessage({ - content: [ - { - type: "image_url", - image_url: { - detail: this.imageUrl.detail, - url: this.imageUrl.url, - }, - }, - ], - }), - ]; - } -} - -// EXTERNAL MODULE: ./node_modules/base64-js/index.js -var base64_js = __nccwpck_require__(8793); -;// CONCATENATED MODULE: ./node_modules/js-tiktoken/dist/chunk-YVJR5WRT.js - - -var __defProp = Object.defineProperty; -var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; -var __publicField = (obj, key, value) => { - __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); - return value; -}; - -// src/utils.ts -function never(_) { -} -function bytePairMerge(piece, ranks) { - let parts = Array.from( - { length: piece.length }, - (_, i) => ({ start: i, end: i + 1 }) - ); - while (parts.length > 1) { - let minRank = null; - for (let i = 0; i < parts.length - 1; i++) { - const slice = piece.slice(parts[i].start, parts[i + 1].end); - const rank = ranks.get(slice.join(",")); - if (rank == null) - continue; - if (minRank == null || rank < minRank[0]) { - minRank = [rank, i]; - } - } - if (minRank != null) { - const i = minRank[1]; - parts[i] = { start: parts[i].start, end: parts[i + 1].end }; - parts.splice(i + 1, 1); - } else { - break; - } - } - return parts; -} -function bytePairEncode(piece, ranks) { - if (piece.length === 1) - return [ranks.get(piece.join(","))]; - return bytePairMerge(piece, ranks).map((p) => ranks.get(piece.slice(p.start, p.end).join(","))).filter((x) => x != null); -} -function escapeRegex(str) { - return str.replace(/[\\^$*+?.()|[\]{}]/g, "\\$&"); -} -var _Tiktoken = class { - /** @internal */ - specialTokens; - /** @internal */ - inverseSpecialTokens; - /** @internal */ - patStr; - /** @internal */ - textEncoder = new TextEncoder(); - /** @internal */ - textDecoder = new TextDecoder("utf-8"); - /** @internal */ - rankMap = /* @__PURE__ */ new Map(); - /** @internal */ - textMap = /* @__PURE__ */ new Map(); - constructor(ranks, extendedSpecialTokens) { - this.patStr = ranks.pat_str; - const uncompressed = ranks.bpe_ranks.split("\n").filter(Boolean).reduce((memo, x) => { - const [_, offsetStr, ...tokens] = x.split(" "); - const offset = Number.parseInt(offsetStr, 10); - tokens.forEach((token, i) => memo[token] = offset + i); - return memo; - }, {}); - for (const [token, rank] of Object.entries(uncompressed)) { - const bytes = base64_js.toByteArray(token); - this.rankMap.set(bytes.join(","), rank); - this.textMap.set(rank, bytes); + this.mapper = fields.mapper; } - this.specialTokens = { ...ranks.special_tokens, ...extendedSpecialTokens }; - this.inverseSpecialTokens = Object.entries(this.specialTokens).reduce((memo, [text, rank]) => { - memo[rank] = this.textEncoder.encode(text); - return memo; - }, {}); - } - encode(text, allowedSpecial = [], disallowedSpecial = "all") { - const regexes = new RegExp(this.patStr, "ug"); - const specialRegex = _Tiktoken.specialTokenRegex( - Object.keys(this.specialTokens) - ); - const ret = []; - const allowedSpecialSet = new Set( - allowedSpecial === "all" ? Object.keys(this.specialTokens) : allowedSpecial - ); - const disallowedSpecialSet = new Set( - disallowedSpecial === "all" ? Object.keys(this.specialTokens).filter( - (x) => !allowedSpecialSet.has(x) - ) : disallowedSpecial - ); - if (disallowedSpecialSet.size > 0) { - const disallowedSpecialRegex = _Tiktoken.specialTokenRegex([ - ...disallowedSpecialSet - ]); - const specialMatch = text.match(disallowedSpecialRegex); - if (specialMatch != null) { - throw new Error( - `The text contains a special token that is not allowed: ${specialMatch[0]}` - ); - } + async invoke(input, options) { + const mapperResult = await this.mapper.invoke(input, options); + return { + ...input, + ...mapperResult, + }; } - let start = 0; - while (true) { - let nextSpecial = null; - let startFind = start; - while (true) { - specialRegex.lastIndex = startFind; - nextSpecial = specialRegex.exec(text); - if (nextSpecial == null || allowedSpecialSet.has(nextSpecial[0])) - break; - startFind = nextSpecial.index + 1; - } - const end = nextSpecial?.index ?? text.length; - for (const match of text.substring(start, end).matchAll(regexes)) { - const piece = this.textEncoder.encode(match[0]); - const token2 = this.rankMap.get(piece.join(",")); - if (token2 != null) { - ret.push(token2); - continue; + async *_transform(generator, runManager, options) { + // collect mapper keys + const mapperKeys = this.mapper.getStepsKeys(); + // create two input gens, one for the mapper, one for the input + const [forPassthrough, forMapper] = atee(generator); + // create mapper output gen + const mapperOutput = this.mapper.transform(forMapper, patchConfig(options, { callbacks: runManager?.getChild() })); + // start the mapper + const firstMapperChunkPromise = mapperOutput.next(); + // yield the passthrough + for await (const chunk of forPassthrough) { + if (typeof chunk !== "object" || Array.isArray(chunk)) { + throw new Error(`RunnableAssign can only be used with objects as input, got ${typeof chunk}`); + } + const filtered = Object.fromEntries(Object.entries(chunk).filter(([key]) => !mapperKeys.includes(key))); + if (Object.keys(filtered).length > 0) { + yield filtered; + } + } + // yield the mapper output + yield (await firstMapperChunkPromise).value; + for await (const chunk of mapperOutput) { + yield chunk; } - ret.push(...bytePairEncode(piece, this.rankMap)); - } - if (nextSpecial == null) - break; - let token = this.specialTokens[nextSpecial[0]]; - ret.push(token); - start = nextSpecial.index + nextSpecial[0].length; - } - return ret; - } - decode(tokens) { - const res = []; - let length = 0; - for (let i2 = 0; i2 < tokens.length; ++i2) { - const token = tokens[i2]; - const bytes = this.textMap.get(token) ?? this.inverseSpecialTokens[token]; - if (bytes != null) { - res.push(bytes); - length += bytes.length; - } - } - const mergedArray = new Uint8Array(length); - let i = 0; - for (const bytes of res) { - mergedArray.set(bytes, i); - i += bytes.length; - } - return this.textDecoder.decode(mergedArray); - } -}; -var Tiktoken = _Tiktoken; -__publicField(Tiktoken, "specialTokenRegex", (tokens) => { - return new RegExp(tokens.map((i) => escapeRegex(i)).join("|"), "g"); -}); -function getEncodingNameForModel(model) { - switch (model) { - case "gpt2": { - return "gpt2"; - } - case "code-cushman-001": - case "code-cushman-002": - case "code-davinci-001": - case "code-davinci-002": - case "cushman-codex": - case "davinci-codex": - case "davinci-002": - case "text-davinci-002": - case "text-davinci-003": { - return "p50k_base"; - } - case "code-davinci-edit-001": - case "text-davinci-edit-001": { - return "p50k_edit"; - } - case "ada": - case "babbage": - case "babbage-002": - case "code-search-ada-code-001": - case "code-search-babbage-code-001": - case "curie": - case "davinci": - case "text-ada-001": - case "text-babbage-001": - case "text-curie-001": - case "text-davinci-001": - case "text-search-ada-doc-001": - case "text-search-babbage-doc-001": - case "text-search-curie-doc-001": - case "text-search-davinci-doc-001": - case "text-similarity-ada-001": - case "text-similarity-babbage-001": - case "text-similarity-curie-001": - case "text-similarity-davinci-001": { - return "r50k_base"; - } - case "gpt-3.5-turbo-instruct-0914": - case "gpt-3.5-turbo-instruct": - case "gpt-3.5-turbo-16k-0613": - case "gpt-3.5-turbo-16k": - case "gpt-3.5-turbo-0613": - case "gpt-3.5-turbo-0301": - case "gpt-3.5-turbo": - case "gpt-4-32k-0613": - case "gpt-4-32k-0314": - case "gpt-4-32k": - case "gpt-4-0613": - case "gpt-4-0314": - case "gpt-4": - case "gpt-3.5-turbo-1106": - case "gpt-35-turbo": - case "gpt-4-1106-preview": - case "gpt-4-vision-preview": - case "gpt-3.5-turbo-0125": - case "gpt-4-turbo": - case "gpt-4-turbo-2024-04-09": - case "gpt-4-turbo-preview": - case "gpt-4-0125-preview": - case "text-embedding-ada-002": - case "text-embedding-3-small": - case "text-embedding-3-large": { - return "cl100k_base"; - } - case "gpt-4o": - case "gpt-4o-2024-05-13": - case "gpt-4o-2024-08-06": - case "gpt-4o-mini-2024-07-18": - case "gpt-4o-mini": - case "o1-mini": - case "o1-preview": - case "o1-preview-2024-09-12": - case "o1-mini-2024-09-12": - case "chatgpt-4o-latest": - case "gpt-4o-realtime": - case "gpt-4o-realtime-preview-2024-10-01": { - return "o200k_base"; - } - default: - throw new Error("Unknown model"); - } -} - - - -;// CONCATENATED MODULE: ./node_modules/js-tiktoken/dist/lite.js - - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/tiktoken.js - - -const cache = {}; -const caller = /* #__PURE__ */ new async_caller_AsyncCaller({}); -async function getEncoding(encoding) { - if (!(encoding in cache)) { - cache[encoding] = caller - .fetch(`https://tiktoken.pages.dev/js/${encoding}.json`) - .then((res) => res.json()) - .then((data) => new Tiktoken(data)) - .catch((e) => { - delete cache[encoding]; - throw e; - }); - } - return await cache[encoding]; -} -async function tiktoken_encodingForModel(model) { - return getEncoding(getEncodingNameForModel(model)); -} - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/language_models/base.js - - - - - - -// https://www.npmjs.com/package/js-tiktoken -const getModelNameForTiktoken = (modelName) => { - if (modelName.startsWith("gpt-3.5-turbo-16k")) { - return "gpt-3.5-turbo-16k"; - } - if (modelName.startsWith("gpt-3.5-turbo-")) { - return "gpt-3.5-turbo"; - } - if (modelName.startsWith("gpt-4-32k")) { - return "gpt-4-32k"; - } - if (modelName.startsWith("gpt-4-")) { - return "gpt-4"; - } - if (modelName.startsWith("gpt-4o")) { - return "gpt-4o"; - } - return modelName; -}; -const getEmbeddingContextSize = (modelName) => { - switch (modelName) { - case "text-embedding-ada-002": - return 8191; - default: - return 2046; } -}; -const getModelContextSize = (modelName) => { - switch (getModelNameForTiktoken(modelName)) { - case "gpt-3.5-turbo-16k": - return 16384; - case "gpt-3.5-turbo": - return 4096; - case "gpt-4-32k": - return 32768; - case "gpt-4": - return 8192; - case "text-davinci-003": - return 4097; - case "text-curie-001": - return 2048; - case "text-babbage-001": - return 2048; - case "text-ada-001": - return 2048; - case "code-davinci-002": - return 8000; - case "code-cushman-001": - return 2048; - default: - return 4097; + transform(generator, options) { + return this._transformStreamWithConfig(generator, this._transform.bind(this), options); } -}; -/** - * Whether or not the input matches the OpenAI tool definition. - * @param {unknown} tool The input to check. - * @returns {boolean} Whether the input is an OpenAI tool definition. - */ -function isOpenAITool(tool) { - if (typeof tool !== "object" || !tool) - return false; - if ("type" in tool && - tool.type === "function" && - "function" in tool && - typeof tool.function === "object" && - tool.function && - "name" in tool.function && - "parameters" in tool.function) { - return true; + async stream(input, options) { + async function* generator() { + yield input; + } + const config = ensureConfig(options); + const wrappedGenerator = new AsyncGeneratorWithSetup({ + generator: this.transform(generator(), config), + config, + }); + await wrappedGenerator.setup; + return IterableReadableStream.fromAsyncGenerator(wrappedGenerator); } - return false; } -const calculateMaxTokens = async ({ prompt, modelName, }) => { - let numTokens; - try { - numTokens = (await encodingForModel(getModelNameForTiktoken(modelName))).encode(prompt).length; - } - catch (error) { - console.warn("Failed to calculate number of tokens, falling back to approximate count"); - // fallback to approximate calculation if tiktoken is not available - // each token is ~4 characters: https://help.openai.com/en/articles/4936856-what-are-tokens-and-how-to-count-them# - numTokens = Math.ceil(prompt.length / 4); - } - const maxTokens = getModelContextSize(modelName); - return maxTokens - numTokens; -}; -const getVerbosity = () => false; /** - * Base class for language models, chains, tools. + * A runnable that assigns key-value pairs to inputs of type `Record`. + * Useful for streaming, can be automatically created and chained by calling `runnable.pick();`. + * @example + * ```typescript + * import { RunnablePick } from "@langchain/core/runnables"; + * + * const inputData = { + * name: "John", + * age: 30, + * city: "New York", + * country: "USA", + * email: "john.doe@example.com", + * phone: "+1234567890", + * }; + * + * const basicInfoRunnable = new RunnablePick(["name", "city"]); + * + * // Example invocation + * const res = await basicInfoRunnable.invoke(inputData); + * + * // { name: 'John', city: 'New York' } + * ``` */ -class BaseLangChain extends Runnable { - get lc_attributes() { - return { - callbacks: undefined, - verbose: undefined, - }; +class RunnablePick extends Runnable { + static lc_name() { + return "RunnablePick"; } - constructor(params) { - super(params); - /** - * Whether to print out response text. - */ - Object.defineProperty(this, "verbose", { + constructor(fields) { + if (typeof fields === "string" || Array.isArray(fields)) { + // eslint-disable-next-line no-param-reassign + fields = { keys: fields }; + } + super(fields); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain_core", "runnables"] + }); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "keys", { enumerable: true, configurable: true, writable: true, value: void 0 }); - Object.defineProperty(this, "callbacks", { + this.keys = fields.keys; + } + async _pick(input) { + if (typeof this.keys === "string") { + return input[this.keys]; + } + else { + const picked = this.keys + .map((key) => [key, input[key]]) + .filter((v) => v[1] !== undefined); + return picked.length === 0 + ? undefined + : Object.fromEntries(picked); + } + } + async invoke(input, options) { + return this._callWithConfig(this._pick.bind(this), input, options); + } + async *_transform(generator) { + for await (const chunk of generator) { + const picked = await this._pick(chunk); + if (picked !== undefined) { + yield picked; + } + } + } + transform(generator, options) { + return this._transformStreamWithConfig(generator, this._transform.bind(this), options); + } + async stream(input, options) { + async function* generator() { + yield input; + } + const config = ensureConfig(options); + const wrappedGenerator = new AsyncGeneratorWithSetup({ + generator: this.transform(generator(), config), + config, + }); + await wrappedGenerator.setup; + return IterableReadableStream.fromAsyncGenerator(wrappedGenerator); + } +} +class RunnableToolLike extends RunnableBinding { + constructor(fields) { + const sequence = RunnableSequence.from([ + base_RunnableLambda.from(async (input) => { + let toolInput; + if (_isToolCall(input)) { + try { + toolInput = await interopParseAsync(this.schema, input.args); + } + catch (e) { + throw new ToolInputParsingException(`Received tool input did not match expected schema`, JSON.stringify(input.args)); + } + } + else { + toolInput = input; + } + return toolInput; + }).withConfig({ runName: `${fields.name}:parse_input` }), + fields.bound, + ]).withConfig({ runName: fields.name }); + super({ + bound: sequence, + config: fields.config ?? {}, + }); + Object.defineProperty(this, "name", { enumerable: true, configurable: true, writable: true, value: void 0 }); - Object.defineProperty(this, "tags", { + Object.defineProperty(this, "description", { enumerable: true, configurable: true, writable: true, value: void 0 }); - Object.defineProperty(this, "metadata", { + Object.defineProperty(this, "schema", { enumerable: true, configurable: true, writable: true, value: void 0 }); - this.verbose = params.verbose ?? getVerbosity(); - this.callbacks = params.callbacks; - this.tags = params.tags ?? []; - this.metadata = params.metadata ?? {}; + this.name = fields.name; + this.description = fields.description; + this.schema = fields.schema; + } + static lc_name() { + return "RunnableToolLike"; } } /** - * Base class for language models. + * Given a runnable and a Zod schema, convert the runnable to a tool. + * + * @template RunInput The input type for the runnable. + * @template RunOutput The output type for the runnable. + * + * @param {Runnable} runnable The runnable to convert to a tool. + * @param fields + * @param {string | undefined} [fields.name] The name of the tool. If not provided, it will default to the name of the runnable. + * @param {string | undefined} [fields.description] The description of the tool. Falls back to the description on the Zod schema if not provided, or undefined if neither are provided. + * @param {InteropZodType} [fields.schema] The Zod schema for the input of the tool. Infers the Zod type from the input type of the runnable. + * @returns {RunnableToolLike, RunOutput>} An instance of `RunnableToolLike` which is a runnable that can be used as a tool. */ -class BaseLanguageModel extends BaseLangChain { - /** - * Keys that the language model accepts as call options. - */ - get callKeys() { - return ["stop", "timeout", "signal", "tags", "metadata", "callbacks"]; +function convertRunnableToTool(runnable, fields) { + const name = fields.name ?? runnable.getName(); + const description = fields.description ?? getSchemaDescription(fields.schema); + if (isSimpleStringZodSchema(fields.schema)) { + return new RunnableToolLike({ + name, + description, + schema: objectType({ input: stringType() }) + .transform((input) => input.input), + bound: runnable, + }); } - constructor({ callbacks, callbackManager, ...params }) { - const { cache, ...rest } = params; + return new RunnableToolLike({ + name, + description, + schema: fields.schema, + bound: runnable, + }); +} + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/modifier.js + +/** + * Message responsible for deleting other messages. + */ +class RemoveMessage extends BaseMessage { + constructor(fields) { super({ - callbacks: callbacks ?? callbackManager, - ...rest, + ...fields, + content: "", }); /** - * The async caller should be used by subclasses to make any async calls, - * which will thus benefit from the concurrency and retry logic. + * The ID of the message to remove. */ - Object.defineProperty(this, "caller", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "cache", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "_encoding", { + Object.defineProperty(this, "id", { enumerable: true, configurable: true, writable: true, value: void 0 }); - if (typeof cache === "object") { - this.cache = cache; + this.id = fields.id; + } + _getType() { + return "remove"; + } + get _printableFields() { + return { + ...super._printableFields, + id: this.id, + }; + } +} + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/transformers.js + + + + + + + + + + +const _isMessageType = (msg, types) => { + const typesAsStrings = [ + ...new Set(types?.map((t) => { + if (typeof t === "string") { + return t; + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const instantiatedMsgClass = new t({}); + if (!("getType" in instantiatedMsgClass) || + typeof instantiatedMsgClass.getType !== "function") { + throw new Error("Invalid type provided."); + } + return instantiatedMsgClass.getType(); + })), + ]; + const msgType = msg.getType(); + return typesAsStrings.some((t) => t === msgType); +}; +function filterMessages(messagesOrOptions, options) { + if (Array.isArray(messagesOrOptions)) { + return _filterMessages(messagesOrOptions, options); + } + return RunnableLambda.from((input) => { + return _filterMessages(input, messagesOrOptions); + }); +} +function _filterMessages(messages, options = {}) { + const { includeNames, excludeNames, includeTypes, excludeTypes, includeIds, excludeIds, } = options; + const filtered = []; + for (const msg of messages) { + if (excludeNames && msg.name && excludeNames.includes(msg.name)) { + continue; } - else if (cache) { - this.cache = InMemoryCache.global(); + else if (excludeTypes && _isMessageType(msg, excludeTypes)) { + continue; } - else { - this.cache = undefined; + else if (excludeIds && msg.id && excludeIds.includes(msg.id)) { + continue; } - this.caller = new async_caller_AsyncCaller(params ?? {}); - } - async getNumTokens(content) { - // TODO: Figure out correct value. - if (typeof content !== "string") { - return 0; + // default to inclusion when no inclusion criteria given. + if (!(includeTypes || includeIds || includeNames)) { + filtered.push(msg); } - // fallback to approximate calculation if tiktoken is not available - let numTokens = Math.ceil(content.length / 4); - if (!this._encoding) { - try { - this._encoding = await tiktoken_encodingForModel("modelName" in this - ? getModelNameForTiktoken(this.modelName) - : "gpt2"); - } - catch (error) { - console.warn("Failed to calculate number of tokens, falling back to approximate count", error); - } + else if (includeNames && + msg.name && + includeNames.some((iName) => iName === msg.name)) { + filtered.push(msg); } - if (this._encoding) { - try { - numTokens = this._encoding.encode(content).length; - } - catch (error) { - console.warn("Failed to calculate number of tokens, falling back to approximate count", error); - } + else if (includeTypes && _isMessageType(msg, includeTypes)) { + filtered.push(msg); + } + else if (includeIds && msg.id && includeIds.some((id) => id === msg.id)) { + filtered.push(msg); } - return numTokens; } - static _convertInputToPromptValue(input) { - if (typeof input === "string") { - return new StringPromptValue(input); + return filtered; +} +function mergeMessageRuns(messages) { + if (Array.isArray(messages)) { + return _mergeMessageRuns(messages); + } + return RunnableLambda.from(_mergeMessageRuns); +} +function _mergeMessageRuns(messages) { + if (!messages.length) { + return []; + } + const merged = []; + for (const msg of messages) { + const curr = msg; + const last = merged.pop(); + if (!last) { + merged.push(curr); } - else if (Array.isArray(input)) { - return new ChatPromptValue(input.map(coerceMessageLikeToMessage)); + else if (curr.getType() === "tool" || + !(curr.getType() === last.getType())) { + merged.push(last, curr); } else { - return input; + const lastChunk = convertToChunk(last); + const currChunk = convertToChunk(curr); + const mergedChunks = lastChunk.concat(currChunk); + if (typeof lastChunk.content === "string" && + typeof currChunk.content === "string") { + mergedChunks.content = `${lastChunk.content}\n${currChunk.content}`; + } + merged.push(_chunkToMsg(mergedChunks)); } } - /** - * Get the identifying parameters of the LLM. - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - _identifyingParams() { - return {}; + return merged; +} +function trimMessages(messagesOrOptions, options) { + if (Array.isArray(messagesOrOptions)) { + const messages = messagesOrOptions; + if (!options) { + throw new Error("Options parameter is required when providing messages."); + } + return _trimMessagesHelper(messages, options); } - /** - * Create a unique cache key for a specific call to a specific language model. - * @param callOptions Call options for the model - * @returns A unique cache key. - */ - _getSerializedCacheKeyParametersForCall( - // TODO: Fix when we remove the RunnableLambda backwards compatibility shim. - { config, ...callOptions }) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const params = { - ...this._identifyingParams(), - ...callOptions, - _type: this._llmType(), - _model: this._modelType(), - }; - const filteredEntries = Object.entries(params).filter(([_, value]) => value !== undefined); - const serializedEntries = filteredEntries - .map(([key, value]) => `${key}:${JSON.stringify(value)}`) - .sort() - .join(","); - return serializedEntries; + else { + const trimmerOptions = messagesOrOptions; + return RunnableLambda.from((input) => _trimMessagesHelper(input, trimmerOptions)).withConfig({ + runName: "trim_messages", + }); } - /** - * @deprecated - * Return a json-like object representing this LLM. - */ - serialize() { - return { - ...this._identifyingParams(), - _type: this._llmType(), - _model: this._modelType(), +} +async function _trimMessagesHelper(messages, options) { + const { maxTokens, tokenCounter, strategy = "last", allowPartial = false, endOn, startOn, includeSystem = false, textSplitter, } = options; + if (startOn && strategy === "first") { + throw new Error("`startOn` should only be specified if `strategy` is 'last'."); + } + if (includeSystem && strategy === "first") { + throw new Error("`includeSystem` should only be specified if `strategy` is 'last'."); + } + let listTokenCounter; + if ("getNumTokens" in tokenCounter) { + listTokenCounter = async (msgs) => { + const tokenCounts = await Promise.all(msgs.map((msg) => tokenCounter.getNumTokens(msg.content))); + return tokenCounts.reduce((sum, count) => sum + count, 0); }; } - /** - * @deprecated - * Load an LLM from a json-like object describing it. - */ - static async deserialize(_data) { - throw new Error("Use .toJSON() instead"); + else { + listTokenCounter = async (msgs) => tokenCounter(msgs); } -} - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/passthrough.js - - - -/** - * A runnable to passthrough inputs unchanged or with additional keys. - * - * This runnable behaves almost like the identity function, except that it - * can be configured to add additional keys to the output, if the input is - * an object. - * - * The example below demonstrates how to use `RunnablePassthrough to - * passthrough the input from the `.invoke()` - * - * @example - * ```typescript - * const chain = RunnableSequence.from([ - * { - * question: new RunnablePassthrough(), - * context: async () => loadContextFromStore(), - * }, - * prompt, - * llm, - * outputParser, - * ]); - * const response = await chain.invoke( - * "I can pass a single string instead of an object since I'm using `RunnablePassthrough`." - * ); - * ``` - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -class RunnablePassthrough extends Runnable { - static lc_name() { - return "RunnablePassthrough"; + let textSplitterFunc = defaultTextSplitter; + if (textSplitter) { + if ("splitText" in textSplitter) { + textSplitterFunc = textSplitter.splitText; + } + else { + textSplitterFunc = async (text) => textSplitter(text); + } } - constructor(fields) { - super(fields); - Object.defineProperty(this, "lc_namespace", { - enumerable: true, - configurable: true, - writable: true, - value: ["langchain_core", "runnables"] - }); - Object.defineProperty(this, "lc_serializable", { - enumerable: true, - configurable: true, - writable: true, - value: true + if (strategy === "first") { + return _firstMaxTokens(messages, { + maxTokens, + tokenCounter: listTokenCounter, + textSplitter: textSplitterFunc, + partialStrategy: allowPartial ? "first" : undefined, + endOn, }); - Object.defineProperty(this, "func", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 + } + else if (strategy === "last") { + return _lastMaxTokens(messages, { + maxTokens, + tokenCounter: listTokenCounter, + textSplitter: textSplitterFunc, + allowPartial, + includeSystem, + startOn, + endOn, }); - if (fields) { - this.func = fields.func; - } } - async invoke(input, options) { - const config = ensureConfig(options); - if (this.func) { - await this.func(input, config); + else { + throw new Error(`Unrecognized strategy: '${strategy}'. Must be one of 'first' or 'last'.`); + } +} +async function _firstMaxTokens(messages, options) { + const { maxTokens, tokenCounter, textSplitter, partialStrategy, endOn } = options; + let messagesCopy = [...messages]; + let idx = 0; + for (let i = 0; i < messagesCopy.length; i += 1) { + const remainingMessages = i > 0 ? messagesCopy.slice(0, -i) : messagesCopy; + if ((await tokenCounter(remainingMessages)) <= maxTokens) { + idx = messagesCopy.length - i; + break; } - return this._callWithConfig((input) => Promise.resolve(input), input, config); } - async *transform(generator, options) { - const config = ensureConfig(options); - let finalOutput; - let finalOutputSupported = true; - for await (const chunk of this._transformStreamWithConfig(generator, (input) => input, config)) { - yield chunk; - if (finalOutputSupported) { - if (finalOutput === undefined) { - finalOutput = chunk; + if (idx < messagesCopy.length - 1 && partialStrategy) { + let includedPartial = false; + if (Array.isArray(messagesCopy[idx].content)) { + const excluded = messagesCopy[idx]; + if (typeof excluded.content === "string") { + throw new Error("Expected content to be an array."); + } + const numBlock = excluded.content.length; + const reversedContent = partialStrategy === "last" + ? [...excluded.content].reverse() + : excluded.content; + for (let i = 1; i <= numBlock; i += 1) { + const partialContent = partialStrategy === "first" + ? reversedContent.slice(0, i) + : reversedContent.slice(-i); + const fields = Object.fromEntries(Object.entries(excluded).filter(([k]) => k !== "type" && !k.startsWith("lc_"))); + const updatedMessage = _switchTypeToMessage(excluded.getType(), { + ...fields, + content: partialContent, + }); + const slicedMessages = [...messagesCopy.slice(0, idx), updatedMessage]; + if ((await tokenCounter(slicedMessages)) <= maxTokens) { + messagesCopy = slicedMessages; + idx += 1; + includedPartial = true; } else { - try { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - finalOutput = concat(finalOutput, chunk); - } - catch { - finalOutput = undefined; - finalOutputSupported = false; + break; + } + } + if (includedPartial && partialStrategy === "last") { + excluded.content = [...reversedContent].reverse(); + } + } + if (!includedPartial) { + const excluded = messagesCopy[idx]; + let text; + if (Array.isArray(excluded.content) && + excluded.content.some((block) => typeof block === "string" || block.type === "text")) { + const textBlock = excluded.content.find((block) => block.type === "text" && block.text); + text = textBlock?.text; + } + else if (typeof excluded.content === "string") { + text = excluded.content; + } + if (text) { + const splitTexts = await textSplitter(text); + const numSplits = splitTexts.length; + if (partialStrategy === "last") { + splitTexts.reverse(); + } + for (let _ = 0; _ < numSplits - 1; _ += 1) { + splitTexts.pop(); + excluded.content = splitTexts.join(""); + if ((await tokenCounter([...messagesCopy.slice(0, idx), excluded])) <= + maxTokens) { + if (partialStrategy === "last") { + excluded.content = [...splitTexts].reverse().join(""); + } + messagesCopy = [...messagesCopy.slice(0, idx), excluded]; + idx += 1; + break; } } } } - if (this.func && finalOutput !== undefined) { - await this.func(finalOutput, config); + } + if (endOn) { + const endOnArr = Array.isArray(endOn) ? endOn : [endOn]; + while (idx > 0 && !_isMessageType(messagesCopy[idx - 1], endOnArr)) { + idx -= 1; } } - /** - * A runnable that assigns key-value pairs to the input. - * - * The example below shows how you could use it with an inline function. - * - * @example - * ```typescript - * const prompt = - * PromptTemplate.fromTemplate(`Write a SQL query to answer the question using the following schema: {schema} - * Question: {question} - * SQL Query:`); - * - * // The `RunnablePassthrough.assign()` is used here to passthrough the input from the `.invoke()` - * // call (in this example it's the question), along with any inputs passed to the `.assign()` method. - * // In this case, we're passing the schema. - * const sqlQueryGeneratorChain = RunnableSequence.from([ - * RunnablePassthrough.assign({ - * schema: async () => db.getTableInfo(), - * }), - * prompt, - * new ChatOpenAI({}).bind({ stop: ["\nSQLResult:"] }), - * new StringOutputParser(), - * ]); - * const result = await sqlQueryGeneratorChain.invoke({ - * question: "How many employees are there?", - * }); - * ``` - */ - static assign(mapping) { - return new RunnableAssign(new RunnableMap({ steps: mapping })); + return messagesCopy.slice(0, idx); +} +async function _lastMaxTokens(messages, options) { + const { allowPartial = false, includeSystem = false, endOn, startOn, ...rest } = options; + // Create a copy of messages to avoid mutation + let messagesCopy = messages.map((message) => { + const fields = Object.fromEntries(Object.entries(message).filter(([k]) => k !== "type" && !k.startsWith("lc_"))); + return _switchTypeToMessage(message.getType(), fields, isBaseMessageChunk(message)); + }); + if (endOn) { + const endOnArr = Array.isArray(endOn) ? endOn : [endOn]; + while (messagesCopy.length > 0 && + !_isMessageType(messagesCopy[messagesCopy.length - 1], endOnArr)) { + messagesCopy = messagesCopy.slice(0, -1); + } + } + const swappedSystem = includeSystem && messagesCopy[0]?.getType() === "system"; + let reversed_ = swappedSystem + ? messagesCopy.slice(0, 1).concat(messagesCopy.slice(1).reverse()) + : messagesCopy.reverse(); + reversed_ = await _firstMaxTokens(reversed_, { + ...rest, + partialStrategy: allowPartial ? "last" : undefined, + endOn: startOn, + }); + if (swappedSystem) { + return [reversed_[0], ...reversed_.slice(1).reverse()]; + } + else { + return reversed_.reverse(); } } - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/types/is_zod_schema.js - -/** - * Given either a Zod schema, or plain object, determine if the input is a Zod schema. - * - * @param {z.ZodType | Record} input - * @returns {boolean} Whether or not the provided input is a Zod schema. - */ -function isZodSchema(input) { - if (!input) { - return false; +const _MSG_CHUNK_MAP = { + human: { + message: human_HumanMessage, + messageChunk: human_HumanMessageChunk, + }, + ai: { + message: ai_AIMessage, + messageChunk: ai_AIMessageChunk, + }, + system: { + message: system_SystemMessage, + messageChunk: system_SystemMessageChunk, + }, + developer: { + message: system_SystemMessage, + messageChunk: system_SystemMessageChunk, + }, + tool: { + message: tool_ToolMessage, + messageChunk: tool_ToolMessageChunk, + }, + function: { + message: function_FunctionMessage, + messageChunk: function_FunctionMessageChunk, + }, + generic: { + message: chat_ChatMessage, + messageChunk: chat_ChatMessageChunk, + }, + remove: { + message: RemoveMessage, + messageChunk: RemoveMessage, // RemoveMessage does not have a chunk class. + }, +}; +function _switchTypeToMessage(messageType, fields, returnChunk) { + let chunk; + let msg; + switch (messageType) { + case "human": + if (returnChunk) { + chunk = new HumanMessageChunk(fields); + } + else { + msg = new HumanMessage(fields); + } + break; + case "ai": + if (returnChunk) { + let aiChunkFields = { + ...fields, + }; + if ("tool_calls" in aiChunkFields) { + aiChunkFields = { + ...aiChunkFields, + tool_call_chunks: aiChunkFields.tool_calls?.map((tc) => ({ + ...tc, + type: "tool_call_chunk", + index: undefined, + args: JSON.stringify(tc.args), + })), + }; + } + chunk = new AIMessageChunk(aiChunkFields); + } + else { + msg = new AIMessage(fields); + } + break; + case "system": + if (returnChunk) { + chunk = new SystemMessageChunk(fields); + } + else { + msg = new SystemMessage(fields); + } + break; + case "developer": + if (returnChunk) { + chunk = new SystemMessageChunk({ + ...fields, + additional_kwargs: { + ...fields.additional_kwargs, + __openai_role__: "developer", + }, + }); + } + else { + msg = new SystemMessage({ + ...fields, + additional_kwargs: { + ...fields.additional_kwargs, + __openai_role__: "developer", + }, + }); + } + break; + case "tool": + if ("tool_call_id" in fields) { + if (returnChunk) { + chunk = new ToolMessageChunk(fields); + } + else { + msg = new ToolMessage(fields); + } + } + else { + throw new Error("Can not convert ToolMessage to ToolMessageChunk if 'tool_call_id' field is not defined."); + } + break; + case "function": + if (returnChunk) { + chunk = new FunctionMessageChunk(fields); + } + else { + if (!fields.name) { + throw new Error("FunctionMessage must have a 'name' field"); + } + msg = new FunctionMessage(fields); + } + break; + case "generic": + if ("role" in fields) { + if (returnChunk) { + chunk = new ChatMessageChunk(fields); + } + else { + msg = new ChatMessage(fields); + } + } + else { + throw new Error("Can not convert ChatMessage to ChatMessageChunk if 'role' field is not defined."); + } + break; + default: + throw new Error(`Unrecognized message type ${messageType}`); } - if (typeof input !== "object") { - return false; + if (returnChunk && chunk) { + return chunk; } - if (Array.isArray(input)) { - return false; + if (msg) { + return msg; } - const asZodSchema = input; - // relies on an internal property of Zod schemas, so this may break in the future, hence the - // additional fallback checks below - if (asZodSchema._def) { - return true; + throw new Error(`Unrecognized message type ${messageType}`); +} +function _chunkToMsg(chunk) { + const chunkType = chunk.getType(); + let msg; + const fields = Object.fromEntries(Object.entries(chunk).filter(([k]) => !["type", "tool_call_chunks"].includes(k) && !k.startsWith("lc_"))); + if (chunkType in _MSG_CHUNK_MAP) { + msg = _switchTypeToMessage(chunkType, fields); } - const zodFirstPartyTypeKinds = Object.values(z.ZodFirstPartyTypeKind); - if (zodFirstPartyTypeKinds.includes(asZodSchema.constructor?.name ?? "NOT_INCLUDED")) { - return true; + if (!msg) { + throw new Error(`Unrecognized message chunk class ${chunkType}. Supported classes are ${Object.keys(_MSG_CHUNK_MAP)}`); } - // if all else fails, assume based on the presence of parse, parseAsync, safeParse, and - // safeParseAsync, as these are characteristic of Zod schemas - return (typeof asZodSchema.parse === "function" && - typeof asZodSchema.parseAsync === "function" && - typeof asZodSchema.safeParse === "function" && - typeof asZodSchema.safeParseAsync === "function"); + return msg; +} +/** + * The default text splitter function that splits text by newlines. + * + * @param {string} text + * @returns A promise that resolves to an array of strings split by newlines. + */ +function defaultTextSplitter(text) { + const splits = text.split("\n"); + return Promise.resolve([ + ...splits.slice(0, -1).map((s) => `${s}\n`), + splits[splits.length - 1], + ]); } -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/language_models/chat_models.js +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/index.js @@ -102477,668 +108172,1008 @@ function isZodSchema(input) { -/** - * Creates a transform stream for encoding chat message chunks. - * @deprecated Use {@link BytesOutputParser} instead - * @returns A TransformStream instance that encodes chat message chunks. - */ -function createChatMessageChunkEncoderStream() { - const textEncoder = new TextEncoder(); - return new TransformStream({ - transform(chunk, controller) { - controller.enqueue(textEncoder.encode(typeof chunk.content === "string" - ? chunk.content - : JSON.stringify(chunk.content))); - }, - }); -} -function _formatForTracing(messages) { - const messagesToTrace = []; - for (const message of messages) { - let messageToTrace = message; - if (Array.isArray(message.content)) { - for (let idx = 0; idx < message.content.length; idx++) { - const block = message.content[idx]; - if (isURLContentBlock(block) || isBase64ContentBlock(block)) { - if (messageToTrace === message) { - // Also shallow-copy content - // eslint-disable-next-line @typescript-eslint/no-explicit-any - messageToTrace = new message.constructor({ - ...messageToTrace, - content: [ - ...message.content.slice(0, idx), - convertToOpenAIImageBlock(block), - ...message.content.slice(idx + 1), - ], - }); - } - } - } - } - messagesToTrace.push(messageToTrace); - } - return messagesToTrace; -} -/** - * Base class for chat models. It extends the BaseLanguageModel class and - * provides methods for generating chat based on input messages. +// TODO: Use a star export when we deprecate the +// existing "ToolCall" type in "base.js". + + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/messages.js + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/js-sha1/hash.js +// @ts-nocheck +// Inlined to deal with portability issues with importing crypto module +/* + * [js-sha1]{@link https://github.com/emn178/js-sha1} + * + * @version 0.6.0 + * @author Chen, Yi-Cyuan [emn178@gmail.com] + * @copyright Chen, Yi-Cyuan 2014-2017 + * @license MIT */ -class BaseChatModel extends BaseLanguageModel { - constructor(fields) { - super(fields); - // Only ever instantiated in main LangChain - Object.defineProperty(this, "lc_namespace", { - enumerable: true, - configurable: true, - writable: true, - value: ["langchain", "chat_models", this._llmType()] - }); - Object.defineProperty(this, "disableStreaming", { - enumerable: true, - configurable: true, - writable: true, - value: false - }); - } - _separateRunnableConfigFromCallOptionsCompat(options) { - // For backwards compat, keep `signal` in both runnableConfig and callOptions - const [runnableConfig, callOptions] = super._separateRunnableConfigFromCallOptions(options); - callOptions.signal = runnableConfig.signal; - return [runnableConfig, callOptions]; - } - /** - * Invokes the chat model with a single input. - * @param input The input for the language model. - * @param options The call options. - * @returns A Promise that resolves to a BaseMessageChunk. - */ - async invoke(input, options) { - const promptValue = BaseChatModel._convertInputToPromptValue(input); - const result = await this.generatePrompt([promptValue], options, options?.callbacks); - const chatGeneration = result.generations[0][0]; - // TODO: Remove cast after figuring out inheritance - return chatGeneration.message; - } - // eslint-disable-next-line require-yield - async *_streamResponseChunks(_messages, _options, _runManager) { - throw new Error("Not implemented."); - } - async *_streamIterator(input, options) { - // Subclass check required to avoid double callbacks with default implementation - if (this._streamResponseChunks === - BaseChatModel.prototype._streamResponseChunks || - this.disableStreaming) { - yield this.invoke(input, options); - } - else { - const prompt = BaseChatModel._convertInputToPromptValue(input); - const messages = prompt.toChatMessages(); - const [runnableConfig, callOptions] = this._separateRunnableConfigFromCallOptionsCompat(options); - const inheritableMetadata = { - ...runnableConfig.metadata, - ...this.getLsParams(callOptions), - }; - const callbackManager_ = await CallbackManager.configure(runnableConfig.callbacks, this.callbacks, runnableConfig.tags, this.tags, inheritableMetadata, this.metadata, { verbose: this.verbose }); - const extra = { - options: callOptions, - invocation_params: this?.invocationParams(callOptions), - batch_size: 1, - }; - const runManagers = await callbackManager_?.handleChatModelStart(this.toJSON(), [_formatForTracing(messages)], runnableConfig.runId, undefined, extra, undefined, undefined, runnableConfig.runName); - let generationChunk; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - let llmOutput; - try { - for await (const chunk of this._streamResponseChunks(messages, callOptions, runManagers?.[0])) { - if (chunk.message.id == null) { - const runId = runManagers?.at(0)?.runId; - if (runId != null) - chunk.message._updateId(`run-${runId}`); - } - chunk.message.response_metadata = { - ...chunk.generationInfo, - ...chunk.message.response_metadata, - }; - yield chunk.message; - if (!generationChunk) { - generationChunk = chunk; - } - else { - generationChunk = generationChunk.concat(chunk); - } - if (isAIMessageChunk(chunk.message) && - chunk.message.usage_metadata !== undefined) { - llmOutput = { - tokenUsage: { - promptTokens: chunk.message.usage_metadata.input_tokens, - completionTokens: chunk.message.usage_metadata.output_tokens, - totalTokens: chunk.message.usage_metadata.total_tokens, - }, - }; - } - } - } - catch (err) { - await Promise.all((runManagers ?? []).map((runManager) => runManager?.handleLLMError(err))); - throw err; - } - await Promise.all((runManagers ?? []).map((runManager) => runManager?.handleLLMEnd({ - // TODO: Remove cast after figuring out inheritance - generations: [[generationChunk]], - llmOutput, - }))); - } +/*jslint bitwise: true */ + +var root = typeof window === "object" ? window : {}; +var HEX_CHARS = "0123456789abcdef".split(""); +var EXTRA = [-2147483648, 8388608, 32768, 128]; +var SHIFT = [24, 16, 8, 0]; +var OUTPUT_TYPES = (/* unused pure expression or super */ null && (["hex", "array", "digest", "arrayBuffer"])); +var blocks = []; +function Sha1(sharedMemory) { + if (sharedMemory) { + blocks[0] = + blocks[16] = + blocks[1] = + blocks[2] = + blocks[3] = + blocks[4] = + blocks[5] = + blocks[6] = + blocks[7] = + blocks[8] = + blocks[9] = + blocks[10] = + blocks[11] = + blocks[12] = + blocks[13] = + blocks[14] = + blocks[15] = + 0; + this.blocks = blocks; } - getLsParams(options) { - const providerName = this.getName().startsWith("Chat") - ? this.getName().replace("Chat", "") - : this.getName(); - return { - ls_model_type: "chat", - ls_stop: options.stop, - ls_provider: providerName, - }; + else { + this.blocks = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; } - /** @ignore */ - async _generateUncached(messages, parsedOptions, handledOptions, startedRunManagers) { - const baseMessages = messages.map((messageList) => messageList.map(coerceMessageLikeToMessage)); - let runManagers; - if (startedRunManagers !== undefined && - startedRunManagers.length === baseMessages.length) { - runManagers = startedRunManagers; - } - else { - const inheritableMetadata = { - ...handledOptions.metadata, - ...this.getLsParams(parsedOptions), - }; - // create callback manager and start run - const callbackManager_ = await CallbackManager.configure(handledOptions.callbacks, this.callbacks, handledOptions.tags, this.tags, inheritableMetadata, this.metadata, { verbose: this.verbose }); - const extra = { - options: parsedOptions, - invocation_params: this?.invocationParams(parsedOptions), - batch_size: 1, - }; - runManagers = await callbackManager_?.handleChatModelStart(this.toJSON(), baseMessages.map(_formatForTracing), handledOptions.runId, undefined, extra, undefined, undefined, handledOptions.runName); + this.h0 = 0x67452301; + this.h1 = 0xefcdab89; + this.h2 = 0x98badcfe; + this.h3 = 0x10325476; + this.h4 = 0xc3d2e1f0; + this.block = this.start = this.bytes = this.hBytes = 0; + this.finalized = this.hashed = false; + this.first = true; +} +Sha1.prototype.update = function (message) { + if (this.finalized) { + return; + } + var notString = typeof message !== "string"; + if (notString && message.constructor === root.ArrayBuffer) { + message = new Uint8Array(message); + } + var code, index = 0, i, length = message.length || 0, blocks = this.blocks; + while (index < length) { + if (this.hashed) { + this.hashed = false; + blocks[0] = this.block; + blocks[16] = + blocks[1] = + blocks[2] = + blocks[3] = + blocks[4] = + blocks[5] = + blocks[6] = + blocks[7] = + blocks[8] = + blocks[9] = + blocks[10] = + blocks[11] = + blocks[12] = + blocks[13] = + blocks[14] = + blocks[15] = + 0; } - const generations = []; - const llmOutputs = []; - // Even if stream is not explicitly called, check if model is implicitly - // called from streamEvents() or streamLog() to get all streamed events. - // Bail out if _streamResponseChunks not overridden - const hasStreamingHandler = !!runManagers?.[0].handlers.find(callbackHandlerPrefersStreaming); - if (hasStreamingHandler && - !this.disableStreaming && - baseMessages.length === 1 && - this._streamResponseChunks !== - BaseChatModel.prototype._streamResponseChunks) { - try { - const stream = await this._streamResponseChunks(baseMessages[0], parsedOptions, runManagers?.[0]); - let aggregated; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - let llmOutput; - for await (const chunk of stream) { - if (chunk.message.id == null) { - const runId = runManagers?.at(0)?.runId; - if (runId != null) - chunk.message._updateId(`run-${runId}`); - } - if (aggregated === undefined) { - aggregated = chunk; - } - else { - aggregated = concat(aggregated, chunk); - } - if (isAIMessageChunk(chunk.message) && - chunk.message.usage_metadata !== undefined) { - llmOutput = { - tokenUsage: { - promptTokens: chunk.message.usage_metadata.input_tokens, - completionTokens: chunk.message.usage_metadata.output_tokens, - totalTokens: chunk.message.usage_metadata.total_tokens, - }, - }; - } - } - if (aggregated === undefined) { - throw new Error("Received empty response from chat model call."); - } - generations.push([aggregated]); - await runManagers?.[0].handleLLMEnd({ - generations, - llmOutput, - }); - } - catch (e) { - await runManagers?.[0].handleLLMError(e); - throw e; + if (notString) { + for (i = this.start; index < length && i < 64; ++index) { + blocks[i >> 2] |= message[index] << SHIFT[i++ & 3]; } } else { - // generate results - const results = await Promise.allSettled(baseMessages.map((messageList, i) => this._generate(messageList, { ...parsedOptions, promptIndex: i }, runManagers?.[i]))); - // handle results - await Promise.all(results.map(async (pResult, i) => { - if (pResult.status === "fulfilled") { - const result = pResult.value; - for (const generation of result.generations) { - if (generation.message.id == null) { - const runId = runManagers?.at(0)?.runId; - if (runId != null) - generation.message._updateId(`run-${runId}`); - } - generation.message.response_metadata = { - ...generation.generationInfo, - ...generation.message.response_metadata, - }; - } - if (result.generations.length === 1) { - result.generations[0].message.response_metadata = { - ...result.llmOutput, - ...result.generations[0].message.response_metadata, - }; - } - generations[i] = result.generations; - llmOutputs[i] = result.llmOutput; - return runManagers?.[i]?.handleLLMEnd({ - generations: [result.generations], - llmOutput: result.llmOutput, - }); + for (i = this.start; index < length && i < 64; ++index) { + code = message.charCodeAt(index); + if (code < 0x80) { + blocks[i >> 2] |= code << SHIFT[i++ & 3]; + } + else if (code < 0x800) { + blocks[i >> 2] |= (0xc0 | (code >> 6)) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; + } + else if (code < 0xd800 || code >= 0xe000) { + blocks[i >> 2] |= (0xe0 | (code >> 12)) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; } else { - // status === "rejected" - await runManagers?.[i]?.handleLLMError(pResult.reason); - return Promise.reject(pResult.reason); + code = + 0x10000 + + (((code & 0x3ff) << 10) | (message.charCodeAt(++index) & 0x3ff)); + blocks[i >> 2] |= (0xf0 | (code >> 18)) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | ((code >> 12) & 0x3f)) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; } - })); + } + } + this.lastByteIndex = i; + this.bytes += i - this.start; + if (i >= 64) { + this.block = blocks[16]; + this.start = i - 64; + this.hash(); + this.hashed = true; + } + else { + this.start = i; } - // create combined output - const output = { - generations, - llmOutput: llmOutputs.length - ? this._combineLLMOutput?.(...llmOutputs) - : undefined, - }; - Object.defineProperty(output, RUN_KEY, { - value: runManagers - ? { runIds: runManagers?.map((manager) => manager.runId) } - : undefined, - configurable: true, - }); - return output; } - async _generateCached({ messages, cache, llmStringKey, parsedOptions, handledOptions, }) { - const baseMessages = messages.map((messageList) => messageList.map(coerceMessageLikeToMessage)); - const inheritableMetadata = { - ...handledOptions.metadata, - ...this.getLsParams(parsedOptions), - }; - // create callback manager and start run - const callbackManager_ = await CallbackManager.configure(handledOptions.callbacks, this.callbacks, handledOptions.tags, this.tags, inheritableMetadata, this.metadata, { verbose: this.verbose }); - const extra = { - options: parsedOptions, - invocation_params: this?.invocationParams(parsedOptions), - batch_size: 1, - }; - const runManagers = await callbackManager_?.handleChatModelStart(this.toJSON(), baseMessages.map(_formatForTracing), handledOptions.runId, undefined, extra, undefined, undefined, handledOptions.runName); - // generate results - const missingPromptIndices = []; - const results = await Promise.allSettled(baseMessages.map(async (baseMessage, index) => { - // Join all content into one string for the prompt index - const prompt = BaseChatModel._convertInputToPromptValue(baseMessage).toString(); - const result = await cache.lookup(prompt, llmStringKey); - if (result == null) { - missingPromptIndices.push(index); - } - return result; - })); - // Map run managers to the results before filtering out null results - // Null results are just absent from the cache. - const cachedResults = results - .map((result, index) => ({ result, runManager: runManagers?.[index] })) - .filter(({ result }) => (result.status === "fulfilled" && result.value != null) || - result.status === "rejected"); - // Handle results and call run managers - const generations = []; - await Promise.all(cachedResults.map(async ({ result: promiseResult, runManager }, i) => { - if (promiseResult.status === "fulfilled") { - const result = promiseResult.value; - generations[i] = result.map((result) => { - if ("message" in result && - isBaseMessage(result.message) && - isAIMessage(result.message)) { - // eslint-disable-next-line no-param-reassign - result.message.usage_metadata = { - input_tokens: 0, - output_tokens: 0, - total_tokens: 0, - }; - } - // eslint-disable-next-line no-param-reassign - result.generationInfo = { - ...result.generationInfo, - tokenUsage: {}, - }; - return result; - }); - if (result.length) { - await runManager?.handleLLMNewToken(result[0].text); - } - return runManager?.handleLLMEnd({ - generations: [result], - }, undefined, undefined, undefined, { - cached: true, - }); + if (this.bytes > 4294967295) { + this.hBytes += (this.bytes / 4294967296) << 0; + this.bytes = this.bytes % 4294967296; + } + return this; +}; +Sha1.prototype.finalize = function () { + if (this.finalized) { + return; + } + this.finalized = true; + var blocks = this.blocks, i = this.lastByteIndex; + blocks[16] = this.block; + blocks[i >> 2] |= EXTRA[i & 3]; + this.block = blocks[16]; + if (i >= 56) { + if (!this.hashed) { + this.hash(); + } + blocks[0] = this.block; + blocks[16] = + blocks[1] = + blocks[2] = + blocks[3] = + blocks[4] = + blocks[5] = + blocks[6] = + blocks[7] = + blocks[8] = + blocks[9] = + blocks[10] = + blocks[11] = + blocks[12] = + blocks[13] = + blocks[14] = + blocks[15] = + 0; + } + blocks[14] = (this.hBytes << 3) | (this.bytes >>> 29); + blocks[15] = this.bytes << 3; + this.hash(); +}; +Sha1.prototype.hash = function () { + var a = this.h0, b = this.h1, c = this.h2, d = this.h3, e = this.h4; + var f, j, t, blocks = this.blocks; + for (j = 16; j < 80; ++j) { + t = blocks[j - 3] ^ blocks[j - 8] ^ blocks[j - 14] ^ blocks[j - 16]; + blocks[j] = (t << 1) | (t >>> 31); + } + for (j = 0; j < 20; j += 5) { + f = (b & c) | (~b & d); + t = (a << 5) | (a >>> 27); + e = (t + f + e + 1518500249 + blocks[j]) << 0; + b = (b << 30) | (b >>> 2); + f = (a & b) | (~a & c); + t = (e << 5) | (e >>> 27); + d = (t + f + d + 1518500249 + blocks[j + 1]) << 0; + a = (a << 30) | (a >>> 2); + f = (e & a) | (~e & b); + t = (d << 5) | (d >>> 27); + c = (t + f + c + 1518500249 + blocks[j + 2]) << 0; + e = (e << 30) | (e >>> 2); + f = (d & e) | (~d & a); + t = (c << 5) | (c >>> 27); + b = (t + f + b + 1518500249 + blocks[j + 3]) << 0; + d = (d << 30) | (d >>> 2); + f = (c & d) | (~c & e); + t = (b << 5) | (b >>> 27); + a = (t + f + a + 1518500249 + blocks[j + 4]) << 0; + c = (c << 30) | (c >>> 2); + } + for (; j < 40; j += 5) { + f = b ^ c ^ d; + t = (a << 5) | (a >>> 27); + e = (t + f + e + 1859775393 + blocks[j]) << 0; + b = (b << 30) | (b >>> 2); + f = a ^ b ^ c; + t = (e << 5) | (e >>> 27); + d = (t + f + d + 1859775393 + blocks[j + 1]) << 0; + a = (a << 30) | (a >>> 2); + f = e ^ a ^ b; + t = (d << 5) | (d >>> 27); + c = (t + f + c + 1859775393 + blocks[j + 2]) << 0; + e = (e << 30) | (e >>> 2); + f = d ^ e ^ a; + t = (c << 5) | (c >>> 27); + b = (t + f + b + 1859775393 + blocks[j + 3]) << 0; + d = (d << 30) | (d >>> 2); + f = c ^ d ^ e; + t = (b << 5) | (b >>> 27); + a = (t + f + a + 1859775393 + blocks[j + 4]) << 0; + c = (c << 30) | (c >>> 2); + } + for (; j < 60; j += 5) { + f = (b & c) | (b & d) | (c & d); + t = (a << 5) | (a >>> 27); + e = (t + f + e - 1894007588 + blocks[j]) << 0; + b = (b << 30) | (b >>> 2); + f = (a & b) | (a & c) | (b & c); + t = (e << 5) | (e >>> 27); + d = (t + f + d - 1894007588 + blocks[j + 1]) << 0; + a = (a << 30) | (a >>> 2); + f = (e & a) | (e & b) | (a & b); + t = (d << 5) | (d >>> 27); + c = (t + f + c - 1894007588 + blocks[j + 2]) << 0; + e = (e << 30) | (e >>> 2); + f = (d & e) | (d & a) | (e & a); + t = (c << 5) | (c >>> 27); + b = (t + f + b - 1894007588 + blocks[j + 3]) << 0; + d = (d << 30) | (d >>> 2); + f = (c & d) | (c & e) | (d & e); + t = (b << 5) | (b >>> 27); + a = (t + f + a - 1894007588 + blocks[j + 4]) << 0; + c = (c << 30) | (c >>> 2); + } + for (; j < 80; j += 5) { + f = b ^ c ^ d; + t = (a << 5) | (a >>> 27); + e = (t + f + e - 899497514 + blocks[j]) << 0; + b = (b << 30) | (b >>> 2); + f = a ^ b ^ c; + t = (e << 5) | (e >>> 27); + d = (t + f + d - 899497514 + blocks[j + 1]) << 0; + a = (a << 30) | (a >>> 2); + f = e ^ a ^ b; + t = (d << 5) | (d >>> 27); + c = (t + f + c - 899497514 + blocks[j + 2]) << 0; + e = (e << 30) | (e >>> 2); + f = d ^ e ^ a; + t = (c << 5) | (c >>> 27); + b = (t + f + b - 899497514 + blocks[j + 3]) << 0; + d = (d << 30) | (d >>> 2); + f = c ^ d ^ e; + t = (b << 5) | (b >>> 27); + a = (t + f + a - 899497514 + blocks[j + 4]) << 0; + c = (c << 30) | (c >>> 2); + } + this.h0 = (this.h0 + a) << 0; + this.h1 = (this.h1 + b) << 0; + this.h2 = (this.h2 + c) << 0; + this.h3 = (this.h3 + d) << 0; + this.h4 = (this.h4 + e) << 0; +}; +Sha1.prototype.hex = function () { + this.finalize(); + var h0 = this.h0, h1 = this.h1, h2 = this.h2, h3 = this.h3, h4 = this.h4; + return (HEX_CHARS[(h0 >> 28) & 0x0f] + + HEX_CHARS[(h0 >> 24) & 0x0f] + + HEX_CHARS[(h0 >> 20) & 0x0f] + + HEX_CHARS[(h0 >> 16) & 0x0f] + + HEX_CHARS[(h0 >> 12) & 0x0f] + + HEX_CHARS[(h0 >> 8) & 0x0f] + + HEX_CHARS[(h0 >> 4) & 0x0f] + + HEX_CHARS[h0 & 0x0f] + + HEX_CHARS[(h1 >> 28) & 0x0f] + + HEX_CHARS[(h1 >> 24) & 0x0f] + + HEX_CHARS[(h1 >> 20) & 0x0f] + + HEX_CHARS[(h1 >> 16) & 0x0f] + + HEX_CHARS[(h1 >> 12) & 0x0f] + + HEX_CHARS[(h1 >> 8) & 0x0f] + + HEX_CHARS[(h1 >> 4) & 0x0f] + + HEX_CHARS[h1 & 0x0f] + + HEX_CHARS[(h2 >> 28) & 0x0f] + + HEX_CHARS[(h2 >> 24) & 0x0f] + + HEX_CHARS[(h2 >> 20) & 0x0f] + + HEX_CHARS[(h2 >> 16) & 0x0f] + + HEX_CHARS[(h2 >> 12) & 0x0f] + + HEX_CHARS[(h2 >> 8) & 0x0f] + + HEX_CHARS[(h2 >> 4) & 0x0f] + + HEX_CHARS[h2 & 0x0f] + + HEX_CHARS[(h3 >> 28) & 0x0f] + + HEX_CHARS[(h3 >> 24) & 0x0f] + + HEX_CHARS[(h3 >> 20) & 0x0f] + + HEX_CHARS[(h3 >> 16) & 0x0f] + + HEX_CHARS[(h3 >> 12) & 0x0f] + + HEX_CHARS[(h3 >> 8) & 0x0f] + + HEX_CHARS[(h3 >> 4) & 0x0f] + + HEX_CHARS[h3 & 0x0f] + + HEX_CHARS[(h4 >> 28) & 0x0f] + + HEX_CHARS[(h4 >> 24) & 0x0f] + + HEX_CHARS[(h4 >> 20) & 0x0f] + + HEX_CHARS[(h4 >> 16) & 0x0f] + + HEX_CHARS[(h4 >> 12) & 0x0f] + + HEX_CHARS[(h4 >> 8) & 0x0f] + + HEX_CHARS[(h4 >> 4) & 0x0f] + + HEX_CHARS[h4 & 0x0f]); +}; +Sha1.prototype.toString = Sha1.prototype.hex; +Sha1.prototype.digest = function () { + this.finalize(); + var h0 = this.h0, h1 = this.h1, h2 = this.h2, h3 = this.h3, h4 = this.h4; + return [ + (h0 >> 24) & 0xff, + (h0 >> 16) & 0xff, + (h0 >> 8) & 0xff, + h0 & 0xff, + (h1 >> 24) & 0xff, + (h1 >> 16) & 0xff, + (h1 >> 8) & 0xff, + h1 & 0xff, + (h2 >> 24) & 0xff, + (h2 >> 16) & 0xff, + (h2 >> 8) & 0xff, + h2 & 0xff, + (h3 >> 24) & 0xff, + (h3 >> 16) & 0xff, + (h3 >> 8) & 0xff, + h3 & 0xff, + (h4 >> 24) & 0xff, + (h4 >> 16) & 0xff, + (h4 >> 8) & 0xff, + h4 & 0xff, + ]; +}; +Sha1.prototype.array = Sha1.prototype.digest; +Sha1.prototype.arrayBuffer = function () { + this.finalize(); + var buffer = new ArrayBuffer(20); + var dataView = new DataView(buffer); + dataView.setUint32(0, this.h0); + dataView.setUint32(4, this.h1); + dataView.setUint32(8, this.h2); + dataView.setUint32(12, this.h3); + dataView.setUint32(16, this.h4); + return buffer; +}; +let hasLoggedWarning = false; +/** + * @deprecated Use `makeDefaultKeyEncoder()` to create a custom key encoder. + * This function will be removed in a future version. + */ +const insecureHash = (message) => { + if (!hasLoggedWarning) { + console.warn([ + `The default method for hashing keys is insecure and will be replaced in a future version,`, + `but hasn't been replaced yet as to not break existing caches. It's recommended that you use`, + `a more secure hashing algorithm to avoid cache poisoning.`, + ``, + `See this page for more information:`, + `|`, + `└> https://js.langchain.com/docs/troubleshooting/warnings/insecure-cache-algorithm`, + ].join("\n")); + hasLoggedWarning = true; + } + return new Sha1(true).update(message)["hex"](); +}; + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/js-sha256/hash.js +// @ts-nocheck +// Inlined to deal with portability issues with importing crypto module +/** + * [js-sha256]{@link https://github.com/emn178/js-sha256} + * + * @version 0.11.1 + * @author Chen, Yi-Cyuan [emn178@gmail.com] + * @copyright Chen, Yi-Cyuan 2014-2025 + * @license MIT + */ +/*jslint bitwise: true */ + +var hash_HEX_CHARS = "0123456789abcdef".split(""); +var hash_EXTRA = [-2147483648, 8388608, 32768, 128]; +var hash_SHIFT = [24, 16, 8, 0]; +var K = [ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, + 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, + 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, + 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, + 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, + 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, + 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, + 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, + 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2, +]; +var hash_OUTPUT_TYPES = (/* unused pure expression or super */ null && (["hex", "array", "digest", "arrayBuffer"])); +var hash_blocks = []; +function Sha256(is224, sharedMemory) { + if (sharedMemory) { + hash_blocks[0] = + hash_blocks[16] = + hash_blocks[1] = + hash_blocks[2] = + hash_blocks[3] = + hash_blocks[4] = + hash_blocks[5] = + hash_blocks[6] = + hash_blocks[7] = + hash_blocks[8] = + hash_blocks[9] = + hash_blocks[10] = + hash_blocks[11] = + hash_blocks[12] = + hash_blocks[13] = + hash_blocks[14] = + hash_blocks[15] = + 0; + this.blocks = hash_blocks; + } + else { + this.blocks = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + } + if (is224) { + this.h0 = 0xc1059ed8; + this.h1 = 0x367cd507; + this.h2 = 0x3070dd17; + this.h3 = 0xf70e5939; + this.h4 = 0xffc00b31; + this.h5 = 0x68581511; + this.h6 = 0x64f98fa7; + this.h7 = 0xbefa4fa4; + } + else { + // 256 + this.h0 = 0x6a09e667; + this.h1 = 0xbb67ae85; + this.h2 = 0x3c6ef372; + this.h3 = 0xa54ff53a; + this.h4 = 0x510e527f; + this.h5 = 0x9b05688c; + this.h6 = 0x1f83d9ab; + this.h7 = 0x5be0cd19; + } + this.block = this.start = this.bytes = this.hBytes = 0; + this.finalized = this.hashed = false; + this.first = true; + this.is224 = is224; +} +Sha256.prototype.update = function (message) { + if (this.finalized) { + return; + } + var notString, type = typeof message; + if (type !== "string") { + if (type === "object") { + if (message === null) { + throw new Error(ERROR); } - else { - // status === "rejected" - await runManager?.handleLLMError(promiseResult.reason, undefined, undefined, undefined, { - cached: true, - }); - return Promise.reject(promiseResult.reason); + else if (ARRAY_BUFFER && message.constructor === ArrayBuffer) { + message = new Uint8Array(message); } - })); - const output = { - generations, - missingPromptIndices, - startedRunManagers: runManagers, - }; - // This defines RUN_KEY as a non-enumerable property on the output object - // so that it is not serialized when the output is stringified, and so that - // it isnt included when listing the keys of the output object. - Object.defineProperty(output, RUN_KEY, { - value: runManagers - ? { runIds: runManagers?.map((manager) => manager.runId) } - : undefined, - configurable: true, - }); - return output; + else if (!Array.isArray(message)) { + if (!ARRAY_BUFFER || !ArrayBuffer.isView(message)) { + throw new Error(ERROR); + } + } + } + else { + throw new Error(ERROR); + } + notString = true; } - /** - * Generates chat based on the input messages. - * @param messages An array of arrays of BaseMessage instances. - * @param options The call options or an array of stop sequences. - * @param callbacks The callbacks for the language model. - * @returns A Promise that resolves to an LLMResult. - */ - async generate(messages, options, callbacks) { - // parse call options - let parsedOptions; - if (Array.isArray(options)) { - parsedOptions = { stop: options }; + var code, index = 0, i, length = message.length, blocks = this.blocks; + while (index < length) { + if (this.hashed) { + this.hashed = false; + blocks[0] = this.block; + this.block = + blocks[16] = + blocks[1] = + blocks[2] = + blocks[3] = + blocks[4] = + blocks[5] = + blocks[6] = + blocks[7] = + blocks[8] = + blocks[9] = + blocks[10] = + blocks[11] = + blocks[12] = + blocks[13] = + blocks[14] = + blocks[15] = + 0; + } + if (notString) { + for (i = this.start; index < length && i < 64; ++index) { + blocks[i >>> 2] |= message[index] << hash_SHIFT[i++ & 3]; + } } else { - parsedOptions = options; + for (i = this.start; index < length && i < 64; ++index) { + code = message.charCodeAt(index); + if (code < 0x80) { + blocks[i >>> 2] |= code << hash_SHIFT[i++ & 3]; + } + else if (code < 0x800) { + blocks[i >>> 2] |= (0xc0 | (code >>> 6)) << hash_SHIFT[i++ & 3]; + blocks[i >>> 2] |= (0x80 | (code & 0x3f)) << hash_SHIFT[i++ & 3]; + } + else if (code < 0xd800 || code >= 0xe000) { + blocks[i >>> 2] |= (0xe0 | (code >>> 12)) << hash_SHIFT[i++ & 3]; + blocks[i >>> 2] |= (0x80 | ((code >>> 6) & 0x3f)) << hash_SHIFT[i++ & 3]; + blocks[i >>> 2] |= (0x80 | (code & 0x3f)) << hash_SHIFT[i++ & 3]; + } + else { + code = + 0x10000 + + (((code & 0x3ff) << 10) | (message.charCodeAt(++index) & 0x3ff)); + blocks[i >>> 2] |= (0xf0 | (code >>> 18)) << hash_SHIFT[i++ & 3]; + blocks[i >>> 2] |= (0x80 | ((code >>> 12) & 0x3f)) << hash_SHIFT[i++ & 3]; + blocks[i >>> 2] |= (0x80 | ((code >>> 6) & 0x3f)) << hash_SHIFT[i++ & 3]; + blocks[i >>> 2] |= (0x80 | (code & 0x3f)) << hash_SHIFT[i++ & 3]; + } + } } - const baseMessages = messages.map((messageList) => messageList.map(coerceMessageLikeToMessage)); - const [runnableConfig, callOptions] = this._separateRunnableConfigFromCallOptionsCompat(parsedOptions); - runnableConfig.callbacks = runnableConfig.callbacks ?? callbacks; - if (!this.cache) { - return this._generateUncached(baseMessages, callOptions, runnableConfig); + this.lastByteIndex = i; + this.bytes += i - this.start; + if (i >= 64) { + this.block = blocks[16]; + this.start = i - 64; + this.hash(); + this.hashed = true; } - const { cache } = this; - const llmStringKey = this._getSerializedCacheKeyParametersForCall(callOptions); - const { generations, missingPromptIndices, startedRunManagers } = await this._generateCached({ - messages: baseMessages, - cache, - llmStringKey, - parsedOptions: callOptions, - handledOptions: runnableConfig, - }); - let llmOutput = {}; - if (missingPromptIndices.length > 0) { - const results = await this._generateUncached(missingPromptIndices.map((i) => baseMessages[i]), callOptions, runnableConfig, startedRunManagers !== undefined - ? missingPromptIndices.map((i) => startedRunManagers?.[i]) - : undefined); - await Promise.all(results.generations.map(async (generation, index) => { - const promptIndex = missingPromptIndices[index]; - generations[promptIndex] = generation; - // Join all content into one string for the prompt index - const prompt = BaseChatModel._convertInputToPromptValue(baseMessages[promptIndex]).toString(); - return cache.update(prompt, llmStringKey, generation); - })); - llmOutput = results.llmOutput ?? {}; + else { + this.start = i; } - return { generations, llmOutput }; } - /** - * Get the parameters used to invoke the model - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - invocationParams(_options) { - return {}; + if (this.bytes > 4294967295) { + this.hBytes += (this.bytes / 4294967296) << 0; + this.bytes = this.bytes % 4294967296; } - _modelType() { - return "base_chat_model"; + return this; +}; +Sha256.prototype.finalize = function () { + if (this.finalized) { + return; } - /** - * @deprecated - * Return a json-like object representing this LLM. - */ - serialize() { + this.finalized = true; + var blocks = this.blocks, i = this.lastByteIndex; + blocks[16] = this.block; + blocks[i >>> 2] |= hash_EXTRA[i & 3]; + this.block = blocks[16]; + if (i >= 56) { + if (!this.hashed) { + this.hash(); + } + blocks[0] = this.block; + blocks[16] = + blocks[1] = + blocks[2] = + blocks[3] = + blocks[4] = + blocks[5] = + blocks[6] = + blocks[7] = + blocks[8] = + blocks[9] = + blocks[10] = + blocks[11] = + blocks[12] = + blocks[13] = + blocks[14] = + blocks[15] = + 0; + } + blocks[14] = (this.hBytes << 3) | (this.bytes >>> 29); + blocks[15] = this.bytes << 3; + this.hash(); +}; +Sha256.prototype.hash = function () { + var a = this.h0, b = this.h1, c = this.h2, d = this.h3, e = this.h4, f = this.h5, g = this.h6, h = this.h7, blocks = this.blocks, j, s0, s1, maj, t1, t2, ch, ab, da, cd, bc; + for (j = 16; j < 64; ++j) { + // rightrotate + t1 = blocks[j - 15]; + s0 = ((t1 >>> 7) | (t1 << 25)) ^ ((t1 >>> 18) | (t1 << 14)) ^ (t1 >>> 3); + t1 = blocks[j - 2]; + s1 = ((t1 >>> 17) | (t1 << 15)) ^ ((t1 >>> 19) | (t1 << 13)) ^ (t1 >>> 10); + blocks[j] = (blocks[j - 16] + s0 + blocks[j - 7] + s1) << 0; + } + bc = b & c; + for (j = 0; j < 64; j += 4) { + if (this.first) { + if (this.is224) { + ab = 300032; + t1 = blocks[0] - 1413257819; + h = (t1 - 150054599) << 0; + d = (t1 + 24177077) << 0; + } + else { + ab = 704751109; + t1 = blocks[0] - 210244248; + h = (t1 - 1521486534) << 0; + d = (t1 + 143694565) << 0; + } + this.first = false; + } + else { + s0 = + ((a >>> 2) | (a << 30)) ^ + ((a >>> 13) | (a << 19)) ^ + ((a >>> 22) | (a << 10)); + s1 = + ((e >>> 6) | (e << 26)) ^ + ((e >>> 11) | (e << 21)) ^ + ((e >>> 25) | (e << 7)); + ab = a & b; + maj = ab ^ (a & c) ^ bc; + ch = (e & f) ^ (~e & g); + t1 = h + s1 + ch + K[j] + blocks[j]; + t2 = s0 + maj; + h = (d + t1) << 0; + d = (t1 + t2) << 0; + } + s0 = + ((d >>> 2) | (d << 30)) ^ + ((d >>> 13) | (d << 19)) ^ + ((d >>> 22) | (d << 10)); + s1 = + ((h >>> 6) | (h << 26)) ^ + ((h >>> 11) | (h << 21)) ^ + ((h >>> 25) | (h << 7)); + da = d & a; + maj = da ^ (d & b) ^ ab; + ch = (g & h) ^ (~g & e); + t1 = f + s1 + ch + K[j + 1] + blocks[j + 1]; + t2 = s0 + maj; + g = (c + t1) << 0; + c = (t1 + t2) << 0; + s0 = + ((c >>> 2) | (c << 30)) ^ + ((c >>> 13) | (c << 19)) ^ + ((c >>> 22) | (c << 10)); + s1 = + ((g >>> 6) | (g << 26)) ^ + ((g >>> 11) | (g << 21)) ^ + ((g >>> 25) | (g << 7)); + cd = c & d; + maj = cd ^ (c & a) ^ da; + ch = (f & g) ^ (~f & h); + t1 = e + s1 + ch + K[j + 2] + blocks[j + 2]; + t2 = s0 + maj; + f = (b + t1) << 0; + b = (t1 + t2) << 0; + s0 = + ((b >>> 2) | (b << 30)) ^ + ((b >>> 13) | (b << 19)) ^ + ((b >>> 22) | (b << 10)); + s1 = + ((f >>> 6) | (f << 26)) ^ + ((f >>> 11) | (f << 21)) ^ + ((f >>> 25) | (f << 7)); + bc = b & c; + maj = bc ^ (b & d) ^ cd; + ch = (f & g) ^ (~f & h); + t1 = e + s1 + ch + K[j + 3] + blocks[j + 3]; + t2 = s0 + maj; + e = (a + t1) << 0; + a = (t1 + t2) << 0; + this.chromeBugWorkAround = true; + } + this.h0 = (this.h0 + a) << 0; + this.h1 = (this.h1 + b) << 0; + this.h2 = (this.h2 + c) << 0; + this.h3 = (this.h3 + d) << 0; + this.h4 = (this.h4 + e) << 0; + this.h5 = (this.h5 + f) << 0; + this.h6 = (this.h6 + g) << 0; + this.h7 = (this.h7 + h) << 0; +}; +Sha256.prototype.hex = function () { + this.finalize(); + var h0 = this.h0, h1 = this.h1, h2 = this.h2, h3 = this.h3, h4 = this.h4, h5 = this.h5, h6 = this.h6, h7 = this.h7; + var hex = hash_HEX_CHARS[(h0 >>> 28) & 0x0f] + + hash_HEX_CHARS[(h0 >>> 24) & 0x0f] + + hash_HEX_CHARS[(h0 >>> 20) & 0x0f] + + hash_HEX_CHARS[(h0 >>> 16) & 0x0f] + + hash_HEX_CHARS[(h0 >>> 12) & 0x0f] + + hash_HEX_CHARS[(h0 >>> 8) & 0x0f] + + hash_HEX_CHARS[(h0 >>> 4) & 0x0f] + + hash_HEX_CHARS[h0 & 0x0f] + + hash_HEX_CHARS[(h1 >>> 28) & 0x0f] + + hash_HEX_CHARS[(h1 >>> 24) & 0x0f] + + hash_HEX_CHARS[(h1 >>> 20) & 0x0f] + + hash_HEX_CHARS[(h1 >>> 16) & 0x0f] + + hash_HEX_CHARS[(h1 >>> 12) & 0x0f] + + hash_HEX_CHARS[(h1 >>> 8) & 0x0f] + + hash_HEX_CHARS[(h1 >>> 4) & 0x0f] + + hash_HEX_CHARS[h1 & 0x0f] + + hash_HEX_CHARS[(h2 >>> 28) & 0x0f] + + hash_HEX_CHARS[(h2 >>> 24) & 0x0f] + + hash_HEX_CHARS[(h2 >>> 20) & 0x0f] + + hash_HEX_CHARS[(h2 >>> 16) & 0x0f] + + hash_HEX_CHARS[(h2 >>> 12) & 0x0f] + + hash_HEX_CHARS[(h2 >>> 8) & 0x0f] + + hash_HEX_CHARS[(h2 >>> 4) & 0x0f] + + hash_HEX_CHARS[h2 & 0x0f] + + hash_HEX_CHARS[(h3 >>> 28) & 0x0f] + + hash_HEX_CHARS[(h3 >>> 24) & 0x0f] + + hash_HEX_CHARS[(h3 >>> 20) & 0x0f] + + hash_HEX_CHARS[(h3 >>> 16) & 0x0f] + + hash_HEX_CHARS[(h3 >>> 12) & 0x0f] + + hash_HEX_CHARS[(h3 >>> 8) & 0x0f] + + hash_HEX_CHARS[(h3 >>> 4) & 0x0f] + + hash_HEX_CHARS[h3 & 0x0f] + + hash_HEX_CHARS[(h4 >>> 28) & 0x0f] + + hash_HEX_CHARS[(h4 >>> 24) & 0x0f] + + hash_HEX_CHARS[(h4 >>> 20) & 0x0f] + + hash_HEX_CHARS[(h4 >>> 16) & 0x0f] + + hash_HEX_CHARS[(h4 >>> 12) & 0x0f] + + hash_HEX_CHARS[(h4 >>> 8) & 0x0f] + + hash_HEX_CHARS[(h4 >>> 4) & 0x0f] + + hash_HEX_CHARS[h4 & 0x0f] + + hash_HEX_CHARS[(h5 >>> 28) & 0x0f] + + hash_HEX_CHARS[(h5 >>> 24) & 0x0f] + + hash_HEX_CHARS[(h5 >>> 20) & 0x0f] + + hash_HEX_CHARS[(h5 >>> 16) & 0x0f] + + hash_HEX_CHARS[(h5 >>> 12) & 0x0f] + + hash_HEX_CHARS[(h5 >>> 8) & 0x0f] + + hash_HEX_CHARS[(h5 >>> 4) & 0x0f] + + hash_HEX_CHARS[h5 & 0x0f] + + hash_HEX_CHARS[(h6 >>> 28) & 0x0f] + + hash_HEX_CHARS[(h6 >>> 24) & 0x0f] + + hash_HEX_CHARS[(h6 >>> 20) & 0x0f] + + hash_HEX_CHARS[(h6 >>> 16) & 0x0f] + + hash_HEX_CHARS[(h6 >>> 12) & 0x0f] + + hash_HEX_CHARS[(h6 >>> 8) & 0x0f] + + hash_HEX_CHARS[(h6 >>> 4) & 0x0f] + + hash_HEX_CHARS[h6 & 0x0f]; + if (!this.is224) { + hex += + hash_HEX_CHARS[(h7 >>> 28) & 0x0f] + + hash_HEX_CHARS[(h7 >>> 24) & 0x0f] + + hash_HEX_CHARS[(h7 >>> 20) & 0x0f] + + hash_HEX_CHARS[(h7 >>> 16) & 0x0f] + + hash_HEX_CHARS[(h7 >>> 12) & 0x0f] + + hash_HEX_CHARS[(h7 >>> 8) & 0x0f] + + hash_HEX_CHARS[(h7 >>> 4) & 0x0f] + + hash_HEX_CHARS[h7 & 0x0f]; + } + return hex; +}; +Sha256.prototype.toString = Sha256.prototype.hex; +Sha256.prototype.digest = function () { + this.finalize(); + var h0 = this.h0, h1 = this.h1, h2 = this.h2, h3 = this.h3, h4 = this.h4, h5 = this.h5, h6 = this.h6, h7 = this.h7; + var arr = [ + (h0 >>> 24) & 0xff, + (h0 >>> 16) & 0xff, + (h0 >>> 8) & 0xff, + h0 & 0xff, + (h1 >>> 24) & 0xff, + (h1 >>> 16) & 0xff, + (h1 >>> 8) & 0xff, + h1 & 0xff, + (h2 >>> 24) & 0xff, + (h2 >>> 16) & 0xff, + (h2 >>> 8) & 0xff, + h2 & 0xff, + (h3 >>> 24) & 0xff, + (h3 >>> 16) & 0xff, + (h3 >>> 8) & 0xff, + h3 & 0xff, + (h4 >>> 24) & 0xff, + (h4 >>> 16) & 0xff, + (h4 >>> 8) & 0xff, + h4 & 0xff, + (h5 >>> 24) & 0xff, + (h5 >>> 16) & 0xff, + (h5 >>> 8) & 0xff, + h5 & 0xff, + (h6 >>> 24) & 0xff, + (h6 >>> 16) & 0xff, + (h6 >>> 8) & 0xff, + h6 & 0xff, + ]; + if (!this.is224) { + arr.push((h7 >>> 24) & 0xff, (h7 >>> 16) & 0xff, (h7 >>> 8) & 0xff, h7 & 0xff); + } + return arr; +}; +Sha256.prototype.array = Sha256.prototype.digest; +Sha256.prototype.arrayBuffer = function () { + this.finalize(); + var buffer = new ArrayBuffer(this.is224 ? 28 : 32); + var dataView = new DataView(buffer); + dataView.setUint32(0, this.h0); + dataView.setUint32(4, this.h1); + dataView.setUint32(8, this.h2); + dataView.setUint32(12, this.h3); + dataView.setUint32(16, this.h4); + dataView.setUint32(20, this.h5); + dataView.setUint32(24, this.h6); + if (!this.is224) { + dataView.setUint32(28, this.h7); + } + return buffer; +}; +const sha256 = (...strings) => { + return new Sha256(false, true).update(strings.join("")).hex(); +}; + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/hash.js + + + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/caches/base.js + + +/** + * This cache key should be consistent across all versions of LangChain. + * It is currently NOT consistent across versions of LangChain. + * + * A huge benefit of having a remote cache (like redis) is that you can + * access the cache from different processes/machines. The allows you to + * separate concerns and scale horizontally. + * + * TODO: Make cache key consistent across versions of LangChain. + * + * @deprecated Use `makeDefaultKeyEncoder()` to create a custom key encoder. + * This function will be removed in a future version. + */ +const getCacheKey = (...strings) => insecureHash(strings.join("_")); +function deserializeStoredGeneration(storedGeneration) { + if (storedGeneration.message !== undefined) { return { - ...this.invocationParams(), - _type: this._llmType(), - _model: this._modelType(), + text: storedGeneration.text, + message: mapStoredMessageToChatMessage(storedGeneration.message), }; } - /** - * Generates a prompt based on the input prompt values. - * @param promptValues An array of BasePromptValue instances. - * @param options The call options or an array of stop sequences. - * @param callbacks The callbacks for the language model. - * @returns A Promise that resolves to an LLMResult. - */ - async generatePrompt(promptValues, options, callbacks) { - const promptMessages = promptValues.map((promptValue) => promptValue.toChatMessages()); - return this.generate(promptMessages, options, callbacks); + else { + return { text: storedGeneration.text }; + } +} +function serializeGeneration(generation) { + const serializedValue = { + text: generation.text, + }; + if (generation.message !== undefined) { + serializedValue.message = generation.message.toDict(); + } + return serializedValue; +} +/** + * Base class for all caches. All caches should extend this class. + */ +class BaseCache { + constructor() { + // For backwards compatibility, we use a default key encoder + // that uses SHA-1 to hash the prompt and LLM key. This will also print a warning + // about the security implications of using SHA-1 as a cache key. + Object.defineProperty(this, "keyEncoder", { + enumerable: true, + configurable: true, + writable: true, + value: getCacheKey + }); } /** - * @deprecated Use .invoke() instead. Will be removed in 0.2.0. - * - * Makes a single call to the chat model. - * @param messages An array of BaseMessage instances. - * @param options The call options or an array of stop sequences. - * @param callbacks The callbacks for the language model. - * @returns A Promise that resolves to a BaseMessage. + * Sets a custom key encoder function for the cache. + * This function should take a prompt and an LLM key and return a string + * that will be used as the cache key. + * @param keyEncoderFn The custom key encoder function. */ - async call(messages, options, callbacks) { - const result = await this.generate([messages.map(coerceMessageLikeToMessage)], options, callbacks); - const generations = result.generations; - return generations[0][0].message; + makeDefaultKeyEncoder(keyEncoderFn) { + this.keyEncoder = keyEncoderFn; + } +} +const GLOBAL_MAP = new Map(); +/** + * A cache for storing LLM generations that stores data in memory. + */ +class InMemoryCache extends BaseCache { + constructor(map) { + super(); + Object.defineProperty(this, "cache", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.cache = map ?? new Map(); } /** - * @deprecated Use .invoke() instead. Will be removed in 0.2.0. - * - * Makes a single call to the chat model with a prompt value. - * @param promptValue The value of the prompt. - * @param options The call options or an array of stop sequences. - * @param callbacks The callbacks for the language model. - * @returns A Promise that resolves to a BaseMessage. + * Retrieves data from the cache using a prompt and an LLM key. If the + * data is not found, it returns null. + * @param prompt The prompt used to find the data. + * @param llmKey The LLM key used to find the data. + * @returns The data corresponding to the prompt and LLM key, or null if not found. */ - async callPrompt(promptValue, options, callbacks) { - const promptMessages = promptValue.toChatMessages(); - return this.call(promptMessages, options, callbacks); + lookup(prompt, llmKey) { + return Promise.resolve(this.cache.get(this.keyEncoder(prompt, llmKey)) ?? null); } /** - * @deprecated Use .invoke() instead. Will be removed in 0.2.0. - * - * Predicts the next message based on the input messages. - * @param messages An array of BaseMessage instances. - * @param options The call options or an array of stop sequences. - * @param callbacks The callbacks for the language model. - * @returns A Promise that resolves to a BaseMessage. + * Updates the cache with new data using a prompt and an LLM key. + * @param prompt The prompt used to store the data. + * @param llmKey The LLM key used to store the data. + * @param value The data to be stored. */ - async predictMessages(messages, options, callbacks) { - return this.call(messages, options, callbacks); + async update(prompt, llmKey, value) { + this.cache.set(this.keyEncoder(prompt, llmKey), value); } /** - * @deprecated Use .invoke() instead. Will be removed in 0.2.0. - * - * Predicts the next message based on a text input. - * @param text The text input. - * @param options The call options or an array of stop sequences. - * @param callbacks The callbacks for the language model. - * @returns A Promise that resolves to a string. + * Returns a global instance of InMemoryCache using a predefined global + * map as the initial cache. + * @returns A global instance of InMemoryCache. */ - async predict(text, options, callbacks) { - const message = new human_HumanMessage(text); - const result = await this.call([message], options, callbacks); - if (typeof result.content !== "string") { - throw new Error("Cannot use predict when output is not a string."); - } - return result.content; - } - withStructuredOutput(outputSchema, config) { - if (typeof this.bindTools !== "function") { - throw new Error(`Chat model must implement ".bindTools()" to use withStructuredOutput.`); - } - if (config?.strict) { - throw new Error(`"strict" mode is not supported for this model by default.`); - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const schema = outputSchema; - const name = config?.name; - const description = schema.description ?? "A function available to call."; - const method = config?.method; - const includeRaw = config?.includeRaw; - if (method === "jsonMode") { - throw new Error(`Base withStructuredOutput implementation only supports "functionCalling" as a method.`); - } - let functionName = name ?? "extract"; - let tools; - if (isZodSchema(schema)) { - tools = [ - { - type: "function", - function: { - name: functionName, - description, - parameters: zodToJsonSchema_zodToJsonSchema(schema), - }, - }, - ]; - } - else { - if ("name" in schema) { - functionName = schema.name; - } - tools = [ - { - type: "function", - function: { - name: functionName, - description, - parameters: schema, - }, - }, - ]; - } - const llm = this.bindTools(tools); - const outputParser = base_RunnableLambda.from((input) => { - if (!input.tool_calls || input.tool_calls.length === 0) { - throw new Error("No tool calls found in the response."); - } - const toolCall = input.tool_calls.find((tc) => tc.name === functionName); - if (!toolCall) { - throw new Error(`No tool call found with name ${functionName}.`); - } - return toolCall.args; - }); - if (!includeRaw) { - return llm.pipe(outputParser).withConfig({ - runName: "StructuredOutput", - }); - } - const parserAssign = RunnablePassthrough.assign({ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - parsed: (input, config) => outputParser.invoke(input.raw, config), - }); - const parserNone = RunnablePassthrough.assign({ - parsed: () => null, - }); - const parsedWithFallback = parserAssign.withFallbacks({ - fallbacks: [parserNone], - }); - return RunnableSequence.from([ - { - raw: llm, - }, - parsedWithFallback, - ]).withConfig({ - runName: "StructuredOutputRunnable", - }); - } -} -/** - * An abstract class that extends BaseChatModel and provides a simple - * implementation of _generate. - */ -class SimpleChatModel extends (/* unused pure expression or super */ null && (BaseChatModel)) { - async _generate(messages, options, runManager) { - const text = await this._call(messages, options, runManager); - const message = new AIMessage(text); - if (typeof message.content !== "string") { - throw new Error("Cannot generate with a simple chat model when output is not a string."); - } - return { - generations: [ - { - text: message.content, - message, - }, - ], - }; + static global() { + return new InMemoryCache(GLOBAL_MAP); } } -;// CONCATENATED MODULE: ./node_modules/@langchain/core/language_models/chat_models.js - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/outputs.js - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/utils/async_caller.js +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/prompt_values.js -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/router.js /** - * A runnable that routes to a set of runnables based on Input['key']. - * Returns the output of the selected runnable. - * @example - * ```typescript - * import { RouterRunnable, RunnableLambda } from "@langchain/core/runnables"; - * - * const router = new RouterRunnable({ - * runnables: { - * toUpperCase: RunnableLambda.from((text: string) => text.toUpperCase()), - * reverseText: RunnableLambda.from((text: string) => - * text.split("").reverse().join("") - * ), - * }, - * }); - * - * // Invoke the 'reverseText' runnable - * const result1 = router.invoke({ key: "reverseText", input: "Hello World" }); - * - * // "dlroW olleH" - * - * // Invoke the 'toUpperCase' runnable - * const result2 = router.invoke({ key: "toUpperCase", input: "Hello World" }); - * - * // "HELLO WORLD" - * ``` + * Base PromptValue class. All prompt values should extend this class. + */ +class BasePromptValue extends Serializable { +} +/** + * Represents a prompt value as a string. It extends the BasePromptValue + * class and overrides the toString and toChatMessages methods. + */ +class StringPromptValue extends BasePromptValue { + static lc_name() { + return "StringPromptValue"; + } + constructor(value) { + super({ value }); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain_core", "prompt_values"] + }); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "value", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.value = value; + } + toString() { + return this.value; + } + toChatMessages() { + return [new human_HumanMessage(this.value)]; + } +} +/** + * Class that represents a chat prompt value. It extends the + * BasePromptValue and includes an array of BaseMessage instances. */ -class RouterRunnable extends Runnable { +class ChatPromptValue extends BasePromptValue { static lc_name() { - return "RouterRunnable"; + return "ChatPromptValue"; } constructor(fields) { + if (Array.isArray(fields)) { + // eslint-disable-next-line no-param-reassign + fields = { messages: fields }; + } super(fields); Object.defineProperty(this, "lc_namespace", { enumerable: true, configurable: true, writable: true, - value: ["langchain_core", "runnables"] + value: ["langchain_core", "prompt_values"] }); Object.defineProperty(this, "lc_serializable", { enumerable: true, @@ -103146,104 +109181,40 @@ class RouterRunnable extends Runnable { writable: true, value: true }); - Object.defineProperty(this, "runnables", { + Object.defineProperty(this, "messages", { enumerable: true, configurable: true, writable: true, value: void 0 }); - this.runnables = fields.runnables; - } - async invoke(input, options) { - const { key, input: actualInput } = input; - const runnable = this.runnables[key]; - if (runnable === undefined) { - throw new Error(`No runnable associated with key "${key}".`); - } - return runnable.invoke(actualInput, ensureConfig(options)); + this.messages = fields.messages; } - async batch(inputs, options, batchOptions) { - const keys = inputs.map((input) => input.key); - const actualInputs = inputs.map((input) => input.input); - const missingKey = keys.find((key) => this.runnables[key] === undefined); - if (missingKey !== undefined) { - throw new Error(`One or more keys do not have a corresponding runnable.`); - } - const runnables = keys.map((key) => this.runnables[key]); - const optionsList = this._getOptionsList(options ?? {}, inputs.length); - const maxConcurrency = optionsList[0]?.maxConcurrency ?? batchOptions?.maxConcurrency; - const batchSize = maxConcurrency && maxConcurrency > 0 ? maxConcurrency : inputs.length; - const batchResults = []; - for (let i = 0; i < actualInputs.length; i += batchSize) { - const batchPromises = actualInputs - .slice(i, i + batchSize) - .map((actualInput, i) => runnables[i].invoke(actualInput, optionsList[i])); - const batchResult = await Promise.all(batchPromises); - batchResults.push(batchResult); - } - return batchResults.flat(); + toString() { + return getBufferString(this.messages); } - async stream(input, options) { - const { key, input: actualInput } = input; - const runnable = this.runnables[key]; - if (runnable === undefined) { - throw new Error(`No runnable associated with key "${key}".`); - } - return runnable.stream(actualInput, options); + toChatMessages() { + return this.messages; } } - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/branch.js - - - /** - * Class that represents a runnable branch. The RunnableBranch is - * initialized with an array of branches and a default branch. When invoked, - * it evaluates the condition of each branch in order and executes the - * corresponding branch if the condition is true. If none of the conditions - * are true, it executes the default branch. - * @example - * ```typescript - * const branch = RunnableBranch.from([ - * [ - * (x: { topic: string; question: string }) => - * x.topic.toLowerCase().includes("anthropic"), - * anthropicChain, - * ], - * [ - * (x: { topic: string; question: string }) => - * x.topic.toLowerCase().includes("langchain"), - * langChainChain, - * ], - * generalChain, - * ]); - * - * const fullChain = RunnableSequence.from([ - * { - * topic: classificationChain, - * question: (input: { question: string }) => input.question, - * }, - * branch, - * ]); - * - * const result = await fullChain.invoke({ - * question: "how do I use LangChain?", - * }); - * ``` + * Class that represents an image prompt value. It extends the + * BasePromptValue and includes an ImageURL instance. */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -class RunnableBranch extends Runnable { +class ImagePromptValue extends BasePromptValue { static lc_name() { - return "RunnableBranch"; + return "ImagePromptValue"; } constructor(fields) { + if (!("imageUrl" in fields)) { + // eslint-disable-next-line no-param-reassign + fields = { imageUrl: fields }; + } super(fields); Object.defineProperty(this, "lc_namespace", { enumerable: true, configurable: true, writable: true, - value: ["langchain_core", "runnables"] + value: ["langchain_core", "prompt_values"] }); Object.defineProperty(this, "lc_serializable", { enumerable: true, @@ -103251,1694 +109222,2059 @@ class RunnableBranch extends Runnable { writable: true, value: true }); - Object.defineProperty(this, "default", { + Object.defineProperty(this, "imageUrl", { enumerable: true, configurable: true, writable: true, value: void 0 }); - Object.defineProperty(this, "branches", { + /** @ignore */ + Object.defineProperty(this, "value", { enumerable: true, configurable: true, writable: true, value: void 0 }); - this.branches = fields.branches; - this.default = fields.default; + this.imageUrl = fields.imageUrl; } - /** - * Convenience method for instantiating a RunnableBranch from - * RunnableLikes (objects, functions, or Runnables). - * - * Each item in the input except for the last one should be a - * tuple with two items. The first is a "condition" RunnableLike that - * returns "true" if the second RunnableLike in the tuple should run. - * - * The final item in the input should be a RunnableLike that acts as a - * default branch if no other branches match. - * - * @example - * ```ts - * import { RunnableBranch } from "@langchain/core/runnables"; - * - * const branch = RunnableBranch.from([ - * [(x: number) => x > 0, (x: number) => x + 1], - * [(x: number) => x < 0, (x: number) => x - 1], - * (x: number) => x - * ]); - * ``` - * @param branches An array where the every item except the last is a tuple of [condition, runnable] - * pairs. The last item is a default runnable which is invoked if no other condition matches. - * @returns A new RunnableBranch. - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - static from(branches) { - if (branches.length < 1) { - throw new Error("RunnableBranch requires at least one branch"); - } - const branchLikes = branches.slice(0, -1); - const coercedBranches = branchLikes.map(([condition, runnable]) => [ - _coerceToRunnable(condition), - _coerceToRunnable(runnable), - ]); - const defaultBranch = _coerceToRunnable(branches[branches.length - 1]); - return new this({ - branches: coercedBranches, - default: defaultBranch, - }); + toString() { + return this.imageUrl.url; } - async _invoke(input, config, runManager) { - let result; - for (let i = 0; i < this.branches.length; i += 1) { - const [condition, branchRunnable] = this.branches[i]; - const conditionValue = await condition.invoke(input, patchConfig(config, { - callbacks: runManager?.getChild(`condition:${i + 1}`), - })); - if (conditionValue) { - result = await branchRunnable.invoke(input, patchConfig(config, { - callbacks: runManager?.getChild(`branch:${i + 1}`), - })); - break; - } - } - if (!result) { - result = await this.default.invoke(input, patchConfig(config, { - callbacks: runManager?.getChild("branch:default"), - })); - } - return result; + toChatMessages() { + return [ + new human_HumanMessage({ + content: [ + { + type: "image_url", + image_url: { + detail: this.imageUrl.detail, + url: this.imageUrl.url, + }, + }, + ], + }), + ]; } - async invoke(input, config = {}) { - return this._callWithConfig(this._invoke, input, config); +} + +// EXTERNAL MODULE: ./node_modules/base64-js/index.js +var base64_js = __nccwpck_require__(8793); +;// CONCATENATED MODULE: ./node_modules/js-tiktoken/dist/chunk-YVJR5WRT.js + + +var __defProp = Object.defineProperty; +var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __publicField = (obj, key, value) => { + __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); + return value; +}; + +// src/utils.ts +function never(_) { +} +function bytePairMerge(piece, ranks) { + let parts = Array.from( + { length: piece.length }, + (_, i) => ({ start: i, end: i + 1 }) + ); + while (parts.length > 1) { + let minRank = null; + for (let i = 0; i < parts.length - 1; i++) { + const slice = piece.slice(parts[i].start, parts[i + 1].end); + const rank = ranks.get(slice.join(",")); + if (rank == null) + continue; + if (minRank == null || rank < minRank[0]) { + minRank = [rank, i]; + } } - async *_streamIterator(input, config) { - const callbackManager_ = await getCallbackManagerForConfig(config); - const runManager = await callbackManager_?.handleChainStart(this.toJSON(), base_coerceToDict(input, "input"), config?.runId, undefined, undefined, undefined, config?.runName); - let finalOutput; - let finalOutputSupported = true; - let stream; - try { - for (let i = 0; i < this.branches.length; i += 1) { - const [condition, branchRunnable] = this.branches[i]; - const conditionValue = await condition.invoke(input, patchConfig(config, { - callbacks: runManager?.getChild(`condition:${i + 1}`), - })); - if (conditionValue) { - stream = await branchRunnable.stream(input, patchConfig(config, { - callbacks: runManager?.getChild(`branch:${i + 1}`), - })); - for await (const chunk of stream) { - yield chunk; - if (finalOutputSupported) { - if (finalOutput === undefined) { - finalOutput = chunk; - } - else { - try { - finalOutput = concat(finalOutput, chunk); - } - catch (e) { - finalOutput = undefined; - finalOutputSupported = false; - } - } - } - } - break; - } - } - if (stream === undefined) { - stream = await this.default.stream(input, patchConfig(config, { - callbacks: runManager?.getChild("branch:default"), - })); - for await (const chunk of stream) { - yield chunk; - if (finalOutputSupported) { - if (finalOutput === undefined) { - finalOutput = chunk; - } - else { - try { - finalOutput = concat(finalOutput, chunk); - } - catch (e) { - finalOutput = undefined; - finalOutputSupported = false; - } - } - } - } - } + if (minRank != null) { + const i = minRank[1]; + parts[i] = { start: parts[i].start, end: parts[i + 1].end }; + parts.splice(i + 1, 1); + } else { + break; + } + } + return parts; +} +function bytePairEncode(piece, ranks) { + if (piece.length === 1) + return [ranks.get(piece.join(","))]; + return bytePairMerge(piece, ranks).map((p) => ranks.get(piece.slice(p.start, p.end).join(","))).filter((x) => x != null); +} +function chunk_YVJR5WRT_escapeRegex(str) { + return str.replace(/[\\^$*+?.()|[\]{}]/g, "\\$&"); +} +var _Tiktoken = class { + /** @internal */ + specialTokens; + /** @internal */ + inverseSpecialTokens; + /** @internal */ + patStr; + /** @internal */ + textEncoder = new TextEncoder(); + /** @internal */ + textDecoder = new TextDecoder("utf-8"); + /** @internal */ + rankMap = /* @__PURE__ */ new Map(); + /** @internal */ + textMap = /* @__PURE__ */ new Map(); + constructor(ranks, extendedSpecialTokens) { + this.patStr = ranks.pat_str; + const uncompressed = ranks.bpe_ranks.split("\n").filter(Boolean).reduce((memo, x) => { + const [_, offsetStr, ...tokens] = x.split(" "); + const offset = Number.parseInt(offsetStr, 10); + tokens.forEach((token, i) => memo[token] = offset + i); + return memo; + }, {}); + for (const [token, rank] of Object.entries(uncompressed)) { + const bytes = base64_js.toByteArray(token); + this.rankMap.set(bytes.join(","), rank); + this.textMap.set(rank, bytes); + } + this.specialTokens = { ...ranks.special_tokens, ...extendedSpecialTokens }; + this.inverseSpecialTokens = Object.entries(this.specialTokens).reduce((memo, [text, rank]) => { + memo[rank] = this.textEncoder.encode(text); + return memo; + }, {}); + } + encode(text, allowedSpecial = [], disallowedSpecial = "all") { + const regexes = new RegExp(this.patStr, "ug"); + const specialRegex = _Tiktoken.specialTokenRegex( + Object.keys(this.specialTokens) + ); + const ret = []; + const allowedSpecialSet = new Set( + allowedSpecial === "all" ? Object.keys(this.specialTokens) : allowedSpecial + ); + const disallowedSpecialSet = new Set( + disallowedSpecial === "all" ? Object.keys(this.specialTokens).filter( + (x) => !allowedSpecialSet.has(x) + ) : disallowedSpecial + ); + if (disallowedSpecialSet.size > 0) { + const disallowedSpecialRegex = _Tiktoken.specialTokenRegex([ + ...disallowedSpecialSet + ]); + const specialMatch = text.match(disallowedSpecialRegex); + if (specialMatch != null) { + throw new Error( + `The text contains a special token that is not allowed: ${specialMatch[0]}` + ); + } + } + let start = 0; + while (true) { + let nextSpecial = null; + let startFind = start; + while (true) { + specialRegex.lastIndex = startFind; + nextSpecial = specialRegex.exec(text); + if (nextSpecial == null || allowedSpecialSet.has(nextSpecial[0])) + break; + startFind = nextSpecial.index + 1; + } + const end = nextSpecial?.index ?? text.length; + for (const match of text.substring(start, end).matchAll(regexes)) { + const piece = this.textEncoder.encode(match[0]); + const token2 = this.rankMap.get(piece.join(",")); + if (token2 != null) { + ret.push(token2); + continue; } - catch (e) { - await runManager?.handleChainError(e); + ret.push(...bytePairEncode(piece, this.rankMap)); + } + if (nextSpecial == null) + break; + let token = this.specialTokens[nextSpecial[0]]; + ret.push(token); + start = nextSpecial.index + nextSpecial[0].length; + } + return ret; + } + decode(tokens) { + const res = []; + let length = 0; + for (let i2 = 0; i2 < tokens.length; ++i2) { + const token = tokens[i2]; + const bytes = this.textMap.get(token) ?? this.inverseSpecialTokens[token]; + if (bytes != null) { + res.push(bytes); + length += bytes.length; + } + } + const mergedArray = new Uint8Array(length); + let i = 0; + for (const bytes of res) { + mergedArray.set(bytes, i); + i += bytes.length; + } + return this.textDecoder.decode(mergedArray); + } +}; +var Tiktoken = _Tiktoken; +__publicField(Tiktoken, "specialTokenRegex", (tokens) => { + return new RegExp(tokens.map((i) => chunk_YVJR5WRT_escapeRegex(i)).join("|"), "g"); +}); +function getEncodingNameForModel(model) { + switch (model) { + case "gpt2": { + return "gpt2"; + } + case "code-cushman-001": + case "code-cushman-002": + case "code-davinci-001": + case "code-davinci-002": + case "cushman-codex": + case "davinci-codex": + case "davinci-002": + case "text-davinci-002": + case "text-davinci-003": { + return "p50k_base"; + } + case "code-davinci-edit-001": + case "text-davinci-edit-001": { + return "p50k_edit"; + } + case "ada": + case "babbage": + case "babbage-002": + case "code-search-ada-code-001": + case "code-search-babbage-code-001": + case "curie": + case "davinci": + case "text-ada-001": + case "text-babbage-001": + case "text-curie-001": + case "text-davinci-001": + case "text-search-ada-doc-001": + case "text-search-babbage-doc-001": + case "text-search-curie-doc-001": + case "text-search-davinci-doc-001": + case "text-similarity-ada-001": + case "text-similarity-babbage-001": + case "text-similarity-curie-001": + case "text-similarity-davinci-001": { + return "r50k_base"; + } + case "gpt-3.5-turbo-instruct-0914": + case "gpt-3.5-turbo-instruct": + case "gpt-3.5-turbo-16k-0613": + case "gpt-3.5-turbo-16k": + case "gpt-3.5-turbo-0613": + case "gpt-3.5-turbo-0301": + case "gpt-3.5-turbo": + case "gpt-4-32k-0613": + case "gpt-4-32k-0314": + case "gpt-4-32k": + case "gpt-4-0613": + case "gpt-4-0314": + case "gpt-4": + case "gpt-3.5-turbo-1106": + case "gpt-35-turbo": + case "gpt-4-1106-preview": + case "gpt-4-vision-preview": + case "gpt-3.5-turbo-0125": + case "gpt-4-turbo": + case "gpt-4-turbo-2024-04-09": + case "gpt-4-turbo-preview": + case "gpt-4-0125-preview": + case "text-embedding-ada-002": + case "text-embedding-3-small": + case "text-embedding-3-large": { + return "cl100k_base"; + } + case "gpt-4o": + case "gpt-4o-2024-05-13": + case "gpt-4o-2024-08-06": + case "gpt-4o-mini-2024-07-18": + case "gpt-4o-mini": + case "o1-mini": + case "o1-preview": + case "o1-preview-2024-09-12": + case "o1-mini-2024-09-12": + case "chatgpt-4o-latest": + case "gpt-4o-realtime": + case "gpt-4o-realtime-preview-2024-10-01": { + return "o200k_base"; + } + default: + throw new Error("Unknown model"); + } +} + + + +;// CONCATENATED MODULE: ./node_modules/js-tiktoken/dist/lite.js + + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/tiktoken.js + + +const cache = {}; +const caller = /* #__PURE__ */ new async_caller_AsyncCaller({}); +async function getEncoding(encoding) { + if (!(encoding in cache)) { + cache[encoding] = caller + .fetch(`https://tiktoken.pages.dev/js/${encoding}.json`) + .then((res) => res.json()) + .then((data) => new Tiktoken(data)) + .catch((e) => { + delete cache[encoding]; throw e; - } - await runManager?.handleChainEnd(finalOutput ?? {}); + }); } + return await cache[encoding]; +} +async function tiktoken_encodingForModel(model) { + return getEncoding(getEncodingNameForModel(model)); } -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/history.js +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/language_models/base.js + + + +// https://www.npmjs.com/package/js-tiktoken +const getModelNameForTiktoken = (modelName) => { + if (modelName.startsWith("gpt-3.5-turbo-16k")) { + return "gpt-3.5-turbo-16k"; + } + if (modelName.startsWith("gpt-3.5-turbo-")) { + return "gpt-3.5-turbo"; + } + if (modelName.startsWith("gpt-4-32k")) { + return "gpt-4-32k"; + } + if (modelName.startsWith("gpt-4-")) { + return "gpt-4"; + } + if (modelName.startsWith("gpt-4o")) { + return "gpt-4o"; + } + return modelName; +}; +const getEmbeddingContextSize = (modelName) => { + switch (modelName) { + case "text-embedding-ada-002": + return 8191; + default: + return 2046; + } +}; +const getModelContextSize = (modelName) => { + switch (getModelNameForTiktoken(modelName)) { + case "gpt-3.5-turbo-16k": + return 16384; + case "gpt-3.5-turbo": + return 4096; + case "gpt-4-32k": + return 32768; + case "gpt-4": + return 8192; + case "text-davinci-003": + return 4097; + case "text-curie-001": + return 2048; + case "text-babbage-001": + return 2048; + case "text-ada-001": + return 2048; + case "code-davinci-002": + return 8000; + case "code-cushman-001": + return 2048; + default: + return 4097; + } +}; /** - * Wraps a LCEL chain and manages history. It appends input messages - * and chain outputs as history, and adds the current history messages to - * the chain input. - * @example - * ```typescript - * // yarn add @langchain/anthropic @langchain/community @upstash/redis - * - * import { - * ChatPromptTemplate, - * MessagesPlaceholder, - * } from "@langchain/core/prompts"; - * import { ChatAnthropic } from "@langchain/anthropic"; - * import { UpstashRedisChatMessageHistory } from "@langchain/community/stores/message/upstash_redis"; - * // For demos, you can also use an in-memory store: - * // import { ChatMessageHistory } from "langchain/stores/message/in_memory"; - * - * const prompt = ChatPromptTemplate.fromMessages([ - * ["system", "You're an assistant who's good at {ability}"], - * new MessagesPlaceholder("history"), - * ["human", "{question}"], - * ]); - * - * const chain = prompt.pipe(new ChatAnthropic({})); - * - * const chainWithHistory = new RunnableWithMessageHistory({ - * runnable: chain, - * getMessageHistory: (sessionId) => - * new UpstashRedisChatMessageHistory({ - * sessionId, - * config: { - * url: process.env.UPSTASH_REDIS_REST_URL!, - * token: process.env.UPSTASH_REDIS_REST_TOKEN!, - * }, - * }), - * inputMessagesKey: "question", - * historyMessagesKey: "history", - * }); - * - * const result = await chainWithHistory.invoke( - * { - * ability: "math", - * question: "What does cosine mean?", - * }, - * { - * configurable: { - * sessionId: "some_string_identifying_a_user", - * }, - * } - * ); - * - * const result2 = await chainWithHistory.invoke( - * { - * ability: "math", - * question: "What's its inverse?", - * }, - * { - * configurable: { - * sessionId: "some_string_identifying_a_user", - * }, - * } - * ); - * ``` + * Whether or not the input matches the OpenAI tool definition. + * @param {unknown} tool The input to check. + * @returns {boolean} Whether the input is an OpenAI tool definition. */ -class RunnableWithMessageHistory extends RunnableBinding { - constructor(fields) { - let historyChain = base_RunnableLambda.from((input, options) => this._enterHistory(input, options ?? {})).withConfig({ runName: "loadHistory" }); - const messagesKey = fields.historyMessagesKey ?? fields.inputMessagesKey; - if (messagesKey) { - historyChain = RunnablePassthrough.assign({ - [messagesKey]: historyChain, - }).withConfig({ runName: "insertHistory" }); - } - const bound = historyChain - .pipe(fields.runnable.withListeners({ - onEnd: (run, config) => this._exitHistory(run, config ?? {}), - })) - .withConfig({ runName: "RunnableWithMessageHistory" }); - const config = fields.config ?? {}; - super({ - ...fields, - config, - bound, +function isOpenAITool(tool) { + if (typeof tool !== "object" || !tool) + return false; + if ("type" in tool && + tool.type === "function" && + "function" in tool && + typeof tool.function === "object" && + tool.function && + "name" in tool.function && + "parameters" in tool.function) { + return true; + } + return false; +} +const calculateMaxTokens = async ({ prompt, modelName, }) => { + let numTokens; + try { + numTokens = (await encodingForModel(getModelNameForTiktoken(modelName))).encode(prompt).length; + } + catch (error) { + console.warn("Failed to calculate number of tokens, falling back to approximate count"); + // fallback to approximate calculation if tiktoken is not available + // each token is ~4 characters: https://help.openai.com/en/articles/4936856-what-are-tokens-and-how-to-count-them# + numTokens = Math.ceil(prompt.length / 4); + } + const maxTokens = getModelContextSize(modelName); + return maxTokens - numTokens; +}; +const getVerbosity = () => false; +/** + * Base class for language models, chains, tools. + */ +class BaseLangChain extends Runnable { + get lc_attributes() { + return { + callbacks: undefined, + verbose: undefined, + }; + } + constructor(params) { + super(params); + /** + * Whether to print out response text. + */ + Object.defineProperty(this, "verbose", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 }); - Object.defineProperty(this, "runnable", { + Object.defineProperty(this, "callbacks", { enumerable: true, configurable: true, writable: true, value: void 0 }); - Object.defineProperty(this, "inputMessagesKey", { + Object.defineProperty(this, "tags", { enumerable: true, configurable: true, writable: true, value: void 0 }); - Object.defineProperty(this, "outputMessagesKey", { + Object.defineProperty(this, "metadata", { enumerable: true, configurable: true, writable: true, value: void 0 }); - Object.defineProperty(this, "historyMessagesKey", { + this.verbose = params.verbose ?? getVerbosity(); + this.callbacks = params.callbacks; + this.tags = params.tags ?? []; + this.metadata = params.metadata ?? {}; + } +} +/** + * Base class for language models. + */ +class BaseLanguageModel extends BaseLangChain { + /** + * Keys that the language model accepts as call options. + */ + get callKeys() { + return ["stop", "timeout", "signal", "tags", "metadata", "callbacks"]; + } + constructor({ callbacks, callbackManager, ...params }) { + const { cache, ...rest } = params; + super({ + callbacks: callbacks ?? callbackManager, + ...rest, + }); + /** + * The async caller should be used by subclasses to make any async calls, + * which will thus benefit from the concurrency and retry logic. + */ + Object.defineProperty(this, "caller", { enumerable: true, configurable: true, writable: true, value: void 0 }); - Object.defineProperty(this, "getMessageHistory", { + Object.defineProperty(this, "cache", { enumerable: true, configurable: true, writable: true, value: void 0 }); - this.runnable = fields.runnable; - this.getMessageHistory = fields.getMessageHistory; - this.inputMessagesKey = fields.inputMessagesKey; - this.outputMessagesKey = fields.outputMessagesKey; - this.historyMessagesKey = fields.historyMessagesKey; - } - _getInputMessages( - // eslint-disable-next-line @typescript-eslint/no-explicit-any - inputValue) { - let parsedInputValue; - if (typeof inputValue === "object" && - !Array.isArray(inputValue) && - !isBaseMessage(inputValue)) { - let key; - if (this.inputMessagesKey) { - key = this.inputMessagesKey; - } - else if (Object.keys(inputValue).length === 1) { - key = Object.keys(inputValue)[0]; - } - else { - key = "input"; - } - if (Array.isArray(inputValue[key]) && Array.isArray(inputValue[key][0])) { - parsedInputValue = inputValue[key][0]; - } - else { - parsedInputValue = inputValue[key]; - } - } - else { - parsedInputValue = inputValue; + Object.defineProperty(this, "_encoding", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + if (typeof cache === "object") { + this.cache = cache; } - if (typeof parsedInputValue === "string") { - return [new human_HumanMessage(parsedInputValue)]; + else if (cache) { + this.cache = InMemoryCache.global(); } - else if (Array.isArray(parsedInputValue)) { - return parsedInputValue; + else { + this.cache = undefined; } - else if (isBaseMessage(parsedInputValue)) { - return [parsedInputValue]; + this.caller = new async_caller_AsyncCaller(params ?? {}); + } + /** + * Get the number of tokens in the content. + * @param content The content to get the number of tokens for. + * @returns The number of tokens in the content. + */ + async getNumTokens(content) { + // Extract text content from MessageContent + let textContent; + if (typeof content === "string") { + textContent = content; } else { - throw new Error(`Expected a string, BaseMessage, or array of BaseMessages.\nGot ${JSON.stringify(parsedInputValue, null, 2)}`); + /** + * Content is an array of MessageContentComplex + * + * ToDo(@christian-bromann): This is a temporary fix to get the number of tokens for the content. + * We need to find a better way to do this. + * @see https://github.com/langchain-ai/langchainjs/pull/8341#pullrequestreview-2933713116 + */ + textContent = content + .map((item) => { + if (typeof item === "string") + return item; + if (item.type === "text" && "text" in item) + return item.text; + return ""; + }) + .join(""); } - } - _getOutputMessages( - // eslint-disable-next-line @typescript-eslint/no-explicit-any - outputValue) { - let parsedOutputValue; - if (!Array.isArray(outputValue) && - !isBaseMessage(outputValue) && - typeof outputValue !== "string") { - let key; - if (this.outputMessagesKey !== undefined) { - key = this.outputMessagesKey; - } - else if (Object.keys(outputValue).length === 1) { - key = Object.keys(outputValue)[0]; + // fallback to approximate calculation if tiktoken is not available + let numTokens = Math.ceil(textContent.length / 4); + if (!this._encoding) { + try { + this._encoding = await tiktoken_encodingForModel("modelName" in this + ? getModelNameForTiktoken(this.modelName) + : "gpt2"); } - else { - key = "output"; + catch (error) { + console.warn("Failed to calculate number of tokens, falling back to approximate count", error); } - // If you are wrapping a chat model directly - // The output is actually this weird generations object - if (outputValue.generations !== undefined) { - parsedOutputValue = outputValue.generations[0][0].message; + } + if (this._encoding) { + try { + numTokens = this._encoding.encode(textContent).length; } - else { - parsedOutputValue = outputValue[key]; + catch (error) { + console.warn("Failed to calculate number of tokens, falling back to approximate count", error); } } - else { - parsedOutputValue = outputValue; - } - if (typeof parsedOutputValue === "string") { - return [new ai_AIMessage(parsedOutputValue)]; - } - else if (Array.isArray(parsedOutputValue)) { - return parsedOutputValue; - } - else if (isBaseMessage(parsedOutputValue)) { - return [parsedOutputValue]; - } - else { - throw new Error(`Expected a string, BaseMessage, or array of BaseMessages. Received: ${JSON.stringify(parsedOutputValue, null, 2)}`); - } + return numTokens; } - async _enterHistory( - // eslint-disable-next-line @typescript-eslint/no-explicit-any - input, kwargs) { - const history = kwargs?.configurable?.messageHistory; - const messages = await history.getMessages(); - if (this.historyMessagesKey === undefined) { - return messages.concat(this._getInputMessages(input)); + static _convertInputToPromptValue(input) { + if (typeof input === "string") { + return new StringPromptValue(input); } - return messages; - } - async _exitHistory(run, config) { - const history = config.configurable?.messageHistory; - // Get input messages - let inputs; - // Chat model inputs are nested arrays - if (Array.isArray(run.inputs) && Array.isArray(run.inputs[0])) { - inputs = run.inputs[0]; + else if (Array.isArray(input)) { + return new ChatPromptValue(input.map(coerceMessageLikeToMessage)); } else { - inputs = run.inputs; - } - let inputMessages = this._getInputMessages(inputs); - // If historic messages were prepended to the input messages, remove them to - // avoid adding duplicate messages to history. - if (this.historyMessagesKey === undefined) { - const existingMessages = await history.getMessages(); - inputMessages = inputMessages.slice(existingMessages.length); - } - // Get output messages - const outputValue = run.outputs; - if (!outputValue) { - throw new Error(`Output values from 'Run' undefined. Run: ${JSON.stringify(run, null, 2)}`); - } - const outputMessages = this._getOutputMessages(outputValue); - await history.addMessages([...inputMessages, ...outputMessages]); - } - async _mergeConfig(...configs) { - const config = await super._mergeConfig(...configs); - // Extract sessionId - if (!config.configurable || !config.configurable.sessionId) { - const exampleInput = { - [this.inputMessagesKey ?? "input"]: "foo", - }; - const exampleConfig = { configurable: { sessionId: "123" } }; - throw new Error(`sessionId is required. Pass it in as part of the config argument to .invoke() or .stream()\n` + - `eg. chain.invoke(${JSON.stringify(exampleInput)}, ${JSON.stringify(exampleConfig)})`); + return input; } - // attach messageHistory - const { sessionId } = config.configurable; - config.configurable.messageHistory = await this.getMessageHistory(sessionId); - return config; } -} - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/index.js - - - - - - - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/output_parsers/base.js - - -/** - * Abstract base class for parsing the output of a Large Language Model - * (LLM) call. It provides methods for parsing the result of an LLM call - * and invoking the parser with a given input. - */ -class BaseLLMOutputParser extends Runnable { /** - * Parses the result of an LLM call with a given prompt. By default, it - * simply calls `parseResult`. - * @param generations The generations from an LLM call. - * @param _prompt The prompt used in the LLM call. - * @param callbacks Optional callbacks. - * @returns A promise of the parsed output. + * Get the identifying parameters of the LLM. */ - parseResultWithPrompt(generations, _prompt, callbacks) { - return this.parseResult(generations, callbacks); - } - _baseMessageToString(message) { - return typeof message.content === "string" - ? message.content - : this._baseMessageContentToString(message.content); - } - _baseMessageContentToString(content) { - return JSON.stringify(content); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + _identifyingParams() { + return {}; } /** - * Calls the parser with a given input and optional configuration options. - * If the input is a string, it creates a generation with the input as - * text and calls `parseResult`. If the input is a `BaseMessage`, it - * creates a generation with the input as a message and the content of the - * input as text, and then calls `parseResult`. - * @param input The input to the parser, which can be a string or a `BaseMessage`. - * @param options Optional configuration options. - * @returns A promise of the parsed output. + * Create a unique cache key for a specific call to a specific language model. + * @param callOptions Call options for the model + * @returns A unique cache key. */ - async invoke(input, options) { - if (typeof input === "string") { - return this._callWithConfig(async (input, options) => this.parseResult([{ text: input }], options?.callbacks), input, { ...options, runType: "parser" }); - } - else { - return this._callWithConfig(async (input, options) => this.parseResult([ - { - message: input, - text: this._baseMessageToString(input), - }, - ], options?.callbacks), input, { ...options, runType: "parser" }); - } - } -} -/** - * Class to parse the output of an LLM call. - */ -class BaseOutputParser extends BaseLLMOutputParser { - parseResult(generations, callbacks) { - return this.parse(generations[0].text, callbacks); - } - async parseWithPrompt(text, _prompt, callbacks) { - return this.parse(text, callbacks); + _getSerializedCacheKeyParametersForCall( + // TODO: Fix when we remove the RunnableLambda backwards compatibility shim. + { config, ...callOptions }) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const params = { + ...this._identifyingParams(), + ...callOptions, + _type: this._llmType(), + _model: this._modelType(), + }; + const filteredEntries = Object.entries(params).filter(([_, value]) => value !== undefined); + const serializedEntries = filteredEntries + .map(([key, value]) => `${key}:${JSON.stringify(value)}`) + .sort() + .join(","); + return serializedEntries; } /** - * Return the string type key uniquely identifying this class of parser + * @deprecated + * Return a json-like object representing this LLM. */ - _type() { - throw new Error("_type not implemented"); + serialize() { + return { + ...this._identifyingParams(), + _type: this._llmType(), + _model: this._modelType(), + }; + } + /** + * @deprecated + * Load an LLM from a json-like object describing it. + */ + static async deserialize(_data) { + throw new Error("Use .toJSON() instead"); } } + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/passthrough.js + + + /** - * Exception that output parsers should raise to signify a parsing error. + * A runnable to passthrough inputs unchanged or with additional keys. * - * This exists to differentiate parsing errors from other code or execution errors - * that also may arise inside the output parser. OutputParserExceptions will be - * available to catch and handle in ways to fix the parsing error, while other - * errors will be raised. + * This runnable behaves almost like the identity function, except that it + * can be configured to add additional keys to the output, if the input is + * an object. * - * @param message - The error that's being re-raised or an error message. - * @param llmOutput - String model output which is error-ing. - * @param observation - String explanation of error which can be passed to a - * model to try and remediate the issue. - * @param sendToLLM - Whether to send the observation and llm_output back to an Agent - * after an OutputParserException has been raised. This gives the underlying - * model driving the agent the context that the previous output was improperly - * structured, in the hopes that it will update the output to the correct - * format. + * The example below demonstrates how to use `RunnablePassthrough to + * passthrough the input from the `.invoke()` + * + * @example + * ```typescript + * const chain = RunnableSequence.from([ + * { + * question: new RunnablePassthrough(), + * context: async () => loadContextFromStore(), + * }, + * prompt, + * llm, + * outputParser, + * ]); + * const response = await chain.invoke( + * "I can pass a single string instead of an object since I'm using `RunnablePassthrough`." + * ); + * ``` */ -class OutputParserException extends Error { - constructor(message, llmOutput, observation, sendToLLM = false) { - super(message); - Object.defineProperty(this, "llmOutput", { +// eslint-disable-next-line @typescript-eslint/no-explicit-any +class RunnablePassthrough extends Runnable { + static lc_name() { + return "RunnablePassthrough"; + } + constructor(fields) { + super(fields); + Object.defineProperty(this, "lc_namespace", { enumerable: true, configurable: true, writable: true, - value: void 0 + value: ["langchain_core", "runnables"] }); - Object.defineProperty(this, "observation", { + Object.defineProperty(this, "lc_serializable", { enumerable: true, configurable: true, writable: true, - value: void 0 + value: true }); - Object.defineProperty(this, "sendToLLM", { + Object.defineProperty(this, "func", { enumerable: true, configurable: true, writable: true, value: void 0 }); - this.llmOutput = llmOutput; - this.observation = observation; - this.sendToLLM = sendToLLM; - if (sendToLLM) { - if (observation === undefined || llmOutput === undefined) { - throw new Error("Arguments 'observation' & 'llmOutput' are required if 'sendToLlm' is true"); - } - } - addLangChainErrorFields(this, "OUTPUT_PARSING_FAILURE"); - } -} - -;// CONCATENATED MODULE: ./node_modules/@cfworker/json-schema/dist/esm/deep-compare-strict.js -function deep_compare_strict_deepCompareStrict(a, b) { - const typeofa = typeof a; - if (typeofa !== typeof b) { - return false; - } - if (Array.isArray(a)) { - if (!Array.isArray(b)) { - return false; - } - const length = a.length; - if (length !== b.length) { - return false; - } - for (let i = 0; i < length; i++) { - if (!deep_compare_strict_deepCompareStrict(a[i], b[i])) { - return false; - } + if (fields) { + this.func = fields.func; } - return true; } - if (typeofa === 'object') { - if (!a || !b) { - return a === b; - } - const aKeys = Object.keys(a); - const bKeys = Object.keys(b); - const length = aKeys.length; - if (length !== bKeys.length) { - return false; - } - for (const k of aKeys) { - if (!deep_compare_strict_deepCompareStrict(a[k], b[k])) { - return false; - } + async invoke(input, options) { + const config = ensureConfig(options); + if (this.func) { + await this.func(input, config); } - return true; + return this._callWithConfig((input) => Promise.resolve(input), input, config); } - return a === b; -} - -;// CONCATENATED MODULE: ./node_modules/@cfworker/json-schema/dist/esm/dereference.js - -const schemaKeyword = { - additionalItems: true, - unevaluatedItems: true, - items: true, - contains: true, - additionalProperties: true, - unevaluatedProperties: true, - propertyNames: true, - not: true, - if: true, - then: true, - else: true -}; -const schemaArrayKeyword = { - prefixItems: true, - items: true, - allOf: true, - anyOf: true, - oneOf: true -}; -const schemaMapKeyword = { - $defs: true, - definitions: true, - properties: true, - patternProperties: true, - dependentSchemas: true -}; -const ignoredKeyword = { - id: true, - $id: true, - $ref: true, - $schema: true, - $anchor: true, - $vocabulary: true, - $comment: true, - default: true, - enum: true, - const: true, - required: true, - type: true, - maximum: true, - minimum: true, - exclusiveMaximum: true, - exclusiveMinimum: true, - multipleOf: true, - maxLength: true, - minLength: true, - pattern: true, - format: true, - maxItems: true, - minItems: true, - uniqueItems: true, - maxProperties: true, - minProperties: true -}; -let initialBaseURI = typeof self !== 'undefined' && - self.location && - self.location.origin !== 'null' - ? - new URL(self.location.origin + self.location.pathname + location.search) - : new URL('https://github.com/cfworker'); -function dereference_dereference(schema, lookup = Object.create(null), baseURI = initialBaseURI, basePointer = '') { - if (schema && typeof schema === 'object' && !Array.isArray(schema)) { - const id = schema.$id || schema.id; - if (id) { - const url = new URL(id, baseURI.href); - if (url.hash.length > 1) { - lookup[url.href] = schema; - } - else { - url.hash = ''; - if (basePointer === '') { - baseURI = url; + async *transform(generator, options) { + const config = ensureConfig(options); + let finalOutput; + let finalOutputSupported = true; + for await (const chunk of this._transformStreamWithConfig(generator, (input) => input, config)) { + yield chunk; + if (finalOutputSupported) { + if (finalOutput === undefined) { + finalOutput = chunk; } else { - dereference_dereference(schema, lookup, baseURI); - } - } - } - } - else if (schema !== true && schema !== false) { - return lookup; - } - const schemaURI = baseURI.href + (basePointer ? '#' + basePointer : ''); - if (lookup[schemaURI] !== undefined) { - throw new Error(`Duplicate schema URI "${schemaURI}".`); - } - lookup[schemaURI] = schema; - if (schema === true || schema === false) { - return lookup; - } - if (schema.__absolute_uri__ === undefined) { - Object.defineProperty(schema, '__absolute_uri__', { - enumerable: false, - value: schemaURI - }); - } - if (schema.$ref && schema.__absolute_ref__ === undefined) { - const url = new URL(schema.$ref, baseURI.href); - url.hash = url.hash; - Object.defineProperty(schema, '__absolute_ref__', { - enumerable: false, - value: url.href - }); - } - if (schema.$recursiveRef && schema.__absolute_recursive_ref__ === undefined) { - const url = new URL(schema.$recursiveRef, baseURI.href); - url.hash = url.hash; - Object.defineProperty(schema, '__absolute_recursive_ref__', { - enumerable: false, - value: url.href - }); - } - if (schema.$anchor) { - const url = new URL('#' + schema.$anchor, baseURI.href); - lookup[url.href] = schema; - } - for (let key in schema) { - if (ignoredKeyword[key]) { - continue; - } - const keyBase = `${basePointer}/${encodePointer(key)}`; - const subSchema = schema[key]; - if (Array.isArray(subSchema)) { - if (schemaArrayKeyword[key]) { - const length = subSchema.length; - for (let i = 0; i < length; i++) { - dereference_dereference(subSchema[i], lookup, baseURI, `${keyBase}/${i}`); + try { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + finalOutput = concat(finalOutput, chunk); + } + catch { + finalOutput = undefined; + finalOutputSupported = false; + } } } } - else if (schemaMapKeyword[key]) { - for (let subKey in subSchema) { - dereference_dereference(subSchema[subKey], lookup, baseURI, `${keyBase}/${encodePointer(subKey)}`); - } - } - else { - dereference_dereference(subSchema, lookup, baseURI, keyBase); + if (this.func && finalOutput !== undefined) { + await this.func(finalOutput, config); } } - return lookup; -} - -;// CONCATENATED MODULE: ./node_modules/@cfworker/json-schema/dist/esm/format.js -const DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/; -const DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; -const TIME = /^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i; -const HOSTNAME = /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i; -const URIREF = /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; -const URITEMPLATE = /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i; -const URL_ = /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu; -const UUID = /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i; -const JSON_POINTER = /^(?:\/(?:[^~/]|~0|~1)*)*$/; -const JSON_POINTER_URI_FRAGMENT = /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i; -const RELATIVE_JSON_POINTER = /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/; -const FASTDATE = /^\d\d\d\d-[0-1]\d-[0-3]\d$/; -const FASTTIME = /^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i; -const FASTDATETIME = /^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i; -const FASTURIREFERENCE = /^(?:(?:[a-z][a-z0-9+-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i; -const EMAIL = (input) => { - if (input[0] === '"') - return false; - const [name, host, ...rest] = input.split('@'); - if (!name || - !host || - rest.length !== 0 || - name.length > 64 || - host.length > 253) - return false; - if (name[0] === '.' || name.endsWith('.') || name.includes('..')) - return false; - if (!/^[a-z0-9.-]+$/i.test(host) || - !/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(name)) - return false; - return host - .split('.') - .every(part => /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(part)); -}; -const IPV4 = /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/; -const IPV6 = /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i; -const DURATION = (input) => input.length > 1 && - input.length < 80 && - (/^P\d+([.,]\d+)?W$/.test(input) || - (/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(input) && - /^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(input))); -function bind(r) { - return r.test.bind(r); -} -const fullFormat = { - date, - time: time.bind(undefined, false), - 'date-time': date_time, - duration: DURATION, - uri, - 'uri-reference': bind(URIREF), - 'uri-template': bind(URITEMPLATE), - url: bind(URL_), - email: EMAIL, - hostname: bind(HOSTNAME), - ipv4: bind(IPV4), - ipv6: bind(IPV6), - regex: regex, - uuid: bind(UUID), - 'json-pointer': bind(JSON_POINTER), - 'json-pointer-uri-fragment': bind(JSON_POINTER_URI_FRAGMENT), - 'relative-json-pointer': bind(RELATIVE_JSON_POINTER) -}; -const format_fastFormat = { - ...fullFormat, - date: bind(FASTDATE), - time: bind(FASTTIME), - 'date-time': bind(FASTDATETIME), - 'uri-reference': bind(FASTURIREFERENCE) -}; -function isLeapYear(year) { - return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); -} -function date(str) { - const matches = str.match(DATE); - if (!matches) - return false; - const year = +matches[1]; - const month = +matches[2]; - const day = +matches[3]; - return (month >= 1 && - month <= 12 && - day >= 1 && - day <= (month == 2 && isLeapYear(year) ? 29 : DAYS[month])); -} -function time(full, str) { - const matches = str.match(TIME); - if (!matches) - return false; - const hour = +matches[1]; - const minute = +matches[2]; - const second = +matches[3]; - const timeZone = !!matches[5]; - return (((hour <= 23 && minute <= 59 && second <= 59) || - (hour == 23 && minute == 59 && second == 60)) && - (!full || timeZone)); -} -const DATE_TIME_SEPARATOR = /t|\s/i; -function date_time(str) { - const dateTime = str.split(DATE_TIME_SEPARATOR); - return dateTime.length == 2 && date(dateTime[0]) && time(true, dateTime[1]); -} -const NOT_URI_FRAGMENT = /\/|:/; -const URI_PATTERN = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; -function uri(str) { - return NOT_URI_FRAGMENT.test(str) && URI_PATTERN.test(str); -} -const Z_ANCHOR = /[^\\]\\Z/; -function regex(str) { - if (Z_ANCHOR.test(str)) - return false; - try { - new RegExp(str, 'u'); - return true; - } - catch (e) { - return false; + /** + * A runnable that assigns key-value pairs to the input. + * + * The example below shows how you could use it with an inline function. + * + * @example + * ```typescript + * const prompt = + * PromptTemplate.fromTemplate(`Write a SQL query to answer the question using the following schema: {schema} + * Question: {question} + * SQL Query:`); + * + * // The `RunnablePassthrough.assign()` is used here to passthrough the input from the `.invoke()` + * // call (in this example it's the question), along with any inputs passed to the `.assign()` method. + * // In this case, we're passing the schema. + * const sqlQueryGeneratorChain = RunnableSequence.from([ + * RunnablePassthrough.assign({ + * schema: async () => db.getTableInfo(), + * }), + * prompt, + * new ChatOpenAI({ model: "gpt-4o-mini" }).withConfig({ stop: ["\nSQLResult:"] }), + * new StringOutputParser(), + * ]); + * const result = await sqlQueryGeneratorChain.invoke({ + * question: "How many employees are there?", + * }); + * ``` + */ + static assign(mapping) { + return new RunnableAssign(new RunnableMap({ steps: mapping })); } } -;// CONCATENATED MODULE: ./node_modules/@cfworker/json-schema/dist/esm/types.js -var OutputFormat; -(function (OutputFormat) { - OutputFormat[OutputFormat["Flag"] = 1] = "Flag"; - OutputFormat[OutputFormat["Basic"] = 2] = "Basic"; - OutputFormat[OutputFormat["Detailed"] = 4] = "Detailed"; -})(OutputFormat || (OutputFormat = {})); +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/language_models/chat_models.js -;// CONCATENATED MODULE: ./node_modules/@cfworker/json-schema/dist/esm/validate.js -function validate_validate(instance, schema, draft = '2019-09', lookup = dereference(schema), shortCircuit = true, recursiveAnchor = null, instanceLocation = '#', schemaLocation = '#', evaluated = Object.create(null)) { - if (schema === true) { - return { valid: true, errors: [] }; - } - if (schema === false) { - return { - valid: false, - errors: [ - { - instanceLocation, - keyword: 'false', - keywordLocation: instanceLocation, - error: 'False boolean schema.' + + + + +/** + * Creates a transform stream for encoding chat message chunks. + * @deprecated Use {@link BytesOutputParser} instead + * @returns A TransformStream instance that encodes chat message chunks. + */ +function createChatMessageChunkEncoderStream() { + const textEncoder = new TextEncoder(); + return new TransformStream({ + transform(chunk, controller) { + controller.enqueue(textEncoder.encode(typeof chunk.content === "string" + ? chunk.content + : JSON.stringify(chunk.content))); + }, + }); +} +function _formatForTracing(messages) { + const messagesToTrace = []; + for (const message of messages) { + let messageToTrace = message; + if (Array.isArray(message.content)) { + for (let idx = 0; idx < message.content.length; idx++) { + const block = message.content[idx]; + if (isURLContentBlock(block) || isBase64ContentBlock(block)) { + if (messageToTrace === message) { + // Also shallow-copy content + // eslint-disable-next-line @typescript-eslint/no-explicit-any + messageToTrace = new message.constructor({ + ...messageToTrace, + content: [ + ...message.content.slice(0, idx), + convertToOpenAIImageBlock(block), + ...message.content.slice(idx + 1), + ], + }); + } } - ] - }; + } + } + messagesToTrace.push(messageToTrace); + } + return messagesToTrace; +} +/** + * Base class for chat models. It extends the BaseLanguageModel class and + * provides methods for generating chat based on input messages. + */ +class BaseChatModel extends BaseLanguageModel { + constructor(fields) { + super(fields); + // Only ever instantiated in main LangChain + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain", "chat_models", this._llmType()] + }); + Object.defineProperty(this, "disableStreaming", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + } + _separateRunnableConfigFromCallOptionsCompat(options) { + // For backwards compat, keep `signal` in both runnableConfig and callOptions + const [runnableConfig, callOptions] = super._separateRunnableConfigFromCallOptions(options); + callOptions.signal = runnableConfig.signal; + return [runnableConfig, callOptions]; } - const rawInstanceType = typeof instance; - let instanceType; - switch (rawInstanceType) { - case 'boolean': - case 'number': - case 'string': - instanceType = rawInstanceType; - break; - case 'object': - if (instance === null) { - instanceType = 'null'; - } - else if (Array.isArray(instance)) { - instanceType = 'array'; - } - else { - instanceType = 'object'; - } - break; - default: - throw new Error(`Instances of "${rawInstanceType}" type are not supported.`); + /** + * Invokes the chat model with a single input. + * @param input The input for the language model. + * @param options The call options. + * @returns A Promise that resolves to a BaseMessageChunk. + */ + async invoke(input, options) { + const promptValue = BaseChatModel._convertInputToPromptValue(input); + const result = await this.generatePrompt([promptValue], options, options?.callbacks); + const chatGeneration = result.generations[0][0]; + // TODO: Remove cast after figuring out inheritance + return chatGeneration.message; } - const { $ref, $recursiveRef, $recursiveAnchor, type: $type, const: $const, enum: $enum, required: $required, not: $not, anyOf: $anyOf, allOf: $allOf, oneOf: $oneOf, if: $if, then: $then, else: $else, format: $format, properties: $properties, patternProperties: $patternProperties, additionalProperties: $additionalProperties, unevaluatedProperties: $unevaluatedProperties, minProperties: $minProperties, maxProperties: $maxProperties, propertyNames: $propertyNames, dependentRequired: $dependentRequired, dependentSchemas: $dependentSchemas, dependencies: $dependencies, prefixItems: $prefixItems, items: $items, additionalItems: $additionalItems, unevaluatedItems: $unevaluatedItems, contains: $contains, minContains: $minContains, maxContains: $maxContains, minItems: $minItems, maxItems: $maxItems, uniqueItems: $uniqueItems, minimum: $minimum, maximum: $maximum, exclusiveMinimum: $exclusiveMinimum, exclusiveMaximum: $exclusiveMaximum, multipleOf: $multipleOf, minLength: $minLength, maxLength: $maxLength, pattern: $pattern, __absolute_ref__, __absolute_recursive_ref__ } = schema; - const errors = []; - if ($recursiveAnchor === true && recursiveAnchor === null) { - recursiveAnchor = schema; + // eslint-disable-next-line require-yield + async *_streamResponseChunks(_messages, _options, _runManager) { + throw new Error("Not implemented."); } - if ($recursiveRef === '#') { - const refSchema = recursiveAnchor === null - ? lookup[__absolute_recursive_ref__] - : recursiveAnchor; - const keywordLocation = `${schemaLocation}/$recursiveRef`; - const result = validate_validate(instance, recursiveAnchor === null ? schema : recursiveAnchor, draft, lookup, shortCircuit, refSchema, instanceLocation, keywordLocation, evaluated); - if (!result.valid) { - errors.push({ - instanceLocation, - keyword: '$recursiveRef', - keywordLocation, - error: 'A subschema had errors.' - }, ...result.errors); + async *_streamIterator(input, options) { + // Subclass check required to avoid double callbacks with default implementation + if (this._streamResponseChunks === + BaseChatModel.prototype._streamResponseChunks || + this.disableStreaming) { + yield this.invoke(input, options); } - } - if ($ref !== undefined) { - const uri = __absolute_ref__ || $ref; - const refSchema = lookup[uri]; - if (refSchema === undefined) { - let message = `Unresolved $ref "${$ref}".`; - if (__absolute_ref__ && __absolute_ref__ !== $ref) { - message += ` Absolute URI "${__absolute_ref__}".`; + else { + const prompt = BaseChatModel._convertInputToPromptValue(input); + const messages = prompt.toChatMessages(); + const [runnableConfig, callOptions] = this._separateRunnableConfigFromCallOptionsCompat(options); + const inheritableMetadata = { + ...runnableConfig.metadata, + ...this.getLsParams(callOptions), + }; + const callbackManager_ = await CallbackManager.configure(runnableConfig.callbacks, this.callbacks, runnableConfig.tags, this.tags, inheritableMetadata, this.metadata, { verbose: this.verbose }); + const extra = { + options: callOptions, + invocation_params: this?.invocationParams(callOptions), + batch_size: 1, + }; + const runManagers = await callbackManager_?.handleChatModelStart(this.toJSON(), [_formatForTracing(messages)], runnableConfig.runId, undefined, extra, undefined, undefined, runnableConfig.runName); + let generationChunk; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let llmOutput; + try { + for await (const chunk of this._streamResponseChunks(messages, callOptions, runManagers?.[0])) { + if (chunk.message.id == null) { + const runId = runManagers?.at(0)?.runId; + if (runId != null) + chunk.message._updateId(`run-${runId}`); + } + chunk.message.response_metadata = { + ...chunk.generationInfo, + ...chunk.message.response_metadata, + }; + yield chunk.message; + if (!generationChunk) { + generationChunk = chunk; + } + else { + generationChunk = generationChunk.concat(chunk); + } + if (isAIMessageChunk(chunk.message) && + chunk.message.usage_metadata !== undefined) { + llmOutput = { + tokenUsage: { + promptTokens: chunk.message.usage_metadata.input_tokens, + completionTokens: chunk.message.usage_metadata.output_tokens, + totalTokens: chunk.message.usage_metadata.total_tokens, + }, + }; + } + } } - message += `\nKnown schemas:\n- ${Object.keys(lookup).join('\n- ')}`; - throw new Error(message); - } - const keywordLocation = `${schemaLocation}/$ref`; - const result = validate_validate(instance, refSchema, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, keywordLocation, evaluated); - if (!result.valid) { - errors.push({ - instanceLocation, - keyword: '$ref', - keywordLocation, - error: 'A subschema had errors.' - }, ...result.errors); - } - if (draft === '4' || draft === '7') { - return { valid: errors.length === 0, errors }; - } - } - if (Array.isArray($type)) { - let length = $type.length; - let valid = false; - for (let i = 0; i < length; i++) { - if (instanceType === $type[i] || - ($type[i] === 'integer' && - instanceType === 'number' && - instance % 1 === 0 && - instance === instance)) { - valid = true; - break; + catch (err) { + await Promise.all((runManagers ?? []).map((runManager) => runManager?.handleLLMError(err))); + throw err; } - } - if (!valid) { - errors.push({ - instanceLocation, - keyword: 'type', - keywordLocation: `${schemaLocation}/type`, - error: `Instance type "${instanceType}" is invalid. Expected "${$type.join('", "')}".` - }); - } - } - else if ($type === 'integer') { - if (instanceType !== 'number' || instance % 1 || instance !== instance) { - errors.push({ - instanceLocation, - keyword: 'type', - keywordLocation: `${schemaLocation}/type`, - error: `Instance type "${instanceType}" is invalid. Expected "${$type}".` - }); + await Promise.all((runManagers ?? []).map((runManager) => runManager?.handleLLMEnd({ + // TODO: Remove cast after figuring out inheritance + generations: [[generationChunk]], + llmOutput, + }))); } } - else if ($type !== undefined && instanceType !== $type) { - errors.push({ - instanceLocation, - keyword: 'type', - keywordLocation: `${schemaLocation}/type`, - error: `Instance type "${instanceType}" is invalid. Expected "${$type}".` - }); + getLsParams(options) { + const providerName = this.getName().startsWith("Chat") + ? this.getName().replace("Chat", "") + : this.getName(); + return { + ls_model_type: "chat", + ls_stop: options.stop, + ls_provider: providerName, + }; } - if ($const !== undefined) { - if (instanceType === 'object' || instanceType === 'array') { - if (!deepCompareStrict(instance, $const)) { - errors.push({ - instanceLocation, - keyword: 'const', - keywordLocation: `${schemaLocation}/const`, - error: `Instance does not match ${JSON.stringify($const)}.` - }); - } + /** @ignore */ + async _generateUncached(messages, parsedOptions, handledOptions, startedRunManagers) { + const baseMessages = messages.map((messageList) => messageList.map(coerceMessageLikeToMessage)); + let runManagers; + if (startedRunManagers !== undefined && + startedRunManagers.length === baseMessages.length) { + runManagers = startedRunManagers; } - else if (instance !== $const) { - errors.push({ - instanceLocation, - keyword: 'const', - keywordLocation: `${schemaLocation}/const`, - error: `Instance does not match ${JSON.stringify($const)}.` - }); + else { + const inheritableMetadata = { + ...handledOptions.metadata, + ...this.getLsParams(parsedOptions), + }; + // create callback manager and start run + const callbackManager_ = await CallbackManager.configure(handledOptions.callbacks, this.callbacks, handledOptions.tags, this.tags, inheritableMetadata, this.metadata, { verbose: this.verbose }); + const extra = { + options: parsedOptions, + invocation_params: this?.invocationParams(parsedOptions), + batch_size: 1, + }; + runManagers = await callbackManager_?.handleChatModelStart(this.toJSON(), baseMessages.map(_formatForTracing), handledOptions.runId, undefined, extra, undefined, undefined, handledOptions.runName); } - } - if ($enum !== undefined) { - if (instanceType === 'object' || instanceType === 'array') { - if (!$enum.some(value => deepCompareStrict(instance, value))) { - errors.push({ - instanceLocation, - keyword: 'enum', - keywordLocation: `${schemaLocation}/enum`, - error: `Instance does not match any of ${JSON.stringify($enum)}.` + const generations = []; + const llmOutputs = []; + // Even if stream is not explicitly called, check if model is implicitly + // called from streamEvents() or streamLog() to get all streamed events. + // Bail out if _streamResponseChunks not overridden + const hasStreamingHandler = !!runManagers?.[0].handlers.find(callbackHandlerPrefersStreaming); + if (hasStreamingHandler && + !this.disableStreaming && + baseMessages.length === 1 && + this._streamResponseChunks !== + BaseChatModel.prototype._streamResponseChunks) { + try { + const stream = await this._streamResponseChunks(baseMessages[0], parsedOptions, runManagers?.[0]); + let aggregated; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let llmOutput; + for await (const chunk of stream) { + if (chunk.message.id == null) { + const runId = runManagers?.at(0)?.runId; + if (runId != null) + chunk.message._updateId(`run-${runId}`); + } + if (aggregated === undefined) { + aggregated = chunk; + } + else { + aggregated = concat(aggregated, chunk); + } + if (isAIMessageChunk(chunk.message) && + chunk.message.usage_metadata !== undefined) { + llmOutput = { + tokenUsage: { + promptTokens: chunk.message.usage_metadata.input_tokens, + completionTokens: chunk.message.usage_metadata.output_tokens, + totalTokens: chunk.message.usage_metadata.total_tokens, + }, + }; + } + } + if (aggregated === undefined) { + throw new Error("Received empty response from chat model call."); + } + generations.push([aggregated]); + await runManagers?.[0].handleLLMEnd({ + generations, + llmOutput, }); } - } - else if (!$enum.some(value => instance === value)) { - errors.push({ - instanceLocation, - keyword: 'enum', - keywordLocation: `${schemaLocation}/enum`, - error: `Instance does not match any of ${JSON.stringify($enum)}.` - }); - } - } - if ($not !== undefined) { - const keywordLocation = `${schemaLocation}/not`; - const result = validate_validate(instance, $not, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, keywordLocation); - if (result.valid) { - errors.push({ - instanceLocation, - keyword: 'not', - keywordLocation, - error: 'Instance matched "not" schema.' - }); - } - } - let subEvaluateds = []; - if ($anyOf !== undefined) { - const keywordLocation = `${schemaLocation}/anyOf`; - const errorsLength = errors.length; - let anyValid = false; - for (let i = 0; i < $anyOf.length; i++) { - const subSchema = $anyOf[i]; - const subEvaluated = Object.create(evaluated); - const result = validate_validate(instance, subSchema, draft, lookup, shortCircuit, $recursiveAnchor === true ? recursiveAnchor : null, instanceLocation, `${keywordLocation}/${i}`, subEvaluated); - errors.push(...result.errors); - anyValid = anyValid || result.valid; - if (result.valid) { - subEvaluateds.push(subEvaluated); + catch (e) { + await runManagers?.[0].handleLLMError(e); + throw e; } } - if (anyValid) { - errors.length = errorsLength; - } else { - errors.splice(errorsLength, 0, { - instanceLocation, - keyword: 'anyOf', - keywordLocation, - error: 'Instance does not match any subschemas.' - }); + // generate results + const results = await Promise.allSettled(baseMessages.map((messageList, i) => this._generate(messageList, { ...parsedOptions, promptIndex: i }, runManagers?.[i]))); + // handle results + await Promise.all(results.map(async (pResult, i) => { + if (pResult.status === "fulfilled") { + const result = pResult.value; + for (const generation of result.generations) { + if (generation.message.id == null) { + const runId = runManagers?.at(0)?.runId; + if (runId != null) + generation.message._updateId(`run-${runId}`); + } + generation.message.response_metadata = { + ...generation.generationInfo, + ...generation.message.response_metadata, + }; + } + if (result.generations.length === 1) { + result.generations[0].message.response_metadata = { + ...result.llmOutput, + ...result.generations[0].message.response_metadata, + }; + } + generations[i] = result.generations; + llmOutputs[i] = result.llmOutput; + return runManagers?.[i]?.handleLLMEnd({ + generations: [result.generations], + llmOutput: result.llmOutput, + }); + } + else { + // status === "rejected" + await runManagers?.[i]?.handleLLMError(pResult.reason); + return Promise.reject(pResult.reason); + } + })); } + // create combined output + const output = { + generations, + llmOutput: llmOutputs.length + ? this._combineLLMOutput?.(...llmOutputs) + : undefined, + }; + Object.defineProperty(output, RUN_KEY, { + value: runManagers + ? { runIds: runManagers?.map((manager) => manager.runId) } + : undefined, + configurable: true, + }); + return output; } - if ($allOf !== undefined) { - const keywordLocation = `${schemaLocation}/allOf`; - const errorsLength = errors.length; - let allValid = true; - for (let i = 0; i < $allOf.length; i++) { - const subSchema = $allOf[i]; - const subEvaluated = Object.create(evaluated); - const result = validate_validate(instance, subSchema, draft, lookup, shortCircuit, $recursiveAnchor === true ? recursiveAnchor : null, instanceLocation, `${keywordLocation}/${i}`, subEvaluated); - errors.push(...result.errors); - allValid = allValid && result.valid; - if (result.valid) { - subEvaluateds.push(subEvaluated); + async _generateCached({ messages, cache, llmStringKey, parsedOptions, handledOptions, }) { + const baseMessages = messages.map((messageList) => messageList.map(coerceMessageLikeToMessage)); + const inheritableMetadata = { + ...handledOptions.metadata, + ...this.getLsParams(parsedOptions), + }; + // create callback manager and start run + const callbackManager_ = await CallbackManager.configure(handledOptions.callbacks, this.callbacks, handledOptions.tags, this.tags, inheritableMetadata, this.metadata, { verbose: this.verbose }); + const extra = { + options: parsedOptions, + invocation_params: this?.invocationParams(parsedOptions), + batch_size: 1, + }; + const runManagers = await callbackManager_?.handleChatModelStart(this.toJSON(), baseMessages.map(_formatForTracing), handledOptions.runId, undefined, extra, undefined, undefined, handledOptions.runName); + // generate results + const missingPromptIndices = []; + const results = await Promise.allSettled(baseMessages.map(async (baseMessage, index) => { + // Join all content into one string for the prompt index + const prompt = BaseChatModel._convertInputToPromptValue(baseMessage).toString(); + const result = await cache.lookup(prompt, llmStringKey); + if (result == null) { + missingPromptIndices.push(index); } - } - if (allValid) { - errors.length = errorsLength; + return result; + })); + // Map run managers to the results before filtering out null results + // Null results are just absent from the cache. + const cachedResults = results + .map((result, index) => ({ result, runManager: runManagers?.[index] })) + .filter(({ result }) => (result.status === "fulfilled" && result.value != null) || + result.status === "rejected"); + // Handle results and call run managers + const generations = []; + await Promise.all(cachedResults.map(async ({ result: promiseResult, runManager }, i) => { + if (promiseResult.status === "fulfilled") { + const result = promiseResult.value; + generations[i] = result.map((result) => { + if ("message" in result && + isBaseMessage(result.message) && + isAIMessage(result.message)) { + // eslint-disable-next-line no-param-reassign + result.message.usage_metadata = { + input_tokens: 0, + output_tokens: 0, + total_tokens: 0, + }; + } + // eslint-disable-next-line no-param-reassign + result.generationInfo = { + ...result.generationInfo, + tokenUsage: {}, + }; + return result; + }); + if (result.length) { + await runManager?.handleLLMNewToken(result[0].text); + } + return runManager?.handleLLMEnd({ + generations: [result], + }, undefined, undefined, undefined, { + cached: true, + }); + } + else { + // status === "rejected" + await runManager?.handleLLMError(promiseResult.reason, undefined, undefined, undefined, { + cached: true, + }); + return Promise.reject(promiseResult.reason); + } + })); + const output = { + generations, + missingPromptIndices, + startedRunManagers: runManagers, + }; + // This defines RUN_KEY as a non-enumerable property on the output object + // so that it is not serialized when the output is stringified, and so that + // it isnt included when listing the keys of the output object. + Object.defineProperty(output, RUN_KEY, { + value: runManagers + ? { runIds: runManagers?.map((manager) => manager.runId) } + : undefined, + configurable: true, + }); + return output; + } + /** + * Generates chat based on the input messages. + * @param messages An array of arrays of BaseMessage instances. + * @param options The call options or an array of stop sequences. + * @param callbacks The callbacks for the language model. + * @returns A Promise that resolves to an LLMResult. + */ + async generate(messages, options, callbacks) { + // parse call options + let parsedOptions; + if (Array.isArray(options)) { + parsedOptions = { stop: options }; } else { - errors.splice(errorsLength, 0, { - instanceLocation, - keyword: 'allOf', - keywordLocation, - error: `Instance does not match every subschema.` - }); + parsedOptions = options; } - } - if ($oneOf !== undefined) { - const keywordLocation = `${schemaLocation}/oneOf`; - const errorsLength = errors.length; - const matches = $oneOf.filter((subSchema, i) => { - const subEvaluated = Object.create(evaluated); - const result = validate_validate(instance, subSchema, draft, lookup, shortCircuit, $recursiveAnchor === true ? recursiveAnchor : null, instanceLocation, `${keywordLocation}/${i}`, subEvaluated); - errors.push(...result.errors); - if (result.valid) { - subEvaluateds.push(subEvaluated); - } - return result.valid; - }).length; - if (matches === 1) { - errors.length = errorsLength; + const baseMessages = messages.map((messageList) => messageList.map(coerceMessageLikeToMessage)); + const [runnableConfig, callOptions] = this._separateRunnableConfigFromCallOptionsCompat(parsedOptions); + runnableConfig.callbacks = runnableConfig.callbacks ?? callbacks; + if (!this.cache) { + return this._generateUncached(baseMessages, callOptions, runnableConfig); } - else { - errors.splice(errorsLength, 0, { - instanceLocation, - keyword: 'oneOf', - keywordLocation, - error: `Instance does not match exactly one subschema (${matches} matches).` - }); + const { cache } = this; + const llmStringKey = this._getSerializedCacheKeyParametersForCall(callOptions); + const { generations, missingPromptIndices, startedRunManagers } = await this._generateCached({ + messages: baseMessages, + cache, + llmStringKey, + parsedOptions: callOptions, + handledOptions: runnableConfig, + }); + let llmOutput = {}; + if (missingPromptIndices.length > 0) { + const results = await this._generateUncached(missingPromptIndices.map((i) => baseMessages[i]), callOptions, runnableConfig, startedRunManagers !== undefined + ? missingPromptIndices.map((i) => startedRunManagers?.[i]) + : undefined); + await Promise.all(results.generations.map(async (generation, index) => { + const promptIndex = missingPromptIndices[index]; + generations[promptIndex] = generation; + // Join all content into one string for the prompt index + const prompt = BaseChatModel._convertInputToPromptValue(baseMessages[promptIndex]).toString(); + return cache.update(prompt, llmStringKey, generation); + })); + llmOutput = results.llmOutput ?? {}; } + return { generations, llmOutput }; } - if (instanceType === 'object' || instanceType === 'array') { - Object.assign(evaluated, ...subEvaluateds); + /** + * Get the parameters used to invoke the model + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + invocationParams(_options) { + return {}; } - if ($if !== undefined) { - const keywordLocation = `${schemaLocation}/if`; - const conditionResult = validate_validate(instance, $if, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, keywordLocation, evaluated).valid; - if (conditionResult) { - if ($then !== undefined) { - const thenResult = validate_validate(instance, $then, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, `${schemaLocation}/then`, evaluated); - if (!thenResult.valid) { - errors.push({ - instanceLocation, - keyword: 'if', - keywordLocation, - error: `Instance does not match "then" schema.` - }, ...thenResult.errors); - } - } - } - else if ($else !== undefined) { - const elseResult = validate_validate(instance, $else, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, `${schemaLocation}/else`, evaluated); - if (!elseResult.valid) { - errors.push({ - instanceLocation, - keyword: 'if', - keywordLocation, - error: `Instance does not match "else" schema.` - }, ...elseResult.errors); - } + _modelType() { + return "base_chat_model"; + } + /** + * @deprecated + * Return a json-like object representing this LLM. + */ + serialize() { + return { + ...this.invocationParams(), + _type: this._llmType(), + _model: this._modelType(), + }; + } + /** + * Generates a prompt based on the input prompt values. + * @param promptValues An array of BasePromptValue instances. + * @param options The call options or an array of stop sequences. + * @param callbacks The callbacks for the language model. + * @returns A Promise that resolves to an LLMResult. + */ + async generatePrompt(promptValues, options, callbacks) { + const promptMessages = promptValues.map((promptValue) => promptValue.toChatMessages()); + return this.generate(promptMessages, options, callbacks); + } + /** + * @deprecated Use .invoke() instead. Will be removed in 0.2.0. + * + * Makes a single call to the chat model. + * @param messages An array of BaseMessage instances. + * @param options The call options or an array of stop sequences. + * @param callbacks The callbacks for the language model. + * @returns A Promise that resolves to a BaseMessage. + */ + async call(messages, options, callbacks) { + const result = await this.generate([messages.map(coerceMessageLikeToMessage)], options, callbacks); + const generations = result.generations; + return generations[0][0].message; + } + /** + * @deprecated Use .invoke() instead. Will be removed in 0.2.0. + * + * Makes a single call to the chat model with a prompt value. + * @param promptValue The value of the prompt. + * @param options The call options or an array of stop sequences. + * @param callbacks The callbacks for the language model. + * @returns A Promise that resolves to a BaseMessage. + */ + async callPrompt(promptValue, options, callbacks) { + const promptMessages = promptValue.toChatMessages(); + return this.call(promptMessages, options, callbacks); + } + /** + * @deprecated Use .invoke() instead. Will be removed in 0.2.0. + * + * Predicts the next message based on the input messages. + * @param messages An array of BaseMessage instances. + * @param options The call options or an array of stop sequences. + * @param callbacks The callbacks for the language model. + * @returns A Promise that resolves to a BaseMessage. + */ + async predictMessages(messages, options, callbacks) { + return this.call(messages, options, callbacks); + } + /** + * @deprecated Use .invoke() instead. Will be removed in 0.2.0. + * + * Predicts the next message based on a text input. + * @param text The text input. + * @param options The call options or an array of stop sequences. + * @param callbacks The callbacks for the language model. + * @returns A Promise that resolves to a string. + */ + async predict(text, options, callbacks) { + const message = new human_HumanMessage(text); + const result = await this.call([message], options, callbacks); + if (typeof result.content !== "string") { + throw new Error("Cannot use predict when output is not a string."); } + return result.content; } - if (instanceType === 'object') { - if ($required !== undefined) { - for (const key of $required) { - if (!(key in instance)) { - errors.push({ - instanceLocation, - keyword: 'required', - keywordLocation: `${schemaLocation}/required`, - error: `Instance does not have required property "${key}".` - }); - } - } + withStructuredOutput(outputSchema, config) { + if (typeof this.bindTools !== "function") { + throw new Error(`Chat model must implement ".bindTools()" to use withStructuredOutput.`); } - const keys = Object.keys(instance); - if ($minProperties !== undefined && keys.length < $minProperties) { - errors.push({ - instanceLocation, - keyword: 'minProperties', - keywordLocation: `${schemaLocation}/minProperties`, - error: `Instance does not have at least ${$minProperties} properties.` - }); + if (config?.strict) { + throw new Error(`"strict" mode is not supported for this model by default.`); } - if ($maxProperties !== undefined && keys.length > $maxProperties) { - errors.push({ - instanceLocation, - keyword: 'maxProperties', - keywordLocation: `${schemaLocation}/maxProperties`, - error: `Instance does not have at least ${$maxProperties} properties.` - }); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const schema = outputSchema; + const name = config?.name; + const description = getSchemaDescription(schema) ?? "A function available to call."; + const method = config?.method; + const includeRaw = config?.includeRaw; + if (method === "jsonMode") { + throw new Error(`Base withStructuredOutput implementation only supports "functionCalling" as a method.`); } - if ($propertyNames !== undefined) { - const keywordLocation = `${schemaLocation}/propertyNames`; - for (const key in instance) { - const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`; - const result = validate_validate(key, $propertyNames, draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, keywordLocation); - if (!result.valid) { - errors.push({ - instanceLocation, - keyword: 'propertyNames', - keywordLocation, - error: `Property name "${key}" does not match schema.` - }, ...result.errors); - } - } + let functionName = name ?? "extract"; + let tools; + if (isInteropZodSchema(schema)) { + tools = [ + { + type: "function", + function: { + name: functionName, + description, + parameters: json_schema_toJsonSchema(schema), + }, + }, + ]; } - if ($dependentRequired !== undefined) { - const keywordLocation = `${schemaLocation}/dependantRequired`; - for (const key in $dependentRequired) { - if (key in instance) { - const required = $dependentRequired[key]; - for (const dependantKey of required) { - if (!(dependantKey in instance)) { - errors.push({ - instanceLocation, - keyword: 'dependentRequired', - keywordLocation, - error: `Instance has "${key}" but does not have "${dependantKey}".` - }); - } - } - } + else { + if ("name" in schema) { + functionName = schema.name; } + tools = [ + { + type: "function", + function: { + name: functionName, + description, + parameters: schema, + }, + }, + ]; } - if ($dependentSchemas !== undefined) { - for (const key in $dependentSchemas) { - const keywordLocation = `${schemaLocation}/dependentSchemas`; - if (key in instance) { - const result = validate_validate(instance, $dependentSchemas[key], draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, `${keywordLocation}/${encodePointer(key)}`, evaluated); - if (!result.valid) { - errors.push({ - instanceLocation, - keyword: 'dependentSchemas', - keywordLocation, - error: `Instance has "${key}" but does not match dependant schema.` - }, ...result.errors); - } - } + const llm = this.bindTools(tools); + const outputParser = base_RunnableLambda.from((input) => { + if (!input.tool_calls || input.tool_calls.length === 0) { + throw new Error("No tool calls found in the response."); } - } - if ($dependencies !== undefined) { - const keywordLocation = `${schemaLocation}/dependencies`; - for (const key in $dependencies) { - if (key in instance) { - const propsOrSchema = $dependencies[key]; - if (Array.isArray(propsOrSchema)) { - for (const dependantKey of propsOrSchema) { - if (!(dependantKey in instance)) { - errors.push({ - instanceLocation, - keyword: 'dependencies', - keywordLocation, - error: `Instance has "${key}" but does not have "${dependantKey}".` - }); - } - } - } - else { - const result = validate_validate(instance, propsOrSchema, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, `${keywordLocation}/${encodePointer(key)}`); - if (!result.valid) { - errors.push({ - instanceLocation, - keyword: 'dependencies', - keywordLocation, - error: `Instance has "${key}" but does not match dependant schema.` - }, ...result.errors); - } - } - } + const toolCall = input.tool_calls.find((tc) => tc.name === functionName); + if (!toolCall) { + throw new Error(`No tool call found with name ${functionName}.`); } + return toolCall.args; + }); + if (!includeRaw) { + return llm.pipe(outputParser).withConfig({ + runName: "StructuredOutput", + }); } - const thisEvaluated = Object.create(null); - let stop = false; - if ($properties !== undefined) { - const keywordLocation = `${schemaLocation}/properties`; - for (const key in $properties) { - if (!(key in instance)) { - continue; - } - const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`; - const result = validate_validate(instance[key], $properties[key], draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, `${keywordLocation}/${encodePointer(key)}`); - if (result.valid) { - evaluated[key] = thisEvaluated[key] = true; - } - else { - stop = shortCircuit; - errors.push({ - instanceLocation, - keyword: 'properties', - keywordLocation, - error: `Property "${key}" does not match schema.` - }, ...result.errors); - if (stop) - break; - } - } + const parserAssign = RunnablePassthrough.assign({ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + parsed: (input, config) => outputParser.invoke(input.raw, config), + }); + const parserNone = RunnablePassthrough.assign({ + parsed: () => null, + }); + const parsedWithFallback = parserAssign.withFallbacks({ + fallbacks: [parserNone], + }); + return RunnableSequence.from([ + { + raw: llm, + }, + parsedWithFallback, + ]).withConfig({ + runName: "StructuredOutputRunnable", + }); + } +} +/** + * An abstract class that extends BaseChatModel and provides a simple + * implementation of _generate. + */ +class SimpleChatModel extends (/* unused pure expression or super */ null && (BaseChatModel)) { + async _generate(messages, options, runManager) { + const text = await this._call(messages, options, runManager); + const message = new AIMessage(text); + if (typeof message.content !== "string") { + throw new Error("Cannot generate with a simple chat model when output is not a string."); } - if (!stop && $patternProperties !== undefined) { - const keywordLocation = `${schemaLocation}/patternProperties`; - for (const pattern in $patternProperties) { - const regex = new RegExp(pattern, 'u'); - const subSchema = $patternProperties[pattern]; - for (const key in instance) { - if (!regex.test(key)) { - continue; - } - const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`; - const result = validate_validate(instance[key], subSchema, draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, `${keywordLocation}/${encodePointer(pattern)}`); - if (result.valid) { - evaluated[key] = thisEvaluated[key] = true; - } - else { - stop = shortCircuit; - errors.push({ - instanceLocation, - keyword: 'patternProperties', - keywordLocation, - error: `Property "${key}" matches pattern "${pattern}" but does not match associated schema.` - }, ...result.errors); - } - } - } + return { + generations: [ + { + text: message.content, + message, + }, + ], + }; + } +} + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/language_models/chat_models.js + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/outputs.js + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/utils/async_caller.js + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/router.js + + +/** + * A runnable that routes to a set of runnables based on Input['key']. + * Returns the output of the selected runnable. + * @example + * ```typescript + * import { RouterRunnable, RunnableLambda } from "@langchain/core/runnables"; + * + * const router = new RouterRunnable({ + * runnables: { + * toUpperCase: RunnableLambda.from((text: string) => text.toUpperCase()), + * reverseText: RunnableLambda.from((text: string) => + * text.split("").reverse().join("") + * ), + * }, + * }); + * + * // Invoke the 'reverseText' runnable + * const result1 = router.invoke({ key: "reverseText", input: "Hello World" }); + * + * // "dlroW olleH" + * + * // Invoke the 'toUpperCase' runnable + * const result2 = router.invoke({ key: "toUpperCase", input: "Hello World" }); + * + * // "HELLO WORLD" + * ``` + */ +class RouterRunnable extends Runnable { + static lc_name() { + return "RouterRunnable"; + } + constructor(fields) { + super(fields); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain_core", "runnables"] + }); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "runnables", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.runnables = fields.runnables; + } + async invoke(input, options) { + const { key, input: actualInput } = input; + const runnable = this.runnables[key]; + if (runnable === undefined) { + throw new Error(`No runnable associated with key "${key}".`); } - if (!stop && $additionalProperties !== undefined) { - const keywordLocation = `${schemaLocation}/additionalProperties`; - for (const key in instance) { - if (thisEvaluated[key]) { - continue; - } - const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`; - const result = validate_validate(instance[key], $additionalProperties, draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, keywordLocation); - if (result.valid) { - evaluated[key] = true; - } - else { - stop = shortCircuit; - errors.push({ - instanceLocation, - keyword: 'additionalProperties', - keywordLocation, - error: `Property "${key}" does not match additional properties schema.` - }, ...result.errors); - } - } + return runnable.invoke(actualInput, ensureConfig(options)); + } + async batch(inputs, options, batchOptions) { + const keys = inputs.map((input) => input.key); + const actualInputs = inputs.map((input) => input.input); + const missingKey = keys.find((key) => this.runnables[key] === undefined); + if (missingKey !== undefined) { + throw new Error(`One or more keys do not have a corresponding runnable.`); } - else if (!stop && $unevaluatedProperties !== undefined) { - const keywordLocation = `${schemaLocation}/unevaluatedProperties`; - for (const key in instance) { - if (!evaluated[key]) { - const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`; - const result = validate_validate(instance[key], $unevaluatedProperties, draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, keywordLocation); - if (result.valid) { - evaluated[key] = true; - } - else { - errors.push({ - instanceLocation, - keyword: 'unevaluatedProperties', - keywordLocation, - error: `Property "${key}" does not match unevaluated properties schema.` - }, ...result.errors); - } - } - } + const runnables = keys.map((key) => this.runnables[key]); + const optionsList = this._getOptionsList(options ?? {}, inputs.length); + const maxConcurrency = optionsList[0]?.maxConcurrency ?? batchOptions?.maxConcurrency; + const batchSize = maxConcurrency && maxConcurrency > 0 ? maxConcurrency : inputs.length; + const batchResults = []; + for (let i = 0; i < actualInputs.length; i += batchSize) { + const batchPromises = actualInputs + .slice(i, i + batchSize) + .map((actualInput, i) => runnables[i].invoke(actualInput, optionsList[i])); + const batchResult = await Promise.all(batchPromises); + batchResults.push(batchResult); } + return batchResults.flat(); } - else if (instanceType === 'array') { - if ($maxItems !== undefined && instance.length > $maxItems) { - errors.push({ - instanceLocation, - keyword: 'maxItems', - keywordLocation: `${schemaLocation}/maxItems`, - error: `Array has too many items (${instance.length} > ${$maxItems}).` - }); + async stream(input, options) { + const { key, input: actualInput } = input; + const runnable = this.runnables[key]; + if (runnable === undefined) { + throw new Error(`No runnable associated with key "${key}".`); } - if ($minItems !== undefined && instance.length < $minItems) { - errors.push({ - instanceLocation, - keyword: 'minItems', - keywordLocation: `${schemaLocation}/minItems`, - error: `Array has too few items (${instance.length} < ${$minItems}).` - }); + return runnable.stream(actualInput, options); + } +} + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/branch.js + + + +/** + * Class that represents a runnable branch. The RunnableBranch is + * initialized with an array of branches and a default branch. When invoked, + * it evaluates the condition of each branch in order and executes the + * corresponding branch if the condition is true. If none of the conditions + * are true, it executes the default branch. + * @example + * ```typescript + * const branch = RunnableBranch.from([ + * [ + * (x: { topic: string; question: string }) => + * x.topic.toLowerCase().includes("anthropic"), + * anthropicChain, + * ], + * [ + * (x: { topic: string; question: string }) => + * x.topic.toLowerCase().includes("langchain"), + * langChainChain, + * ], + * generalChain, + * ]); + * + * const fullChain = RunnableSequence.from([ + * { + * topic: classificationChain, + * question: (input: { question: string }) => input.question, + * }, + * branch, + * ]); + * + * const result = await fullChain.invoke({ + * question: "how do I use LangChain?", + * }); + * ``` + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +class RunnableBranch extends Runnable { + static lc_name() { + return "RunnableBranch"; + } + constructor(fields) { + super(fields); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain_core", "runnables"] + }); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "default", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "branches", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.branches = fields.branches; + this.default = fields.default; + } + /** + * Convenience method for instantiating a RunnableBranch from + * RunnableLikes (objects, functions, or Runnables). + * + * Each item in the input except for the last one should be a + * tuple with two items. The first is a "condition" RunnableLike that + * returns "true" if the second RunnableLike in the tuple should run. + * + * The final item in the input should be a RunnableLike that acts as a + * default branch if no other branches match. + * + * @example + * ```ts + * import { RunnableBranch } from "@langchain/core/runnables"; + * + * const branch = RunnableBranch.from([ + * [(x: number) => x > 0, (x: number) => x + 1], + * [(x: number) => x < 0, (x: number) => x - 1], + * (x: number) => x + * ]); + * ``` + * @param branches An array where the every item except the last is a tuple of [condition, runnable] + * pairs. The last item is a default runnable which is invoked if no other condition matches. + * @returns A new RunnableBranch. + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + static from(branches) { + if (branches.length < 1) { + throw new Error("RunnableBranch requires at least one branch"); } - const length = instance.length; - let i = 0; - let stop = false; - if ($prefixItems !== undefined) { - const keywordLocation = `${schemaLocation}/prefixItems`; - const length2 = Math.min($prefixItems.length, length); - for (; i < length2; i++) { - const result = validate_validate(instance[i], $prefixItems[i], draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, `${keywordLocation}/${i}`); - evaluated[i] = true; - if (!result.valid) { - stop = shortCircuit; - errors.push({ - instanceLocation, - keyword: 'prefixItems', - keywordLocation, - error: `Items did not match schema.` - }, ...result.errors); - if (stop) - break; - } + const branchLikes = branches.slice(0, -1); + const coercedBranches = branchLikes.map(([condition, runnable]) => [ + _coerceToRunnable(condition), + _coerceToRunnable(runnable), + ]); + const defaultBranch = _coerceToRunnable(branches[branches.length - 1]); + return new this({ + branches: coercedBranches, + default: defaultBranch, + }); + } + async _invoke(input, config, runManager) { + let result; + for (let i = 0; i < this.branches.length; i += 1) { + const [condition, branchRunnable] = this.branches[i]; + const conditionValue = await condition.invoke(input, patchConfig(config, { + callbacks: runManager?.getChild(`condition:${i + 1}`), + })); + if (conditionValue) { + result = await branchRunnable.invoke(input, patchConfig(config, { + callbacks: runManager?.getChild(`branch:${i + 1}`), + })); + break; } } - if ($items !== undefined) { - const keywordLocation = `${schemaLocation}/items`; - if (Array.isArray($items)) { - const length2 = Math.min($items.length, length); - for (; i < length2; i++) { - const result = validate_validate(instance[i], $items[i], draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, `${keywordLocation}/${i}`); - evaluated[i] = true; - if (!result.valid) { - stop = shortCircuit; - errors.push({ - instanceLocation, - keyword: 'items', - keywordLocation, - error: `Items did not match schema.` - }, ...result.errors); - if (stop) - break; - } - } - } - else { - for (; i < length; i++) { - const result = validate_validate(instance[i], $items, draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, keywordLocation); - evaluated[i] = true; - if (!result.valid) { - stop = shortCircuit; - errors.push({ - instanceLocation, - keyword: 'items', - keywordLocation, - error: `Items did not match schema.` - }, ...result.errors); - if (stop) - break; + if (!result) { + result = await this.default.invoke(input, patchConfig(config, { + callbacks: runManager?.getChild("branch:default"), + })); + } + return result; + } + async invoke(input, config = {}) { + return this._callWithConfig(this._invoke, input, config); + } + async *_streamIterator(input, config) { + const callbackManager_ = await getCallbackManagerForConfig(config); + const runManager = await callbackManager_?.handleChainStart(this.toJSON(), base_coerceToDict(input, "input"), config?.runId, undefined, undefined, undefined, config?.runName); + let finalOutput; + let finalOutputSupported = true; + let stream; + try { + for (let i = 0; i < this.branches.length; i += 1) { + const [condition, branchRunnable] = this.branches[i]; + const conditionValue = await condition.invoke(input, patchConfig(config, { + callbacks: runManager?.getChild(`condition:${i + 1}`), + })); + if (conditionValue) { + stream = await branchRunnable.stream(input, patchConfig(config, { + callbacks: runManager?.getChild(`branch:${i + 1}`), + })); + for await (const chunk of stream) { + yield chunk; + if (finalOutputSupported) { + if (finalOutput === undefined) { + finalOutput = chunk; + } + else { + try { + finalOutput = concat(finalOutput, chunk); + } + catch (e) { + finalOutput = undefined; + finalOutputSupported = false; + } + } + } } + break; } } - if (!stop && $additionalItems !== undefined) { - const keywordLocation = `${schemaLocation}/additionalItems`; - for (; i < length; i++) { - const result = validate_validate(instance[i], $additionalItems, draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, keywordLocation); - evaluated[i] = true; - if (!result.valid) { - stop = shortCircuit; - errors.push({ - instanceLocation, - keyword: 'additionalItems', - keywordLocation, - error: `Items did not match additional items schema.` - }, ...result.errors); + if (stream === undefined) { + stream = await this.default.stream(input, patchConfig(config, { + callbacks: runManager?.getChild("branch:default"), + })); + for await (const chunk of stream) { + yield chunk; + if (finalOutputSupported) { + if (finalOutput === undefined) { + finalOutput = chunk; + } + else { + try { + finalOutput = concat(finalOutput, chunk); + } + catch (e) { + finalOutput = undefined; + finalOutputSupported = false; + } + } } } } } - if ($contains !== undefined) { - if (length === 0 && $minContains === undefined) { - errors.push({ - instanceLocation, - keyword: 'contains', - keywordLocation: `${schemaLocation}/contains`, - error: `Array is empty. It must contain at least one item matching the schema.` - }); - } - else if ($minContains !== undefined && length < $minContains) { - errors.push({ - instanceLocation, - keyword: 'minContains', - keywordLocation: `${schemaLocation}/minContains`, - error: `Array has less items (${length}) than minContains (${$minContains}).` - }); - } - else { - const keywordLocation = `${schemaLocation}/contains`; - const errorsLength = errors.length; - let contained = 0; - for (let j = 0; j < length; j++) { - const result = validate_validate(instance[j], $contains, draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${j}`, keywordLocation); - if (result.valid) { - evaluated[j] = true; - contained++; - } - else { - errors.push(...result.errors); - } - } - if (contained >= ($minContains || 0)) { - errors.length = errorsLength; - } - if ($minContains === undefined && - $maxContains === undefined && - contained === 0) { - errors.splice(errorsLength, 0, { - instanceLocation, - keyword: 'contains', - keywordLocation, - error: `Array does not contain item matching schema.` - }); - } - else if ($minContains !== undefined && contained < $minContains) { - errors.push({ - instanceLocation, - keyword: 'minContains', - keywordLocation: `${schemaLocation}/minContains`, - error: `Array must contain at least ${$minContains} items matching schema. Only ${contained} items were found.` - }); - } - else if ($maxContains !== undefined && contained > $maxContains) { - errors.push({ - instanceLocation, - keyword: 'maxContains', - keywordLocation: `${schemaLocation}/maxContains`, - error: `Array may contain at most ${$maxContains} items matching schema. ${contained} items were found.` - }); - } - } + catch (e) { + await runManager?.handleChainError(e); + throw e; } - if (!stop && $unevaluatedItems !== undefined) { - const keywordLocation = `${schemaLocation}/unevaluatedItems`; - for (i; i < length; i++) { - if (evaluated[i]) { - continue; - } - const result = validate_validate(instance[i], $unevaluatedItems, draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, keywordLocation); - evaluated[i] = true; - if (!result.valid) { - errors.push({ - instanceLocation, - keyword: 'unevaluatedItems', - keywordLocation, - error: `Items did not match unevaluated items schema.` - }, ...result.errors); - } - } + await runManager?.handleChainEnd(finalOutput ?? {}); + } +} + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/history.js + + + +/** + * Wraps a LCEL chain and manages history. It appends input messages + * and chain outputs as history, and adds the current history messages to + * the chain input. + * @example + * ```typescript + * // yarn add @langchain/anthropic @langchain/community @upstash/redis + * + * import { + * ChatPromptTemplate, + * MessagesPlaceholder, + * } from "@langchain/core/prompts"; + * import { ChatAnthropic } from "@langchain/anthropic"; + * import { UpstashRedisChatMessageHistory } from "@langchain/community/stores/message/upstash_redis"; + * // For demos, you can also use an in-memory store: + * // import { ChatMessageHistory } from "langchain/stores/message/in_memory"; + * + * const prompt = ChatPromptTemplate.fromMessages([ + * ["system", "You're an assistant who's good at {ability}"], + * new MessagesPlaceholder("history"), + * ["human", "{question}"], + * ]); + * + * const chain = prompt.pipe(new ChatAnthropic({})); + * + * const chainWithHistory = new RunnableWithMessageHistory({ + * runnable: chain, + * getMessageHistory: (sessionId) => + * new UpstashRedisChatMessageHistory({ + * sessionId, + * config: { + * url: process.env.UPSTASH_REDIS_REST_URL!, + * token: process.env.UPSTASH_REDIS_REST_TOKEN!, + * }, + * }), + * inputMessagesKey: "question", + * historyMessagesKey: "history", + * }); + * + * const result = await chainWithHistory.invoke( + * { + * ability: "math", + * question: "What does cosine mean?", + * }, + * { + * configurable: { + * sessionId: "some_string_identifying_a_user", + * }, + * } + * ); + * + * const result2 = await chainWithHistory.invoke( + * { + * ability: "math", + * question: "What's its inverse?", + * }, + * { + * configurable: { + * sessionId: "some_string_identifying_a_user", + * }, + * } + * ); + * ``` + */ +class RunnableWithMessageHistory extends RunnableBinding { + constructor(fields) { + let historyChain = base_RunnableLambda.from((input, options) => this._enterHistory(input, options ?? {})).withConfig({ runName: "loadHistory" }); + const messagesKey = fields.historyMessagesKey ?? fields.inputMessagesKey; + if (messagesKey) { + historyChain = RunnablePassthrough.assign({ + [messagesKey]: historyChain, + }).withConfig({ runName: "insertHistory" }); } - if ($uniqueItems) { - for (let j = 0; j < length; j++) { - const a = instance[j]; - const ao = typeof a === 'object' && a !== null; - for (let k = 0; k < length; k++) { - if (j === k) { - continue; - } - const b = instance[k]; - const bo = typeof b === 'object' && b !== null; - if (a === b || (ao && bo && deepCompareStrict(a, b))) { - errors.push({ - instanceLocation, - keyword: 'uniqueItems', - keywordLocation: `${schemaLocation}/uniqueItems`, - error: `Duplicate items at indexes ${j} and ${k}.` - }); - j = Number.MAX_SAFE_INTEGER; - k = Number.MAX_SAFE_INTEGER; - } - } + const bound = historyChain + .pipe(fields.runnable.withListeners({ + onEnd: (run, config) => this._exitHistory(run, config ?? {}), + })) + .withConfig({ runName: "RunnableWithMessageHistory" }); + const config = fields.config ?? {}; + super({ + ...fields, + config, + bound, + }); + Object.defineProperty(this, "runnable", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "inputMessagesKey", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "outputMessagesKey", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "historyMessagesKey", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "getMessageHistory", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.runnable = fields.runnable; + this.getMessageHistory = fields.getMessageHistory; + this.inputMessagesKey = fields.inputMessagesKey; + this.outputMessagesKey = fields.outputMessagesKey; + this.historyMessagesKey = fields.historyMessagesKey; + } + _getInputMessages( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + inputValue) { + let parsedInputValue; + if (typeof inputValue === "object" && + !Array.isArray(inputValue) && + !isBaseMessage(inputValue)) { + let key; + if (this.inputMessagesKey) { + key = this.inputMessagesKey; } - } - } - else if (instanceType === 'number') { - if (draft === '4') { - if ($minimum !== undefined && - (($exclusiveMinimum === true && instance <= $minimum) || - instance < $minimum)) { - errors.push({ - instanceLocation, - keyword: 'minimum', - keywordLocation: `${schemaLocation}/minimum`, - error: `${instance} is less than ${$exclusiveMinimum ? 'or equal to ' : ''} ${$minimum}.` - }); + else if (Object.keys(inputValue).length === 1) { + key = Object.keys(inputValue)[0]; } - if ($maximum !== undefined && - (($exclusiveMaximum === true && instance >= $maximum) || - instance > $maximum)) { - errors.push({ - instanceLocation, - keyword: 'maximum', - keywordLocation: `${schemaLocation}/maximum`, - error: `${instance} is greater than ${$exclusiveMaximum ? 'or equal to ' : ''} ${$maximum}.` - }); + else { + key = "input"; + } + if (Array.isArray(inputValue[key]) && Array.isArray(inputValue[key][0])) { + parsedInputValue = inputValue[key][0]; + } + else { + parsedInputValue = inputValue[key]; } } else { - if ($minimum !== undefined && instance < $minimum) { - errors.push({ - instanceLocation, - keyword: 'minimum', - keywordLocation: `${schemaLocation}/minimum`, - error: `${instance} is less than ${$minimum}.` - }); + parsedInputValue = inputValue; + } + if (typeof parsedInputValue === "string") { + return [new human_HumanMessage(parsedInputValue)]; + } + else if (Array.isArray(parsedInputValue)) { + return parsedInputValue; + } + else if (isBaseMessage(parsedInputValue)) { + return [parsedInputValue]; + } + else { + throw new Error(`Expected a string, BaseMessage, or array of BaseMessages.\nGot ${JSON.stringify(parsedInputValue, null, 2)}`); + } + } + _getOutputMessages( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + outputValue) { + let parsedOutputValue; + if (!Array.isArray(outputValue) && + !isBaseMessage(outputValue) && + typeof outputValue !== "string") { + let key; + if (this.outputMessagesKey !== undefined) { + key = this.outputMessagesKey; } - if ($maximum !== undefined && instance > $maximum) { - errors.push({ - instanceLocation, - keyword: 'maximum', - keywordLocation: `${schemaLocation}/maximum`, - error: `${instance} is greater than ${$maximum}.` - }); + else if (Object.keys(outputValue).length === 1) { + key = Object.keys(outputValue)[0]; } - if ($exclusiveMinimum !== undefined && instance <= $exclusiveMinimum) { - errors.push({ - instanceLocation, - keyword: 'exclusiveMinimum', - keywordLocation: `${schemaLocation}/exclusiveMinimum`, - error: `${instance} is less than ${$exclusiveMinimum}.` - }); + else { + key = "output"; } - if ($exclusiveMaximum !== undefined && instance >= $exclusiveMaximum) { - errors.push({ - instanceLocation, - keyword: 'exclusiveMaximum', - keywordLocation: `${schemaLocation}/exclusiveMaximum`, - error: `${instance} is greater than or equal to ${$exclusiveMaximum}.` - }); + // If you are wrapping a chat model directly + // The output is actually this weird generations object + if (outputValue.generations !== undefined) { + parsedOutputValue = outputValue.generations[0][0].message; } - } - if ($multipleOf !== undefined) { - const remainder = instance % $multipleOf; - if (Math.abs(0 - remainder) >= 1.1920929e-7 && - Math.abs($multipleOf - remainder) >= 1.1920929e-7) { - errors.push({ - instanceLocation, - keyword: 'multipleOf', - keywordLocation: `${schemaLocation}/multipleOf`, - error: `${instance} is not a multiple of ${$multipleOf}.` - }); + else { + parsedOutputValue = outputValue[key]; } } - } - else if (instanceType === 'string') { - const length = $minLength === undefined && $maxLength === undefined - ? 0 - : ucs2length(instance); - if ($minLength !== undefined && length < $minLength) { - errors.push({ - instanceLocation, - keyword: 'minLength', - keywordLocation: `${schemaLocation}/minLength`, - error: `String is too short (${length} < ${$minLength}).` - }); + else { + parsedOutputValue = outputValue; } - if ($maxLength !== undefined && length > $maxLength) { - errors.push({ - instanceLocation, - keyword: 'maxLength', - keywordLocation: `${schemaLocation}/maxLength`, - error: `String is too long (${length} > ${$maxLength}).` - }); + if (typeof parsedOutputValue === "string") { + return [new ai_AIMessage(parsedOutputValue)]; } - if ($pattern !== undefined && !new RegExp($pattern, 'u').test(instance)) { - errors.push({ - instanceLocation, - keyword: 'pattern', - keywordLocation: `${schemaLocation}/pattern`, - error: `String does not match pattern.` - }); + else if (Array.isArray(parsedOutputValue)) { + return parsedOutputValue; } - if ($format !== undefined && - fastFormat[$format] && - !fastFormat[$format](instance)) { - errors.push({ - instanceLocation, - keyword: 'format', - keywordLocation: `${schemaLocation}/format`, - error: `String does not match format "${$format}".` - }); + else if (isBaseMessage(parsedOutputValue)) { + return [parsedOutputValue]; + } + else { + throw new Error(`Expected a string, BaseMessage, or array of BaseMessages. Received: ${JSON.stringify(parsedOutputValue, null, 2)}`); } } - return { valid: errors.length === 0, errors }; -} - -;// CONCATENATED MODULE: ./node_modules/@cfworker/json-schema/dist/esm/validator.js - - -class Validator { - schema; - draft; - shortCircuit; - lookup; - constructor(schema, draft = '2019-09', shortCircuit = true) { - this.schema = schema; - this.draft = draft; - this.shortCircuit = shortCircuit; - this.lookup = dereference(schema); + async _enterHistory( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + input, kwargs) { + const history = kwargs?.configurable?.messageHistory; + const messages = await history.getMessages(); + if (this.historyMessagesKey === undefined) { + return messages.concat(this._getInputMessages(input)); + } + return messages; } - validate(instance) { - return validate(instance, this.schema, this.draft, this.lookup, this.shortCircuit); + async _exitHistory(run, config) { + const history = config.configurable?.messageHistory; + // Get input messages + let inputs; + // Chat model inputs are nested arrays + if (Array.isArray(run.inputs) && Array.isArray(run.inputs[0])) { + inputs = run.inputs[0]; + } + else { + inputs = run.inputs; + } + let inputMessages = this._getInputMessages(inputs); + // If historic messages were prepended to the input messages, remove them to + // avoid adding duplicate messages to history. + if (this.historyMessagesKey === undefined) { + const existingMessages = await history.getMessages(); + inputMessages = inputMessages.slice(existingMessages.length); + } + // Get output messages + const outputValue = run.outputs; + if (!outputValue) { + throw new Error(`Output values from 'Run' undefined. Run: ${JSON.stringify(run, null, 2)}`); + } + const outputMessages = this._getOutputMessages(outputValue); + await history.addMessages([...inputMessages, ...outputMessages]); } - addSchema(schema, id) { - if (id) { - schema = { ...schema, $id: id }; + async _mergeConfig(...configs) { + const config = await super._mergeConfig(...configs); + // Extract sessionId + if (!config.configurable || !config.configurable.sessionId) { + const exampleInput = { + [this.inputMessagesKey ?? "input"]: "foo", + }; + const exampleConfig = { configurable: { sessionId: "123" } }; + throw new Error(`sessionId is required. Pass it in as part of the config argument to .invoke() or .stream()\n` + + `eg. chain.invoke(${JSON.stringify(exampleInput)}, ${JSON.stringify(exampleConfig)})`); } - dereference(schema, this.lookup); + // attach messageHistory + const { sessionId } = config.configurable; + config.configurable.messageHistory = await this.getMessageHistory(sessionId); + return config; } } -;// CONCATENATED MODULE: ./node_modules/@cfworker/json-schema/dist/esm/index.js +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/index.js + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/output_parsers/base.js +/** + * Abstract base class for parsing the output of a Large Language Model + * (LLM) call. It provides methods for parsing the result of an LLM call + * and invoking the parser with a given input. + */ +class BaseLLMOutputParser extends Runnable { + /** + * Parses the result of an LLM call with a given prompt. By default, it + * simply calls `parseResult`. + * @param generations The generations from an LLM call. + * @param _prompt The prompt used in the LLM call. + * @param callbacks Optional callbacks. + * @returns A promise of the parsed output. + */ + parseResultWithPrompt(generations, _prompt, callbacks) { + return this.parseResult(generations, callbacks); + } + _baseMessageToString(message) { + return typeof message.content === "string" + ? message.content + : this._baseMessageContentToString(message.content); + } + _baseMessageContentToString(content) { + return JSON.stringify(content); + } + /** + * Calls the parser with a given input and optional configuration options. + * If the input is a string, it creates a generation with the input as + * text and calls `parseResult`. If the input is a `BaseMessage`, it + * creates a generation with the input as a message and the content of the + * input as text, and then calls `parseResult`. + * @param input The input to the parser, which can be a string or a `BaseMessage`. + * @param options Optional configuration options. + * @returns A promise of the parsed output. + */ + async invoke(input, options) { + if (typeof input === "string") { + return this._callWithConfig(async (input, options) => this.parseResult([{ text: input }], options?.callbacks), input, { ...options, runType: "parser" }); + } + else { + return this._callWithConfig(async (input, options) => this.parseResult([ + { + message: input, + text: this._baseMessageToString(input), + }, + ], options?.callbacks), input, { ...options, runType: "parser" }); + } + } +} +/** + * Class to parse the output of an LLM call. + */ +class BaseOutputParser extends BaseLLMOutputParser { + parseResult(generations, callbacks) { + return this.parse(generations[0].text, callbacks); + } + async parseWithPrompt(text, _prompt, callbacks) { + return this.parse(text, callbacks); + } + /** + * Return the string type key uniquely identifying this class of parser + */ + _type() { + throw new Error("_type not implemented"); + } +} +/** + * Exception that output parsers should raise to signify a parsing error. + * + * This exists to differentiate parsing errors from other code or execution errors + * that also may arise inside the output parser. OutputParserExceptions will be + * available to catch and handle in ways to fix the parsing error, while other + * errors will be raised. + * + * @param message - The error that's being re-raised or an error message. + * @param llmOutput - String model output which is error-ing. + * @param observation - String explanation of error which can be passed to a + * model to try and remediate the issue. + * @param sendToLLM - Whether to send the observation and llm_output back to an Agent + * after an OutputParserException has been raised. This gives the underlying + * model driving the agent the context that the previous output was improperly + * structured, in the hopes that it will update the output to the correct + * format. + */ +class OutputParserException extends Error { + constructor(message, llmOutput, observation, sendToLLM = false) { + super(message); + Object.defineProperty(this, "llmOutput", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "observation", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "sendToLLM", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.llmOutput = llmOutput; + this.observation = observation; + this.sendToLLM = sendToLLM; + if (sendToLLM) { + if (observation === undefined || llmOutput === undefined) { + throw new Error("Arguments 'observation' & 'llmOutput' are required if 'sendToLlm' is true"); + } + } + addLangChainErrorFields(this, "OUTPUT_PARSING_FAILURE"); + } +} ;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/output_parsers/transform.js @@ -105338,7 +111674,7 @@ class MarkdownListOutputParser extends ListOutputParser { * * const chain = RunnableSequence.from([ * promptTemplate, - * new ChatOpenAI({}), + * new ChatOpenAI({ model: "gpt-4o-mini" }), * new StringOutputParser(), * ]); * @@ -105414,6 +111750,7 @@ class StringOutputParser extends BaseTransformOutputParser { + class StructuredOutputParser extends BaseOutputParser { static lc_name() { return "StructuredOutputParser"; @@ -105451,7 +111788,7 @@ class StructuredOutputParser extends BaseOutputParser { * @returns A new instance of StructuredOutputParser. */ static fromNamesAndDescriptions(schemas) { - const zodSchema = z.object(Object.fromEntries(Object.entries(schemas).map(([name, description]) => [name, z.string().describe(description)]))); + const zodSchema = objectType(Object.fromEntries(Object.entries(schemas).map(([name, description]) => [name, stringType().describe(description)]))); return new this(zodSchema); } /** @@ -105473,7 +111810,7 @@ Your output will be parsed and type-checked according to the provided schema ins Here is the JSON Schema instance your output must adhere to. Include the enclosing markdown codeblock: \`\`\`json -${JSON.stringify(zodToJsonSchema_zodToJsonSchema(this.schema))} +${JSON.stringify(json_schema_toJsonSchema(this.schema))} \`\`\` `; } @@ -105493,7 +111830,7 @@ ${JSON.stringify(zodToJsonSchema_zodToJsonSchema(this.schema))} return `"${escapedInsideQuotes}"`; }) .replace(/\n/g, ""); - return await this.schema.parseAsync(JSON.parse(escapedJson)); + return await interopParseAsync(this.schema, JSON.parse(escapedJson)); } catch (e) { throw new OutputParserException(`Failed to parse. Text: "${text}". Error: ${e}`, text); @@ -105513,7 +111850,7 @@ class JsonMarkdownStructuredOutputParser extends StructuredOutputParser { if (interpolationDepth < 1) { throw new Error("f string interpolation depth must be at least 1"); } - return `Return a markdown code snippet with a JSON object formatted to look like:\n\`\`\`json\n${this._schemaToInstruction(zodToJsonSchema_zodToJsonSchema(this.schema)) + return `Return a markdown code snippet with a JSON object formatted to look like:\n\`\`\`json\n${this._schemaToInstruction(json_schema_toJsonSchema(this.schema)) .replaceAll("{", "{".repeat(interpolationDepth)) .replaceAll("}", "}".repeat(interpolationDepth))}\n\`\`\``; } @@ -105568,7 +111905,7 @@ class JsonMarkdownStructuredOutputParser extends StructuredOutputParser { return new this(schema); } static fromNamesAndDescriptions(schemas) { - const zodSchema = z.object(Object.fromEntries(Object.entries(schemas).map(([name, description]) => [name, z.string().describe(description)]))); + const zodSchema = objectType(Object.fromEntries(Object.entries(schemas).map(([name, description]) => [name, stringType().describe(description)]))); return new this(zodSchema); } } @@ -105936,41 +112273,41 @@ const initializeSax = function () { } var S = 0; sax.STATE = { - BEGIN: S++, - BEGIN_WHITESPACE: S++, - TEXT: S++, - TEXT_ENTITY: S++, - OPEN_WAKA: S++, - SGML_DECL: S++, - SGML_DECL_QUOTED: S++, - DOCTYPE: S++, - DOCTYPE_QUOTED: S++, - DOCTYPE_DTD: S++, - DOCTYPE_DTD_QUOTED: S++, - COMMENT_STARTING: S++, - COMMENT: S++, - COMMENT_ENDING: S++, - COMMENT_ENDED: S++, - CDATA: S++, - CDATA_ENDING: S++, - CDATA_ENDING_2: S++, - PROC_INST: S++, - PROC_INST_BODY: S++, - PROC_INST_ENDING: S++, - OPEN_TAG: S++, - OPEN_TAG_SLASH: S++, - ATTRIB: S++, - ATTRIB_NAME: S++, - ATTRIB_NAME_SAW_WHITE: S++, - ATTRIB_VALUE: S++, - ATTRIB_VALUE_QUOTED: S++, - ATTRIB_VALUE_CLOSED: S++, - ATTRIB_VALUE_UNQUOTED: S++, - ATTRIB_VALUE_ENTITY_Q: S++, - ATTRIB_VALUE_ENTITY_U: S++, - CLOSE_TAG: S++, - CLOSE_TAG_SAW_WHITE: S++, - SCRIPT: S++, + BEGIN: S++, // leading byte order mark or whitespace + BEGIN_WHITESPACE: S++, // leading whitespace + TEXT: S++, // general stuff + TEXT_ENTITY: S++, // & and such. + OPEN_WAKA: S++, // < + SGML_DECL: S++, // + SCRIPT: S++, //