module.exports=[190949,e=>{"use strict";var t=Object.defineProperty;e.s(["__exportAll",0,(e,r)=>{let a={};for(var n in e)t(a,n,{get:e[n],enumerable:!0});return r||t(a,Symbol.toStringTag,{value:"Module"}),a}])},869065,e=>{"use strict";var t=e.i(190949);let r=function e(t){let r=Symbol.for(t);return{brand(e,a){let n=a?Symbol.for(`${t}.${a}`):r;class i extends e{[n]=!0;constructor(...e){super(...e)}static isInstance(e){return"object"==typeof e&&null!==e&&n in e&&!0===e[n]}}return Object.defineProperty(i,"name",{value:e.name}),i},sub:r=>e(`${t}.${r}`),isInstance:e=>"object"==typeof e&&null!==e&&r in e&&!0===e[r]}}("langchain");var a=(0,t.__exportAll)({ContextOverflowError:()=>l,LangChainError:()=>s,ModelAbortError:()=>o,addLangChainErrorFields:()=>n,ns:()=>i});function n(e,t){return e.lc_error_code=t,e.message=`${e.message} Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${t}/ `,e}let i=r.sub("error");var s=class extends i.brand(Error){name="LangChainError";constructor(e){super(e),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}},o=class extends i.brand(s,"model-abort"){name="ModelAbortError";partialOutput;constructor(e,t){super(e),this.partialOutput=t}},l=class e extends i.brand(s,"context-overflow"){name="ContextOverflowError";cause;constructor(e){super(e??"Input exceeded the model's context window.")}static fromError(t){let r=new e(t.message);return r.cause=t,r}};e.s(["ContextOverflowError",0,l,"ModelAbortError",0,o,"addLangChainErrorFields",0,n,"errors_exports",0,a],869065)},507577,e=>{"use strict";function t(e){return"object"==typeof e&&null!==e&&"type"in e&&"string"==typeof e.type&&"source_type"in e&&("url"===e.source_type||"base64"===e.source_type||"text"===e.source_type||"id"===e.source_type)}e.s(["convertToOpenAIImageBlock",0,function(e){if(t(e)){if("url"===e.source_type)return{type:"image_url",image_url:{url:e.url}};if("base64"===e.source_type){if(!e.mime_type)throw Error("mime_type key is required for base64 data.");return{type:"image_url",image_url:{url:`data:${e.mime_type};base64,${e.data}`}}}}throw Error("Unsupported source type. Only 'url' and 'base64' are supported.")},"convertToProviderContentBlock",0,function(e,t){if("text"===e.type){if(!t.fromStandardTextBlock)throw Error(`Converter for ${t.providerName} does not implement \`fromStandardTextBlock\` method.`);return t.fromStandardTextBlock(e)}if("image"===e.type){if(!t.fromStandardImageBlock)throw Error(`Converter for ${t.providerName} does not implement \`fromStandardImageBlock\` method.`);return t.fromStandardImageBlock(e)}if("audio"===e.type){if(!t.fromStandardAudioBlock)throw Error(`Converter for ${t.providerName} does not implement \`fromStandardAudioBlock\` method.`);return t.fromStandardAudioBlock(e)}if("file"===e.type){if(!t.fromStandardFileBlock)throw Error(`Converter for ${t.providerName} does not implement \`fromStandardFileBlock\` method.`);return t.fromStandardFileBlock(e)}throw Error(`Unable to convert content block type '${e.type}' to provider-specific format: not recognized.`)},"isBase64ContentBlock",0,function(e){return t(e)&&"base64"===e.source_type&&"data"in e&&"string"==typeof e.data},"isDataContentBlock",0,t,"isIDContentBlock",0,function(e){return t(e)&&"id"===e.source_type&&"id"in e&&"string"==typeof e.id},"isPlainTextContentBlock",0,function(e){return t(e)&&"text"===e.source_type&&"text"in e&&"string"==typeof e.text},"isURLContentBlock",0,function(e){return t(e)&&"url"===e.source_type&&"url"in e&&"string"==typeof e.url},"parseBase64DataUrl",0,function({dataUrl:e,asTypedArray:t=!1}){let r=e.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/);if(r)return{mime_type:r[1].toLowerCase(),data:t?Uint8Array.from(atob(r[2]),e=>e.charCodeAt(0)):r[2]}},"parseMimeType",0,function(e){let t=e.split(";")[0].split("/");if(2!==t.length)throw Error(`Invalid mime type: "${e}" - does not match type/subtype format.`);let r=t[0].trim(),a=t[1].trim();if(""===r||""===a)throw Error(`Invalid mime type: "${e}" - type or subtype is empty.`);let n={};for(let t of e.split(";").slice(1)){let r=t.split("=");if(2!==r.length)throw Error(`Invalid parameter syntax in mime type: "${e}".`);let a=r[0].trim(),i=r[1].trim();if(""===a)throw Error(`Invalid parameter syntax in mime type: "${e}".`);n[a]=i}return{type:r,subtype:a,parameters:n}}])},403929,e=>{"use strict";e.s(["isMessage",0,function(e){return"object"==typeof e&&null!==e&&"type"in e&&"content"in e&&("string"==typeof e.content||Array.isArray(e.content))}])},283285,(e,t,r)=>{"use strict";t.exports=function(e,t){if("string"!=typeof e)throw TypeError("Expected a string");return t=void 0===t?"_":t,e.replace(/([a-z\d])([A-Z])/g,"$1"+t+"$2").replace(/([A-Z]+)([A-Z][a-z\d]+)/g,"$1"+t+"$2").toLowerCase()}},94380,(e,t,r)=>{"use strict";let a=/[\p{Lu}]/u,n=/[\p{Ll}]/u,i=/^[\p{Lu}](?![\p{Lu}])/gu,s=/([\p{Alpha}\p{N}_]|$)/u,o=/[_.\- ]+/,l=RegExp("^"+o.source),u=RegExp(o.source+s.source,"gu"),d=RegExp("\\d+"+s.source,"gu"),c=(e,t)=>{var r,s;if(!("string"==typeof e||Array.isArray(e)))throw TypeError("Expected the input to be `string | string[]`");if(t={pascalCase:!1,preserveConsecutiveUppercase:!1,...t},0===(e=Array.isArray(e)?e.map(e=>e.trim()).filter(e=>e.length).join("-"):e.trim()).length)return"";let o=!1===t.locale?e=>e.toLowerCase():e=>e.toLocaleLowerCase(t.locale),c=!1===t.locale?e=>e.toUpperCase():e=>e.toLocaleUpperCase(t.locale);return 1===e.length?t.pascalCase?c(e):o(e):((e!==o(e)&&(e=((e,t,r)=>{let i=!1,s=!1,o=!1;for(let l=0;lo(e))):e=o(e),t.pascalCase&&(e=c(e.charAt(0))+e.slice(1)),s=e,u.lastIndex=0,d.lastIndex=0,s.replace(u,(e,t)=>c(t)).replace(d,e=>c(e)))};t.exports=c,t.exports.default=c},756740,473247,72110,e=>{"use strict";var t=e.i(190949),r=e.i(283285),a=e.i(94380);function n(e,t){return t?.[e]||(0,r.default)(e)}function i(e,t,r){let a={};for(let n in e)Object.hasOwn(e,n)&&(a[t(n,r)]=e[n]);return a}e.s(["keyFromJson",0,function(e,t){return t?.[e]||(0,a.default)(e)},"keyToJson",0,n,"mapKeys",0,i],473247);let s="__lc_escaped__";function o(e){return 1===Object.keys(e).length&&"__lc_escaped__"in e}function l(e,t=new WeakSet){if(null!==e&&"object"==typeof e&&!Array.isArray(e)){if(t.has(e))return{lc:1,type:"not_implemented",id:null!==e&&"object"==typeof e?"lc_id"in e&&Array.isArray(e.lc_id)?e.lc_id:[e.constructor?.name??"Object"]:[typeof e]};if(null!==e&&"object"==typeof e&&"lc_serializable"in e&&"function"==typeof e.toJSON)return e;if(t.add(e),"lc"in e||1===Object.keys(e).length&&"__lc_escaped__"in e)return t.delete(e),{[s]:e};let r={};for(let[a,n]of Object.entries(e))r[a]=l(n,t);return t.delete(e),r}return Array.isArray(e)?e.map(e=>l(e,t)):e}e.s(["escapeIfNeeded",0,l,"isEscapedObject",0,o,"unescapeValue",0,function e(t){if(null!==t&&"object"==typeof t&&!Array.isArray(t)){if(o(t))return t[s];let r={};for(let[a,n]of Object.entries(t))r[a]=e(n);return r}return Array.isArray(t)?t.map(t=>e(t)):t}],72110);var u=(0,t.__exportAll)({Serializable:()=>h,get_lc_unique_name:()=>c});function d(e){return Array.isArray(e)?[...e]:{...e}}function c(e){let t=Object.getPrototypeOf(e);return"function"==typeof e.lc_name&&("function"!=typeof t.lc_name||e.lc_name()!==t.lc_name())?e.lc_name():e.name}var h=class e{lc_serializable=!1;lc_kwargs;static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,c(this.constructor)]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}constructor(e,...t){void 0!==this.lc_serializable_keys?this.lc_kwargs=Object.fromEntries(Object.entries(e||{}).filter(([e])=>this.lc_serializable_keys?.includes(e))):this.lc_kwargs=e??{}}toJSON(){if(!this.lc_serializable||this.lc_kwargs instanceof e||"object"!=typeof this.lc_kwargs||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();let t={},r={},a=Object.keys(this.lc_kwargs).reduce((e,t)=>(e[t]=t in this?this[t]:this.lc_kwargs[t],e),{});for(let e=Object.getPrototypeOf(this);e;e=Object.getPrototypeOf(e))Object.assign(t,Reflect.get(e,"lc_aliases",this)),Object.assign(r,Reflect.get(e,"lc_secrets",this)),Object.assign(a,Reflect.get(e,"lc_attributes",this));Object.keys(r).forEach(e=>{let t=this,r=a,[n,...i]=e.split(".").reverse();for(let e of i.reverse()){if(!(e in t)||void 0===t[e])return;e in r&&void 0!==r[e]||("object"==typeof t[e]&&null!=t[e]?r[e]={}:Array.isArray(t[e])&&(r[e]=[])),t=t[e],r=r[e]}n in t&&void 0!==t[n]&&(r[n]=r[n]||t[n])});let s={},o=new WeakSet;for(let[e,t]of(o.add(this),Object.entries(a)))s[e]=l(t,o);let u=i(Object.keys(r).length?function(e,t){let r=d(e);for(let[e,a]of Object.entries(t)){let[t,...n]=e.split(".").reverse(),i=r;for(let e of n.reverse()){if(void 0===i[e])break;i[e]=d(i[e]),i=i[e]}void 0!==i[t]&&(i[t]={lc:1,type:"secret",id:[a]})}return r}(s,r):s,n,t);return{lc:1,type:"constructor",id:this.lc_id,kwargs:u}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}};e.s(["Serializable",0,h,"get_lc_unique_name",0,c,"serializable_exports",0,u],756740)},703649,650284,864701,729082,e=>{"use strict";function t(e,t){return r(e)&&e.type===t}function r(e){return"object"==typeof e&&null!==e}function a(e){return Array.isArray(e)}function n(e){return"string"==typeof e}function i(e){return"number"==typeof e}function s(e){try{return JSON.parse(e)}catch{return}}let o=e=>e();function l(e){if(t(e,"document")&&r(e.source)&&"type"in e.source){if("base64"===e.source.type&&n(e.source.media_type)&&n(e.source.data))return{type:"file",mimeType:e.source.media_type,data:e.source.data};else if("url"===e.source.type&&n(e.source.url))return{type:"file",url:e.source.url};else if("file"===e.source.type&&n(e.source.file_id))return{type:"file",fileId:e.source.file_id};else if("text"===e.source.type&&n(e.source.data))return{type:"file",mimeType:String(e.source.media_type??"text/plain"),data:e.source.data}}else if(t(e,"image")&&r(e.source)&&"type"in e.source){if("base64"===e.source.type&&n(e.source.media_type)&&n(e.source.data))return{type:"image",mimeType:e.source.media_type,data:e.source.data};else if("url"===e.source.type&&n(e.source.url))return{type:"image",url:e.source.url};else if("file"===e.source.type&&n(e.source.file_id))return{type:"image",fileId:e.source.file_id}}}function u(e){return Array.from(function*(){for(let d of"string"==typeof e.content?[{type:"text",text:e.content}]:e.content){if(t(d,"text")&&n(d.text)){let{text:e,citations:t,...r}=d;if(a(t)&&t.length){let a=t.reduce((e,t)=>{let r=function(e){if("char_location"===e.type&&n(e.document_title)&&i(e.start_char_index)&&i(e.end_char_index)&&n(e.cited_text)){let{document_title:t,start_char_index:r,end_char_index:a,cited_text:n,...i}=e;return{...i,type:"citation",source:"char",title:t??void 0,startIndex:r,endIndex:a,citedText:n}}if("page_location"===e.type&&n(e.document_title)&&i(e.start_page_number)&&i(e.end_page_number)&&n(e.cited_text)){let{document_title:t,start_page_number:r,end_page_number:a,cited_text:n,...i}=e;return{...i,type:"citation",source:"page",title:t??void 0,startIndex:r,endIndex:a,citedText:n}}if("content_block_location"===e.type&&n(e.document_title)&&i(e.start_block_index)&&i(e.end_block_index)&&n(e.cited_text)){let{document_title:t,start_block_index:r,end_block_index:a,cited_text:n,...i}=e;return{...i,type:"citation",source:"block",title:t??void 0,startIndex:r,endIndex:a,citedText:n}}if("web_search_result_location"===e.type&&n(e.url)&&n(e.title)&&n(e.encrypted_index)&&n(e.cited_text)){let{url:t,title:r,encrypted_index:a,cited_text:n,...i}=e;return{...i,type:"citation",source:"url",url:t,title:r,startIndex:Number(a),endIndex:Number(a),citedText:n}}if("search_result_location"===e.type&&n(e.source)&&n(e.title)&&i(e.start_block_index)&&i(e.end_block_index)&&n(e.cited_text)){let{source:t,title:r,start_block_index:a,end_block_index:n,cited_text:i,...s}=e;return{...s,type:"citation",source:"search",url:t,title:r??void 0,startIndex:a,endIndex:n,citedText:i}}}(t);return r?[...e,r]:e},[]);yield{...r,type:"text",text:e,annotations:a};continue}yield{...r,type:"text",text:e};continue}if(t(d,"thinking")&&n(d.thinking)){let{thinking:e,signature:t,...r}=d;yield{...r,type:"reasoning",reasoning:e,signature:t};continue}if(t(d,"redacted_thinking")){yield{type:"non_standard",value:d};continue}else if(t(d,"tool_use")&&n(d.name)&&n(d.id)){yield{type:"tool_call",id:d.id,name:d.name,args:d.input};continue}else if(t(d,"input_json_delta")){var u;if(u=e,"function"==typeof u?._getType&&"function"==typeof u.concat&&"ai"===u._getType()&&e.tool_call_chunks?.length){let t=e.tool_call_chunks[0];yield{type:"tool_call_chunk",id:t.id,name:t.name,args:t.args,index:t.index};continue}}else if(t(d,"server_tool_use")&&n(d.name)&&n(d.id)){let{name:e,id:t}=d;if("web_search"===e){yield{id:t,type:"server_tool_call",name:"web_search",args:{query:o(()=>{if("string"==typeof d.input)return d.input;if(r(d.input)&&n(d.input.query))return d.input.query;if(n(d.partial_json)){let e=s(d.partial_json);if(e?.query)return e.query}return""})}};continue}if("code_execution"===d.name){yield{id:t,type:"server_tool_call",name:"code_execution",args:{code:o(()=>{if("string"==typeof d.input)return d.input;if(r(d.input)&&n(d.input.code))return d.input.code;if(n(d.partial_json)){let e=s(d.partial_json);if(e?.code)return e.code}return""})}};continue}}else if(t(d,"web_search_tool_result")&&n(d.tool_use_id)&&a(d.content)){let{content:e,tool_use_id:r}=d;yield{type:"server_tool_call_result",name:"web_search",toolCallId:r,status:"success",output:{urls:e.reduce((e,r)=>t(r,"web_search_result")?[...e,r.url]:e,[])}};continue}else if(t(d,"code_execution_tool_result")&&n(d.tool_use_id)&&r(d.content)){yield{type:"server_tool_call_result",name:"code_execution",toolCallId:d.tool_use_id,status:"success",output:d.content};continue}else if(t(d,"mcp_tool_use")){yield{id:d.id,type:"server_tool_call",name:"mcp_tool_use",args:d.input};continue}else if(t(d,"mcp_tool_result")&&n(d.tool_use_id)&&r(d.content)){yield{type:"server_tool_call_result",name:"mcp_tool_use",toolCallId:d.tool_use_id,status:"success",output:d.content};continue}else if(t(d,"container_upload")){yield{type:"server_tool_call",name:"container_upload",args:d.input};continue}else if(t(d,"search_result")){yield{id:d.id,type:"non_standard",value:d};continue}else if(t(d,"tool_result")){yield{id:d.id,type:"non_standard",value:d};continue}else{let e=l(d);if(e){yield e;continue}}yield{type:"non_standard",value:d}}}())}e.s(["_isArray",0,a,"_isBytesArray",0,function(e){return e instanceof Uint8Array},"_isContentBlock",0,t,"_isNumber",0,i,"_isObject",0,r,"_isString",0,n,"iife",0,o,"safeParseJson",0,s],650284),e.s(["ChatAnthropicTranslator",0,{translateContent:u,translateContentChunk:u},"convertToV1FromAnthropicInput",0,function(e){return Array.from(function*(){for(let t of e){let e=l(t);e?yield e:yield t}}())}],703649);var d=e.i(507577);function c(e){return(0,d.isURLContentBlock)(e)?{type:e.type,mimeType:e.mime_type,url:e.url,metadata:e.metadata}:(0,d.isBase64ContentBlock)(e)?{type:e.type,mimeType:e.mime_type??"application/octet-stream",data:e.data,metadata:e.metadata}:(0,d.isIDContentBlock)(e)?{type:e.type,mimeType:e.mime_type,fileId:e.id,metadata:e.metadata}:e}function h(e){return!!(t(e,"image_url")&&r(e.image_url)||t(e,"input_audio")&&r(e.input_audio)||t(e,"file")&&r(e.file))}function p(e){if(t(e,"image_url")&&r(e.image_url)&&n(e.image_url.url)){let t=(0,d.parseBase64DataUrl)({dataUrl:e.image_url.url});return t?{type:"image",mimeType:t.mime_type,data:t.data}:{type:"image",url:e.image_url.url}}if(t(e,"input_audio")&&r(e.input_audio)&&n(e.input_audio.data)&&n(e.input_audio.format))return{type:"audio",data:e.input_audio.data,mimeType:`audio/${e.input_audio.format}`};if(t(e,"file")&&r(e.file)&&n(e.file.data)){let t=(0,d.parseBase64DataUrl)({dataUrl:e.file.data});if(t)return{type:"file",data:t.data,mimeType:t.mime_type};if(n(e.file.file_id))return{type:"file",fileId:e.file.file_id}}return e}function f(e){let t=[];for(let r of e)h(r)?t.push(p(r)):t.push(r);return t}function m(e){if("url_citation"===e.type){let{url:t,title:r,start_index:a,end_index:n}=e;return{type:"citation",url:t,title:r,startIndex:a,endIndex:n}}if("file_citation"===e.type){let{file_id:t,filename:r,index:a}=e;return{type:"citation",title:r,startIndex:a,endIndex:a,fileId:t}}return e}function g(e){return Array.from(function*(){for(let i of(r(e.additional_kwargs?.reasoning)&&a(e.additional_kwargs.reasoning.summary)&&(yield{type:"reasoning",reasoning:e.additional_kwargs.reasoning.summary.reduce((e,t)=>r(t)&&n(t.text)?`${e}${t.text}`:e,"")}),"string"==typeof e.content?[{type:"text",text:e.content}]:e.content))if(t(i,"text")){let{text:e,annotations:t,phase:a,extras:s,...o}=i,l=r(s)?{...s}:{};n(a)&&(l.phase=a);let u=Object.keys(l).length>0?{extras:l}:{};Array.isArray(t)?yield{...o,...u,type:"text",text:String(e),annotations:t.map(m)}:yield{...o,...u,type:"text",text:String(e)}}for(let t of e.tool_calls??[])yield{type:"tool_call",id:t.id,name:t.name,args:t.args};if(r(e.additional_kwargs)&&a(e.additional_kwargs.tool_outputs))for(let i of e.additional_kwargs.tool_outputs){if(t(i,"web_search_call")){let e={};if(r(i.action)&&n(i.action.query)&&(e.query=i.action.query),yield{id:i.id,type:"server_tool_call",name:"web_search",args:e},"completed"===i.status||"failed"===i.status){let e={};r(i.action)&&(e.action=i.action),yield{type:"server_tool_call_result",toolCallId:n(i.id)?i.id:"",status:"completed"===i.status?"success":"error",output:e}}continue}if(t(i,"file_search_call")){yield{id:i.id,type:"server_tool_call",name:"file_search",args:{queries:a(i.queries)?i.queries:[]}},("completed"===i.status||"failed"===i.status)&&(yield{type:"server_tool_call_result",toolCallId:n(i.id)?i.id:"",status:"completed"===i.status?"success":"error",output:a(i.results)?{results:i.results}:{}});continue}if(t(i,"computer_call")){yield{type:"non_standard",value:i};continue}else if(t(i,"code_interpreter_call")){if(n(i.code)&&(yield{id:i.id,type:"server_tool_call",name:"code_interpreter",args:{code:i.code}}),a(i.outputs)){let e=o(()=>{if("in_progress"!==i.status){if("completed"===i.status)return 0;if("incomplete"===i.status)return 127;if("interpreting"!==i.status&&"failed"===i.status)return 1}});for(let r of i.outputs)if(t(r,"logs")){yield{type:"server_tool_call_result",toolCallId:i.id??"",status:"success",output:{type:"code_interpreter_output",returnCode:e??0,stderr:[0,void 0].includes(e)?void 0:String(r.logs),stdout:[0,void 0].includes(e)?String(r.logs):void 0}};continue}}continue}else if(t(i,"mcp_call")){yield{id:i.id,type:"server_tool_call",name:"mcp_call",args:i.input};continue}else if(t(i,"mcp_list_tools")){yield{id:i.id,type:"server_tool_call",name:"mcp_list_tools",args:i.input};continue}else if(t(i,"mcp_approval_request")){yield{type:"non_standard",value:i};continue}else if(t(i,"tool_search_call")){let e={};r(i.arguments)&&Object.assign(e,i.arguments);let t={};n(i.execution)&&(t.execution=i.execution),n(i.status)&&(t.status=i.status),n(i.call_id)&&(t.call_id=i.call_id),yield{id:n(i.id)?i.id:"",type:"server_tool_call",name:"tool_search",args:e,...Object.keys(t).length>0?{extras:t}:{}};continue}else if(t(i,"tool_search_output")){let e={name:"tool_search"};n(i.execution)&&(e.execution=i.execution),yield{type:"server_tool_call_result",toolCallId:n(i.id)?i.id:"",status:"completed"===i.status?"success":"failed"===i.status?"error":"success",output:{tools:a(i.tools)?i.tools:[]},extras:e};continue}else if(t(i,"image_generation_call")){n(i.result)&&(yield{type:"image",mimeType:"image/png",data:i.result,id:n(i.id)?i.id:void 0,metadata:{status:n(i.status)?i.status:void 0}}),yield{type:"non_standard",value:i};continue}r(i)&&(yield{type:"non_standard",value:i})}}())}e.s(["convertToV1FromDataContent",0,function(e){return e.map(c)},"convertToV1FromOpenAIDataBlock",0,p,"isOpenAIDataBlock",0,h],864701),e.s(["ChatOpenAITranslator",0,{translateContent:e=>{if("string"==typeof e.content){let t=[];for(let r of("string"==typeof e.content?e.content.length>0&&t.push({type:"text",text:e.content}):t.push(...f(e.content)),e.tool_calls??[]))t.push({type:"tool_call",id:r.id,name:r.name,args:r.args});return t}return g(e)},translateContentChunk:e=>{if("string"==typeof e.content){let t=[];for(let r of("string"==typeof e.content?e.content.length>0&&t.push({type:"text",text:e.content}):t.push(...f(e.content)),e.tool_calls??[]))t.push({type:"tool_call",id:r.id,name:r.name,args:r.args});return t}return Array.from(function*(){for(let t of(yield*g(e),e.tool_call_chunks??[]))yield{type:"tool_call_chunk",id:t.id,name:t.name,args:t.args}}())}},"convertToV1FromChatCompletionsInput",0,f],729082)},640470,e=>{"use strict";var t=e.i(756740),r=e.i(507577),a=e.i(703649),n=e.i(864701),i=e.i(729082),s=e.i(403929);let o=Symbol.for("langchain.message");function l(e){return Array.isArray(e)?e:"string"==typeof e?""===e?[]:[{type:"text",text:e}]:null==e?[]:[e]}var u=class extends t.Serializable{lc_namespace=["langchain_core","messages"];lc_serializable=!0;get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}[o]=!0;id;name;content;additional_kwargs;response_metadata;_getType(){return this.type}getType(){return this._getType()}constructor(e){const t="string"==typeof e||Array.isArray(e)?{content:e}:e;t.additional_kwargs||(t.additional_kwargs={}),t.response_metadata||(t.response_metadata={}),super(t),this.name=t.name,void 0===t.content&&void 0!==t.contentBlocks?(this.content=t.contentBlocks,this.response_metadata={output_version:"v1",...t.response_metadata}):(void 0!==t.content?this.content=t.content??[]:this.content=[],this.response_metadata=t.response_metadata),this.additional_kwargs=t.additional_kwargs,this.id=t.id}get text(){return"string"==typeof this.content?this.content:Array.isArray(this.content)?this.content.map(e=>"string"==typeof e?e:"text"===e.type?e.text:"").join(""):""}get contentBlocks(){let e="string"==typeof this.content?[{type:"text",text:this.content}]:this.content;return[n.convertToV1FromDataContent,i.convertToV1FromChatCompletionsInput,a.convertToV1FromAnthropicInput].reduce((e,t)=>t(e),e)}toDict(){return{type:this.getType(),data:this.toJSON().kwargs}}static lc_name(){return"BaseMessage"}get _printableFields(){return{id:this.id,content:this.content,name:this.name,additional_kwargs:this.additional_kwargs,response_metadata:this.response_metadata}}static isInstance(e){return"object"==typeof e&&null!==e&&o in e&&!0===e[o]&&(0,s.isMessage)(e)}_updateId(e){this.id=e,this.lc_kwargs.id=e}get[Symbol.toStringTag](){return this.constructor.lc_name()}[Symbol.for("nodejs.util.inspect.custom")](e){var t,r;if(null===e)return this;let a=(t=this._printableFields,r=Math.max(4,e),JSON.stringify(function e(t,a){if("object"!=typeof t||null==t)return t;if(a>=r)return Array.isArray(t)?"[Array]":"[Object]";if(Array.isArray(t))return t.map(t=>e(t,a+1));let n={};for(let r of Object.keys(t))n[r]=e(t[r],a+1);return n}(t,0),null,2));return`${this.constructor.lc_name()} ${a}`}toFormattedString(e="pretty"){return function(e,t="pretty"){return"pretty"===t?function(e){let t=[],r=` ${e.type.charAt(0).toUpperCase()+e.type.slice(1)} Message `,a=Math.floor((80-r.length)/2),n="=".repeat(a),i=r.length%2==0?n:`${n}=`;if(t.push(`${n}${r}${i}`),"ai"===e.type&&e.tool_calls&&e.tool_calls.length>0)for(let r of(t.push("Tool Calls:"),e.tool_calls))for(let[e,a]of(t.push(` ${r.name} (${r.id})`),t.push(` Call ID: ${r.id}`),t.push(" Args:"),Object.entries(r.args)))t.push(` ${e}: ${"object"==typeof a?JSON.stringify(a):a}`);return"tool"===e.type&&e.name&&t.push(`Name: ${e.name}`),"string"==typeof e.content&&e.content.trim()&&(t.length>1&&t.push(""),t.push(e.content)),t.join("\n")}(e):JSON.stringify(e)}(this,e)}};let d=["index","created","timestamp"];function c(e,t,r){let a=r?.ignoreKeys??d;if(null==e&&null==t)return;if(null==e||null==t)return e??t;let n={...e};for(let[e,i]of Object.entries(t))if(null==n[e])n[e]=i;else if(null==i)continue;else if(typeof n[e]!=typeof i||Array.isArray(n[e])!==Array.isArray(i))throw Error(`field[${e}] already exists in the message chunk, but with a different type.`);else if("string"==typeof n[e])if("type"===e)continue;else if(["id","name","output_version","model_provider"].includes(e))i&&(n[e]=i);else{if(a.includes(e))continue;n[e]+=i}else if("number"==typeof n[e]){if(a.includes(e))continue;n[e]=n[e]+i}else if("object"!=typeof n[e]||Array.isArray(n[e]))if(Array.isArray(n[e]))n[e]=f(n[e],i,r);else{if(n[e]===i)continue;console.warn(`field[${e}] already exists in this message chunk and value has unsupported type.`)}else n[e]=c(n[e],i,r);return n}function h(e){var t;return"object"==typeof e&&null!==e&&"index"in e&&("number"==typeof(t=e.index)||"string"==typeof t)}function p(e){if("object"!=typeof e||null===e||!("id"in e))return!1;let t=e.id;return null!=t&&""!==t}function f(e,t,r){if(null!=e||null!=t){if(null==e||null==t)return e||t;let a=[...e];for(let e of t){let t=function(e,t){let r=h(t),a=p(t);return r||a?e.findIndex(e=>{let n=h(e),i=p(e);return r&&n?e.index===t.index&&(!i||!a||e.id===t.id):!r&&!n&&!!a&&!!i&&e.id===t.id}):-1}(a,e);if(-1!==t)a[t]=c(a[t],e,r);else{if("object"==typeof e&&null!==e&&"text"in e&&""===e.text)continue;a.push(e)}}return a}}var m=class e extends u{static isInstance(t){if(!super.isInstance(t))return!1;let r=Object.getPrototypeOf(t);for(;null!==r;){if(r===e.prototype)return!0;r=Object.getPrototypeOf(r)}return!1}};e.s(["BaseMessage",0,u,"BaseMessageChunk",0,m,"DEFAULT_MERGE_IGNORE_KEYS",0,d,"_isMessageFieldWithRole",0,function(e){return"string"==typeof e.role},"_mergeDicts",0,c,"_mergeLists",0,f,"_mergeObj",0,function(e,t,r){if(null!=e||null!=t)if(null==e||null==t)return e??t;else if(typeof e!=typeof t)throw Error(`Cannot merge objects of different types. Left ${typeof e} Right ${typeof t}`);else if("string"==typeof e&&"string"==typeof t)return e+t;else if(Array.isArray(e)&&Array.isArray(t))return f(e,t,r);else if("object"==typeof e&&"object"==typeof t)return c(e,t,r);else if(e===t)return e;else throw Error(`Can not merge objects of different types. Left ${e} Right ${t}`)},"_mergeStatus",0,function(e,t){return"error"===e||"error"===t?"error":"success"},"isBaseMessage",0,function(e){return"function"==typeof e?._getType},"isBaseMessageChunk",0,function(e){return m.isInstance(e)},"isOpenAIToolCallArray",0,function(e){return Array.isArray(e)&&e.every(e=>"number"==typeof e.index)},"mergeContent",0,function(e,t){if("string"==typeof e)return""===e?t:"string"==typeof t?e+t:Array.isArray(t)&&0===t.length?e:Array.isArray(t)&&t.some(e=>(0,r.isDataContentBlock)(e))?[{type:"text",source_type:"text",text:e},...t]:[{type:"text",text:e},...t];if(Array.isArray(t)){let r=l(e);return f(r,t)??[...r,...t]}return""===t?e:Array.isArray(e)&&e.some(e=>(0,r.isDataContentBlock)(e))?[...e,{type:"file",source_type:"text",text:t}]:[...l(e),{type:"text",text:t}]}],640470)},367751,e=>{"use strict";var t=e.i(640470);function r(e,t){let r={};return(e?.audio!==void 0||t?.audio!==void 0)&&(r.audio=(e?.audio??0)+(t?.audio??0)),(e?.image!==void 0||t?.image!==void 0)&&(r.image=(e?.image??0)+(t?.image??0)),(e?.video!==void 0||t?.video!==void 0)&&(r.video=(e?.video??0)+(t?.video??0)),(e?.document!==void 0||t?.document!==void 0)&&(r.document=(e?.document??0)+(t?.document??0)),(e?.text!==void 0||t?.text!==void 0)&&(r.text=(e?.text??0)+(t?.text??0)),r}e.s(["mergeResponseMetadata",0,function(e,r){return(0,t._mergeDicts)(e,r)??{}},"mergeUsageMetadata",0,function(e,t){var a,n,i,s;let o,l;return{input_tokens:(e?.input_tokens??0)+(t?.input_tokens??0),output_tokens:(e?.output_tokens??0)+(t?.output_tokens??0),total_tokens:(e?.total_tokens??0)+(t?.total_tokens??0),input_token_details:(o={...r(a=e?.input_token_details,n=t?.input_token_details)},(a?.cache_read!==void 0||n?.cache_read!==void 0)&&(o.cache_read=(a?.cache_read??0)+(n?.cache_read??0)),(a?.cache_creation!==void 0||n?.cache_creation!==void 0)&&(o.cache_creation=(a?.cache_creation??0)+(n?.cache_creation??0)),o),output_token_details:(l={...r(i=e?.output_token_details,s=t?.output_token_details)},(i?.reasoning!==void 0||s?.reasoning!==void 0)&&(l.reasoning=(i?.reasoning??0)+(s?.reasoning??0)),l)}}])},771863,943082,e=>{"use strict";var t=e.i(190949),r=e.i(640470),a=(0,t.__exportAll)({ToolMessage:()=>i,ToolMessageChunk:()=>s,defaultToolCallParser:()=>o,isDirectToolOutput:()=>n,isToolMessage:()=>l,isToolMessageChunk:()=>u});function n(e){return null!=e&&"object"==typeof e&&"lc_direct_tool_output"in e&&!0===e.lc_direct_tool_output}var i=class extends r.BaseMessage{static lc_name(){return"ToolMessage"}get lc_aliases(){return{tool_call_id:"tool_call_id"}}lc_direct_tool_output=!0;type="tool";status;tool_call_id;metadata;artifact;constructor(e,t,r){const a="string"==typeof e||Array.isArray(e)?{content:e,name:r,tool_call_id:t}:e;super(a),this.tool_call_id=a.tool_call_id,this.artifact=a.artifact,this.status=a.status,this.metadata=a.metadata}static isInstance(e){return super.isInstance(e)&&"tool"===e.type}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}},s=class extends r.BaseMessageChunk{type="tool";tool_call_id;status;artifact;constructor(e){super(e),this.tool_call_id=e.tool_call_id,this.artifact=e.artifact,this.status=e.status}static lc_name(){return"ToolMessageChunk"}concat(e){return new this.constructor({content:(0,r.mergeContent)(this.content,e.content),additional_kwargs:(0,r._mergeDicts)(this.additional_kwargs,e.additional_kwargs),response_metadata:(0,r._mergeDicts)(this.response_metadata,e.response_metadata),artifact:(0,r._mergeObj)(this.artifact,e.artifact),tool_call_id:this.tool_call_id,id:this.id??e.id,status:(0,r._mergeStatus)(this.status,e.status)})}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}};function o(e){let t=[],r=[];for(let a of e)if(!a.function)continue;else{let e=a.function.name;try{let r=JSON.parse(a.function.arguments);t.push({name:e||"",args:r||{},id:a.id})}catch{r.push({name:e,args:a.function.arguments,id:a.id,error:"Malformed args."})}}return[t,r]}function l(e){return"object"==typeof e&&null!==e&&"getType"in e&&"function"==typeof e.getType&&"tool"===e.getType()}function u(e){return"tool"===e._getType()}e.s(["ToolMessage",0,i,"ToolMessageChunk",0,s,"defaultToolCallParser",0,o,"isDirectToolOutput",0,n,"isToolMessage",0,l,"isToolMessageChunk",0,u,"tool_exports",0,a],771863);var d=e.i(703649),c=e.i(729082),h=e.i(650284);function p(e){switch(e){case"csv":return"text/csv";case"doc":case"docx":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case"html":return"text/html";case"md":return"text/markdown";case"pdf":return"application/pdf";case"txt":return"text/plain";case"xls":return"application/vnd.ms-excel";case"xlsx":return"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";case"gif":return"image/gif";case"jpeg":case"jpg":return"image/jpeg";case"png":return"image/png";case"webp":return"image/webp";case"flv":return"video/flv";case"mkv":return"video/mkv";case"mov":return"video/mov";case"mp4":return"video/mp4";case"mpeg":return"video/mpeg";case"mpg":return"video/mpg";case"three_gp":return"video/three_gp";case"webm":return"video/webm";case"wmv":return"video/wmv";default:return"application/octet-stream"}}function f(e){return Array.from(function*(){for(let t of"string"==typeof e.content?[{type:"text",text:e.content}]:e.content){if((0,h._isContentBlock)(t,"cache_point")){yield{type:"non_standard",value:t};continue}if((0,h._isContentBlock)(t,"citations_content")&&(0,h._isObject)(t.citationsContent)){yield{type:"text",text:(0,h._isArray)(t.citationsContent.content)?t.citationsContent.content.reduce((e,t)=>(0,h._isObject)(t)&&(0,h._isString)(t.text)?e+t.text:e,""):"",annotations:(0,h._isArray)(t.citationsContent.citations)?t.citationsContent.citations.reduce((e,t)=>{if((0,h._isObject)(t)){let r=(0,h._isArray)(t.sourceContent)?t.sourceContent.reduce((e,t)=>(0,h._isObject)(t)&&(0,h._isString)(t.text)?e+t.text:e,""):"",a=(0,h.iife)(()=>{if((0,h._isObject)(t.location)){let e=t.location.documentChar||t.location.documentPage||t.location.documentChunk;if((0,h._isObject)(e))return{source:(0,h._isNumber)(e.documentIndex)?e.documentIndex.toString():void 0,startIndex:(0,h._isNumber)(e.start)?e.start:void 0,endIndex:(0,h._isNumber)(e.end)?e.end:void 0}}return{}});e.push({type:"citation",citedText:r,...a})}return e},[]):[]};continue}if((0,h._isContentBlock)(t,"document")&&(0,h._isObject)(t.document)){yield function(e){if((0,h._isObject)(e.document)&&(0,h._isObject)(e.document.source)){let t=p((0,h._isObject)(e.document)&&(0,h._isString)(e.document.format)?e.document.format:"");if((0,h._isObject)(e.document.source)){if((0,h._isObject)(e.document.source.s3Location)&&(0,h._isString)(e.document.source.s3Location.uri))return{type:"file",mimeType:t,fileId:e.document.source.s3Location.uri};if((0,h._isBytesArray)(e.document.source.bytes))return{type:"file",mimeType:t,data:e.document.source.bytes};if((0,h._isString)(e.document.source.text))return{type:"file",mimeType:t,data:Buffer.from(e.document.source.text).toString("base64")};if((0,h._isArray)(e.document.source.content))return{type:"file",mimeType:t,data:e.document.source.content.reduce((e,t)=>(0,h._isObject)(t)&&(0,h._isString)(t.text)?e+t.text:e,"")}}}return{type:"non_standard",value:e}}(t);continue}else if((0,h._isContentBlock)(t,"guard_content")){yield{type:"non_standard",value:t};continue}else if((0,h._isContentBlock)(t,"image")&&(0,h._isObject)(t.image)){yield function(e){if((0,h._isContentBlock)(e,"image")&&(0,h._isObject)(e.image)){let t=p((0,h._isObject)(e.image)&&(0,h._isString)(e.image.format)?e.image.format:"");if((0,h._isObject)(e.image.source)){if((0,h._isObject)(e.image.source.s3Location)&&(0,h._isString)(e.image.source.s3Location.uri))return{type:"image",mimeType:t,fileId:e.image.source.s3Location.uri};if((0,h._isBytesArray)(e.image.source.bytes))return{type:"image",mimeType:t,data:e.image.source.bytes}}}return{type:"non_standard",value:e}}(t);continue}else if((0,h._isContentBlock)(t,"reasoning_content")&&(0,h._isString)(t.reasoningText)){yield{type:"reasoning",reasoning:t.reasoningText};continue}else if((0,h._isContentBlock)(t,"text")&&(0,h._isString)(t.text)){yield{type:"text",text:t.text};continue}else if((0,h._isContentBlock)(t,"tool_result")){yield{type:"non_standard",value:t};continue}else if((0,h._isContentBlock)(t,"tool_call"))continue;else if((0,h._isContentBlock)(t,"video")&&(0,h._isObject)(t.video)){yield function(e){if((0,h._isContentBlock)(e,"video")&&(0,h._isObject)(e.video)){let t=p((0,h._isObject)(e.video)&&(0,h._isString)(e.video.format)?e.video.format:"");if((0,h._isObject)(e.video.source)){if((0,h._isObject)(e.video.source.s3Location)&&(0,h._isString)(e.video.source.s3Location.uri))return{type:"video",mimeType:t,fileId:e.video.source.s3Location.uri};if((0,h._isBytesArray)(e.video.source.bytes))return{type:"video",mimeType:t,data:e.video.source.bytes}}}return{type:"non_standard",value:e}}(t);continue}yield{type:"non_standard",value:t}}}())}function m(e){let t=[],r=e.additional_kwargs?.reasoning_content;if((0,h._isString)(r)&&r.length>0&&t.push({type:"reasoning",reasoning:r}),"string"==typeof e.content)e.content.length>0&&t.push({type:"text",text:e.content});else for(let r of e.content)"object"==typeof r&&"type"in r&&"text"===r.type&&"text"in r&&(0,h._isString)(r.text)&&t.push({type:"text",text:r.text});for(let r of e.tool_calls??[])t.push({type:"tool_call",id:r.id,name:r.name,args:r.args});return t}function g(e){return Array.from(function*(){for(let t of"string"==typeof e.content?[{type:"text",text:e.content}]:e.content){if((0,h._isContentBlock)(t,"text")&&(0,h._isString)(t.text)){yield{type:"text",text:t.text};continue}if((0,h._isContentBlock)(t,"thinking")&&(0,h._isString)(t.thinking)){yield{type:"reasoning",reasoning:t.thinking,...t.signature?{signature:t.signature}:{}};continue}if((0,h._isContentBlock)(t,"inlineData")&&(0,h._isObject)(t.inlineData)&&(0,h._isString)(t.inlineData.mimeType)&&(0,h._isString)(t.inlineData.data)){yield{type:"file",mimeType:t.inlineData.mimeType,data:t.inlineData.data};continue}else if((0,h._isContentBlock)(t,"functionCall")&&(0,h._isObject)(t.functionCall)&&(0,h._isString)(t.functionCall.name)&&(0,h._isObject)(t.functionCall.args)){yield{type:"tool_call",id:e.id,name:t.functionCall.name,args:t.functionCall.args};continue}else if((0,h._isContentBlock)(t,"functionResponse")){yield{type:"non_standard",value:t};continue}else if((0,h._isContentBlock)(t,"fileData")&&(0,h._isObject)(t.fileData)&&(0,h._isString)(t.fileData.mimeType)&&(0,h._isString)(t.fileData.fileUri)){yield{type:"file",mimeType:t.fileData.mimeType,fileId:t.fileData.fileUri};continue}else if((0,h._isContentBlock)(t,"executableCode")){yield{type:"non_standard",value:t};continue}else if((0,h._isContentBlock)(t,"codeExecutionResult")){yield{type:"non_standard",value:t};continue}yield{type:"non_standard",value:t}}}())}function _(e){return Array.from(function*(){let t="string"==typeof e.content?[{type:"text",text:e.content}]:e.content;for(let r of t){if((0,h._isContentBlock)(r,"reasoning")&&(0,h._isString)(r.reasoning)){let a=(0,h.iife)(()=>{let a=t.indexOf(r);if((0,h._isArray)(e.additional_kwargs?.signatures)&&a>=0)return e.additional_kwargs.signatures.at(a)});(0,h._isString)(a)?yield{type:"reasoning",reasoning:r.reasoning,signature:a}:yield{type:"reasoning",reasoning:r.reasoning};continue}if((0,h._isContentBlock)(r,"thinking")&&(0,h._isString)(r.thinking)){yield{type:"reasoning",reasoning:r.thinking,...r.signature?{signature:r.signature}:{}};continue}if((0,h._isContentBlock)(r,"text")&&(0,h._isString)(r.text)){yield{type:"text",text:r.text};continue}else if((0,h._isContentBlock)(r,"image_url")){if((0,h._isString)(r.image_url))if(r.image_url.startsWith("data:")){let e=r.image_url.match(/^data:([^;]+);base64,(.+)$/);e?yield{type:"image",data:e[2],mimeType:e[1]}:yield{type:"image",url:r.image_url}}else yield{type:"image",url:r.image_url};continue}else if((0,h._isContentBlock)(r,"media")&&(0,h._isString)(r.mimeType)&&(0,h._isString)(r.data)){yield{type:"file",mimeType:r.mimeType,data:r.data};continue}yield{type:"non_standard",value:r}}}())}function y(e){let t=[],r=e.additional_kwargs?.reasoning;if((0,h._isString)(r)&&r.length>0&&t.push({type:"reasoning",reasoning:r}),"string"==typeof e.content){let r=e.content,a=r.match(/([\s\S]*?)<\/think>/);if(a){let e=a[1].trim();e.length>0&&t.push({type:"reasoning",reasoning:e}),r=r.replace(/[\s\S]*?<\/think>/,"").trim()}r.length>0&&t.push({type:"text",text:r})}else for(let r of e.content)if("object"==typeof r&&"type"in r&&"text"===r.type&&"text"in r&&(0,h._isString)(r.text)){let e=r.text,a=e.match(/([\s\S]*?)<\/think>/);if(a){let r=a[1].trim();r.length>0&&t.push({type:"reasoning",reasoning:r}),e=e.replace(/[\s\S]*?<\/think>/,"").trim()}e.length>0&&t.push({type:"text",text:e})}for(let r of e.tool_calls??[])t.push({type:"tool_call",id:r.id,name:r.name,args:r.args});return t}function v(e){let t=[],r=e.additional_kwargs?.reasoning_content;if((0,h._isString)(r)&&r.length>0&&t.push({type:"reasoning",reasoning:r}),"string"==typeof e.content)e.content.length>0&&t.push({type:"text",text:e.content});else for(let r of e.content)"object"==typeof r&&"type"in r&&"text"===r.type&&"text"in r&&(0,h._isString)(r.text)&&t.push({type:"text",text:r.text});for(let r of e.tool_calls??[])t.push({type:"tool_call",id:r.id,name:r.name,args:r.args});return t}function b(e){let t=[];if((0,h._isObject)(e.additional_kwargs?.reasoning)){let r=e.additional_kwargs.reasoning;if((0,h._isArray)(r.summary)){let e=r.summary.reduce((e,t)=>(0,h._isObject)(t)&&(0,h._isString)(t.text)?`${e}${t.text}`:e,"");e.length>0&&t.push({type:"reasoning",reasoning:e})}}let r=e.additional_kwargs?.reasoning_content;if((0,h._isString)(r)&&r.length>0&&t.push({type:"reasoning",reasoning:r}),"string"==typeof e.content)e.content.length>0&&t.push({type:"text",text:e.content});else for(let r of e.content)"object"==typeof r&&"type"in r&&"text"===r.type&&"text"in r&&(0,h._isString)(r.text)&&t.push({type:"text",text:r.text});for(let r of e.tool_calls??[])t.push({type:"tool_call",id:r.id,name:r.name,args:r.args});return t}function w(e){return Array.from(function*(){for(let t of(0,h.iife)(()=>{if("string"==typeof e.content)if(e.additional_kwargs.originalTextContentBlock)return[{...e.additional_kwargs.originalTextContentBlock,type:"text"}];else return[{type:"text",text:e.content}];{let t=e.additional_kwargs?.originalTextContentBlock;if(t?.thoughtSignature&&!e.content.some(e=>"thoughtSignature"in e)){let r=[...e.content];for(let e=r.length-1;e>=0;e--){let a=r[e];if("text"===a.type&&!a.thought)return a.thoughtSignature=t.thoughtSignature,r}}return e.content}})){let r=(0,h.iife)(()=>{if((0,h._isContentBlock)(t,"text")&&(0,h._isString)(t.text))return{type:"text",text:t.text};if((0,h._isContentBlock)(t,"inlineData")&&(0,h._isObject)(t.inlineData)&&(0,h._isString)(t.inlineData.mimeType)&&(0,h._isString)(t.inlineData.data))return{type:"file",mimeType:t.inlineData.mimeType,data:t.inlineData.data};if((0,h._isContentBlock)(t,"functionCall")&&(0,h._isObject)(t.functionCall)&&(0,h._isString)(t.functionCall.name)&&(0,h._isObject)(t.functionCall.args))return{type:"tool_call",id:e.id,name:t.functionCall.name,args:t.functionCall.args};if((0,h._isContentBlock)(t,"functionResponse"));else{if((0,h._isContentBlock)(t,"fileData")&&(0,h._isObject)(t.fileData)&&(0,h._isString)(t.fileData.mimeType)&&(0,h._isString)(t.fileData.fileUri))return{type:"file",mimeType:t.fileData.mimeType,fileId:t.fileData.fileUri};(0,h._isContentBlock)(t,"executableCode")||(0,h._isContentBlock)(t,"codeExecutionResult")}return{type:"non_standard",value:t}}),a=(0,h.iife)(()=>"thought"in t&&t.thought?{type:"reasoning",reasoning:"text"===r.type?r.text:"",reasoningContentBlock:r}:r),n={thought:t.thought,thoughtSignature:t.thoughtSignature,partMetadata:t.partMetadata,...a};for(let e in n)void 0===n[e]&&delete n[e];yield n}}())}globalThis.lc_block_translators_registry??=new Map([["anthropic",d.ChatAnthropicTranslator],["bedrock-converse",{translateContent:f,translateContentChunk:f}],["deepseek",{translateContent:m,translateContentChunk:m}],["google",{translateContent:w,translateContentChunk:w}],["google-genai",{translateContent:g,translateContentChunk:g}],["google-vertexai",{translateContent:_,translateContentChunk:_}],["groq",{translateContent:y,translateContentChunk:y}],["ollama",{translateContent:v,translateContentChunk:v}],["openai",c.ChatOpenAITranslator],["xai",{translateContent:b,translateContentChunk:b}]]),e.s(["getTranslator",0,function(e){return globalThis.lc_block_translators_registry.get(e)}],943082)},642416,202438,e=>{"use strict";var t=class extends Error{output;constructor(e,t){super(e),this.output=t}};function r(e){try{if(void 0===e)return null;return function(e){try{return JSON.parse(e)}catch{}let t=e.trim();if(0===t.length)throw Error("Unexpected end of JSON input");let r=0;function a(){for(;r=t.length)throw Error(`Unexpected end of input at position ${r}`);let i=t[r];if("{"===i){if("{"!==t[r])throw Error(`Expected '{' at position ${r}, got '${t[r]}'`);let i={};if(r+=1,a(),r>=t.length)return i;if("}"===t[r])return r+=1,i;for(;r=t.length));){let s=n();if(a(),r>=t.length)break;if(":"!==t[r])throw Error(`Expected ':' at position ${r}, got '${t[r]}'`);if(r+=1,a(),r>=t.length||(i[s]=e(),a(),r>=t.length))break;if("}"===t[r]){r+=1;break}if(","===t[r]){r+=1;continue}throw Error(`Expected ',' or '}' at position ${r}, got '${t[r]}'`)}return i}if("["===i){if("["!==t[r])throw Error(`Expected '[' at position ${r}, got '${t[r]}'`);let n=[];if(r+=1,a(),r>=t.length)return n;if("]"===t[r])return r+=1,n;for(;r=t.length))&&(n.push(e()),a(),!(r>=t.length));){;if("]"===t[r]){r+=1;break}if(","===t[r]){r+=1;continue}throw Error(`Expected ',' or ']' at position ${r}, got '${t[r]}'`)}return n}if('"'===i)return n();if("null".startsWith(t.substring(r,r+4)))return r+=Math.min(4,t.length-r),null;if("true".startsWith(t.substring(r,r+4)))return r+=Math.min(4,t.length-r),!0;if("false".startsWith(t.substring(r,r+5)))return r+=Math.min(5,t.length-r),!1;if("-"===i||i>="0"&&i<="9"){let e=r,a="";if("-"===t[r]&&(a+="-",r+=1),r="0"&&t[r]<="9"))throw Error(`Invalid number at position ${e}`);if(r="1"&&t[r]<="9")for(;r="0"&&t[r]<="9";)a+=t[r],r+=1;if(r="0"&&t[r]<="9";)a+=t[r],r+=1;if(r="0"&&t[r]<="9";)a+=t[r],r+=1;if("-"===a)return -0;let n=Number.parseFloat(a);if(Number.isNaN(n))throw r=e,Error(`Invalid number '${a}' at position ${e}`);return n}throw Error(`Unexpected character '${i}' at position ${r}`)}();if(a(),r{"use strict";e.s(["coerceMessageLikeToMessage",()=>S,"collapseToolCallChunks",()=>I,"convertToChunk",()=>O,"getBufferString",()=>E,"iife",()=>w,"mapChatMessagesToStoredMessages",()=>C,"mapStoredMessageToChatMessage",()=>T,"mapStoredMessagesToChatMessages",()=>A],329494);var t=e.i(869065),r=e.i(642416),a=e.i(202438),n=e.i(640470),i=e.i(771863),s=e.i(649835),o=n,l=class e extends o.BaseMessage{static lc_name(){return"ChatMessage"}type="generic";role;static _chatMessageClass(){return e}constructor(e,t){("string"==typeof e||Array.isArray(e))&&(e={content:e,role:t}),super(e),this.role=e.role}static isInstance(e){return super.isInstance(e)&&"generic"===e.type}get _printableFields(){return{...super._printableFields,role:this.role}}},u=class extends o.BaseMessageChunk{static lc_name(){return"ChatMessageChunk"}type="generic";role;constructor(e,t){("string"==typeof e||Array.isArray(e))&&(e={content:e,role:t}),super(e),this.role=e.role}concat(e){return new this.constructor({content:(0,o.mergeContent)(this.content,e.content),additional_kwargs:(0,o._mergeDicts)(this.additional_kwargs,e.additional_kwargs),response_metadata:(0,o._mergeDicts)(this.response_metadata,e.response_metadata),role:this.role,id:this.id??e.id})}static isInstance(e){return super.isInstance(e)&&"generic"===e.type}get _printableFields(){return{...super._printableFields,role:this.role}}};e.s(["ChatMessage",0,l,"ChatMessageChunk",0,u,"isChatMessage",0,function(e){return"generic"===e._getType()},"isChatMessageChunk",0,function(e){return"generic"===e._getType()}],151191);var d=n,c=class extends d.BaseMessage{static lc_name(){return"FunctionMessage"}type="function";name;constructor(e){super(e),this.name=e.name}},h=class extends d.BaseMessageChunk{static lc_name(){return"FunctionMessageChunk"}type="function";concat(e){return new this.constructor({content:(0,d.mergeContent)(this.content,e.content),additional_kwargs:(0,d._mergeDicts)(this.additional_kwargs,e.additional_kwargs),response_metadata:(0,d._mergeDicts)(this.response_metadata,e.response_metadata),name:this.name??"",id:this.id??e.id})}};e.s(["FunctionMessage",0,c,"FunctionMessageChunk",0,h,"isFunctionMessage",0,function(e){return"function"===e._getType()},"isFunctionMessageChunk",0,function(e){return"function"===e._getType()}],622480);var p=n,f=class extends p.BaseMessage{static lc_name(){return"HumanMessage"}type="human";constructor(e){super(e)}static isInstance(e){return super.isInstance(e)&&"human"===e.type}},m=class extends p.BaseMessageChunk{static lc_name(){return"HumanMessageChunk"}type="human";constructor(e){super(e)}concat(e){return new this.constructor({content:(0,p.mergeContent)(this.content,e.content),additional_kwargs:(0,p._mergeDicts)(this.additional_kwargs,e.additional_kwargs),response_metadata:(0,p._mergeDicts)(this.response_metadata,e.response_metadata),id:this.id??e.id})}static isInstance(e){return super.isInstance(e)&&"human"===e.type}};e.s(["HumanMessage",0,f,"HumanMessageChunk",0,m,"isHumanMessage",0,function(e){return"human"===e.getType()},"isHumanMessageChunk",0,function(e){return"human"===e.getType()}],60427);var g=n,_=class extends g.BaseMessage{type="remove";id;constructor(e){super({...e,content:[]}),this.id=e.id}get _printableFields(){return{...super._printableFields,id:this.id}}static isInstance(e){return super.isInstance(e)&&"remove"===e.type}};e.s(["RemoveMessage",0,_],65955);var y=n,v=class e extends y.BaseMessage{static lc_name(){return"SystemMessage"}type="system";constructor(e){super(e)}concat(t){if("string"==typeof t)return new e({content:(0,y.mergeContent)(this.content,t),additional_kwargs:this.additional_kwargs,response_metadata:this.response_metadata,id:this.id,name:this.name});if(e.isInstance(t))return new e({content:(0,y.mergeContent)(this.content,t.content),additional_kwargs:{...this.additional_kwargs,...t.additional_kwargs},response_metadata:{...this.response_metadata,...t.response_metadata},id:this.id??t.id,name:this.name??t.name});throw Error("Unexpected chunk type for system message")}static isInstance(e){return super.isInstance(e)&&"system"===e.type}},b=class extends y.BaseMessageChunk{static lc_name(){return"SystemMessageChunk"}type="system";constructor(e){super(e)}concat(e){return new this.constructor({content:(0,y.mergeContent)(this.content,e.content),additional_kwargs:(0,y._mergeDicts)(this.additional_kwargs,e.additional_kwargs),response_metadata:(0,y._mergeDicts)(this.response_metadata,e.response_metadata),id:this.id??e.id})}static isInstance(e){return super.isInstance(e)&&"system"===e.type}};e.s(["SystemMessage",0,v,"SystemMessageChunk",0,b,"isSystemMessage",0,function(e){return"system"===e._getType()},"isSystemMessageChunk",0,function(e){return"system"===e._getType()}],211614);let w=e=>e();function k(e){return(0,r._isToolCall)(e)?e:"string"==typeof e.id&&"function"===e.type&&"object"==typeof e.function&&null!==e.function&&"arguments"in e.function&&"string"==typeof e.function.arguments&&"name"in e.function&&"string"==typeof e.function.name?{id:e.id,args:JSON.parse(e.function.arguments),name:e.function.name,type:"tool_call"}:e}function x(e){let r,a;if("object"==typeof e&&null!=e&&1===e.lc&&Array.isArray(e.id)&&null!=e.kwargs&&"object"==typeof e.kwargs){let t=e.id.at(-1);r="HumanMessage"===t||"HumanMessageChunk"===t?"user":"AIMessage"===t||"AIMessageChunk"===t?"assistant":"SystemMessage"===t||"SystemMessageChunk"===t?"system":"FunctionMessage"===t||"FunctionMessageChunk"===t?"function":"ToolMessage"===t||"ToolMessageChunk"===t?"tool":"unknown",a=e.kwargs}else{let{type:t,...n}=e;r=t,a=n}if("human"===r||"user"===r)return new f(a);if("ai"===r||"assistant"===r){let{tool_calls:e,...t}=a;if(!Array.isArray(e))return new s.AIMessage(a);let r=e.map(k);return new s.AIMessage({...t,tool_calls:r})}if("system"===r)return new v(a);if("developer"===r)return new v({...a,additional_kwargs:{...a.additional_kwargs,__openai_role__:"developer"}});if("tool"===r&&"tool_call_id"in a)return new i.ToolMessage({...a,content:a.content,tool_call_id:a.tool_call_id,name:a.name});else if("remove"===r&&"id"in a&&"string"==typeof a.id)return new _({...a,id:a.id});else throw(0,t.addLangChainErrorFields)(Error(`Unable to coerce message from array: only human, AI, system, developer, or tool message coercion is currently supported. Received: ${JSON.stringify(e,null,2)}`),"MESSAGE_COERCION_FAILURE")}function S(e){if("string"==typeof e)return new f(e);if((0,n.isBaseMessage)(e))return e;if(Array.isArray(e)){let[t,r]=e;return x({type:t,content:r})}if(!(0,n._isMessageFieldWithRole)(e))return x(e);{let{role:t,...r}=e;return x({...r,type:t})}}function $(e){if("string"==typeof e)return e;switch(e.type){case"text":return e.text??"";case"text-plain":return e.text??"[text-plain file]";case"image":case"image_url":return"[image]";case"audio":case"input_audio":return"[audio]";case"video":return"[video]";case"file":return"[file]";case"reasoning":case"tool_call":case"tool_call_chunk":case"invalid_tool_call":case"server_tool_call":case"server_tool_call_chunk":case"server_tool_call_result":case"non_standard":return"";default:return e.type?`[${e.type}]`:""}}function E(e,t="Human",r="AI"){let a=[];for(let n of e){let e;if("human"===n.type)e=t;else if("ai"===n.type)e=r;else if("system"===n.type)e="System";else if("tool"===n.type)e="Tool";else if("generic"===n.type)e=n.role;else throw Error(`Got unsupported message type: ${n.type}`);let i=n.name?`${n.name}, `:"",s="string"==typeof n.content?n.content:Array.isArray(n.content)?n.content.map($).filter(Boolean).join(""):"",o=`${e}: ${i}${s}`;"ai"===n.type&&(n.tool_calls&&n.tool_calls.length>0?o+=JSON.stringify(n.tool_calls):n.additional_kwargs&&"function_call"in n.additional_kwargs&&(o+=JSON.stringify(n.additional_kwargs.function_call))),a.push(o)}return a.join("\n")}function T(e){let t=void 0!==e.data?e:{type:e.type,data:{content:e.text,role:e.role,name:void 0,tool_call_id:void 0}};switch(t.type){case"human":return new f(t.data);case"ai":return new s.AIMessage(t.data);case"system":return new v(t.data);case"function":if(void 0===t.data.name)throw Error("Name must be defined for function messages");return new c(t.data);case"tool":if(void 0===t.data.tool_call_id)throw Error("Tool call ID must be defined for tool messages");return new i.ToolMessage(t.data);case"generic":if(void 0===t.data.role)throw Error("Role must be defined for chat messages");return new l(t.data);default:throw Error(`Got unexpected type: ${t.type}`)}}function A(e){return e.map(T)}function C(e){return e.map(e=>e.toDict())}function O(e){let t=e._getType();if("human"===t)return new m({...e});if("ai"===t){let t={...e};return"tool_calls"in t&&(t={...t,tool_call_chunks:t.tool_calls?.map(e=>({...e,type:"tool_call_chunk",index:void 0,args:JSON.stringify(e.args)}))}),new s.AIMessageChunk({...t})}if("system"===t)return new b({...e});if("function"===t)return new h({...e});if(l.isInstance(e))return new u({...e});else throw Error("Unknown message type.")}function I(e){let t=e.reduce((e,t)=>{let r=e.findIndex(([e])=>"id"in t&&t.id&&"index"in t&&void 0!==t.index?t.id===e.id&&t.index===e.index:"id"in t&&t.id?t.id===e.id:"index"in t&&void 0!==t.index&&t.index===e.index);return -1!==r?e[r].push(t):e.push([t]),e},[]),r=[],n=[];for(let e of t){let t=null,i=e[0]?.name??"",s=e.map(e=>e.args||"").join("").trim(),o=s.length?s:"{}",l=e[0]?.id;try{if(t=(0,a.parsePartialJson)(o),!l||null===t||"object"!=typeof t||Array.isArray(t))throw Error("Malformed tool call chunk args.");r.push({name:i,args:t,id:l,type:"tool_call"})}catch{n.push({name:i,args:o,id:l,error:"Malformed args.",type:"invalid_tool_call"})}}return{tool_call_chunks:e,tool_calls:r,invalid_tool_calls:n}}},649835,e=>{"use strict";e.s(["AIMessage",()=>s,"AIMessageChunk",()=>u,"isAIMessage",()=>o,"isAIMessageChunk",()=>l]);var t=e.i(640470),r=e.i(943082),a=e.i(367751),n=e.i(771863),i=e.i(329494),s=class extends t.BaseMessage{type="ai";tool_calls=[];invalid_tool_calls=[];usage_metadata;get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls",usage_metadata:"usage_metadata"}}constructor(e){let t;if("string"==typeof e||Array.isArray(e))t={content:e,tool_calls:[],invalid_tool_calls:[],additional_kwargs:{}};else{t=e;const r=t.additional_kwargs?.tool_calls,a=t.tool_calls;null!=r&&r.length>0&&(void 0===a||0===a.length)&&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., `pnpm install @langchain/anthropic`, pnpm install @langchain/openai`, etc.");try{if(null!=r&&void 0===a){const[e,a]=(0,n.defaultToolCallParser)(r);t.tool_calls=e??[],t.invalid_tool_calls=a??[]}else t.tool_calls=t.tool_calls??[],t.invalid_tool_calls=t.invalid_tool_calls??[]}catch{t.tool_calls=[],t.invalid_tool_calls=[]}if(void 0!==t.response_metadata&&"output_version"in t.response_metadata&&"v1"===t.response_metadata.output_version&&(t.contentBlocks=t.content,t.content=void 0),void 0!==t.contentBlocks){if(t.tool_calls){const e=t.tool_calls.filter(e=>!t.contentBlocks?.some(t=>"tool_call"===t.type&&t.id===e.id&&t.name===e.name));t.contentBlocks.push(...e.map(e=>({type:"tool_call",id:e.id,name:e.name,args:e.args})))}const e=t.contentBlocks.filter(e=>"tool_call"===e.type).filter(e=>!t.tool_calls?.some(t=>t.id===e.id&&t.name===e.name));e.length>0&&(t.tool_calls=[...t.tool_calls??[],...e.map(e=>({type:"tool_call",id:e.id,name:e.name,args:e.args}))])}}super(t),"string"!=typeof t&&(this.tool_calls=t.tool_calls??this.tool_calls,this.invalid_tool_calls=t.invalid_tool_calls??this.invalid_tool_calls),this.usage_metadata=t.usage_metadata}static lc_name(){return"AIMessage"}get contentBlocks(){if(this.response_metadata&&"output_version"in this.response_metadata&&"v1"===this.response_metadata.output_version)return this.content;if(this.response_metadata&&"model_provider"in this.response_metadata&&"string"==typeof this.response_metadata.model_provider){let e=(0,r.getTranslator)(this.response_metadata.model_provider);if(e)return e.translateContent(this)}let e=super.contentBlocks;if(this.tool_calls){let t=this.tool_calls.filter(t=>!e.some(e=>e.id===t.id&&e.name===t.name));e.push(...t.map(e=>({type:"tool_call",id:e.id,name:e.name,args:e.args})))}return e}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}static isInstance(e){return super.isInstance(e)&&"ai"===e.type}};function o(e){return"ai"===e._getType()}function l(e){return"ai"===e._getType()}var u=class extends t.BaseMessageChunk{type="ai";tool_calls=[];invalid_tool_calls=[];tool_call_chunks=[];usage_metadata;constructor(e){let t;if("string"==typeof e||Array.isArray(e))t={content:e,tool_calls:[],invalid_tool_calls:[],tool_call_chunks:[]};else if(void 0===e.tool_call_chunks||0===e.tool_call_chunks.length)t={...e,tool_calls:e.tool_calls??[],invalid_tool_calls:[],tool_call_chunks:[],usage_metadata:void 0!==e.usage_metadata?e.usage_metadata:void 0};else{const r=(0,i.collapseToolCallChunks)(e.tool_call_chunks??[]);t={...e,tool_call_chunks:r.tool_call_chunks,tool_calls:r.tool_calls,invalid_tool_calls:r.invalid_tool_calls,usage_metadata:void 0!==e.usage_metadata?e.usage_metadata:void 0}}super(t),this.tool_call_chunks=t.tool_call_chunks??this.tool_call_chunks,this.tool_calls=t.tool_calls??this.tool_calls,this.invalid_tool_calls=t.invalid_tool_calls??this.invalid_tool_calls,this.usage_metadata=t.usage_metadata}get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls",tool_call_chunks:"tool_call_chunks",usage_metadata:"usage_metadata"}}static lc_name(){return"AIMessageChunk"}get contentBlocks(){if(this.response_metadata&&"output_version"in this.response_metadata&&"v1"===this.response_metadata.output_version)return this.content;if(this.response_metadata&&"model_provider"in this.response_metadata&&"string"==typeof this.response_metadata.model_provider){let e=(0,r.getTranslator)(this.response_metadata.model_provider);if(e)return e.translateContent(this)}let e=super.contentBlocks;if(this.tool_calls&&"string"!=typeof this.content){let t=this.content.filter(e=>"tool_call"===e.type).map(e=>e.id);for(let r of this.tool_calls)r.id&&!t.includes(r.id)&&e.push({...r,type:"tool_call",id:r.id,name:r.name,args:r.args})}return e}get _printableFields(){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}}concat(e){let r={content:(0,t.mergeContent)(this.content,e.content),additional_kwargs:(0,t._mergeDicts)(this.additional_kwargs,e.additional_kwargs),response_metadata:(0,a.mergeResponseMetadata)(this.response_metadata,e.response_metadata),tool_call_chunks:[],tool_calls:[],id:this.id??e.id};if(void 0!==this.tool_call_chunks||void 0!==e.tool_call_chunks){let a=(0,t._mergeLists)(this.tool_call_chunks,e.tool_call_chunks);void 0!==a&&a.length>0&&(r.tool_call_chunks=a)}if(void 0!==this.tool_calls||void 0!==e.tool_calls){let a=(0,t._mergeLists)(this.tool_calls,e.tool_calls);void 0!==a&&a.length>0&&(r.tool_calls=a)}return(void 0!==this.usage_metadata||void 0!==e.usage_metadata)&&(r.usage_metadata=(0,a.mergeUsageMetadata)(this.usage_metadata,e.usage_metadata)),new this.constructor(r)}static isInstance(e){return super.isInstance(e)&&"ai"===e.type}}},738573,818154,444303,635099,827007,e=>{"use strict";var t=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function r(e){return"string"==typeof e&&t.test(e)}e.s(["default",0,r],818154);let a=[];for(let e=0;e<256;++e)a.push((e+256).toString(16).slice(1));function n(e,t=0){return(a[e[t+0]]+a[e[t+1]]+a[e[t+2]]+a[e[t+3]]+"-"+a[e[t+4]]+a[e[t+5]]+"-"+a[e[t+6]]+a[e[t+7]]+"-"+a[e[t+8]]+a[e[t+9]]+"-"+a[e[t+10]]+a[e[t+11]]+a[e[t+12]]+a[e[t+13]]+a[e[t+14]]+a[e[t+15]]).toLowerCase()}function i(e,t=0){let a=n(e,t);if(!r(a))throw TypeError("Stringified UUID is invalid");return a}let s=new Uint8Array(16);function o(){return crypto.getRandomValues(s)}let l={};function u(e,t,r){let a;if(e)a=d(e.random??e.rng?.()??o(),e.msecs,e.seq,t,r);else{var i,s,u;let e=Date.now(),n=o();i=l,s=e,u=n,i.msecs??=-1/0,i.seq??=0,s>i.msecs?(i.seq=u[6]<<23|u[7]<<16|u[8]<<8|u[9],i.msecs=s):(i.seq=i.seq+1|0,0===i.seq&&i.msecs++),a=d(n,l.msecs,l.seq,t,r)}return t??n(a)}function d(e,t,r,a,n=0){if(e.length<16)throw Error("Random bytes length must be >= 16");if(a){if(n<0||n+16>a.length)throw RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`)}else a=new Uint8Array(16),n=0;return t??=Date.now(),r??=127*e[6]<<24|e[7]<<16|e[8]<<8|e[9],a[n++]=t/0x10000000000&255,a[n++]=t/0x100000000&255,a[n++]=t/0x1000000&255,a[n++]=t/65536&255,a[n++]=t/256&255,a[n++]=255&t,a[n++]=112|r>>>28&15,a[n++]=r>>>20&255,a[n++]=128|r>>>14&63,a[n++]=r>>>6&255,a[n++]=r<<2&255|3&e[10],a[n++]=e[11],a[n++]=e[12],a[n++]=e[13],a[n++]=e[14],a[n++]=e[15],a}e.s(["default",0,u],738573);var c=e.i(190949);function h(e){let t;if(!r(e))throw TypeError("Invalid UUID");return Uint8Array.of((t=parseInt(e.slice(0,8),16))>>>24,t>>>16&255,t>>>8&255,255&t,(t=parseInt(e.slice(9,13),16))>>>8,255&t,(t=parseInt(e.slice(14,18),16))>>>8,255&t,(t=parseInt(e.slice(19,23),16))>>>8,255&t,(t=parseInt(e.slice(24,36),16))/0x10000000000&255,t/0x100000000&255,t>>>24&255,t>>>16&255,t>>>8&255,255&t)}let p={};function f(e,t,r){let a,i=e?._v6??!1;if(e){let t=Object.keys(e);1===t.length&&"_v6"===t[0]&&(e=void 0)}if(e)a=m(e.random??e.rng?.()??o(),e.msecs,e.nsecs,e.clockseq,e.node,t,r);else{var s,l,u;let e=Date.now(),n=o();s=p,l=e,u=n,s.msecs??=-1/0,s.nsecs??=0,l===s.msecs?(s.nsecs++,s.nsecs>=1e4&&(s.node=void 0,s.nsecs=0)):l>s.msecs?s.nsecs=0:l= 16");if(i){if(s<0||s+16>i.length)throw RangeError(`UUID byte range ${s}:${s+15} is out of buffer bounds`)}else i=new Uint8Array(16),s=0;t??=Date.now(),r??=0,a??=(e[8]<<8|e[9])&16383,n??=e.slice(10,16);let o=((0xfffffff&(t+=122192928e5))*1e4+r)%0x100000000;i[s++]=o>>>24&255,i[s++]=o>>>16&255,i[s++]=o>>>8&255,i[s++]=255&o;let l=t/0x100000000*1e4&0xfffffff;i[s++]=l>>>8&255,i[s++]=255&l,i[s++]=l>>>24&15|16,i[s++]=l>>>16&255,i[s++]=a>>>8|128,i[s++]=255&a;for(let e=0;e<6;++e)i[s++]=n[e];return i}function g(e,t,r){return t||e||!crypto.randomUUID?function(e,t,r){let a=(e=e||{}).random??e.rng?.()??o();if(a.length<16)throw Error("Random bytes length must be >= 16");if(a[6]=15&a[6]|64,a[8]=63&a[8]|128,t){if((r=r||0)<0||r+16>t.length)throw RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let e=0;e<16;++e)t[r+e]=a[e];return t}return n(a)}(e,t,r):crypto.randomUUID()}function _(e,t){return e<>>32-t}function y(e){let t=[0x5a827999,0x6ed9eba1,0x8f1bbcdc,0xca62c1d6],r=[0x67452301,0xefcdab89,0x98badcfe,0x10325476,0xc3d2e1f0],a=new Uint8Array(e.length+1);a.set(e),a[e.length]=128;let n=Math.ceil(((e=a).length/4+2)/16),i=Array(n);for(let t=0;t>>0;u=l,l=o,o=_(s,30)>>>0,s=n,n=i}r[0]=r[0]+n>>>0,r[1]=r[1]+s>>>0,r[2]=r[2]+o>>>0,r[3]=r[3]+l>>>0,r[4]=r[4]+u>>>0}return Uint8Array.of(r[0]>>24,r[0]>>16,r[0]>>8,r[0],r[1]>>24,r[1]>>16,r[1]>>8,r[1],r[2]>>24,r[2]>>16,r[2]>>8,r[2],r[3]>>24,r[3]>>16,r[3]>>8,r[3],r[4]>>24,r[4]>>16,r[4]>>8,r[4])}function v(e,t,r,a){var i=t,s=a;let o="string"==typeof e?function(e){let t=new Uint8Array((e=unescape(encodeURIComponent(e))).length);for(let r=0;rr.length)throw RangeError(`UUID byte range ${s}:${s+15} is out of buffer bounds`);for(let e=0;e<16;++e)r[s+e]=u[e];return r}return n(u)}function b(e){if(!r(e))throw TypeError("Invalid UUID");return parseInt(e.slice(14,15),16)}e.s(["default",0,g],444303),v.DNS="6ba7b810-9dad-11d1-80b4-00c04fd430c8",v.URL="6ba7b811-9dad-11d1-80b4-00c04fd430c8",e.s(["default",0,v],635099);var w=(0,c.__exportAll)({MAX:()=>"ffffffff-ffff-ffff-ffff-ffffffffffff",NIL:()=>"00000000-0000-0000-0000-000000000000",parse:()=>h,stringify:()=>i,v1:()=>f,v4:()=>g,v5:()=>v,v7:()=>u,validate:()=>r,version:()=>b});e.s(["uuid_exports",0,w],827007)},301025,e=>{"use strict";let t=Symbol.for("ls:tracing_async_local_storage"),r=Symbol.for("lc:context_variables");e.s(["_CONTEXT_VARIABLES_KEY",0,r,"getGlobalAsyncLocalStorageInstance",0,()=>globalThis[t],"setGlobalAsyncLocalStorageInstance",0,e=>{globalThis[t]=e}])},248271,(e,t,r)=>{"use strict";var a=Object.prototype.hasOwnProperty,n="~";function i(){}function s(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function o(e,t,r,a,i){if("function"!=typeof r)throw TypeError("The listener must be a function");var o=new s(r,a||e,i),l=n?n+t:t;return e._events[l]?e._events[l].fn?e._events[l]=[e._events[l],o]:e._events[l].push(o):(e._events[l]=o,e._eventsCount++),e}function l(e,t){0==--e._eventsCount?e._events=new i:delete e._events[t]}function u(){this._events=new i,this._eventsCount=0}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(n=!1)),u.prototype.eventNames=function(){var e,t,r=[];if(0===this._eventsCount)return r;for(t in e=this._events)a.call(e,t)&&r.push(n?t.slice(1):t);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(e)):r},u.prototype.listeners=function(e){var t=n?n+e:e,r=this._events[t];if(!r)return[];if(r.fn)return[r.fn];for(var a=0,i=r.length,s=Array(i);a{"use strict";t.exports=(e,t)=>(t=t||(()=>{}),e.then(e=>new Promise(e=>{e(t())}).then(()=>e),e=>new Promise(e=>{e(t())}).then(()=>{throw e})))},676469,(e,t,r)=>{"use strict";let a=e.r(352933);class n extends Error{constructor(e){super(e),this.name="TimeoutError"}}let i=(e,t,r)=>new Promise((i,s)=>{if("number"!=typeof t||t<0)throw TypeError("Expected `milliseconds` to be a positive number");if(t===1/0)return void i(e);let o=setTimeout(()=>{if("function"==typeof r){try{i(r())}catch(e){s(e)}return}let a="string"==typeof r?r:`Promise timed out after ${t} milliseconds`,o=r instanceof Error?r:new n(a);"function"==typeof e.cancel&&e.cancel(),s(o)},t);a(e.then(i,s),()=>{clearTimeout(o)})});t.exports=i,t.exports.default=i,t.exports.TimeoutError=n},6362,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e,t,r){let a=0,n=e.length;for(;n>0;){let i=n/2|0,s=a+i;0>=r(e[s],t)?(a=++s,n-=i+1):n=i}return a}},4264,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0});let a=e.r(6362);r.default=class{constructor(){this._queue=[]}enqueue(e,t){let r={priority:(t=Object.assign({priority:0},t)).priority,run:e};if(this.size&&this._queue[this.size-1].priority>=t.priority)return void this._queue.push(r);let n=a.default(this._queue,r,(e,t)=>t.priority-e.priority);this._queue.splice(n,0,r)}dequeue(){let e=this._queue.shift();return null==e?void 0:e.run}filter(e){return this._queue.filter(t=>t.priority===e.priority).map(e=>e.run)}get size(){return this._queue.length}}},655747,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0});let a=e.r(248271),n=e.r(676469),i=e.r(4264),s=()=>{},o=new n.TimeoutError;r.default=class extends a{constructor(e){var t,r,a,n;if(super(),this._intervalCount=0,this._intervalEnd=0,this._pendingCount=0,this._resolveEmpty=s,this._resolveIdle=s,!("number"==typeof(e=Object.assign({carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:i.default},e)).intervalCap&&e.intervalCap>=1))throw TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${null!=(r=null==(t=e.intervalCap)?void 0:t.toString())?r:""}\` (${typeof e.intervalCap})`);if(void 0===e.interval||!(Number.isFinite(e.interval)&&e.interval>=0))throw TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${null!=(n=null==(a=e.interval)?void 0:a.toString())?n:""}\` (${typeof e.interval})`);this._carryoverConcurrencyCount=e.carryoverConcurrencyCount,this._isIntervalIgnored=e.intervalCap===1/0||0===e.interval,this._intervalCap=e.intervalCap,this._interval=e.interval,this._queue=new e.queueClass,this._queueClass=e.queueClass,this.concurrency=e.concurrency,this._timeout=e.timeout,this._throwOnTimeout=!0===e.throwOnTimeout,this._isPaused=!1===e.autoStart}get _doesIntervalAllowAnother(){return this._isIntervalIgnored||this._intervalCount{this._onResumeInterval()},t)),!0;this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0}return!1}_tryToStartAnother(){if(0===this._queue.size)return this._intervalId&&clearInterval(this._intervalId),this._intervalId=void 0,this._resolvePromises(),!1;if(!this._isPaused){let e=!this._isIntervalPaused();if(this._doesIntervalAllowAnother&&this._doesConcurrentAllowAnother){let t=this._queue.dequeue();return!!t&&(this.emit("active"),t(),e&&this._initializeIntervalIfNeeded(),!0)}}return!1}_initializeIntervalIfNeeded(){this._isIntervalIgnored||void 0!==this._intervalId||(this._intervalId=setInterval(()=>{this._onInterval()},this._interval),this._intervalEnd=Date.now()+this._interval)}_onInterval(){0===this._intervalCount&&0===this._pendingCount&&this._intervalId&&(clearInterval(this._intervalId),this._intervalId=void 0),this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0,this._processQueue()}_processQueue(){for(;this._tryToStartAnother(););}get concurrency(){return this._concurrency}set concurrency(e){if(!("number"==typeof e&&e>=1))throw TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this._concurrency=e,this._processQueue()}async add(e,t={}){return new Promise((r,a)=>{let i=async()=>{this._pendingCount++,this._intervalCount++;try{let i=void 0===this._timeout&&void 0===t.timeout?e():n.default(Promise.resolve(e()),void 0===t.timeout?this._timeout:t.timeout,()=>{(void 0===t.throwOnTimeout?this._throwOnTimeout:t.throwOnTimeout)&&a(o)});r(await i)}catch(e){a(e)}this._next()};this._queue.enqueue(i,t),this._tryToStartAnother(),this.emit("add")})}async addAll(e,t){return Promise.all(e.map(async e=>this.add(e,t)))}start(){return this._isPaused&&(this._isPaused=!1,this._processQueue()),this}pause(){this._isPaused=!0}clear(){this._queue=new this._queueClass}async onEmpty(){if(0!==this._queue.size)return new Promise(e=>{let t=this._resolveEmpty;this._resolveEmpty=()=>{t(),e()}})}async onIdle(){if(0!==this._pendingCount||0!==this._queue.size)return new Promise(e=>{let t=this._resolveIdle;this._resolveIdle=()=>{t(),e()}})}get size(){return this._queue.size}sizeBy(e){return this._queue.filter(e).length}get pending(){return this._pendingCount}get isPaused(){return this._isPaused}get timeout(){return this._timeout}set timeout(e){this._timeout=e}}},704567,(e,t,r)=>{"use strict";let a=(e=0)=>t=>`\u001B[${38+e};5;${t}m`,n=(e=0)=>(t,r,a)=>`\u001B[${38+e};2;${t};${r};${a}m`;Object.defineProperty(t,"exports",{enumerable:!0,get:function(){let e=new Map,t={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};for(let[r,a]of(t.color.gray=t.color.blackBright,t.bgColor.bgGray=t.bgColor.bgBlackBright,t.color.grey=t.color.blackBright,t.bgColor.bgGrey=t.bgColor.bgBlackBright,Object.entries(t))){for(let[r,n]of Object.entries(a))t[r]={open:`\u001B[${n[0]}m`,close:`\u001B[${n[1]}m`},a[r]=t[r],e.set(n[0],n[1]);Object.defineProperty(t,r,{value:a,enumerable:!1})}return Object.defineProperty(t,"codes",{value:e,enumerable:!1}),t.color.close="\x1b[39m",t.bgColor.close="\x1b[49m",t.color.ansi256=a(),t.color.ansi16m=n(),t.bgColor.ansi256=a(10),t.bgColor.ansi16m=n(10),Object.defineProperties(t,{rgbToAnsi256:{value:(e,t,r)=>e===t&&t===r?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(t/255*5)+Math.round(r/255*5),enumerable:!1},hexToRgb:{value:e=>{let t=/(?[a-f\d]{6}|[a-f\d]{3})/i.exec(e.toString(16));if(!t)return[0,0,0];let{colorString:r}=t.groups;3===r.length&&(r=r.split("").map(e=>e+e).join(""));let a=Number.parseInt(r,16);return[a>>16&255,a>>8&255,255&a]},enumerable:!1},hexToAnsi256:{value:e=>t.rgbToAnsi256(...t.hexToRgb(e)),enumerable:!1}}),t}})},869070,496827,662394,617776,191325,804017,779571,76719,184698,146833,131059,206696,200587,640516,115995,890406,991740,707224,99815,976044,e=>{"use strict";let t,r,a,n,i,s,o;var l=e.i(190949),u=e.i(301025),d=e.i(329494),c=e.i(738573);e.i(827007);var h=(0,l.__exportAll)({getEnv:()=>y,getEnvironmentVariable:()=>b,getRuntimeEnvironment:()=>v,isBrowser:()=>p,isDeno:()=>g,isJsDom:()=>m,isNode:()=>_,isWebWorker:()=>f});let p=()=>!1,f=()=>"object"==typeof globalThis&&globalThis.constructor&&"DedicatedWorkerGlobalScope"===globalThis.constructor.name,m=()=>"u">typeof navigator&&navigator.userAgent.includes("jsdom"),g=()=>"u">typeof Deno,_=()=>"u">typeof process&&void 0!==process.versions&&void 0!==process.versions.node&&!g(),y=()=>p()?"browser":_()?"node":f()?"webworker":m()?"jsdom":g()?"deno":"other";function v(){return void 0===t&&(t={library:"langchain-js",runtime:y()}),t}function b(e){try{if("u">typeof process)return process.env?.[e];if(g())return Deno?.env.get(e);return}catch{return}}e.s(["env_exports",0,h,"getEnv",0,y,"getEnvironmentVariable",0,b,"getRuntimeEnvironment",0,v],496827);var w=e.i(756740),k=(0,l.__exportAll)({BaseCallbackHandler:()=>E,callbackHandlerPrefersChatModelStreamEvents:()=>$,callbackHandlerPrefersStreaming:()=>S,isBaseCallbackHandler:()=>T}),x=class{};function S(e){return"lc_prefer_streaming"in e&&e.lc_prefer_streaming}function $(e){return"lc_prefer_chat_model_stream_events"in e&&e.lc_prefer_chat_model_stream_events}var E=class extends x{lc_serializable=!1;get lc_namespace(){return["langchain_core","callbacks",this.name]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,(0,w.get_lc_unique_name)(this.constructor)]}lc_kwargs;ignoreLLM=!1;ignoreChain=!1;ignoreAgent=!1;ignoreRetriever=!1;ignoreCustomEvent=!1;raiseError=!1;awaitHandlers="false"===b("LANGCHAIN_CALLBACKS_BACKGROUND");constructor(e){super(),this.lc_kwargs=e||{},e&&(this.ignoreLLM=e.ignoreLLM??this.ignoreLLM,this.ignoreChain=e.ignoreChain??this.ignoreChain,this.ignoreAgent=e.ignoreAgent??this.ignoreAgent,this.ignoreRetriever=e.ignoreRetriever??this.ignoreRetriever,this.ignoreCustomEvent=e.ignoreCustomEvent??this.ignoreCustomEvent,this.raiseError=e.raiseError??this.raiseError,this.awaitHandlers=this.raiseError||(e._awaitHandler??this.awaitHandlers))}copy(){return new this.constructor(this)}toJSON(){return w.Serializable.prototype.toJSON.call(this)}toJSONNotImplemented(){return w.Serializable.prototype.toJSONNotImplemented.call(this)}static fromMethods(e){class t extends E{name=(0,c.default)();constructor(){super(),Object.assign(this,e)}}return new t}};let T=e=>void 0!==e&&"function"==typeof e.copy&&"string"==typeof e.name&&"boolean"==typeof e.awaitHandlers;e.s(["BaseCallbackHandler",0,E,"base_exports",0,k,"callbackHandlerPrefersChatModelStreamEvents",0,$,"callbackHandlerPrefersStreaming",0,S,"isBaseCallbackHandler",0,T],662394),e.s(["Client",()=>tL],617776);let A=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i,C=[];for(let e=0;e<256;++e)C.push((e+256).toString(16).slice(1));function O(e,t=0){return(C[e[t+0]]+C[e[t+1]]+C[e[t+2]]+C[e[t+3]]+"-"+C[e[t+4]]+C[e[t+5]]+"-"+C[e[t+6]]+C[e[t+7]]+"-"+C[e[t+8]]+C[e[t+9]]+"-"+C[e[t+10]]+C[e[t+11]]+C[e[t+12]]+C[e[t+13]]+C[e[t+14]]+C[e[t+15]]).toLowerCase()}let I=new Uint8Array(16);function j(){return crypto.getRandomValues(I)}let P=function(e,t,r){return t||e||!crypto.randomUUID?function(e,t,r){let a=(e=e||{}).random??e.rng?.()??j();if(a.length<16)throw Error("Random bytes length must be >= 16");if(a[6]=15&a[6]|64,a[8]=63&a[8]|128,t){if((r=r||0)<0||r+16>t.length)throw RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let e=0;e<16;++e)t[r+e]=a[e];return t}return O(a)}(e,t,r):crypto.randomUUID()};function z(e,t){return e<>>32-t}let N=function(e){let t=[0x5a827999,0x6ed9eba1,0x8f1bbcdc,0xca62c1d6],r=[0x67452301,0xefcdab89,0x98badcfe,0x10325476,0xc3d2e1f0],a=new Uint8Array(e.length+1);a.set(e),a[e.length]=128;let n=Math.ceil(((e=a).length/4+2)/16),i=Array(n);for(let t=0;t>>0;u=l,l=o,o=z(s,30)>>>0,s=n,n=i}r[0]=r[0]+n>>>0,r[1]=r[1]+s>>>0,r[2]=r[2]+o>>>0,r[3]=r[3]+l>>>0,r[4]=r[4]+u>>>0}return Uint8Array.of(r[0]>>24,r[0]>>16,r[0]>>8,r[0],r[1]>>24,r[1]>>16,r[1]>>8,r[1],r[2]>>24,r[2]>>16,r[2]>>8,r[2],r[3]>>24,r[3]>>16,r[3]>>8,r[3],r[4]>>24,r[4]>>16,r[4]>>8,r[4])},R=function(e){let t;if(!("string"==typeof e&&A.test(e)))throw TypeError("Invalid UUID");return Uint8Array.of((t=parseInt(e.slice(0,8),16))>>>24,t>>>16&255,t>>>8&255,255&t,(t=parseInt(e.slice(9,13),16))>>>8,255&t,(t=parseInt(e.slice(14,18),16))>>>8,255&t,(t=parseInt(e.slice(19,23),16))>>>8,255&t,(t=parseInt(e.slice(24,36),16))/0x10000000000&255,t/0x100000000&255,t>>>24&255,t>>>16&255,t>>>8&255,255&t)};function M(e,t,r,a){var n=t,i=a;let s="string"==typeof e?function(e){let t=new Uint8Array((e=unescape(encodeURIComponent(e))).length);for(let r=0;rr.length)throw RangeError(`UUID byte range ${i}:${i+15} is out of buffer bounds`);for(let e=0;e<16;++e)r[i+e]=l[e];return r}return O(l)}M.DNS="6ba7b810-9dad-11d1-80b4-00c04fd430c8",M.URL="6ba7b811-9dad-11d1-80b4-00c04fd430c8";let L={};function Z(e,t,r,a,n=0){if(e.length<16)throw Error("Random bytes length must be >= 16");if(a){if(n<0||n+16>a.length)throw RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`)}else a=new Uint8Array(16),n=0;return t??=Date.now(),r??=127*e[6]<<24|e[7]<<16|e[8]<<8|e[9],a[n++]=t/0x10000000000&255,a[n++]=t/0x100000000&255,a[n++]=t/0x1000000&255,a[n++]=t/65536&255,a[n++]=t/256&255,a[n++]=255&t,a[n++]=112|r>>>28&15,a[n++]=r>>>20&255,a[n++]=128|r>>>14&63,a[n++]=r>>>6&255,a[n++]=r<<2&255|3&e[10],a[n++]=e[11],a[n++]=e[12],a[n++]=e[13],a[n++]=e[14],a[n++]=e[15],a}let D=function(e,t,r){let a;if(e)a=Z(e.random??e.rng?.()??j(),e.msecs,e.seq,t,r);else{var n,i,s;let e=Date.now(),o=j();n=L,i=e,s=o,n.msecs??=-1/0,n.seq??=0,i>n.msecs?(n.seq=s[6]<<23|s[7]<<16|s[8]<<8|s[9],n.msecs=i):(n.seq=n.seq+1|0,0===n.seq&&n.msecs++),a=Z(o,L.msecs,L.seq,t,r)}return t??O(a)},U="gen_ai.request.model",B="gen_ai.usage.input_tokens",F="gen_ai.usage.output_tokens",H="gen_ai.usage.total_tokens",q="langsmith.span.tags",J=Symbol.for("ls:fetch_implementation"),G=()=>eH("PROJECT")??eF("LANGCHAIN_SESSION")??"default",W=e=>BigInt(e),V=W("0x9E3779B1"),K=W("0x85EBCA77"),Y=W("0xC2B2AE3D"),Q=W("0x9E3779B185EBCA87"),X=W("0xC2B2AE3D27D4EB4F"),ee=W("0x165667B19E3779F9"),et=W("0x85EBCA77C2B2AE63"),er=W("0x27D4EB2F165667C5"),ea=W("0x165667919E3779F9"),en=W("0x9FB21C651E98DF25"),ei=function(e){let t=new Uint8Array(e.length/2);for(let r=0;r(e&el)*(t&el)&eo,ef=e=>{if(!e)throw Error("Assert failed")};function em(e,t,r){for(let a=0;a<8;a++){let n=ed(t,8*a),i=n^ed(r,8*a);e[1^a]+=n,e[a]+=ep(i,i>>W(32))}return e}function eg(e,t,r,a){for(let n=0;n>W(47)^n)*V,e[a]=i&eo}return e}function ey(e,t){return eb(e[0]^ed(t,0),e[1]^ed(t,8))}function ev(e,t,r){let a=r;return a+=ey(e.slice(0),eu(t,0)),a+=ey(e.slice(2),eu(t,16)),a+=ey(e.slice(4),eu(t,32)),ex((a+=ey(e.slice(6),eu(t,48)))&eo)}function eb(e,t){let r=e*t&es;return r&eo^r>>W(64)}function ew(e,t,r){return eb((ed(e,0)^ed(t,0)+r)&eo,(ed(e,8)^ed(t,8)-r)&eo)}function ek(e,t,r,a,n){let i=e&eo,s=e>>W(64)&eo;return i+=ew(t,a,n),i^=ed(r,0)+ed(r,8),i&=eo,s+=ew(r,eu(a,16),n),s^=ed(t,0)+ed(t,8),(s&=eo)<>W(37),e*=ea,e&=eo,e^=e>>W(32)}function eS(e){return e^=e>>W(33),e*=X,e&=eo,e^=e>>W(29),e*=ee,e&=eo,e^=e>>W(32)}function e$(e){return~e+W(1)&eo}let eE=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function eT(e,t){if(!eE.test(e))throw Error(void 0!==t?`Invalid UUID for ${t}: ${e}`:`Invalid UUID: ${e}`);return e}let eA=new TextEncoder;function eC(e,t){var r,a;let n,i,s,o,l=(r=`${e}:${t}`,a=function(e,t=W(0)){let r,a,n=e.byteLength;return n<=16?function(e,t){var r,a,n,i,s;let o=e.byteLength;if(ef(o<=16),o>8){let r,a,n,i,s,o,l,u;return ef((r=e.byteLength)>=9&&r<=16),a=(ed(ei,32)^ed(ei,40))+t&eo,n=(ed(ei,48)^ed(ei,56))-t&eo,o=((s=(ed(e)^(i=ed(e,r-8))^a)*Q)&eo)+(W(r-1)<>W(64))&W(255))<>W(8)|(l&W(0xff0000000000))>>W(24)|(l&W(0xff000000000000))>>W(40)|(l&W(0xff00000000000000))>>W(56),ex((u=(s&eo)*X+((s>>W(64))*X<>W(64))<=4){let n,i,s,o,l;return ef((n=e.byteLength)>=4&&n<=8),i=ec(e,0),s=ec(e,n-4),o=W(i)|W(s)<>W(67),(a=((r=l&eo)^r>>W(35))*en&eo)^a>>W(28)|ex(l>>W(64))<0){let r,a,o,l;return ef((r=e.byteLength)>0&&r<=3),o=((a=W(eh(e,r-1))|W(r<<8)|W(eh(e,0)<<16)|W(eh(e,r>>1)<<24))^(W(ec(ei,0))^W(ec(ei,4)))+t)&eo,l=(W(ec(ei,8))^W(ec(ei,12)))-t,(eS((((i=n=((n=((n=a)&W(65535))<>W(16))&W(0xff00ff))<>W(8))<<(s=W(13))|i>>W(32)-s)&el^l)&eo)&eo)<=0;){let i=Number(n);a=ek(a,eu(e,16*i),eu(e,e.byteLength-16*(i+1)),eu(t,32*i),r),n--}let i=a+(a>>W(64))&eo;i=ex(i);let s=(a&eo)*Q+(a>>W(64))*et+(W(e.byteLength)-r&eo)*X;return s&=eo,i|(s=e$(ex(s)))<>W(64))<>W(64))&eo;n=ex(n);let i=(a&eo)*Q+(a>>W(64))*et+(W(e.byteLength)-r&eo)*X;return i&=eo,n|(i=e$(ex(i)))<128),ef(8*(r=function(e,t,r,a,n){let i=Math.floor((r.byteLength-64)/8),s=64*i,o=Math.floor((t.byteLength-1)/s);for(let a=0;a>W(64),i.setBigUint64(0,s,!1),i.setBigUint64(8,a&eo,!1),n),u=new Uint8Array(16);if(7===(eE.test(e)?parseInt(e[14],16):null)){let t=function(e){let t=e.replace(/-/g,""),r=new Uint8Array(16);for(let e=0;e<16;e++)r[e]=parseInt(t.slice(2*e,2*e+2),16);return r}(e);u.set(t.slice(0,6),0)}else{let e=Date.now();u[0]=e/0x10000000000&255,u[1]=e/0x100000000&255,u[2]=e/0x1000000&255,u[3]=e/65536&255,u[4]=e/256&255,u[5]=255&e}return u[6]=112|15&l[0],u[7]=l[1],u[8]=128|63&l[2],u.set(l.slice(3,10),9),o=Array.from(u).map(e=>e.toString(16).padStart(2,"0")).join(""),`${o.slice(0,8)}-${o.slice(8,12)}-${o.slice(12,16)}-${o.slice(16,20)}-${o.slice(20)}`}var eO=e.i(902157),eI=e.i(912714),ej=e.i(750227);async function eP(e){await eI.mkdir(e,{recursive:!0})}async function ez(e,t){let r=`${e}.tmp`;await eI.writeFile(r,t,{encoding:"utf8",mode:384}),await eI.rename(r,e)}async function eN(e){return eI.readdir(e)}async function eR(e){return eI.stat(e)}function eM(e){return eO.existsSync(e)}let eL=new class{constructor(e={}){Object.defineProperty(this,"cache",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ttlSeconds",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"refreshIntervalSeconds",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"refreshTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_metrics",{enumerable:!0,configurable:!0,writable:!0,value:{hits:0,misses:0,refreshes:0,refreshErrors:0}}),this.configure(e)}get metrics(){return{...this._metrics}}get totalRequests(){return this._metrics.hits+this._metrics.misses}get hitRate(){let e=this.totalRequests;return e>0?this._metrics.hits/e:0}resetMetrics(){this._metrics={hits:0,misses:0,refreshes:0,refreshErrors:0}}get(e,t){if(0===this.maxSize)return;let r=this.cache.get(e);if(!r){this._metrics.misses+=1;return}return this.cache.delete(e),this.cache.set(e,{...r,refreshFunc:t}),this._metrics.hits+=1,r.value}set(e,t,r){if(0===this.maxSize)return;if(void 0===this.refreshTimer&&this.startRefreshLoop(),!this.cache.has(e)&&this.cache.size>=this.maxSize){let e=this.cache.keys().next().value;void 0!==e&&this.cache.delete(e)}let a={value:t,createdAt:Date.now(),refreshFunc:r};this.cache.delete(e),this.cache.set(e,a)}invalidate(e){this.cache.delete(e)}clear(){this.cache.clear()}get size(){return this.cache.size}stop(){this.refreshTimer&&(clearInterval(this.refreshTimer),this.refreshTimer=void 0)}dump(e){var t;let r={};for(let[e,t]of this.cache.entries())r[e]=t.value;let a=ej.dirname(e);eM(a)||eO.mkdirSync(a,{recursive:!0});let n=`${e}.tmp`;try{t=JSON.stringify({entries:r},null,2),eO.writeFileSync(n,t),eO.renameSync(n,e)}catch(e){throw eM(n)&&eO.unlinkSync(n),e}}load(e){let t;if(!eM(e))return 0;try{let r=eO.readFileSync(e,"utf-8");t=JSON.parse(r).entries??null}catch{return 0}if(!t)return 0;let r=0,a=Date.now();for(let[e,n]of Object.entries(t)){if(this.cache.size>=this.maxSize)break;let t={value:n,createdAt:a};this.cache.set(e,t),r+=1}return r}startRefreshLoop(){this.stop(),null!==this.ttlSeconds&&(this.refreshTimer=setInterval(()=>{this.refreshStaleEntries().catch(e=>{console.warn("Unexpected error in cache refresh loop:",e)})},1e3*this.refreshIntervalSeconds),this.refreshTimer.unref&&this.refreshTimer.unref())}getStaleEntries(){let e=[];for(let[r,a]of this.cache.entries()){var t;null!==(t=this.ttlSeconds)&&Date.now()-a.createdAt>1e3*t&&e.push([r,a])}return e}async refreshStaleEntries(){let e=this.getStaleEntries();if(0!==e.length){for(let[t,r]of e)if(void 0!==r.refreshFunc)try{let e=await r.refreshFunc();this.set(t,e,r.refreshFunc),this._metrics.refreshes+=1}catch(e){this._metrics.refreshErrors+=1,console.warn(`Failed to refresh cache entry ${t}:`,e)}}}configure(e){this.stop(),this.refreshIntervalSeconds=e.refreshIntervalSeconds??60,this.maxSize=e.maxSize??100,this.ttlSeconds=e.ttlSeconds??300}},eZ="0.6.0",eD=()=>r||(r="u">typeof Bun?"bun":"u">typeof process&&void 0!==process.versions&&void 0!==process.versions.node&&!("u">typeof Deno)?"node":"object"==typeof globalThis&&globalThis.constructor&&"DedicatedWorkerGlobalScope"===globalThis.constructor.name?"webworker":"u">typeof navigator&&navigator.userAgent.includes("jsdom")?"jsdom":"u">typeof Deno?"deno":"other");function eU(){return void 0===a&&(a={library:"langsmith",runtime:eD(),sdk:"langsmith-js",sdk_version:eZ,...function(){if(void 0!==n)return n;let e={};for(let t of["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"]){let r=eF(t);void 0!==r&&(e[t]=r)}return n=e,e}()}),a}function eB(){let e=function(){let e={};try{if("u">typeof process&&process.env)for(let[t,r]of Object.entries(process.env))(t.startsWith("LANGCHAIN_")||t.startsWith("LANGSMITH_"))&&null!=r&&((t.toLowerCase().includes("key")||t.toLowerCase().includes("secret")||t.toLowerCase().includes("token"))&&"string"==typeof r?e[t]=r.slice(0,2)+"*".repeat(r.length-4)+r.slice(-2):e[t]=r)}catch(e){}return e}(),t={},r=["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(let[a,n]of Object.entries(e))"string"!=typeof n||r.includes(a)||a.toLowerCase().includes("key")||a.toLowerCase().includes("secret")||a.toLowerCase().includes("token")||("LANGCHAIN_REVISION_ID"===a?t.revision_id=n:t[a]=n);return t}function eF(e){try{return"u">typeof process?process.env?.[e]:void 0}catch(e){return}}function eH(e){return eF(`LANGSMITH_${e}`)||eF(`LANGCHAIN_${e}`)}function eq(){return"true"===eF("OTEL_ENABLED")||"true"===eH("OTEL_ENABLED")}let eJ=new Set(["langsmith","otel"]);function eG(e){if(void 0!==e)return e;let t=eH("TRACING_MODE");if(void 0!==t&&""!==t){let e=t.toLowerCase();if(!eJ.has(e))throw Error(`Invalid LANGSMITH_TRACING_MODE=${JSON.stringify(t)}. Must be one of: ${[...eJ].sort().join(", ")}`);return eq()&&console.warn("Both LANGSMITH_TRACING_MODE and the legacy OTEL_ENABLED / LANGSMITH_OTEL_ENABLED env vars are set. LANGSMITH_TRACING_MODE takes precedence."),e}return eq()?"otel":"langsmith"}class eW{constructor(){Object.defineProperty(this,"hasWarned",{enumerable:!0,configurable:!0,writable:!0,value:!1})}startActiveSpan(e,...t){let r;if(this.hasWarned||"otel"!==eG()||(console.warn('OTel tracing mode is active (via LANGSMITH_TRACING_MODE, OTEL_ENABLED, or LANGSMITH_OTEL_ENABLED), but the required OTEL instances have not been initialized. Please add:\n```\nimport { initializeOTEL } from "langsmith/experimental/otel/setup";\ninitializeOTEL();\n```\nat the beginning of your code.'),this.hasWarned=!0),1===t.length&&"function"==typeof t[0]?r=t[0]:2===t.length&&"function"==typeof t[1]?r=t[1]:3===t.length&&"function"==typeof t[2]&&(r=t[2]),"function"==typeof r)return r()}}let eV=Symbol.for("ls:otel_trace"),eK=Symbol.for("ls:otel_context"),eY=Symbol.for("ls:otel_get_default_otlp_tracer_provider"),eQ=new class{constructor(){Object.defineProperty(this,"mockTracer",{enumerable:!0,configurable:!0,writable:!0,value:new eW})}getTracer(e,t){return this.mockTracer}getActiveSpan(){}setSpan(e,t){return e}getSpan(e){}setSpanContext(e,t){return e}getTracerProvider(){}setGlobalTracerProvider(e){return!1}},eX=new class{active(){return{}}with(e,t){return t()}},e0=new class{getTraceInstance(){return globalThis[eV]??eQ}getContextInstance(){return globalThis[eK]??eX}initializeGlobalInstances(e){void 0===globalThis[eV]&&(globalThis[eV]=e.trace),void 0===globalThis[eK]&&(globalThis[eK]=e.context)}setDefaultOTLPTracerComponents(e){globalThis[eY]=e}getDefaultOTLPTracerComponents(){return globalThis[eY]??void 0}};function e1(){return e0.getTraceInstance()}let e4={llm:"chat",tool:"execute_tool",retriever:"embeddings",embedding:"embeddings",prompt:"chat"};class e2{constructor(){Object.defineProperty(this,"spans",{enumerable:!0,configurable:!0,writable:!0,value:new Map})}exportBatch(e,t){for(let r of e)try{if(!r.run)continue;if("post"===r.operation){let e=this.createSpanForRun(r,r.run,t.get(r.id));e&&!r.run.end_time&&this.spans.set(r.id,e)}else this.updateSpanForRun(r,r.run)}catch(e){console.error(`Error processing operation ${r.id}:`,e)}}createSpanForRun(e,t,r){let a=r&&e1().getSpan(r);if(a)try{return this.finishSpanSetup(a,t,e)}catch(t){console.error(`Failed to create span for run ${e.id}:`,t);return}}finishSpanSetup(e,t,r){return this.setSpanAttributes(e,t,r),t.error?(e.setStatus({code:2}),e.recordException(Error(t.error))):e.setStatus({code:1}),t.end_time&&e.end(new Date(t.end_time)),e}updateSpanForRun(e,t){try{let r=this.spans.get(e.id);if(!r)return void console.debug(`No span found for run ${e.id} during update`);this.setSpanAttributes(r,t,e),t.error?(r.setStatus({code:2}),r.recordException(Error(t.error))):r.setStatus({code:1});let a=t.end_time;a&&(r.end(new Date(a)),this.spans.delete(e.id))}catch(t){console.error(`Failed to update span for run ${e.id}:`,t)}}extractModelName(e){if(e.extra?.metadata){let t=e.extra.metadata;if(t.ls_model_name)return t.ls_model_name;if(t.invocation_params){let e=t.invocation_params;if(e.model)return e.model;if(e.model_name)return e.model_name}}}setSpanAttributes(e,t,r){if("run_type"in t&&t.run_type){var a;e.setAttribute("langsmith.span.kind",t.run_type);let r=e4[a=t.run_type||"chain"]||a;e.setAttribute("gen_ai.operation.name",r)}"name"in t&&t.name&&e.setAttribute("langsmith.trace.name",t.name),"session_id"in t&&t.session_id&&e.setAttribute("langsmith.trace.session_id",t.session_id),"session_name"in t&&t.session_name&&e.setAttribute("langsmith.trace.session_name",t.session_name),this.setGenAiSystem(e,t);let n=this.extractModelName(t);for(let[r,a]of(n&&e.setAttribute(U,n),"prompt_tokens"in t&&"number"==typeof t.prompt_tokens&&e.setAttribute(B,t.prompt_tokens),"completion_tokens"in t&&"number"==typeof t.completion_tokens&&e.setAttribute(F,t.completion_tokens),"total_tokens"in t&&"number"==typeof t.total_tokens&&e.setAttribute(H,t.total_tokens),this.setInvocationParameters(e,t),Object.entries(t.extra?.metadata||{})))null!=a&&e.setAttribute(`langsmith.metadata.${r}`,String(a));let i=t.tags;if(i&&Array.isArray(i)?e.setAttribute(q,i.join(", ")):i&&e.setAttribute(q,String(i)),"serialized"in t&&"object"==typeof t.serialized){let r=t.serialized;r.name&&e.setAttribute("gen_ai.serialized.name",String(r.name)),r.signature&&e.setAttribute("gen_ai.serialized.signature",String(r.signature)),r.doc&&e.setAttribute("gen_ai.serialized.doc",String(r.doc))}this.setIOAttributes(e,r)}setGenAiSystem(e,t){let r="langchain",a=this.extractModelName(t);if(a){let e=a.toLowerCase();e.includes("anthropic")||e.startsWith("claude")?r="anthropic":e.includes("bedrock")?r="aws.bedrock":e.includes("azure")&&e.includes("openai")?r="az.ai.openai":e.includes("azure")&&e.includes("inference")?r="az.ai.inference":e.includes("cohere")?r="cohere":e.includes("deepseek")?r="deepseek":e.includes("gemini")?r="gemini":e.includes("groq")?r="groq":e.includes("watson")||e.includes("ibm")?r="ibm.watsonx.ai":e.includes("mistral")?r="mistral_ai":e.includes("gpt")||e.includes("openai")?r="openai":e.includes("perplexity")||e.includes("sonar")?r="perplexity":e.includes("vertex")?r="vertex_ai":(e.includes("xai")||e.includes("grok"))&&(r="xai")}e.setAttribute("gen_ai.system",r)}setInvocationParameters(e,t){if(!t.extra?.metadata?.invocation_params)return;let r=t.extra.metadata.invocation_params;void 0!==r.max_tokens&&e.setAttribute("gen_ai.request.max_tokens",r.max_tokens),void 0!==r.temperature&&e.setAttribute("gen_ai.request.temperature",r.temperature),void 0!==r.top_p&&e.setAttribute("gen_ai.request.top_p",r.top_p),void 0!==r.frequency_penalty&&e.setAttribute("gen_ai.request.frequency_penalty",r.frequency_penalty),void 0!==r.presence_penalty&&e.setAttribute("gen_ai.request.presence_penalty",r.presence_penalty)}setIOAttributes(e,t){if(t.run.inputs)try{let r=t.run.inputs;"object"==typeof r&&null!==r&&(r.model&&Array.isArray(r.messages)&&e.setAttribute(U,r.model),void 0!==r.stream&&e.setAttribute("langsmith.request.streaming",r.stream),r.extra_headers&&e.setAttribute("langsmith.request.headers",JSON.stringify(r.extra_headers)),r.extra_query&&e.setAttribute("gen_ai.request.extra_query",JSON.stringify(r.extra_query)),r.extra_body&&e.setAttribute("gen_ai.request.extra_body",JSON.stringify(r.extra_body))),e.setAttribute("gen_ai.prompt",JSON.stringify(r))}catch(e){console.debug(`Failed to process inputs for run ${t.id}`,e)}if(t.run.outputs)try{let r=t.run.outputs,a=this.getUnifiedRunTokens(r);if(a&&(e.setAttribute(B,a[0]),e.setAttribute(F,a[1]),e.setAttribute(H,a[0]+a[1])),r&&"object"==typeof r){if(r.model&&e.setAttribute("gen_ai.response.model",String(r.model)),r.id&&e.setAttribute("gen_ai.response.id",r.id),r.choices&&Array.isArray(r.choices)){let t=r.choices.map(e=>e.finish_reason).filter(e=>e).map(String);t.length>0&&e.setAttribute("gen_ai.response.finish_reasons",t.join(", "))}if(r.service_tier&&e.setAttribute("gen_ai.response.service_tier",r.service_tier),r.system_fingerprint&&e.setAttribute("gen_ai.response.system_fingerprint",r.system_fingerprint),r.usage_metadata&&"object"==typeof r.usage_metadata){let t=r.usage_metadata;t.input_token_details&&e.setAttribute("gen_ai.usage.input_token_details",JSON.stringify(t.input_token_details)),t.output_token_details&&e.setAttribute("gen_ai.usage.output_token_details",JSON.stringify(t.output_token_details))}}e.setAttribute("gen_ai.completion",JSON.stringify(r))}catch(e){console.debug(`Failed to process outputs for run ${t.id}`,e)}}getUnifiedRunTokens(e){if(!e)return null;let t=this.extractUnifiedRunTokens(e.usage_metadata);if(t)return t;for(let r of Object.keys(e)){let a=e[r];if(a&&"object"==typeof a&&((t=this.extractUnifiedRunTokens(a.usage_metadata))||1===a.lc&&a.kwargs&&"object"==typeof a.kwargs&&(t=this.extractUnifiedRunTokens(a.kwargs.usage_metadata))))return t}let r=e.generations||[];if(!Array.isArray(r))return null;for(let e of Array.isArray(r[0])?r.flat():r)if("object"==typeof e&&e.message&&"object"==typeof e.message&&e.message.kwargs&&"object"==typeof e.message.kwargs&&(t=this.extractUnifiedRunTokens(e.message.kwargs.usage_metadata)))return t;return null}extractUnifiedRunTokens(e){return e&&"object"==typeof e&&"number"==typeof e.input_tokens&&"number"==typeof e.output_tokens?[e.input_tokens,e.output_tokens]:null}}let e9=Object.prototype.toString,e6=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"]);function e5(e,t,{min:r=0,allowInfinity:a=!1}={}){if(void 0!==t){if("number"!=typeof t||Number.isNaN(t))throw TypeError(`Expected \`${e}\` to be a number${a?" or Infinity":""}.`);if(!a&&!Number.isFinite(t))throw TypeError(`Expected \`${e}\` to be a finite number.`);if(t=e8(a,l))throw s;let d=await n.shouldConsumeRetry(u),c=e8(a,l);if(c<=0||o<=0)throw s;if(s instanceof TypeError&&!function(e){if(!(e&&"[object Error]"===e9.call(e)&&"TypeError"===e.name&&"string"==typeof e.message))return!1;let{message:t,stack:r}=e;return"Load failed"===t?void 0===r||"__sentry_captured__"in e:!!t.startsWith("error sending request for url")||e6.has(t)}(s)){if(d)throw s;return n.signal?.throwIfAborted(),!1}if(!await n.shouldRetry(u))throw s;if(!d)return n.signal?.throwIfAborted(),!1;let h=Math.min((i=Math.max(1,r+1),Math.min(Math.round((n.randomize?Math.random()+1:1)*n.minTimeout*n.factor**(i-1)),n.maxTimeout)),c);return h>0&&await new Promise((e,t)=>{let r=()=>{clearTimeout(a),n.signal?.removeEventListener("abort",r),t(n.signal.reason)},a=setTimeout(()=>{n.signal?.removeEventListener("abort",r),e()},h);n.unref&&a.unref?.(),n.signal?.addEventListener("abort",r,{once:!0})}),n.signal?.throwIfAborted(),!0}async function te(e,t={}){var r=(t={...t}).retries;if("number"==typeof r){if(r<0)throw TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(r))throw TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(void 0!==r)throw TypeError("Expected `retries` to be a number or Infinity.");if(Object.hasOwn(t,"forever"))throw Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");t.retries??=10,t.factor??=2,t.minTimeout??=1e3,t.maxTimeout??=1/0,t.maxRetryTime??=1/0,t.randomize??=!1,t.onFailedAttempt??=()=>{},t.shouldRetry??=()=>!0,t.shouldConsumeRetry??=()=>!0,e5("factor",t.factor,{min:0,allowInfinity:!1}),e5("minTimeout",t.minTimeout,{min:0,allowInfinity:!1}),e5("maxTimeout",t.maxTimeout,{min:0,allowInfinity:!0}),e5("maxRetryTime",t.maxRetryTime,{min:0,allowInfinity:!0}),t.factor>0||(t.factor=1),t.signal?.throwIfAborted();let a=0,n=0,i=performance.now();for(;!Number.isFinite(t.retries)||n<=t.retries;){a++;try{t.signal?.throwIfAborted();let r=await e(a);return t.signal?.throwIfAborted(),r}catch(e){await e7({error:e,attemptNumber:a,retriesConsumed:n,startTime:i,options:t})&&n++}}throw Error("Retry attempts exhausted without throwing an error.")}var tt=e.i(655747);let tr="default"in tt.default?tt.default.default:tt.default,ta=[408,425,429,500,502,503,504];class tn{constructor(e){Object.defineProperty(this,"maxConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxRetries",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxQueueSizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onFailedResponseHook",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queueSizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0}),this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,this.maxQueueSizeBytes=e.maxQueueSizeBytes,this.queue=new tr({concurrency:this.maxConcurrency}),this.onFailedResponseHook=e?.onFailedResponseHook}call(e,...t){return this.callWithOptions({},e,...t)}callWithOptions(e,t,...r){let a=e.sizeBytes??0;if(void 0!==this.maxQueueSizeBytes&&a>0&&this.queueSizeBytes+a>this.maxQueueSizeBytes)return Promise.reject(Error(`Queue size limit (${this.maxQueueSizeBytes} bytes) exceeded. Current queue size: ${this.queueSizeBytes} bytes, attempted addition: ${a} bytes.`));a>0&&(this.queueSizeBytes+=a);let n=this.onFailedResponseHook,i=this.queue.add(()=>te(()=>t(...r).catch(e=>{if(e instanceof Error)throw e;throw Error(e)}),{async onFailedAttempt({error:e}){if("object"!=typeof e||null==e)throw e;let t="message"in e&&"string"==typeof e.message?e.message:void 0;if(t?.startsWith("Cancel")||t?.startsWith("TimeoutError")||t?.startsWith("AbortError")||"name"in e&&"TimeoutError"===e.name||"code"in e&&"ECONNABORTED"===e.code)throw e;let r="response"in e?e.response:void 0;if(n&&await n(r))return;let a=r?.status??("status"in e?e.status:void 0);if(null!=a&&("number"==typeof a||"string"==typeof a)&&!ta.includes(+a))throw e},retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0});return(a>0&&(i=i.finally(()=>{this.queueSizeBytes-=a})),e.signal)?Promise.race([i,new Promise((t,r)=>{e.signal?.addEventListener("abort",()=>{r(Error("AbortError"))})})]):i}}function ti(e){return"function"==typeof e?._getType}function ts(e){let t={type:e._getType(),data:{content:e.content}};return e?.additional_kwargs&&Object.keys(e.additional_kwargs).length>0&&(t.data.additional_kwargs={...e.additional_kwargs}),t}let to={};function tl(e){to[e]||(console.warn(e),to[e]=!0)}function tu(e){return`Invalid prompt identifier format: "${e}". Expected one of: - "prompt-name" (for private prompts) - "owner/prompt-name" (for prompts with explicit owner) - "prompt-name:commit-hash" (with commit reference) - "owner/prompt-name:commit-hash" (with owner and commit)`}class td extends Error{constructor(e){super(e),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="LangSmithConflictError",this.status=409}}class tc extends Error{constructor(e){super(e),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="LangSmithNotFoundError",this.status=404}}function th(e){return null!=e&&"object"==typeof e&&"name"in e&&e?.name==="LangSmithNotFoundError"}async function tp(e,t,r){let a;if(e.ok){r&&(a=await e.text());return}if(403===e.status)try{let t=await e.json(),r=t?.error;"org_scoped_key_requires_workspace"===r&&(a="This API key is org-scoped and requires workspace specification. Please provide 'workspaceId' parameter, or set LANGSMITH_WORKSPACE_ID environment variable.")}catch(r){let t=Error(`${e.status} ${e.statusText}`);throw t.status=e?.status,t}if(void 0===a)try{a=await e.text()}catch(e){a=""}let n=`Failed to ${t}. Received status [${e.status}]: ${e.statusText}. Message: ${a}`;if(404===e.status)throw new tc(n);if(409===e.status)throw new td(n);let i=Error(n);throw i.status=e.status,i}let tf="ERR_CONFLICTING_ENDPOINTS";class tm extends Error{constructor(){super("You cannot provide both LANGSMITH_ENDPOINT / LANGCHAIN_ENDPOINT and LANGSMITH_RUNS_ENDPOINTS."),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:tf}),this.name="ConflictingEndpointsError"}}function tg(e){if(!e||e.split("/").length>2||e.startsWith("/")||e.endsWith("/")||e.split(":").length>2)throw Error(tu(e));let[t,r]=e.split(":"),a=r||"latest";if(t.includes("/")){let[r,n]=t.split("/",2);if(!r||!n)throw Error(tu(e));return[r,n,a]}if(!t)throw Error(tu(e));return["-",t,a]}var t_={result:"[Circular]"},ty=[],tv=[];let tb=new TextEncoder;function tw(e){return tb.encode(e)}function tk(e){if(e&&"object"==typeof e&&null!==e){if(e instanceof Map)return Object.fromEntries(e);else if(e instanceof Set)return Array.from(e);else if(e instanceof Date)return e.toISOString();else if(e instanceof RegExp)return e.toString();else if(e instanceof Error)return{name:e.name,message:e.message}}else if("bigint"==typeof e)return e.toString();return e}function tx(e,t,r,a,n){try{let t=JSON.stringify(e,function(e,t){if(r){let a=r.call(this,e,t);if(void 0!==a)return a}return tk(t)},a);return tw(t)}catch(o){let s;if(!o.message?.includes("Converting circular structure to JSON"))return console.warn(`[WARNING]: LangSmith received unserializable value.${t?` Context: ${t}`:""}`),tw("[Unserializable]");"true"!==eH("SUPPRESS_CIRCULAR_JSON_WARNINGS")&&console.warn(`[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. ${t?` Context: ${t}`:""}`),void 0===n&&(n={depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}),function e(t,r,a,n,i,s,o){if(s+=1,"object"==typeof t&&null!==t){for(l=0;lo.depthLimit||void 0!==o.edgesLimit&&a+1>o.edgesLimit)return void tS("[...]",t,r,i);if(n.push(t),Array.isArray(t))for(l=0;l0)for(var r=0;r string). if (normalized === val) { const keys = Object.keys(val); for (let i = 0; i < keys.length; i++) decirc(val[keys[i]], keys[i], stack, val); } } stack.pop(); } } function serialize(obj) { try { return JSON.stringify(obj, defaultReplacer); } catch (e) { if (!String(e && e.message).includes("Converting circular structure to JSON")) { return "[Unserializable]"; } decirc(obj, "", [], { "": obj }); try { return JSON.stringify(obj, defaultReplacer); } catch (_) { return "[unable to serialize, circular reference is too complex to analyze]"; } finally { while (restoreStack.length) { const [p, k, v] = restoreStack.pop(); p[k] = v; } } } } parentPort.on("message", (msg) => { const { id, op, payload } = msg; try { if (op === "serialize") { const str = serialize(payload); const buf = Buffer.from(str, "utf8"); // Slice into its own ArrayBuffer so we can transfer without dragging // unrelated bytes from any shared pool buffer. const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); parentPort.postMessage({ id, bytes: ab, length: buf.byteLength }, [ab]); } else if (op === "ping") { parentPort.postMessage({ id }); } else { parentPort.postMessage({ id, error: "unknown op: " + op }); } } catch (e) { parentPort.postMessage({ id, error: String((e && e.message) || e) }); } }); `;class tT{constructor(){Object.defineProperty(this,"worker",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"nextId",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"pending",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"disabled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"startPromise",{enumerable:!0,configurable:!0,writable:!0,value:null})}async ensureStarted(){if(this.disabled)return!1;if(null!==this.worker)return!0;if(null!==this.startPromise)return this.startPromise;this.startPromise=this._start();try{return await this.startPromise}finally{this.startPromise=null}}async _start(){if(null===t$)return this.disabled=!0,!1;try{let e=new t$(tE,{eval:!0});return e.on("message",e=>{let t=this.pending.get(e.id);t&&(this.pending.delete(e.id),e.error?t.reject(Error(e.error)):e.bytes&&"number"==typeof e.length?t.resolve(new Uint8Array(e.bytes,0,e.length)):t.reject(Error("worker returned malformed message")))}),e.on("error",e=>{for(let[,t]of this.pending)t.reject(e);this.pending.clear(),this.disabled=!0,this.worker=null}),e.on("exit",e=>{for(let[,t]of this.pending)t.reject(Error(`worker exited with code ${e}`));this.pending.clear(),this.worker=null}),e.unref(),this.worker=e,!0}catch{return this.disabled=!0,!1}}async serialize(e){if(!await this.ensureStarted())return null;let t=this.nextId++;return new Promise((r,a)=>{this.pending.set(t,{resolve:r,reject:a});try{this.worker.postMessage({id:t,op:"serialize",payload:e})}catch(e){this.pending.delete(t),a(e)}})}async terminate(){for(let[,e]of(this.worker&&(await this.worker.terminate(),this.worker=null),this.pending))e.reject(Error("worker terminated"));this.pending.clear()}}let tA=null;function tC(e){return"string"!=typeof e||!(e.length>0)||e.includes("Z")||e.includes("+")||e.includes("-",10)?e:e+"Z"}function tO(e){return{...e,start_time:tC(e.start_time),end_time:tC(e.end_time)}}function tI(e,t,r){if(r)return e;let a=eU(),n=t??eB(),i=e.extra??{},s=i.metadata;return e.extra={...i,runtime:{...a,...i?.runtime},metadata:{...n,...n.revision_id||"revision_id"in e&&e.revision_id?{revision_id:("revision_id"in e?e.revision_id:void 0)??n.revision_id}:{},...s}},e}async function tj(e){let t=[];for await(let r of e)t.push(r);return t}function tP(e){if(void 0!==e)return e.trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}let tz=async e=>{if(e?.status===429){let t=1e3*parseInt(e.headers.get("retry-after")??"10",10);if(t>0)return await new Promise(e=>setTimeout(e,t)),!0}return!1};function tN(e){return"number"==typeof e?Number(e.toFixed(4)):e}let tR="https://api.smith.langchain.com";class tM{constructor(e){Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"sizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"maxSizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSizeBytes=e??0x40000000}peek(){return this.items[0]}push(e){let t,r=new Promise(e=>{t=e}),a=function(e){try{let n=new Set,i=0,s="u">typeof Buffer&&"function"==typeof Buffer.byteLength?e=>Buffer.byteLength(e,"utf8"):e=>e.length;function t(e){return void 0===e||"function"==typeof e||"symbol"==typeof e}function r(e){return void 0===e||"function"==typeof e||"symbol"==typeof e?4:a(e)}function a(e){var o;let l;if(null===e)return 4;if(void 0===e)return 0;let u=typeof e;if("boolean"===u)return 5;if("number"===u)return Number.isFinite(e)?e.toString().length:4;if("bigint"===u)return e.toString().length+2;if("string"===u){let t;return(t=s(e))>i&&(i=t),t+2}if("function"===u||"symbol"===u)return 0;if(e instanceof Date)return 26;if(e instanceof RegExp)return s(e.toString())+2;if(e instanceof Error){let t=e.name??"",r=e.message??"";return 22+s(t)+s(r)}if("u">typeof Buffer&&e instanceof Buffer)return 28+(o=e.byteLength,0===o?2:2+4*o);if(ArrayBuffer.isView(e)){if(e instanceof DataView)return 2;let t=e.length??0,r=e instanceof Float32Array||e instanceof Float64Array;return 2+t*(r?30:12)}if(e instanceof ArrayBuffer)return 2;if(n.has(e))return 24;if("function"==typeof e.toJSON){let t;try{t=e.toJSON("")}catch{return 16}n.add(e);let r=a(t);return n.delete(e),r}if(n.add(e),Array.isArray(e)){l=2;let t=e.length;for(let a=0;a0&&(l+=1);let e="string"==typeof n?n:String(n);l+=s(e)+3,l+=a(i),r++}}else if(e instanceof Set){l=2;let t=0;for(let a of e)t>0&&(l+=1),l+=r(a),t++}else{l=2;let r=0,n=Object.keys(e);for(let i=0;i0&&(l+=1),l+=s(o)+3,l+=a(u),r++)}}return n.delete(e),l}return{size:a(e),maxStringLen:i}}catch{return{size:tx(e).length,maxStringLen:0}}}(e.item).size;return this.sizeBytes+a>this.maxSizeBytes&&this.items.length>0?(console.warn(`AutoBatchQueue size limit (${this.maxSizeBytes} bytes) exceeded. Dropping run with id: ${e.item.id}. Current queue size: ${this.sizeBytes} bytes, attempted addition: ${a} bytes.`),t()):(this.items.push({action:e.action,payload:e.item,otelContext:e.otelContext,apiKey:e.apiKey,apiUrl:e.apiUrl,itemPromiseResolve:t,itemPromise:r,size:a}),this.sizeBytes+=a),r}pop({upToSizeBytes:e,upToSize:t}){if(e<1)throw Error("Number of bytes to pop off may not be less than 1.");let r=[],a=0;for(;a+(this.peek()?.size??0)0&&r.length0){let e=this.items.shift();r.push(e),a+=e.size,this.sizeBytes-=e.size}return[r.map(e=>({action:e.action,item:e.payload,otelContext:e.otelContext,apiKey:e.apiKey,apiUrl:e.apiUrl,size:e.size})),()=>r.forEach(e=>e.itemPromiseResolve())]}}class tL{get tracingMode(){return this._tracingMode}get _fetch(){let e;return this.fetchImplementation||(e=this.debug,async(...t)=>{if(e||"true"===eH("DEBUG")){let[e,r]=t;console.log(`→ ${r?.method||"GET"} ${e}`)}let r=await (globalThis[J]??((...e)=>fetch(...e)))(...t);return(e||"true"===eH("DEBUG"))&&console.log(`← ${r.status} ${r.statusText} ${r.url}`),r})}_trackDrain(e){this._pendingDrains.add(e),e.finally(()=>{this._pendingDrains.delete(e)})}async _serializeBody(e,t){if(this.manualFlushMode||!function(e,t=65536,r=2048){if(null===e||"object"!=typeof e)return"string"==typeof e&&e.length>=t;let a=[e],n=new Set,i=0;for(;a.length>0&&!(i++>=r);){let e=a.pop();if(null==e)continue;let r=typeof e;if("string"===r){if(e.length>=t)return!0;continue}if("object"!==r||n.has(e)||(n.add(e),e instanceof Date||e instanceof RegExp||e instanceof Error||e instanceof ArrayBuffer||ArrayBuffer.isView(e)))continue;if(Array.isArray(e)){for(let t=e.length-1;t>=0;t--)a.push(e[t]);continue}if(e instanceof Map){for(let[,t]of e)a.push(t);continue}if(e instanceof Set){for(let t of e)a.push(t);continue}let i=Object.keys(e);for(let t=i.length-1;t>=0;t--)a.push(e[i[t]])}return!1}(e)||(void 0===this._serializeWorker&&(this._serializeWorker=(null===tA&&(tA=new tT),tA)),null===this._serializeWorker))return tx(e,t);try{let r=await this._serializeWorker.serialize(e);if(null===r)return this._serializeWorker=null,tx(e,t);return r}catch{return tx(e,t)}}constructor(e={}){Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"apiUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"webUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"workspaceId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"caller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchIngestCaller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"timeout_ms",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_tenantId",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"hideInputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"hideOutputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"hideMetadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"omitTracedRuntimeInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingSampleRate",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"filteredPostUuids",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"autoBatchTracing",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"autoBatchQueue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"autoBatchTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"autoBatchAggregationDelayMs",{enumerable:!0,configurable:!0,writable:!0,value:250}),Object.defineProperty(this,"batchSizeBytesLimit",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchSizeLimit",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetchOptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"settings",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"blockOnRootRunFinalization",{enumerable:!0,configurable:!0,writable:!0,value:"false"===eF("LANGSMITH_TRACING_BACKGROUND")}),Object.defineProperty(this,"traceBatchConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:5}),Object.defineProperty(this,"_serverInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_getServerInfoPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"manualFlushMode",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_serializeWorker",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_pendingDrains",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"langSmithToOTELTranslator",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_tracingMode",{enumerable:!0,configurable:!0,writable:!0,value:"langsmith"}),Object.defineProperty(this,"fetchImplementation",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cachedLSEnvVarsForMetadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_promptCache",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"multipartStreamingDisabled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_multipartDisabled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_runCompressionDisabled",{enumerable:!0,configurable:!0,writable:!0,value:"true"===eH("DISABLE_RUN_COMPRESSION")}),Object.defineProperty(this,"failedTracesDir",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"failedTracesMaxBytes",{enumerable:!0,configurable:!0,writable:!0,value:0x6400000}),Object.defineProperty(this,"_customHeaders",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"debug",{enumerable:!0,configurable:!0,writable:!0,value:"true"===eF("LANGSMITH_DEBUG")});const t=tL.getDefaultClientConfig();if(this.tracingSampleRate=(e=>{let t=e?.toString()??eH("TRACING_SAMPLING_RATE");if(void 0===t)return;let r=parseFloat(t);if(r<0||r>1)throw Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${r}`);return r})(e.tracingSamplingRate),this.apiUrl=tP(e.apiUrl??t.apiUrl)??"",this.apiUrl.endsWith("/")&&(this.apiUrl=this.apiUrl.slice(0,-1)),this.apiKey=tP(e.apiKey??t.apiKey),this.webUrl=tP(e.webUrl??t.webUrl),this.webUrl?.endsWith("/")&&(this.webUrl=this.webUrl.slice(0,-1)),this.workspaceId=tP(e.workspaceId??eH("WORKSPACE_ID")),this.timeout_ms=e.timeout_ms??9e4,this.caller=new tn({...e.callerOptions??{},maxRetries:4,debug:e.debug??this.debug}),this.traceBatchConcurrency=e.traceBatchConcurrency??this.traceBatchConcurrency,this.traceBatchConcurrency<1)throw Error("Trace batch concurrency must be positive.");this.debug=e.debug??this.debug,this.fetchImplementation=e.fetchImplementation,this.failedTracesDir=eH("FAILED_TRACES_DIR")||void 0;const r=eH("FAILED_TRACES_MAX_MB");if(r){const e=parseInt(r,10);Number.isFinite(e)&&e>0&&(this.failedTracesMaxBytes=1024*e*1024)}const a=e.maxIngestMemoryBytes??0x40000000;this.batchIngestCaller=new tn({maxRetries:4,maxConcurrency:this.traceBatchConcurrency,maxQueueSizeBytes:a,...e.callerOptions??{},onFailedResponseHook:tz,debug:e.debug??this.debug}),this.hideInputs=e.hideInputs??e.anonymizer??t.hideInputs,this.hideOutputs=e.hideOutputs??e.anonymizer??t.hideOutputs,this.hideMetadata=e.hideMetadata??t.hideMetadata,this.omitTracedRuntimeInfo=e.omitTracedRuntimeInfo??!1,this.autoBatchTracing=e.autoBatchTracing??this.autoBatchTracing,this.autoBatchQueue=new tM(a),this.blockOnRootRunFinalization=e.blockOnRootRunFinalization??this.blockOnRootRunFinalization,this.batchSizeBytesLimit=e.batchSizeBytesLimit,this.batchSizeLimit=e.batchSizeLimit,this.fetchOptions=e.fetchOptions||{},this.manualFlushMode=e.manualFlushMode??this.manualFlushMode,this._tracingMode=eG(e.tracingMode),"otel"===this._tracingMode&&(this.langSmithToOTELTranslator=new e2),this.cachedLSEnvVarsForMetadata=eB(),void 0!==e.cache&&e.disablePromptCache&&tl("Both 'cache' and 'disablePromptCache' were provided. The 'cache' parameter is deprecated and will be removed in a future version. Using 'cache' parameter value."),void 0!==e.cache?(tl("The 'cache' parameter is deprecated and will be removed in a future version. Use 'configureGlobalPromptCache()' to configure the global cache, or 'disablePromptCache: true' to disable caching for this client."),!1===e.cache?this._promptCache=void 0:!0===e.cache?this._promptCache=eL:this._promptCache=e.cache):e.disablePromptCache||(this._promptCache=eL),this._customHeaders=e.headers??{}}static getDefaultClientConfig(){let e=eH("API_KEY");return{apiUrl:eH("ENDPOINT")??tR,apiKey:e,webUrl:void 0,hideInputs:"true"===eH("HIDE_INPUTS"),hideOutputs:"true"===eH("HIDE_OUTPUTS"),hideMetadata:"true"===eH("HIDE_METADATA")}}getHostUrl(){let e;if(this.webUrl)return this.webUrl;if("localhost"===(e=this.apiUrl.replace("http://","").replace("https://","").split("/")[0].split(":")[0])||"127.0.0.1"===e||"::1"===e)return this.webUrl="http://localhost:3000",this.webUrl;if(this.apiUrl.endsWith("/api/v1"))return this.webUrl=this.apiUrl.replace("/api/v1",""),this.webUrl;if(this.apiUrl.includes("/api")&&!this.apiUrl.split(".",1)[0].endsWith("api"))return this.webUrl=this.apiUrl.replace("/api",""),this.webUrl;if(this.apiUrl.split(".",1)[0].includes("dev"))return this.webUrl="https://dev.smith.langchain.com",this.webUrl;else if(this.apiUrl.split(".",1)[0].includes("eu"))return this.webUrl="https://eu.smith.langchain.com",this.webUrl;else if(this.apiUrl.split(".",1)[0].includes("aws"))return this.webUrl="https://aws.smith.langchain.com",this.webUrl;else if(this.apiUrl.split(".",1)[0].includes("apac"))return this.webUrl="https://apac.smith.langchain.com",this.webUrl;else if(this.apiUrl.split(".",1)[0].includes("beta"))return this.webUrl="https://beta.smith.langchain.com",this.webUrl;else return this.webUrl="https://smith.langchain.com",this.webUrl}get _mergedHeaders(){let e={"User-Agent":`langsmith-js/${eZ}`,...this._customHeaders};return this.apiKey&&(e["x-api-key"]=`${this.apiKey}`),this.workspaceId&&(e["x-tenant-id"]=this.workspaceId),e}get headers(){return this._customHeaders}set headers(e){this._customHeaders=e??{}}_getPlatformEndpointPath(e){return"/v1"!==this.apiUrl.slice(-3)&&"/v1/"!==this.apiUrl.slice(-4)?`/v1/platform/${e}`:`/platform/${e}`}async processInputs(e){return!1===this.hideInputs?e:!0===this.hideInputs?{}:"function"==typeof this.hideInputs?this.hideInputs(e):e}async processOutputs(e){return!1===this.hideOutputs?e:!0===this.hideOutputs?{}:"function"==typeof this.hideOutputs?this.hideOutputs(e):e}async processMetadata(e){return!1===this.hideMetadata?e:!0===this.hideMetadata?{}:"function"==typeof this.hideMetadata?this.hideMetadata(e):e}_filterNewTokenEvents(e){return e&&0!==e.length?e.map(e=>{if("new_token"===e.name){let{kwargs:t,...r}=e;return r}return e}):e}async prepareRunCreateOrUpdateInputs(e){let t={...e};return void 0!==t.inputs&&(t.inputs=await this.processInputs(t.inputs)),void 0!==t.outputs&&(t.outputs=await this.processOutputs(t.outputs)),null!=t.extra&&"metadata"in t.extra&&(t.extra={...t.extra,metadata:await this.processMetadata(t.extra.metadata)}),void 0!==t.events&&(t.events=this._filterNewTokenEvents(t.events)),t}async _getResponse(e,t){let r=t?.toString()??"",a=`${this.apiUrl}${e}?${r}`;return await this.caller.call(async()=>{let t=await this._fetch(a,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await tp(t,`fetch ${e}`),t})}async _get(e,t){return(await this._getResponse(e,t)).json()}async *_getPaginated(e,t=new URLSearchParams,r){let a=Number(t.get("offset"))||0,n=Number(t.get("limit"))||100;for(;;){t.set("offset",String(a)),t.set("limit",String(n));let i=`${this.apiUrl}${e}?${t}`,s=await this.caller.call(async()=>{let t=await this._fetch(i,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await tp(t,`fetch ${e}`),t}),o=r?r(await s.json()):await s.json();if(0===o.length||(yield o,o.length{let a=await this._fetch(`${this.apiUrl}${e}`,{method:r,headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:t});return await tp(a,`fetch ${e}`),a}),s=await i.json();if(!s||!s[a])break;yield s[a];let o=s.cursors;if(!o||!o.next)break;n.cursor=o.next}}_shouldSample(){return void 0===this.tracingSampleRate||Math.random()0;){let[a,n]=this.autoBatchQueue.pop({upToSizeBytes:e,upToSize:t});if(!a.length){n();break}let i=a.reduce((e,t)=>{let r=t.apiUrl??this.apiUrl,a=t.apiKey??this.apiKey,n=t.apiKey===this.apiKey&&t.apiUrl===this.apiUrl?"default":`${r}|${a}`;return e[n]||(e[n]=[]),e[n].push(t),e},{}),s=[];for(let[e,t]of Object.entries(i)){let r=this._processBatch(t,{apiUrl:"default"===e?void 0:e.split("|")[0],apiKey:"default"===e?void 0:e.split("|")[1]});s.push(r)}let o=Promise.all(s).finally(n);r.push(o)}return Promise.all(r)}static async _writeTraceToFallbackDir(e,t,r,a,n){try{let i="string"==typeof t?Buffer.from(t,"utf8"):Buffer.from(t),s=JSON.stringify({version:1,endpoint:a,headers:r,body_base64:i.toString("base64")}),o=`trace_${Date.now()}_${P().slice(0,8)}.json`,l=ej.join(e,o);if(tL._fallbackDirsCreated.has(e)||(await eP(e),tL._fallbackDirsCreated.add(e)),void 0!==n&&n>0)try{let t=(await eN(e)).filter(e=>e.startsWith("trace_")&&e.endsWith(".json")),r=0;for(let a of t){let{size:t}=await eR(ej.join(e,a));r+=t}if(r>=n)return void console.warn(`Could not write trace to fallback dir ${e} as it's already over size limit (${r} bytes >= ${n} bytes). Increase LANGSMITH_FAILED_TRACES_MAX_MB if possible.`)}catch{}await ez(l,s),console.warn(`LangSmith trace upload failed; data saved to ${l} for later replay.`)}catch(t){console.error(`LangSmith tracing error: could not write trace to fallback dir ${e}:`,t)}}async _processBatch(e,t){if(!e.length)return;let r=e.reduce((e,t)=>e+(t.size??0),0);try{if(void 0!==this.langSmithToOTELTranslator)this._sendBatchToOTELTranslator(e);else{let a={runCreates:e.filter(e=>"create"===e.action).map(e=>e.item),runUpdates:e.filter(e=>"update"===e.action).map(e=>e.item)},n=await this._ensureServerInfo();if(!this._multipartDisabled&&(n?.batch_ingest_config?.use_multipart_endpoint??!0)){let e=!this._runCompressionDisabled&&n?.instance_flags?.gzip_body_enabled;try{await this.multipartIngestRuns(a,{...t,useGzip:e,sizeBytes:r})}catch(e){if(th(e))this._multipartDisabled=!0,await this.batchIngestRuns(a,{...t,sizeBytes:r});else throw e}}else await this.batchIngestRuns(a,{...t,sizeBytes:r})}}catch(e){console.error("Error exporting batch:",e)}}_sendBatchToOTELTranslator(e){if(void 0!==this.langSmithToOTELTranslator){let t=new Map,r=[];for(let a of e)a.item.id&&a.otelContext&&(t.set(a.item.id,a.otelContext),"create"===a.action?r.push({operation:"post",id:a.item.id,trace_id:a.item.trace_id??a.item.id,run:a.item}):r.push({operation:"patch",id:a.item.id,trace_id:a.item.trace_id??a.item.id,run:a.item}));this.langSmithToOTELTranslator.exportBatch(r,t)}}async processRunOperation(e){clearTimeout(this.autoBatchTimeout),this.autoBatchTimeout=void 0,e.item=tI(e.item,this.cachedLSEnvVarsForMetadata,this.omitTracedRuntimeInfo);let t=this.autoBatchQueue.push(e);if(this.manualFlushMode)return t;let r=await this._getBatchSizeLimitBytes(),a=await this._getBatchSizeLimit();return(this.autoBatchQueue.sizeBytes>r||this.autoBatchQueue.items.length>a)&&this._trackDrain(this.drainAutoBatchQueue({batchSizeLimitBytes:r,batchSizeLimit:a})),this.autoBatchQueue.items.length>0&&(this.autoBatchTimeout=setTimeout(()=>{this.autoBatchTimeout=void 0,this._trackDrain(this.drainAutoBatchQueue({batchSizeLimitBytes:r,batchSizeLimit:a}))},this.autoBatchAggregationDelayMs)),t}async _getServerInfo(){let e=await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/info`,{method:"GET",headers:{...this._mergedHeaders,Accept:"application/json"},signal:AbortSignal.timeout(1e4),...this.fetchOptions});return await tp(e,"get server info"),e}),t=await e.json();return this.debug&&console.log("\n=== LangSmith Server Configuration ===\n"+JSON.stringify(t,null,2)+"\n"),t}async _ensureServerInfo(){return void 0===this._getServerInfoPromise&&(this._getServerInfoPromise=(async()=>{if(void 0===this._serverInfo)try{this._serverInfo=await this._getServerInfo()}catch(e){console.warn(`[LANGSMITH]: Failed to fetch info on supported operations. Falling back to batch operations and default limits. Info: ${e.status??"Unspecified status code"} ${e.message}`)}return this._serverInfo??{}})()),this._getServerInfoPromise.then(e=>(void 0===this._serverInfo&&(this._getServerInfoPromise=void 0),e))}async _getSettings(){return this.settings||(this.settings=this._get("/settings")),await this.settings}async flush(){let e=await this._getBatchSizeLimitBytes(),t=await this._getBatchSizeLimit();await this.drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:t})}_cloneCurrentOTELContext(){let e=e1(),t=e0.getContextInstance();if(void 0!==this.langSmithToOTELTranslator){let r=e.getActiveSpan();if(r)return e.setSpan(t.active(),r)}}async createRun(e,t){if(!this._filterForSampling([e]).length)return;let r={...this._mergedHeaders,"Content-Type":"application/json"},a=e.project_name;delete e.project_name;let n=await this.prepareRunCreateOrUpdateInputs({session_name:a,...e,start_time:e.start_time??Date.now()});if(this.autoBatchTracing&&void 0!==n.trace_id&&void 0!==n.dotted_order){let e=this._cloneCurrentOTELContext();this.processRunOperation({action:"create",item:n,otelContext:e,apiKey:t?.apiKey,apiUrl:t?.apiUrl}).catch(console.error);return}let i=tI(n,this.cachedLSEnvVarsForMetadata,this.omitTracedRuntimeInfo);t?.apiKey!==void 0&&(r["x-api-key"]=t.apiKey),t?.workspaceId!==void 0&&(r["x-tenant-id"]=t.workspaceId);let s=tx(i,`Creating run with id: ${i.id}`);await this.caller.call(async()=>{let e=await this._fetch(`${t?.apiUrl??this.apiUrl}/runs`,{method:"POST",headers:r,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await tp(e,"create run",!0),e})}async batchIngestRuns({runCreates:e,runUpdates:t},r){if(void 0===e&&void 0===t)return;let a=await Promise.all(e?.map(e=>this.prepareRunCreateOrUpdateInputs(e))??[]),n=await Promise.all(t?.map(e=>this.prepareRunCreateOrUpdateInputs(e))??[]);if(a.length>0&&n.length>0){let e=a.reduce((e,t)=>(t.id&&(e[t.id]=t),e),{}),t=[];for(let r of n)void 0!==r.id&&e[r.id]?e[r.id]={...e[r.id],...r}:t.push(r);a=Object.values(e),n=t}let i={post:a,patch:n};if(!i.post.length&&!i.patch.length)return;let s={post:[],patch:[]};for(let e of["post","patch"]){let t=i[e].reverse(),r=t.pop();for(;void 0!==r;)s[e].push(r),r=t.pop()}if(s.post.length>0||s.patch.length>0){let e=s.post.map(e=>e.id).concat(s.patch.map(e=>e.id)).join(",");await this._postBatchIngestRuns(await this._serializeBody(s,`Ingesting runs with ids: ${e}`),r)}}async _postBatchIngestRuns(e,t){let r={...this._mergedHeaders,"Content-Type":"application/json",Accept:"application/json"};t?.apiKey!==void 0&&(r["x-api-key"]=t.apiKey),await this.batchIngestCaller.callWithOptions({sizeBytes:t?.sizeBytes},async()=>{let a=await this._fetch(`${t?.apiUrl??this.apiUrl}/runs/batch`,{method:"POST",headers:r,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:e});return await tp(a,"batch create run",!0),a})}async multipartIngestRuns({runCreates:e,runUpdates:t},r){if(void 0===e&&void 0===t)return;let a={},n=[];for(let t of e??[]){let e=await this.prepareRunCreateOrUpdateInputs(t);void 0!==e.id&&void 0!==e.attachments&&(a[e.id]=e.attachments),delete e.attachments,n.push(e)}let i=[];for(let e of t??[])i.push(await this.prepareRunCreateOrUpdateInputs(e));if(void 0!==n.find(e=>void 0===e.trace_id||void 0===e.dotted_order))throw Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when creating a run');if(void 0!==i.find(e=>void 0===e.trace_id||void 0===e.dotted_order))throw Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when updating a run');if(n.length>0&&i.length>0){let e=n.reduce((e,t)=>(t.id&&(e[t.id]=t),e),{}),t=[];for(let r of i)void 0!==r.id&&e[r.id]?e[r.id]={...e[r.id],...r}:t.push(r);n=Object.values(e),i=t}if(0===n.length&&0===i.length)return;let s=[],o=[];for(let[e,t]of[["post",n],["patch",i]])for(let r of t){let{inputs:t,outputs:n,events:i,extra:l,error:u,serialized:d,attachments:c,...h}=r,p={inputs:t,outputs:n,events:i,extra:l,error:u,serialized:d},f=await this._serializeBody(h,`Serializing for multipart ingestion of run with id: ${h.id}`);for(let[t,r]of(o.push({name:`${e}.${h.id}`,payload:new Blob([f],{type:`application/json; length=${f.length}`})}),Object.entries(p))){if(void 0===r)continue;let a=await this._serializeBody(r,`Serializing ${t} for multipart ingestion of run with id: ${h.id}`);o.push({name:`${e}.${h.id}.${t}`,payload:new Blob([a],{type:`application/json; length=${a.length}`})})}if(void 0!==h.id){let e=a[h.id];if(e)for(let[t,r]of(delete a[h.id],Object.entries(e))){let e,a;if(Array.isArray(r)?[e,a]=r:(e=r.mimeType,a=r.data),t.includes(".")){console.warn(`Skipping attachment '${t}' for run ${h.id}: Invalid attachment name. Attachment names must not contain periods ('.'). Please rename the attachment and try again.`);continue}o.push({name:`attachment.${h.id}.${t}`,payload:new Blob([a],{type:`${e}; length=${a.byteLength}`})})}}s.push(`trace=${h.trace_id},id=${h.id}`)}await this._sendMultipartRequest(o,s.join("; "),r)}async _createNodeFetchBody(e,t){let r=[];for(let a of e)r.push(new Blob([`--${t}\r `])),r.push(new Blob([`Content-Disposition: form-data; name="${a.name}"\r `,`Content-Type: ${a.payload.type}\r \r `])),r.push(a.payload),r.push(new Blob(["\r\n"]));r.push(new Blob([`--${t}--\r `]));let a=new Blob(r);return await a.arrayBuffer()}async _createMultipartStream(e,t){let r=new TextEncoder;return new ReadableStream({async start(a){let n=async e=>{"string"==typeof e?a.enqueue(r.encode(e)):a.enqueue(e)};for(let r of e){await n(`--${t}\r `),await n(`Content-Disposition: form-data; name="${r.name}"\r `),await n(`Content-Type: ${r.payload.type}\r \r `);let e=r.payload.stream().getReader();try{let t;for(;!(t=await e.read()).done;)a.enqueue(t.value)}finally{e.releaseLock()}await n("\r\n")}await n(`--${t}--\r `),a.close()}})}async _sendMultipartRequest(e,t,r){let a="----LangSmithFormBoundary"+Math.random().toString(36).slice(2),n=()=>this._createNodeFetchBody(e,a),i=()=>this._createMultipartStream(e,a),s=async e=>this.batchIngestCaller.callWithOptions({sizeBytes:r?.sizeBytes},async()=>{let t=await e(),n={...this._mergedHeaders,"Content-Type":`multipart/form-data; boundary=${a}`};r?.apiKey!==void 0&&(n["x-api-key"]=r.apiKey);let i=t;r?.useGzip&&"object"==typeof t&&"pipeThrough"in t&&(i=t.pipeThrough(new CompressionStream("gzip")),n["Content-Encoding"]="gzip");let s=await this._fetch(`${r?.apiUrl??this.apiUrl}/runs/multipart`,{method:"POST",headers:n,body:i,duplex:"half",signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await tp(s,"Failed to send multipart request",!0),s});try{let e,a=!1;(void 0===globalThis[J]||o)&&!this.multipartStreamingDisabled&&"bun"!==eD()?(a=!0,e=await s(i)):e=await s(n),(!this.multipartStreamingDisabled||a)&&422===e.status&&(r?.apiUrl??this.apiUrl)!==tR&&(console.warn(`Streaming multipart upload to ${r?.apiUrl??this.apiUrl}/runs/multipart failed. This usually means the host does not support chunked uploads. Retrying with a buffered upload for operation "${t}".`),this.multipartStreamingDisabled=!0,e=await s(n))}catch(r){if(th(r))throw r;if(console.warn(`${r.message.trim()} Context: ${t}`),this.failedTracesDir){let t=await this._createNodeFetchBody(e,a).catch(()=>null);t&&await tL._writeTraceToFallbackDir(this.failedTracesDir,t,{"Content-Type":`multipart/form-data; boundary=${a}`},"runs/multipart",this.failedTracesMaxBytes)}}}async updateRun(e,t,r){eT(e),t.inputs&&(t.inputs=await this.processInputs(t.inputs)),t.outputs&&(t.outputs=await this.processOutputs(t.outputs)),null!=t.extra&&"metadata"in t.extra&&(t.extra={...t.extra,metadata:await this.processMetadata(t.extra.metadata)}),t.events&&(t.events=this._filterNewTokenEvents(t.events));let a={...t,id:e};if(!this._filterForSampling([a],!0).length)return;if(this.autoBatchTracing&&void 0!==a.trace_id&&void 0!==a.dotted_order){let e=this._cloneCurrentOTELContext();return void 0!==t.end_time&&void 0===a.parent_run_id&&this.blockOnRootRunFinalization&&!this.manualFlushMode?void await this.processRunOperation({action:"update",item:a,otelContext:e,apiKey:r?.apiKey,apiUrl:r?.apiUrl}).catch(console.error):void this.processRunOperation({action:"update",item:a,otelContext:e,apiKey:r?.apiKey,apiUrl:r?.apiUrl}).catch(console.error)}let n={...this._mergedHeaders,"Content-Type":"application/json"};r?.apiKey!==void 0&&(n["x-api-key"]=r.apiKey),r?.workspaceId!==void 0&&(n["x-tenant-id"]=r.workspaceId);let i=tx(t,`Serializing payload to update run with id: ${e}`);await this.caller.call(async()=>{let t=await this._fetch(`${r?.apiUrl??this.apiUrl}/runs/${e}`,{method:"PATCH",headers:n,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await tp(t,"update run",!0),t})}async readRun(e,{loadChildRuns:t}={loadChildRuns:!1}){eT(e);let r=tO(await this._get(`/runs/${e}`));return t&&(r=await this._loadChildRuns(r)),r}async getRunUrl({runId:e,run:t,projectOpts:r}){if(void 0!==t){let e;e=t.session_id?t.session_id:r?.projectName?(await this.readProject({projectName:r?.projectName})).id:r?.projectId?r?.projectId:(await this.readProject({projectName:eH("PROJECT")||"default"})).id;let a=await this._getTenantId();return`${this.getHostUrl()}/o/${a}/projects/p/${e}/r/${t.id}?poll=true`}if(void 0!==e){let t=await this.readRun(e);if(!t.app_path)throw Error(`Run ${e} has no app_path`);let r=this.getHostUrl();return`${r}${t.app_path}`}throw Error("Must provide either runId or run")}async _loadChildRuns(e){let t=await tj(this.listRuns({isRoot:!1,projectId:e.session_id,traceId:e.trace_id})),r={},a={};for(let n of(t.sort((e,t)=>(e?.dotted_order??"").localeCompare(t?.dotted_order??"")),t)){if(null===n.parent_run_id||void 0===n.parent_run_id)throw Error(`Child run ${n.id} has no parent`);n.dotted_order?.startsWith(e.dotted_order??"")&&n.id!==e.id&&(n.parent_run_id in r||(r[n.parent_run_id]=[]),r[n.parent_run_id].push(n),a[n.id]=n)}for(let t in e.child_runs=r[e.id]||[],r)t!==e.id&&(a[t].child_runs=r[t]);return e}async *listRuns(e){let{projectId:t,projectName:r,parentRunId:a,traceId:n,referenceExampleId:i,startTime:s,executionOrder:o,isRoot:l,runType:u,error:d,id:c,query:h,filter:p,traceFilter:f,treeFilter:m,limit:g,select:_,order:y}=e,v=[];if(t&&(v=Array.isArray(t)?t:[t]),r){let e=Array.isArray(r)?r:[r],t=await Promise.all(e.map(e=>this.readProject({projectName:e}).then(e=>e.id)));v.push(...t)}let b={session:v.length?v:null,run_type:u,reference_example:i,query:h,filter:p,trace_filter:f,tree_filter:m,execution_order:o,parent_run:a,start_time:s?s.toISOString():null,error:d,id:c,limit:g,trace:n,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"],is_root:l,order:y};b.select.includes("child_run_ids")&&tl("Deprecated: 'child_run_ids' in the listRuns select parameter is deprecated and will be removed in a future version.");let w=0;for await(let e of this._getCursorPaginatedList("/runs/query",b)){let t=e.map(tO);if(g){if(w>=g)break;if(t.length+w>g){let e=t.slice(0,g-w);yield*e;break}w+=t.length,yield*t}else yield*t}}async *listGroupRuns(e){let{projectId:t,projectName:r,groupBy:a,filter:n,startTime:i,endTime:s,limit:o,offset:l}=e,u={session_id:t||(await this.readProject({projectName:r})).id,group_by:a,filter:n,start_time:i?i.toISOString():null,end_time:s?s.toISOString():null,limit:Number(o)||100},d=Number(l)||0,c="/runs/group",h=`${this.apiUrl}${c}`;for(;;){let e=JSON.stringify(Object.fromEntries(Object.entries({...u,offset:d}).filter(([e,t])=>void 0!==t))),t=await this.caller.call(async()=>{let t=await this._fetch(h,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:e});return await tp(t,`Failed to fetch ${c}`),t}),{groups:r,total:a}=await t.json();if(0===r.length)break;for(let e of r)yield e;if((d+=r.length)>=a)break}}async *readThread(e){let{threadId:t,projectId:r,projectName:a,isRoot:n=!0,limit:i,filter:s,order:o="asc"}=e;if(!r&&!a)throw Error("threadId requires projectId or projectName");let l=`eq(thread_id, ${JSON.stringify(t)})`,u=s?`and(${l}, ${s})`:l;yield*this.listRuns({projectId:r??void 0,projectName:a??void 0,isRoot:n,limit:i,filter:u,order:o})}async listThreads(e){let{projectId:t,projectName:r,limit:a,offset:n=0,filter:i,startTime:s,isRoot:o=!0}=e;if(!t&&!r)throw Error("Either projectId or projectName must be provided");if(t&&r)throw Error("Provide exactly one of projectId or projectName");let l={session:[t??(await this.readProject({projectName:r})).id],is_root:o,limit:100,order:"desc",select:["id","name","status","start_time","end_time","thread_id","trace_id","run_type","error","tags","session_id","parent_run_id","total_tokens","total_cost","dotted_order","reference_example_id","feedback_stats","app_path","completion_cost","completion_tokens","prompt_cost","prompt_tokens","first_token_time"],start_time:(s??new Date(Date.now()-864e5)).toISOString()};null!=i&&(l.filter=i);let u=new Map;for await(let e of this._getCursorPaginatedList("/runs/query",l))for(let t of e){let e=tO(t),r=e.thread_id;if(r){let t=u.get(r)??[];t.push(e),u.set(r,t)}}let d=[];for(let[e,t]of u.entries()){t.sort((e,t)=>{let r=e.start_time??"",a=t.start_time??"";if(r!==a)return r.localeCompare(a);let n=e.dotted_order??"",i=t.dotted_order??"";return n.localeCompare(i)});let r=[...t.map(e=>e.start_time).filter(Boolean)].sort(),a=r.length?r[0]:"",n=r.length?r[r.length-1]:"";d.push({thread_id:e,runs:t,count:t.length,filter:"",total_tokens:0,total_cost:null,min_start_time:a,max_start_time:n,latency_p50:0,latency_p99:0,feedback_stats:null,first_inputs:"",last_outputs:"",last_error:null})}d.sort((e,t)=>{let r=e.max_start_time??"";return(t.max_start_time??"").localeCompare(r)});let c=n>0?d.slice(n):d;return void 0!==a?c.slice(0,a):c}async getRunStats({id:e,trace:t,parentRun:r,runType:a,projectNames:n,projectIds:i,referenceExampleIds:s,startTime:o,endTime:l,error:u,query:d,filter:c,traceFilter:h,treeFilter:p,isRoot:f,dataSourceType:m}){let g=i||[];n&&(g=[...i||[],...await Promise.all(n.map(e=>this.readProject({projectName:e}).then(e=>e.id)))]);let _=JSON.stringify(Object.fromEntries(Object.entries({id:e,trace:t,parent_run:r,run_type:a,session:g,reference_example:s,start_time:o,end_time:l,error:u,query:d,filter:c,trace_filter:h,tree_filter:p,is_root:f,data_source_type:m}).filter(([e,t])=>void 0!==t))),y=await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/runs/stats`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:_});return await tp(e,"get run stats"),e});return await y.json()}async shareRun(e,{shareId:t}={}){let r={run_id:e,share_token:t||P()};eT(e);let a=JSON.stringify(r),n=await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"PUT",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await tp(t,"share run"),t}),i=await n.json();if(null===i||!("share_token"in i))throw Error("Invalid response from server");return`${this.getHostUrl()}/public/${i.share_token}/r`}async unshareRun(e){eT(e),await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await tp(t,"unshare run",!0),t})}async readRunSharedLink(e){eT(e);let t=await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await tp(t,"read run shared link"),t}),r=await t.json();if(null!==r&&"share_token"in r)return`${this.getHostUrl()}/public/${r.share_token}/r`}async listSharedRuns(e,{runIds:t}={}){let r=new URLSearchParams({share_token:e});if(void 0!==t)for(let e of t)r.append("id",e);eT(e);let a=await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/public/${e}/runs${r}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await tp(t,"list shared runs"),t});return(await a.json()).map(tO)}async readDatasetSharedSchema(e,t){if(!e&&!t)throw Error("Either datasetId or datasetName must be given");e||(e=(await this.readDataset({datasetName:t})).id),eT(e);let r=await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await tp(t,"read dataset shared schema"),t}),a=await r.json();return a.url=`${this.getHostUrl()}/public/${a.share_token}/d`,a}async shareDataset(e,t){if(!e&&!t)throw Error("Either datasetId or datasetName must be given");e||(e=(await this.readDataset({datasetName:t})).id);let r={dataset_id:e};eT(e);let a=JSON.stringify(r),n=await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"PUT",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await tp(t,"share dataset"),t}),i=await n.json();return i.url=`${this.getHostUrl()}/public/${i.share_token}/d`,i}async unshareDataset(e){eT(e),await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await tp(t,"unshare dataset",!0),t})}async readSharedDataset(e){eT(e);let t=await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/public/${e}/datasets`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await tp(t,"read shared dataset"),t});return await t.json()}async listSharedExamples(e,t){let r={};t?.exampleIds&&(r.id=t.exampleIds);let a=new URLSearchParams;Object.entries(r).forEach(([e,t])=>{Array.isArray(t)?t.forEach(t=>a.append(e,t)):a.append(e,t)});let n=await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/public/${e}/examples?${a.toString()}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await tp(t,"list shared examples"),t}),i=await n.json();if(!n.ok){if("detail"in i)throw Error(`Failed to list shared examples. Status: ${n.status} Message: ${Array.isArray(i.detail)?i.detail.join("\n"):"Unspecified error"}`);throw Error(`Failed to list shared examples: ${n.status} ${n.statusText}`)}return i.map(e=>({...e,_hostUrl:this.getHostUrl()}))}async createProject({projectName:e,description:t=null,metadata:r=null,upsert:a=!1,projectExtra:n=null,referenceDatasetId:i=null}){let s=`${this.apiUrl}/sessions${a?"?upsert=true":""}`,o=n||{};r&&(o.metadata=r);let l={name:e,extra:o,description:t};null!==i&&(l.reference_dataset_id=i);let u=JSON.stringify(l),d=await this.caller.call(async()=>{let e=await this._fetch(s,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await tp(e,"create project"),e});return await d.json()}async updateProject(e,{name:t=null,description:r=null,metadata:a=null,projectExtra:n=null,endTime:i=null}){let s=`${this.apiUrl}/sessions/${e}`,o=n;a&&(o={...o||{},metadata:a});let l=JSON.stringify({name:t,extra:o,description:r,end_time:i?new Date(i).toISOString():null}),u=await this.caller.call(async()=>{let e=await this._fetch(s,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await tp(e,"update project"),e});return await u.json()}async hasProject({projectId:e,projectName:t}){let r="/sessions",a=new URLSearchParams;if(void 0!==e&&void 0!==t)throw Error("Must provide either projectName or projectId, not both");if(void 0!==e)eT(e),r+=`/${e}`;else if(void 0!==t)a.append("name",t);else throw Error("Must provide projectName or projectId");let n=await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}${r}?${a}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await tp(e,"has project"),e});try{let e=await n.json();if(!n.ok)return!1;if(Array.isArray(e))return e.length>0;return!0}catch(e){return!1}}async readProject({projectId:e,projectName:t,includeStats:r}){let a,n="/sessions",i=new URLSearchParams;if(void 0!==e&&void 0!==t)throw Error("Must provide either projectName or projectId, not both");if(void 0!==e)eT(e),n+=`/${e}`;else if(void 0!==t)i.append("name",t);else throw Error("Must provide projectName or projectId");void 0!==r&&i.append("include_stats",r.toString());let s=await this._get(n,i);if(Array.isArray(s)){if(0===s.length)throw Error(`Project[id=${e}, name=${t}] not found`);a=s[0]}else a=s;return a}async getProjectUrl({projectId:e,projectName:t}){if(void 0===e&&void 0===t)throw Error("Must provide either projectName or projectId");let r=await this.readProject({projectId:e,projectName:t}),a=await this._getTenantId();return`${this.getHostUrl()}/o/${a}/projects/p/${r.id}`}async getDatasetUrl({datasetId:e,datasetName:t}){if(void 0===e&&void 0===t)throw Error("Must provide either datasetName or datasetId");let r=await this.readDataset({datasetId:e,datasetName:t}),a=await this._getTenantId();return`${this.getHostUrl()}/o/${a}/datasets/${r.id}`}async _getTenantId(){if(null!==this._tenantId)return this._tenantId;let e=new URLSearchParams({limit:"1"});for await(let t of this._getPaginated("/sessions",e))return this._tenantId=t[0].tenant_id,t[0].tenant_id;throw Error("No projects found to resolve tenant.")}async *listProjects({projectIds:e,name:t,nameContains:r,referenceDatasetId:a,referenceDatasetName:n,includeStats:i,datasetVersion:s,referenceFree:o,metadata:l}={}){let u=new URLSearchParams;if(void 0!==e)for(let t of e)u.append("id",t);if(void 0!==t&&u.append("name",t),void 0!==r&&u.append("name_contains",r),void 0!==a)u.append("reference_dataset",a);else if(void 0!==n){let e=await this.readDataset({datasetName:n});u.append("reference_dataset",e.id)}for await(let e of(void 0!==i&&u.append("include_stats",i.toString()),void 0!==s&&u.append("dataset_version",s),void 0!==o&&u.append("reference_free",o.toString()),void 0!==l&&u.append("metadata",JSON.stringify(l)),this._getPaginated("/sessions",u)))yield*e}async deleteProject({projectId:e,projectName:t}){let r;if(void 0===e&&void 0===t)throw Error("Must provide projectName or projectId");if(void 0!==e&&void 0!==t)throw Error("Must provide either projectName or projectId, not both");eT(r=void 0===e?(await this.readProject({projectName:t})).id:e),await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/sessions/${r}`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await tp(e,`delete session ${r} (${t})`,!0),e})}async uploadCsv({csvFile:e,fileName:t,inputKeys:r,outputKeys:a,description:n,dataType:i,name:s}){let o=`${this.apiUrl}/datasets/upload`,l=new FormData,u=new Blob([e],{type:"text/csv"});l.append("file",u,t),r.forEach(e=>{l.append("input_keys",e)}),a.forEach(e=>{l.append("output_keys",e)}),n&&l.append("description",n),i&&l.append("data_type",i),s&&l.append("name",s);let d=await this.caller.call(async()=>{let e=await this._fetch(o,{method:"POST",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await tp(e,"upload CSV"),e});return await d.json()}async createDataset(e,{description:t,dataType:r,inputsSchema:a,outputsSchema:n,metadata:i}={}){let s={name:e,description:t,extra:{source:"sdk",...i?{metadata:i}:{}}};r&&(s.data_type=r),a&&(s.inputs_schema_definition=a),n&&(s.outputs_schema_definition=n);let o=JSON.stringify(s),l=await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/datasets`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await tp(e,"create dataset"),e});return await l.json()}async readDataset({datasetId:e,datasetName:t}){let r,a="/datasets",n=new URLSearchParams({limit:"1"});if(e&&t)throw Error("Must provide either datasetName or datasetId, not both");if(e)eT(e),a+=`/${e}`;else if(t)n.append("name",t);else throw Error("Must provide datasetName or datasetId");let i=await this._get(a,n);if(Array.isArray(i)){if(0===i.length)throw Error(`Dataset[id=${e}, name=${t}] not found`);r=i[0]}else r=i;return r}async hasDataset({datasetId:e,datasetName:t}){try{return await this.readDataset({datasetId:e,datasetName:t}),!0}catch(e){if(e instanceof Error&&e.message.toLocaleLowerCase().includes("not found"))return!1;throw e}}async diffDatasetVersions({datasetId:e,datasetName:t,fromVersion:r,toVersion:a}){let n=e;if(void 0===n&&void 0===t)throw Error("Must provide either datasetName or datasetId");if(void 0!==n&&void 0!==t)throw Error("Must provide either datasetName or datasetId, not both");void 0===n&&(n=(await this.readDataset({datasetName:t})).id);let i=new URLSearchParams({from_version:"string"==typeof r?r:r.toISOString(),to_version:"string"==typeof a?a:a.toISOString()});return await this._get(`/datasets/${n}/versions/diff`,i)}async readDatasetOpenaiFinetuning({datasetId:e,datasetName:t}){if(void 0!==e);else if(void 0!==t)e=(await this.readDataset({datasetName:t})).id;else throw Error("Must provide either datasetName or datasetId");let r=await this._getResponse(`/datasets/${e}/openai_ft`);return(await r.text()).trim().split("\n").map(e=>JSON.parse(e))}async *listDatasets({limit:e=100,offset:t=0,datasetIds:r,datasetName:a,datasetNameContains:n,metadata:i}={}){let s=new URLSearchParams({limit:e.toString(),offset:t.toString()});if(void 0!==r)for(let e of r)s.append("id",e);for await(let e of(void 0!==a&&s.append("name",a),void 0!==n&&s.append("name_contains",n),void 0!==i&&s.append("metadata",JSON.stringify(i)),this._getPaginated("/datasets",s)))yield*e}async updateDataset(e){let{datasetId:t,datasetName:r,...a}=e;if(!t&&!r)throw Error("Must provide either datasetName or datasetId");let n=t??(await this.readDataset({datasetName:r})).id;eT(n);let i=JSON.stringify(a),s=await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/datasets/${n}`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await tp(e,"update dataset"),e});return await s.json()}async updateDatasetTag(e){let{datasetId:t,datasetName:r,asOf:a,tag:n}=e;if(!t&&!r)throw Error("Must provide either datasetName or datasetId");let i=t??(await this.readDataset({datasetName:r})).id;eT(i);let s=JSON.stringify({as_of:"string"==typeof a?a:a.toISOString(),tag:n});await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/datasets/${i}/tags`,{method:"PUT",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await tp(e,"update dataset tags",!0),e})}async deleteDataset({datasetId:e,datasetName:t}){let r="/datasets",a=e;if(void 0!==e&&void 0!==t)throw Error("Must provide either datasetName or datasetId, not both");if(void 0!==t&&(a=(await this.readDataset({datasetName:t})).id),void 0!==a)eT(a),r+=`/${a}`;else throw Error("Must provide datasetName or datasetId");await this.caller.call(async()=>{let e=await this._fetch(this.apiUrl+r,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await tp(e,`delete ${r}`,!0),e})}async createExample(e,t,r){let a;if(tZ(e)&&(void 0!==t||void 0!==r))throw Error("Cannot provide outputs or options when using ExampleCreate object");let n=t?r?.datasetId:e.dataset_id,i=t?r?.datasetName:e.dataset_name;if(void 0===n&&void 0===i)throw Error("Must provide either datasetName or datasetId");if(void 0!==n&&void 0!==i)throw Error("Must provide either datasetName or datasetId, not both");void 0===n&&(n=(await this.readDataset({datasetName:i})).id);let s=(t?r?.createdAt:e.created_at)||new Date;a=tZ(e)?e:{inputs:e,outputs:t,created_at:s?.toISOString(),id:r?.exampleId,metadata:r?.metadata,split:r?.split,source_run_id:r?.sourceRunId,use_source_run_io:r?.useSourceRunIO,use_source_run_attachments:r?.useSourceRunAttachments,attachments:r?.attachments};let o=await this._uploadExamplesMultipart(n,[a]);return await this.readExample(o.example_ids?.[0]??P())}async createExamples(e){if(Array.isArray(e)){if(0===e.length)return[];let t=e[0].dataset_id,r=e[0].dataset_name;if(void 0===t&&void 0===r)throw Error("Must provide either datasetName or datasetId");if(void 0!==t&&void 0!==r)throw Error("Must provide either datasetName or datasetId, not both");void 0===t&&(t=(await this.readDataset({datasetName:r})).id);let a=await this._uploadExamplesMultipart(t,e);return await Promise.all(a.example_ids.map(e=>this.readExample(e)))}let{inputs:t,outputs:r,metadata:a,splits:n,sourceRunIds:i,useSourceRunIOs:s,useSourceRunAttachments:o,attachments:l,exampleIds:u,datasetId:d,datasetName:c}=e;if(void 0===t)throw Error("Must provide inputs when using legacy parameters");let h=d;if(void 0===h&&void 0===c)throw Error("Must provide either datasetName or datasetId");if(void 0!==h&&void 0!==c)throw Error("Must provide either datasetName or datasetId, not both");void 0===h&&(h=(await this.readDataset({datasetName:c})).id);let p=t.map((e,t)=>({dataset_id:h,inputs:e,outputs:r?.[t],metadata:a?.[t],split:n?.[t],id:u?.[t],attachments:l?.[t],source_run_id:i?.[t],use_source_run_io:s?.[t],use_source_run_attachments:o?.[t]})),f=await this._uploadExamplesMultipart(h,p);return await Promise.all(f.example_ids.map(e=>this.readExample(e)))}async createLLMExample(e,t,r){return this.createExample({input:e},{output:t},r)}async createChatExample(e,t,r){let a=e.map(e=>ti(e)?ts(e):e),n=ti(t)?ts(t):t;return this.createExample({input:a},{output:n},r)}async readExample(e){eT(e);let t=`/examples/${e}`,{attachment_urls:r,...a}=await this._get(t);return r&&(a.attachments=Object.entries(r).reduce((e,[t,r])=>(e[t.slice(11)]={presigned_url:r.presigned_url,mime_type:r.mime_type},e),{})),a}async *listExamples({datasetId:e,datasetName:t,exampleIds:r,asOf:a,splits:n,inlineS3Urls:i,metadata:s,limit:o,offset:l,filter:u,includeAttachments:d}={}){let c;if(void 0!==e&&void 0!==t)throw Error("Must provide either datasetName or datasetId, not both");if(void 0!==e)c=e;else if(void 0!==t)c=(await this.readDataset({datasetName:t})).id;else throw Error("Must provide a datasetName or datasetId");let h=new URLSearchParams({dataset:c}),p=a?"string"==typeof a?a:a?.toISOString():void 0;if(p&&h.append("as_of",p),h.append("inline_s3_urls",(i??!0).toString()),void 0!==r)for(let e of r)h.append("id",e);if(void 0!==n)for(let e of n)h.append("splits",e);if(void 0!==s){let e=JSON.stringify(s);h.append("metadata",e)}void 0!==o&&h.append("limit",o.toString()),void 0!==l&&h.append("offset",l.toString()),void 0!==u&&h.append("filter",u),!0===d&&["attachment_urls","outputs","metadata"].forEach(e=>h.append("select",e));let f=0;for await(let e of this._getPaginated("/examples",h)){for(let t of e){let{attachment_urls:e,...r}=t;e&&(r.attachments=Object.entries(e).reduce((e,[t,r])=>(e[t.slice(11)]={presigned_url:r.presigned_url,mime_type:r.mime_type||void 0},e),{})),yield r,f++}if(void 0!==o&&f>=o)break}}async deleteExample(e){eT(e);let t=`/examples/${e}`;await this.caller.call(async()=>{let e=await this._fetch(this.apiUrl+t,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await tp(e,`delete ${t}`,!0),e})}async deleteExamples(e,t){if(e.forEach(e=>eT(e)),t?.hardDelete){let t=this._getPlatformEndpointPath("datasets/examples/delete");await this.caller.call(async()=>{let r=await this._fetch(`${this.apiUrl}${t}`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},body:JSON.stringify({example_ids:e,hard_delete:!0}),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await tp(r,"hard delete examples",!0),r})}else{let t=new URLSearchParams;e.forEach(e=>t.append("example_ids",e)),await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/examples?${t.toString()}`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await tp(e,"delete examples",!0),e})}}async updateExample(e,t){let r,a,n;return eT(r=t?e:e.id),n=void 0!==(a=t?{id:r,...t}:e).dataset_id?a.dataset_id:(await this.readExample(r)).dataset_id,this._updateExamplesMultipart(n,[a])}async updateExamples(e){let t;return t=void 0===e[0].dataset_id?(await this.readExample(e[0].id)).dataset_id:e[0].dataset_id,this._updateExamplesMultipart(t,e)}async readDatasetVersion({datasetId:e,datasetName:t,asOf:r,tag:a}){let n;if(eT(n=e||(await this.readDataset({datasetName:t})).id),r&&a||!r&&!a)throw Error("Exactly one of asOf and tag must be specified.");let i=new URLSearchParams;void 0!==r&&i.append("as_of","string"==typeof r?r:r.toISOString()),void 0!==a&&i.append("tag",a);let s=await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/datasets/${n}/version?${i.toString()}`,{method:"GET",headers:{...this._mergedHeaders},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await tp(e,"read dataset version"),e});return await s.json()}async listDatasetSplits({datasetId:e,datasetName:t,asOf:r}){let a;if(void 0===e&&void 0===t)throw Error("Must provide dataset name or ID");if(void 0!==e&&void 0!==t)throw Error("Must provide either datasetName or datasetId, not both");eT(a=void 0===e?(await this.readDataset({datasetName:t})).id:e);let n=new URLSearchParams,i=r?"string"==typeof r?r:r?.toISOString():void 0;return i&&n.append("as_of",i),await this._get(`/datasets/${a}/splits`,n)}async updateDatasetSplits({datasetId:e,datasetName:t,splitName:r,exampleIds:a,remove:n=!1}){let i;if(void 0===e&&void 0===t)throw Error("Must provide dataset name or ID");if(void 0!==e&&void 0!==t)throw Error("Must provide either datasetName or datasetId, not both");eT(i=void 0===e?(await this.readDataset({datasetName:t})).id:e);let s=JSON.stringify({split_name:r,examples:a.map(e=>(eT(e),e)),remove:n});await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/datasets/${i}/splits`,{method:"PUT",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await tp(e,"update dataset splits",!0),e})}async createFeedback(e,t,{score:r,value:a,correction:n,comment:i,sourceInfo:s,feedbackSourceType:o="api",sourceRunId:l,feedbackId:u,feedbackConfig:d,projectId:c,comparativeExperimentId:h,sessionId:p,startTime:f}){if(!e&&!c)throw Error("One of runId or projectId must be provided");if(e&&c)throw Error("Only one of runId or projectId can be provided");let m={type:o??"api",metadata:s??{}};void 0===l||m?.metadata===void 0||m.metadata.__run||(m.metadata.__run={run_id:l}),m?.metadata!==void 0&&m.metadata.__run?.run_id!==void 0&&eT(m.metadata.__run.run_id);let g={id:u??D(),run_id:e,key:t,score:tN(r),value:a,correction:n,comment:i,feedback_source:m,comparative_experiment_id:h,feedbackConfig:d,session_id:p??c,start_time:f},_=JSON.stringify(g),y=`${this.apiUrl}/feedback`;return await this.caller.call(async()=>{let e=await this._fetch(y,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:_});return await tp(e,"create feedback",!0),e}),g}async updateFeedback(e,{score:t,value:r,correction:a,comment:n}){let i={};null!=t&&(i.score=tN(t)),null!=r&&(i.value=r),null!=a&&(i.correction=a),null!=n&&(i.comment=n),eT(e);let s=JSON.stringify(i);await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/feedback/${e}`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await tp(t,"update feedback",!0),t})}async readFeedback(e){eT(e);let t=`/feedback/${e}`;return await this._get(t)}async deleteFeedback(e){eT(e);let t=`/feedback/${e}`;await this.caller.call(async()=>{let e=await this._fetch(this.apiUrl+t,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await tp(e,`delete ${t}`,!0),e})}async *listFeedback({runIds:e,feedbackKeys:t,feedbackSourceTypes:r}={}){let a=new URLSearchParams;if(e)for(let t of e)eT(t),a.append("run",t);if(t)for(let e of t)a.append("key",e);if(r)for(let e of r)a.append("source",e);for await(let e of this._getPaginated("/feedback",a))yield*e}async createPresignedFeedbackToken(e,t,{expiration:r,feedbackConfig:a}={}){let n={run_id:e,feedback_key:t,feedback_config:a};r?"string"==typeof r?n.expires_at=r:(r?.hours||r?.minutes||r?.days)&&(n.expires_in=r):n.expires_in={hours:3};let i=JSON.stringify(n),s=await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/feedback/tokens`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await tp(e,"create presigned feedback token"),e});return await s.json()}async createComparativeExperiment({name:e,experimentIds:t,referenceDatasetId:r,createdAt:a,description:n,metadata:i,id:s}){if(0===t.length)throw Error("At least one experiment is required");if(r||(r=(await this.readProject({projectId:t[0]})).reference_dataset_id),null==!r)throw Error("A reference dataset is required");let o={id:s,name:e,experiment_ids:t,reference_dataset_id:r,description:n,created_at:(a??new Date)?.toISOString(),extra:{}};i&&(o.extra.metadata=i);let l=JSON.stringify(o);return(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/datasets/comparative`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await tp(e,"create comparative experiment"),e})).json()}async *listPresignedFeedbackTokens(e){eT(e);let t=new URLSearchParams({run_id:e});for await(let e of this._getPaginated("/feedback/tokens",t))yield*e}_selectEvalResults(e){return"results"in e?e.results:Array.isArray(e)?e:[e]}async _logEvaluationFeedback(e,t,r){let a=this._selectEvalResults(e),n=[];for(let e of a){let a=r||{};e.evaluatorInfo&&(a={...e.evaluatorInfo,...a});let i=null;e.targetRunId?i=e.targetRunId:t&&(i=t.id),n.push(await this.createFeedback(i,e.key,{score:e.score,value:e.value,comment:e.comment,correction:e.correction,sourceInfo:a,sourceRunId:e.sourceRunId,feedbackConfig:e.feedbackConfig,feedbackSourceType:"model",sessionId:t?.session_id,startTime:t?.start_time}))}return[a,n]}async logEvaluationFeedback(e,t,r){let[a]=await this._logEvaluationFeedback(e,t,r);return a}async createFeedbackConfig(e){let{feedbackKey:t,feedbackConfig:r,isLowerScoreBetter:a=!1}=e,n={feedback_key:t,feedback_config:r,is_lower_score_better:a};return(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/feedback-configs`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(n)});return await tp(e,"create feedback config"),e})).json()}async *listFeedbackConfigs(e={}){let{feedbackKeys:t,nameContains:r,limit:a}=e,n=new URLSearchParams;t&&t.forEach(e=>{n.append("key",e)}),r&&n.append("name_contains",r),n.append("limit",(void 0!==a?Math.min(a,100):100).toString());let i=0;for await(let e of this._getPaginated("/feedback-configs",n))if(yield*e,i+=e.length,void 0!==a&&i>=a)break}async updateFeedbackConfig(e,t={}){let{feedbackConfig:r,isLowerScoreBetter:a}=t,n={feedback_key:e};return void 0!==r&&(n.feedback_config=r),void 0!==a&&(n.is_lower_score_better=a),(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/feedback-configs`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(n)});return await tp(e,"update feedback config"),e})).json()}async deleteFeedbackConfig(e){let t=new URLSearchParams({feedback_key:e});await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/feedback-configs?${t}`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await tp(e,"delete feedback config",!0),e})}async *listAnnotationQueues(e={}){let{queueIds:t,name:r,nameContains:a,limit:n}=e,i=new URLSearchParams;t&&t.forEach((e,t)=>{eT(e,`queueIds[${t}]`),i.append("ids",e)}),r&&i.append("name",r),a&&i.append("name_contains",a),i.append("limit",(void 0!==n?Math.min(n,100):100).toString());let s=0;for await(let e of this._getPaginated("/annotation-queues",i))if(yield*e,s++,void 0!==n&&s>=n)break}async createAnnotationQueue(e){let{name:t,description:r,queueId:a,rubricInstructions:n,rubricItems:i}=e,s=JSON.stringify(Object.fromEntries(Object.entries({name:t,description:r,id:a||P(),rubric_instructions:n,rubric_items:i}).filter(([e,t])=>void 0!==t)));return(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/annotation-queues`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await tp(e,"create annotation queue"),e})).json()}async readAnnotationQueue(e){return(await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/annotation-queues/${eT(e,"queueId")}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await tp(t,"read annotation queue"),t})).json()}async updateAnnotationQueue(e,t){let{name:r,description:a,rubricInstructions:n,rubricItems:i}=t,s={};void 0!==r&&(s.name=r),void 0!==a&&(s.description=a),void 0!==n&&(s.rubric_instructions=n),void 0!==i&&(s.rubric_items=i);let o=JSON.stringify(s);await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/annotation-queues/${eT(e,"queueId")}`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await tp(t,"update annotation queue",!0),t})}async deleteAnnotationQueue(e){await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/annotation-queues/${eT(e,"queueId")}`,{method:"DELETE",headers:{...this._mergedHeaders,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await tp(t,"delete annotation queue",!0),t})}async addRunsToAnnotationQueue(e,t){let r=JSON.stringify(t.map((e,t)=>eT(e,`runIds[${t}]`).toString()));await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/annotation-queues/${eT(e,"queueId")}/runs`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:r});return await tp(t,"add runs to annotation queue",!0),t})}async getRunFromAnnotationQueue(e,t){let r=`/annotation-queues/${eT(e,"queueId")}/run`,a=await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}${r}/${t}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await tp(e,"get run from annotation queue"),e});return tO(await a.json())}async deleteRunFromAnnotationQueue(e,t){await this.caller.call(async()=>{let r=await this._fetch(`${this.apiUrl}/annotation-queues/${eT(e,"queueId")}/runs/${eT(t,"queueRunId")}`,{method:"DELETE",headers:{...this._mergedHeaders,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await tp(r,"delete run from annotation queue",!0),r})}async getSizeFromAnnotationQueue(e){return(await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/annotation-queues/${eT(e,"queueId")}/size`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await tp(t,"get size from annotation queue"),t})).json()}async _currentTenantIsOwner(e){let t=await this._getSettings();return"-"==e||t.tenant_handle===e}async _ownerConflictError(e,t){let r=await this._getSettings();return Error(`Cannot ${e} for another tenant. Current tenant: ${r.tenant_handle} Requested tenant: ${t}`)}async _getLatestCommitHash(e){let t=await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/commits/${e}/?limit=1&offset=0`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await tp(t,"get latest commit hash"),t}),r=await t.json();if(0!==r.commits.length)return r.commits[0].commit_hash}async _likeOrUnlikePrompt(e,t){let[r,a,n]=tg(e),i=JSON.stringify({like:t});return(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/likes/${r}/${a}`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await tp(e,`${t?"like":"unlike"} prompt`),e})).json()}async _getPromptUrl(e){let[t,r,a]=tg(e);if(await this._currentTenantIsOwner(t)){let e=await this._getSettings();return"latest"!==a?`${this.getHostUrl()}/prompts/${r}/${a.substring(0,8)}?organizationId=${e.id}`:`${this.getHostUrl()}/prompts/${r}?organizationId=${e.id}`}return"latest"!==a?`${this.getHostUrl()}/hub/${t}/${r}/${a.substring(0,8)}`:`${this.getHostUrl()}/hub/${t}/${r}`}async promptExists(e){return!!await this.getPrompt(e)}async likePrompt(e){return this._likeOrUnlikePrompt(e,!0)}async unlikePrompt(e){return this._likeOrUnlikePrompt(e,!1)}async *listCommits(e){let[t,r,a]=tg(e);for await(let e of this._getPaginated(`/commits/${t}/${r}/`,new URLSearchParams,e=>e.commits))yield*e}async *listPrompts(e){let t=new URLSearchParams;for await(let r of(t.append("sort_field",e?.sortField??"updated_at"),t.append("sort_direction","desc"),t.append("is_archived",(!!e?.isArchived).toString()),e?.isPublic!==void 0&&t.append("is_public",e.isPublic.toString()),e?.query&&t.append("query",e.query),this._getPaginated("/repos",t,e=>e.repos)))yield*r}async getPrompt(e){let[t,r,a]=tg(e),n=await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/repos/${t}/${r}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return e?.status===404?null:(await tp(e,"get prompt"),e)}),i=await n?.json();return i?.repo?i.repo:null}async createPrompt(e,t){let r=await this._getSettings();if(t?.isPublic&&!r.tenant_handle)throw Error(`Cannot create a public prompt without first creating a LangChain Hub handle. You can add a handle by creating a public prompt at: https://smith.langchain.com/prompts`);let[a,n,i]=tg(e);if(!await this._currentTenantIsOwner(a))throw await this._ownerConflictError("create a prompt",a);let s=JSON.stringify({repo_handle:n,...t?.description&&{description:t.description},...t?.readme&&{readme:t.readme},...t?.tags&&{tags:t.tags},is_public:!!t?.isPublic}),o=await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/repos/`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await tp(e,"create prompt"),e}),{repo:l}=await o.json();return l}async createCommit(e,t,r){if(!await this.promptExists(e))throw Error("Prompt does not exist, you must create it first.");let[a,n,i]=tg(e),s=r?.parentCommitHash!=="latest"&&r?.parentCommitHash?r?.parentCommitHash:await this._getLatestCommitHash(`${a}/${n}`),o=JSON.stringify({manifest:JSON.parse(JSON.stringify(t)),parent_commit:s,...r?.description!==void 0&&{description:r.description}}),l=await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/commits/${a}/${n}`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await tp(e,"create commit"),e}),u=await l.json();return this._getPromptUrl(`${a}/${n}${u.commit_hash?`:${u.commit_hash}`:""}`)}async updateExamplesMultipart(e,t=[]){return this._updateExamplesMultipart(e,t)}async _updateExamplesMultipart(e,t=[]){if(!await this._getDatasetExamplesMultiPartSupport())throw Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");let r=new FormData;for(let e of t){let t=e.id,a=new Blob([tx({...e.metadata&&{metadata:e.metadata},...e.split&&{split:e.split}},`Serializing body for example with id: ${t}`)],{type:"application/json"});if(r.append(t,a),e.inputs){let a=new Blob([tx(e.inputs,`Serializing inputs for example with id: ${t}`)],{type:"application/json"});r.append(`${t}.inputs`,a)}if(e.outputs){let a=new Blob([tx(e.outputs,`Serializing outputs whle updating example with id: ${t}`)],{type:"application/json"});r.append(`${t}.outputs`,a)}if(e.attachments)for(let[a,n]of Object.entries(e.attachments)){let e,i;Array.isArray(n)?[e,i]=n:(e=n.mimeType,i=n.data);let s=new Blob([i],{type:`${e}; length=${i.byteLength}`});r.append(`${t}.attachment.${a}`,s)}if(e.attachments_operations){let a=new Blob([tx(e.attachments_operations,`Serializing attachments while updating example with id: ${t}`)],{type:"application/json"});r.append(`${t}.attachments_operations`,a)}}let a=e??t[0]?.dataset_id;return(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${a}/examples`)}`,{method:"PATCH",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:r});return await tp(e,"update examples"),e})).json()}async uploadExamplesMultipart(e,t=[]){return this._uploadExamplesMultipart(e,t)}async _uploadExamplesMultipart(e,t=[]){if(!await this._getDatasetExamplesMultiPartSupport())throw Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");let r=new FormData;for(let e of t){let t=(e.id??P()).toString(),a=new Blob([tx({created_at:e.created_at,...e.metadata&&{metadata:e.metadata},...e.split&&{split:e.split},...e.source_run_id&&{source_run_id:e.source_run_id},...e.use_source_run_io&&{use_source_run_io:e.use_source_run_io},...e.use_source_run_attachments&&{use_source_run_attachments:e.use_source_run_attachments}},`Serializing body for uploaded example with id: ${t}`)],{type:"application/json"});if(r.append(t,a),e.inputs){let a=new Blob([tx(e.inputs,`Serializing inputs for uploaded example with id: ${t}`)],{type:"application/json"});r.append(`${t}.inputs`,a)}if(e.outputs){let a=new Blob([tx(e.outputs,`Serializing outputs for uploaded example with id: ${t}`)],{type:"application/json"});r.append(`${t}.outputs`,a)}if(e.attachments)for(let[a,n]of Object.entries(e.attachments)){let e,i;Array.isArray(n)?[e,i]=n:(e=n.mimeType,i=n.data);let s=new Blob([i],{type:`${e}; length=${i.byteLength}`});r.append(`${t}.attachment.${a}`,s)}}return(await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${e}/examples`)}`,{method:"POST",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:r});return await tp(t,"upload examples"),t})).json()}async updatePrompt(e,t){if(!await this.promptExists(e))throw Error("Prompt does not exist, you must create it first.");let[r,a]=tg(e);if(!await this._currentTenantIsOwner(r))throw await this._ownerConflictError("update a prompt",r);let n={};if(t?.description!==void 0&&(n.description=t.description),t?.readme!==void 0&&(n.readme=t.readme),t?.tags!==void 0&&(n.tags=t.tags),t?.isPublic!==void 0&&(n.is_public=t.isPublic),t?.isArchived!==void 0&&(n.is_archived=t.isArchived),0===Object.keys(n).length)throw Error("No valid update options provided");let i=JSON.stringify(n);return(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/repos/${r}/${a}`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await tp(e,"update prompt"),e})).json()}async deletePrompt(e){if(!await this.promptExists(e))throw Error("Prompt does not exist, you must create it first.");let[t,r,a]=tg(e);if(!await this._currentTenantIsOwner(t))throw await this._ownerConflictError("delete a prompt",t);return(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/repos/${t}/${r}`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await tp(e,"delete prompt"),e})).json()}_getPromptCacheKey(e,t){return`${e}${t?":with_model":""}`}async _fetchPromptFromApi(e,t){let[r,a,n]=tg(e),i=await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/commits/${r}/${a}/${n}${t?.includeModel?"?include_model=true":""}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await tp(e,"pull prompt commit"),e}),s=await i.json();return{owner:r,repo:a,commit_hash:s.commit_hash,manifest:s.manifest,examples:s.examples,hub_model_config:s.model_config,hub_model_provider:s.model_provider}}async pullPromptCommit(e,t){!function(e,t){let[r]=tg(e);if("-"!==r&&!t)throw Error("Pulling a public prompt by owner/name is disabled by default because prompts may contain untrusted serialized LangChain objects. If you trust this prompt, set `dangerouslyPullPublicPrompt: true` to acknowledge the risk.")}(e,t?.dangerouslyPullPublicPrompt);let r=this._fetchPromptFromApi.bind(this,e,t);if(!t?.skipCache&&this._promptCache){let a=this._getPromptCacheKey(e,t?.includeModel),n=this._promptCache.get(a,r);if(n)return n;let i=await r();return this._promptCache.set(a,i,r),i}return this._fetchPromptFromApi(e,t)}async _pullPrompt(e,t){return JSON.stringify((await this.pullPromptCommit(e,{includeModel:t?.includeModel,skipCache:t?.skipCache,dangerouslyPullPublicPrompt:t?.dangerouslyPullPublicPrompt})).manifest)}async pushPrompt(e,t){return(await this.promptExists(e)?t&&Object.keys(t).some(e=>"object"!==e)&&await this.updatePrompt(e,{description:t?.description,readme:t?.readme,tags:t?.tags,isPublic:t?.isPublic}):await this.createPrompt(e,{description:t?.description,readme:t?.readme,tags:t?.tags,isPublic:t?.isPublic}),t?.object)?await this.createCommit(e,t?.object,{parentCommitHash:t?.parentCommitHash,description:t?.commitDescription}):await this._getPromptUrl(e)}async agentExists(e){let[t,r]=tg(e);return this._repoExists(t,r)}async skillExists(e){let[t,r]=tg(e);return this._repoExists(t,r)}async pullAgent(e,t){return await this._pullDirectory(e,"agent",t?.version)}async pullSkill(e,t){return await this._pullDirectory(e,"skill",t?.version)}async pushAgent(e,t){return this._pushDirectory(e,"agent",t)}async pushSkill(e,t){return this._pushDirectory(e,"skill",t)}async deleteAgent(e){return this._deleteDirectory(e)}async deleteSkill(e){return this._deleteDirectory(e)}async *listAgents(e){yield*this._listReposByType("agent",e)}async *listSkills(e){yield*this._listReposByType("skill",e)}async *_listReposByType(e,t){let r=new URLSearchParams;for await(let a of(r.append("repo_type",e),r.append("is_archived",(!!t?.isArchived).toString()),t?.isPublic!==void 0&&r.append("is_public",t.isPublic.toString()),t?.query&&r.append("query",t.query),this._getPaginated("/repos",r,e=>e.repos)))yield*a}async _pullDirectory(e,t,r){let[a,n,i]=tg(e),s=r??("latest"!==i?i:void 0),o=new URL(`${this.apiUrl}/v1/platform/hub/repos/${a}/${n}/directories`);o.searchParams.set("repo_type",t),s&&o.searchParams.set("commit",s);let l=await this.caller.call(async()=>{let e=await this._fetch(o.toString(),{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await tp(e,"pull directory"),e});return await l.json()}async _pushDirectory(e,t,r){if(void 0!==r.parentCommit&&(r.parentCommit.length<8||r.parentCommit.length>64))throw Error("parent_commit must be 8-64 characters");let[a,n]=tg(e);if(!await this._currentTenantIsOwner(a))throw await this._ownerConflictError(`push ${t}`,a);if(await this._repoExists(a,n))(void 0!==r.description||void 0!==r.readme||void 0!==r.tags||void 0!==r.isPublic)&&await this._updateRepoMetadata(a,n,r);else{let e=/^[a-z][a-z0-9-_]*$/;if(!e.test(n))throw Error(`Invalid repo_handle ${JSON.stringify(n)}: must match ${e}`);await this._createRepo(n,t,r)}let i={files:r.files};r.parentCommit&&(i.parent_commit=r.parentCommit);let s=await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/v1/platform/hub/repos/${a}/${n}/directories/commits`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(i)});return await tp(e,`push ${t}`),e}),o=(await s.json()).commit.commit_hash;return`${this.getHostUrl()}/hub/${a}/${n}:${o.slice(0,8)}`}async _deleteDirectory(e){let[t,r]=tg(e);if(!await this._currentTenantIsOwner(t))throw await this._ownerConflictError("delete",t);await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/v1/platform/hub/repos/${t}/${r}/directories`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await tp(e,"delete directory"),e})}async _repoExists(e,t){try{return await this.caller.call(async()=>{let r=await this._fetch(`${this.apiUrl}/repos/${e}/${t}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await tp(r,"check repo exists"),r}),!0}catch(e){if(th(e))return!1;throw e}}async _createRepo(e,t,r){let a={repo_handle:e,repo_type:t,is_public:!!r.isPublic};void 0!==r.description&&(a.description=r.description),void 0!==r.readme&&(a.readme=r.readme),void 0!==r.tags&&(a.tags=r.tags);try{await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/repos/`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(a)});return await tp(e,`create ${t}`),e})}catch(e){if(null!=e&&"object"==typeof e&&"name"in e&&e?.name==="LangSmithConflictError")return;throw e}}async _updateRepoMetadata(e,t,r){let a={};void 0!==r.description&&(a.description=r.description),void 0!==r.readme&&(a.readme=r.readme),void 0!==r.tags&&(a.tags=r.tags),void 0!==r.isPublic&&(a.is_public=r.isPublic),0!==Object.keys(a).length&&await this.caller.call(async()=>{let r=await this._fetch(`${this.apiUrl}/repos/${e}/${t}`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(a)});return await tp(r,"update repo metadata"),r})}async clonePublicDataset(e,t={}){let{sourceApiUrl:r=this.apiUrl,datasetName:a}=t,[n,i]=this.parseTokenOrUrl(e,r),s=new tL({apiUrl:n,apiKey:"placeholder"}),o=await s.readSharedDataset(i),l=a||o.name;try{if(await this.hasDataset({datasetId:l}))return void console.log(`Dataset ${l} already exists in your tenant. Skipping.`)}catch(e){}let u=await s.listSharedExamples(i),d=await this.createDataset(l,{description:o.description,dataType:o.data_type||"kv",inputsSchema:o.inputs_schema_definition??void 0,outputsSchema:o.outputs_schema_definition??void 0});try{await this.createExamples({inputs:u.map(e=>e.inputs),outputs:u.flatMap(e=>e.outputs?[e.outputs]:[]),datasetId:d.id})}catch(e){throw console.error(`An error occurred while creating dataset ${l}. You should delete it manually.`),e}}parseTokenOrUrl(e,t,r=2,a="dataset"){try{return eT(e),[t,e]}catch(e){}try{let n=new URL(e).pathname.split("/").filter(e=>""!==e);if(n.length>=r){let e=n[n.length-r];return[t,e]}throw Error(`Invalid public ${a} URL: ${e}`)}catch(t){throw Error(`Invalid public ${a} URL or token: ${e}`)}}cleanup(){this._promptCache&&this._promptCache.stop()}async awaitPendingTraceBatches(){if(this.manualFlushMode)return console.warn("[WARNING]: When tracing in manual flush mode, you must call `await client.flush()` manually to submit trace batches."),Promise.resolve();for(await new Promise(e=>setTimeout(e,1));this._pendingDrains.size>0;)await Promise.all([...this._pendingDrains]);await Promise.all([...this.autoBatchQueue.items.map(({itemPromise:e})=>e),this.batchIngestCaller.queue.onIdle()]),void 0!==this.langSmithToOTELTranslator&&await e0.getDefaultOTLPTracerComponents()?.DEFAULT_LANGSMITH_SPAN_PROCESSOR?.forceFlush()}toString(){let e=[`apiUrl=${JSON.stringify(this.apiUrl)}`];return void 0!==this.webUrl&&e.push(`webUrl=${JSON.stringify(this.webUrl)}`),void 0!==this.workspaceId&&e.push(`workspaceId=${JSON.stringify(this.workspaceId)}`),`[LangSmithClient ${e.join(" ")}]`}[Symbol.for("nodejs.util.inspect.custom")](){return this.toString()}}function tZ(e){return"dataset_id"in e||"dataset_name"in e}Object.defineProperty(tL,"_fallbackDirsCreated",{enumerable:!0,configurable:!0,writable:!0,value:new Set});let tD=Symbol.for("lc:context_variables");Symbol.for("lc:child_run_end_promises");let tU=Symbol.for("langsmith:replica_trace_roots");function tB(e,t){if(tD in e)return e[tD][t]}function tF(e){return M(Object.keys(e).sort().map(t=>`${t}:${e[t]??""}`).join("|"),"6ba7b810-9dad-11d1-80b4-00c04fd430c8")}function tH(e,t=1){let r=t.toFixed(0).slice(0,3).padStart(3,"0");return`${new Date(e).toISOString().slice(0,-1)}${r}Z`}function tq(e,t,r=1){let a=tH(e,r);return{dottedOrder:a.replace(/[-:.]/g,"")+t,microsecondPrecisionDatestring:a}}let tJ=new Set(["projectName","updates","reroot"]);class tG{constructor(e,t,r,a){Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"project_name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"replicas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.metadata=e,this.tags=t,this.project_name=r,this.replicas=a}static fromHeader(e){let t,r,a=e.split(","),n={},i=[];for(let e of a){let[a,s]=e.split("="),o=decodeURIComponent(s);"langsmith-metadata"===a?n=JSON.parse(o):"langsmith-tags"===a?i=o.split(","):"langsmith-project"===a?t=o:"langsmith-replicas"===a&&(r=JSON.parse(o).map(e=>Array.isArray(e)?e:function(e){let t={};for(let r of Object.keys(e))tJ.has(r)&&(t[r]=e[r]);return t}(e)))}return new tG(n,i,t,r)}toHeader(){let e=[];return this.metadata&&Object.keys(this.metadata).length>0&&e.push(`langsmith-metadata=${encodeURIComponent(JSON.stringify(this.metadata))}`),this.tags&&this.tags.length>0&&e.push(`langsmith-tags=${encodeURIComponent(this.tags.join(","))}`),this.project_name&&e.push(`langsmith-project=${encodeURIComponent(this.project_name)}`),e.join(",")}}class tW{constructor(e){if(Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"run_type",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"project_name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parent_run",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parent_run_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_runs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"end_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"extra",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"error",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"serialized",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"inputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"outputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reference_example_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"events",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"trace_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dotted_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingEnabled",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"attachments",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"replicas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"distributedParentId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_serialized_start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_awaitInputsOnPost",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),function(e){return null!=e&&"function"==typeof e.createChild&&"function"==typeof e.postRun}(e))return void Object.assign(this,{...e});const t=tW.getDefaultConfig(),{metadata:r,...a}=e,n=a.client??tW.getSharedClient(),i={...r,...a?.extra?.metadata};if(a.extra={...a.extra,metadata:i},"id"in a&&null==a.id&&delete a.id,Object.assign(this,{...t,...a,client:n}),this.execution_order??=1,this.child_execution_order??=1,this.dotted_order||(this._serialized_start_time=tH(this.start_time,this.execution_order)),this.id||(this.id=function(e){return D({msecs:"string"==typeof e?Date.parse(e):e,seq:0})}(this._serialized_start_time??this.start_time)),this.trace_id||(this.parent_run?this.trace_id=this.parent_run.trace_id??this.id:this.trace_id=this.id),this.replicas=function(e){return e?e.map(e=>Array.isArray(e)?{projectName:e[0],updates:e[1]}:e):function(){let e=eF("LANGSMITH_RUNS_ENDPOINTS");if(!e)return[];try{let r=JSON.parse(e);if(Array.isArray(r)){let e=[];for(let t of r){if("object"!=typeof t||null===t){console.warn(`Invalid item type in LANGSMITH_RUNS_ENDPOINTS: expected object, got ${typeof t}`);continue}if("string"!=typeof t.api_url){console.warn(`Invalid api_url type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof t.api_url}`);continue}if("string"!=typeof t.api_key){console.warn(`Invalid api_key type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof t.api_key}`);continue}e.push({apiUrl:t.api_url.replace(/\/$/,""),apiKey:t.api_key})}return e}if("object"!=typeof r||null===r)return 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 r}`),[];{var t=r;if(Object.keys(t).length>0&&eH("ENDPOINT"))throw new tm;let e=[];for(let[t,a]of Object.entries(r)){let r=t.replace(/\/$/,"");if("string"==typeof a)e.push({apiUrl:r,apiKey:a});else{console.warn(`Invalid value type in LANGSMITH_RUNS_ENDPOINTS for URL ${t}: expected string, got ${typeof a}`);continue}}return e}}catch(e){if("object"==typeof e&&null!==e&&e.code===tf)throw e;return 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"),[]}}()}(this.replicas),!this.dotted_order){const{dottedOrder:e}=tq(this.start_time,this.id,this.execution_order);this.parent_run?this.dotted_order=this.parent_run.dotted_order+"."+e:this.dotted_order=e}}set metadata(e){this.extra={...this.extra,metadata:{...this.extra?.metadata,...e}}}get metadata(){return this.extra?.metadata}static getDefaultConfig(){let e=Date.now();return{run_type:"chain",project_name:G(),child_runs:[],api_url:eF("LANGCHAIN_ENDPOINT")??"http://localhost:1984",api_key:eF("LANGCHAIN_API_KEY"),caller_options:{},start_time:e,serialized:{},inputs:{},extra:{}}}static getSharedClient(){return tW.sharedClient||(tW.sharedClient=new tL),tW.sharedClient}createChild(e){var t,r;let a,n=this.child_execution_order+1,i=this.replicas?.map(e=>{let{reroot:t,...r}=e;return r}),s=e.replicas??i,o=new tW({...e,parent_run:this,project_name:this.project_name,replicas:s,client:this.client,tracingEnabled:this.tracingEnabled,execution_order:n,child_execution_order:n}),l=this.extra?.metadata??{},u=o.extra?.metadata??{};Object.keys(l).length>0&&(o.extra={...o.extra,metadata:{...l,...u}}),tD in this&&(o[tD]=this[tD]);let d=Symbol.for("lc:child_config"),c=e.extra?.[d]??this.extra[d];if(t=c,a=t?.callbacks,null!=t&&"object"==typeof a&&(tK(a?.handlers)||tK(a))){let e={...c},t="object"==typeof(r=e.callbacks)&&null!=r&&Array.isArray(r.handlers)?e.callbacks.copy?.():void 0;t&&(Object.assign(t,{_parentRunId:o.id}),t.handlers?.find(tV)?.updateFromRunTree?.(o),e.callbacks=t),o.extra[d]=e}let h=new Set,p=this;for(;null!=p&&!h.has(p.id);)h.add(p.id),p.child_execution_order=Math.max(p.child_execution_order,n),p=p.parent_run;return this.child_runs.push(o),o}async end(e,t,r=Date.now(),a){this.outputs=this.outputs??e,this.error=this.error??t,this.end_time=this.end_time??r,a&&Object.keys(a).length>0&&(this.extra=this.extra?{...this.extra,metadata:{...this.extra.metadata,...a}}:{metadata:a})}_convertToCreate(e,t,r=!0){let a,n=e.extra??{};if(n?.runtime?.library===void 0&&(n.runtime||(n.runtime={}),t))for(let[e,r]of Object.entries(t))n.runtime[e]||(n.runtime[e]=r);let i=e.parent_run?.id??e.parent_run_id;return a=r?[]:e.child_runs.map(e=>this._convertToCreate(e,t,r)),{id:e.id,name:e.name,start_time:e._serialized_start_time??e.start_time,end_time:e.end_time,run_type:e.run_type,reference_example_id:e.reference_example_id,extra:n,serialized:e.serialized,error:e.error,inputs:e.inputs,outputs:e.outputs,session_name:e.project_name,child_runs:a,parent_run_id:i,trace_id:e.trace_id,dotted_order:e.dotted_order,tags:e.tags,attachments:e.attachments,events:e.events}}_sliceParentId(e,t){if(t.dotted_order){let r=t.dotted_order.split("."),a=null;for(let t=0;t0?t.trace_id=e[0].slice(-36):t.trace_id=t.id}}t.parent_run_id===e&&(t.parent_run_id=void 0)}_setReplicaTraceRoot(e,t){let r,a=tB(this,tU)??{};for(let n of(a[e]=t,(r=tD in this?this[tD]:{})[tU]=a,this[tD]=r,this.child_runs))n._setReplicaTraceRoot(e,t)}_remapForProject(e){let t,r,a,n,{projectName:i,runtimeEnv:s,excludeChildRuns:o=!0,reroot:l=!1,distributedParentId:u,apiUrl:d,apiKey:c,workspaceId:h}=e,p=this._convertToCreate(this,s,o);if(i===this.project_name)return{...p,session_name:i};if(l){if(u)this._sliceParentId(u,p);else if(p.parent_run_id=void 0,p.dotted_order){let e=p.dotted_order.split(".");e.length>0&&(p.dotted_order=e[e.length-1],p.trace_id=p.id)}let e=tF({projectName:i,apiUrl:d,apiKey:c,workspaceId:h});this._setReplicaTraceRoot(e,p.id)}if(!l&&(t=(tB(this,tU)??{})[tF({projectName:i,apiUrl:d,apiKey:c,workspaceId:h})])&&(p.trace_id=t,p.dotted_order)){let e=p.dotted_order.split("."),r=null;for(let a=0;a{let t=eC(e.slice(-36),i);return e.slice(0,-36)+t}).join(".")),{...p,id:f,trace_id:r,parent_run_id:a,dotted_order:n,session_name:i}}async postRun(e=!0){this._awaitInputsOnPost&&(this.inputs=await this.inputs);try{let t=eU();if(this.replicas&&this.replicas.length>0)for(let{projectName:e,apiKey:r,apiUrl:a,workspaceId:n,reroot:i,client:s}of this.replicas){let o=this._remapForProject({projectName:e??this.project_name,runtimeEnv:t,excludeChildRuns:!0,reroot:i,distributedParentId:this.distributedParentId,apiUrl:a,apiKey:r,workspaceId:n}),l=s??this.client;await l.createRun(o,{apiKey:r,apiUrl:a,workspaceId:n})}else{let r=this._convertToCreate(this,t,e);await this.client.createRun(r)}if(!e)for(let e of(tl("Posting with excludeChildRuns=false is deprecated and will be removed in a future version."),this.child_runs))await e.postRun(!1);this.child_runs=[]}catch(e){console.error(`Error in postRun for run ${this.id}:`,e)}}async patchRun(e){if(this.replicas&&this.replicas.length>0)for(let{projectName:t,apiKey:r,apiUrl:a,workspaceId:n,updates:i,reroot:s,client:o}of this.replicas){let l=this._remapForProject({projectName:t??this.project_name,runtimeEnv:void 0,excludeChildRuns:!0,reroot:s,distributedParentId:this.distributedParentId,apiUrl:a,apiKey:r,workspaceId:n}),u={id:l.id,name:l.name,run_type:l.run_type,start_time:l.start_time,outputs:l.outputs,error:l.error,parent_run_id:l.parent_run_id,session_name:l.session_name,reference_example_id:l.reference_example_id,end_time:l.end_time,dotted_order:l.dotted_order,trace_id:l.trace_id,events:l.events,tags:l.tags,extra:l.extra,attachments:this.attachments,...i};e?.excludeInputs||(u.inputs=l.inputs);let d=o??this.client;await d.updateRun(l.id,u,{apiKey:r,apiUrl:a,workspaceId:n})}else try{let t={name:this.name,run_type:this.run_type,start_time:this._serialized_start_time??this.start_time,end_time:this.end_time,error:this.error,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};e?.excludeInputs||(t.inputs=this.inputs),await this.client.updateRun(this.id,t)}catch(e){console.error(`Error in patchRun for run ${this.id}`,e)}this.child_runs=[]}toJSON(){return this._convertToCreate(this,void 0,!1)}addEvent(e){this.events||(this.events=[]),"string"==typeof e?this.events.push({name:"event",time:new Date().toISOString(),message:e}):this.events.push({...e,time:e.time??new Date().toISOString()})}static fromRunnableConfig(e,t){var r;let a,n,i,s=e?.callbacks,o=void 0!==r?r:!!["TRACING_V2","TRACING"].find(e=>"true"===eH(e));if(s){let e=s?.getParentRunId?.()??"",t=s?.handlers?.find(e=>e?.name=="langchain_tracer");a=t?.getRun?.(e),n=t?.projectName,i=t?.client,o=o||!!t}return a?new tW({name:a.name,id:a.id,trace_id:a.trace_id,dotted_order:a.dotted_order,client:i,tracingEnabled:o,project_name:n,tags:[...new Set((a?.tags??[]).concat(e?.tags??[]))],extra:{metadata:{...a?.extra?.metadata,...e?.metadata}}}).createChild(t):new tW({...t,client:i,tracingEnabled:o,project_name:n})}static fromDottedOrder(e){return this.fromHeaders({"langsmith-trace":e})}static fromHeaders(e,t){let r="get"in e&&"function"==typeof e.get?{"langsmith-trace":e.get("langsmith-trace"),baggage:e.get("baggage")}:e,a=r["langsmith-trace"];if(!a||"string"!=typeof a)return;let n=a.trim(),i=n.split(".").map(e=>{let[t,r]=e.split("Z");return{strTime:t,time:Date.parse(t+"Z"),uuid:r}}),s=i[0].uuid,o={...t,name:t?.name??"parent",run_type:t?.run_type??"chain",start_time:t?.start_time??Date.now(),id:i.at(-1)?.uuid,trace_id:s,dotted_order:n};if(r.baggage&&"string"==typeof r.baggage){let e=tG.fromHeader(r.baggage);o.metadata=e.metadata,o.tags=e.tags,o.project_name=e.project_name,o.replicas=e.replicas}let l=new tW(o);return l.distributedParentId=l.id,l}toHeaders(e){let t={"langsmith-trace":this.dotted_order,baggage:new tG(this.extra?.metadata,this.tags,this.project_name,this.replicas).toHeader()};if(e)for(let[r,a]of Object.entries(t))e.set(r,a);return t}}function tV(e){return"object"==typeof e&&null!=e&&"string"==typeof e.name&&"langchain_tracer"===e.name}function tK(e){return Array.isArray(e)&&e.some(e=>tV(e))}Object.defineProperty(tW,"sharedClient",{enumerable:!0,configurable:!0,writable:!0,value:null});var tY=(0,l.__exportAll)({BaseTracer:()=>t0,isBaseTracer:()=>tX});function tQ(e,t){return e&&!Array.isArray(e)&&"object"==typeof e?e:{[t]:e}}function tX(e){return"function"==typeof e._addRunToRunMap}var t0=class extends E{runMap=new Map;runTreeMap=new Map;usesRunTreeMap=!1;constructor(e){super(...arguments)}copy(){return this}getRunById(e){if(void 0!==e)return this.usesRunTreeMap?(e=>{if(e)return e.events=e.events??[],e.child_runs=e.child_runs??[],e})(this.runTreeMap.get(e)):this.runMap.get(e)}stringifyError(e){return e instanceof Error?e.message+(e?.stack?` ${e.stack}`:""):"string"==typeof e?e:`${e}`}_addChildRun(e,t){e.child_runs.push(t)}_addRunToRunMap(e){let{dottedOrder:t,microsecondPrecisionDatestring:r}=tq(new Date(e.start_time).getTime(),e.id,e.execution_order),a={...e},n=this.getRunById(a.parent_run_id);if(void 0!==a.parent_run_id?n?(this._addChildRun(n,a),n.child_execution_order=Math.max(n.child_execution_order,a.child_execution_order),a.trace_id=n.trace_id,void 0!==n.dotted_order&&(a.dotted_order=[n.dotted_order,t].join("."),a._serialized_start_time=r)):a.parent_run_id=void 0:(a.trace_id=a.id,a.dotted_order=t,a._serialized_start_time=r),this.usesRunTreeMap){let e=function e(t,r){if(t)return new tW({...t,start_time:t._serialized_start_time??t.start_time,parent_run:e(r),child_runs:t.child_runs.map(t=>e(t)).filter(e=>void 0!==e),extra:{...t.extra,runtime:v()},tracingEnabled:!1})}(a,n);void 0!==e&&this.runTreeMap.set(a.id,e)}else this.runMap.set(a.id,a);return a}async _endTrace(e){let t=void 0!==e.parent_run_id&&this.getRunById(e.parent_run_id);t?t.child_execution_order=Math.max(t.child_execution_order,e.child_execution_order):await this.persistRun(e),await this.onRunUpdate?.(e),this.usesRunTreeMap?this.runTreeMap.delete(e.id):this.runMap.delete(e.id)}_getExecutionOrder(e){let t=void 0!==e&&this.getRunById(e);return t?t.child_execution_order+1:1}_createRunForLLMStart(e,t,r,a,n,i,s,o){let l=this._getExecutionOrder(a),u=Date.now(),d=s?{...n,metadata:s}:n,c={id:r,name:o??e.id[e.id.length-1],parent_run_id:a,start_time:u,serialized:e,events:[{name:"start",time:new Date(u).toISOString()}],inputs:{prompts:t},execution_order:l,child_runs:[],child_execution_order:l,run_type:"llm",extra:d??{},tags:i||[]};return this._addRunToRunMap(c)}async handleLLMStart(e,t,r,a,n,i,s,o){let l=this.getRunById(r)??this._createRunForLLMStart(e,t,r,a,n,i,s,o);return await this.onRunCreate?.(l),await this.onLLMStart?.(l),l}_createRunForChatModelStart(e,t,r,a,n,i,s,o){let l=this._getExecutionOrder(a),u=Date.now(),d=s?{...n,metadata:s}:n,c={id:r,name:o??e.id[e.id.length-1],parent_run_id:a,start_time:u,serialized:e,events:[{name:"start",time:new Date(u).toISOString()}],inputs:{messages:t},execution_order:l,child_runs:[],child_execution_order:l,run_type:"llm",extra:d??{},tags:i||[]};return this._addRunToRunMap(c)}async handleChatModelStart(e,t,r,a,n,i,s,o){let l=this.getRunById(r)??this._createRunForChatModelStart(e,t,r,a,n,i,s,o);return await this.onRunCreate?.(l),await this.onLLMStart?.(l),l}async handleLLMEnd(e,t,r,a,n){let i=this.getRunById(t);if(!i||i?.run_type!=="llm")throw Error("No LLM run to end.");return i.end_time=Date.now(),i.outputs=e,i.events.push({name:"end",time:new Date(i.end_time).toISOString()}),i.extra={...i.extra,...n},await this.onLLMEnd?.(i),await this._endTrace(i),i}async handleLLMError(e,t,r,a,n){let i=this.getRunById(t);if(!i||i?.run_type!=="llm")throw Error("No LLM run to end.");return i.end_time=Date.now(),i.error=this.stringifyError(e),i.events.push({name:"error",time:new Date(i.end_time).toISOString()}),i.extra={...i.extra,...n},await this.onLLMError?.(i),await this._endTrace(i),i}_createRunForChainStart(e,t,r,a,n,i,s,o,l){let u=this._getExecutionOrder(a),d=Date.now(),c={id:r,name:o??e.id[e.id.length-1],parent_run_id:a,start_time:d,serialized:e,events:[{name:"start",time:new Date(d).toISOString()}],inputs:t,execution_order:u,child_execution_order:u,run_type:s??"chain",child_runs:[],extra:i?{...l,metadata:i}:{...l},tags:n||[]};return this._addRunToRunMap(c)}async handleChainStart(e,t,r,a,n,i,s,o){let l=this.getRunById(r)??this._createRunForChainStart(e,t,r,a,n,i,s,o);return await this.onRunCreate?.(l),await this.onChainStart?.(l),l}async handleChainEnd(e,t,r,a,n){let i=this.getRunById(t);if(!i)throw Error("No chain run to end.");return i.end_time=Date.now(),i.outputs=tQ(e,"output"),i.events.push({name:"end",time:new Date(i.end_time).toISOString()}),n?.inputs!==void 0&&(i.inputs=tQ(n.inputs,"input")),await this.onChainEnd?.(i),await this._endTrace(i),i}async handleChainError(e,t,r,a,n){let i=this.getRunById(t);if(!i)throw Error("No chain run to end.");return i.end_time=Date.now(),i.error=this.stringifyError(e),i.events.push({name:"error",time:new Date(i.end_time).toISOString()}),n?.inputs!==void 0&&(i.inputs=tQ(n.inputs,"input")),await this.onChainError?.(i),await this._endTrace(i),i}_createRunForToolStart(e,t,r,a,n,i,s){let o=this._getExecutionOrder(a),l=Date.now(),u={id:r,name:s??e.id[e.id.length-1],parent_run_id:a,start_time:l,serialized:e,events:[{name:"start",time:new Date(l).toISOString()}],inputs:{input:t},execution_order:o,child_execution_order:o,run_type:"tool",child_runs:[],extra:i?{metadata:i}:{},tags:n||[]};return this._addRunToRunMap(u)}async handleToolStart(e,t,r,a,n,i,s){let o=this.getRunById(r)??this._createRunForToolStart(e,t,r,a,n,i,s);return await this.onRunCreate?.(o),await this.onToolStart?.(o),o}async handleToolEnd(e,t){let r=this.getRunById(t);if(!r||r?.run_type!=="tool")throw Error("No tool run to end");return r.end_time=Date.now(),r.outputs={output:e},r.events.push({name:"end",time:new Date(r.end_time).toISOString()}),await this.onToolEnd?.(r),await this._endTrace(r),r}async handleToolError(e,t){let r=this.getRunById(t);if(!r||r?.run_type!=="tool")throw Error("No tool run to end");return r.end_time=Date.now(),r.error=this.stringifyError(e),r.events.push({name:"error",time:new Date(r.end_time).toISOString()}),await this.onToolError?.(r),await this._endTrace(r),r}async handleAgentAction(e,t){let r=this.getRunById(t);r&&r?.run_type==="chain"&&(r.actions=r.actions||[],r.actions.push(e),r.events.push({name:"agent_action",time:new Date().toISOString(),kwargs:{action:e}}),await this.onAgentAction?.(r))}async handleAgentEnd(e,t){let r=this.getRunById(t);r&&r?.run_type==="chain"&&(r.events.push({name:"agent_end",time:new Date().toISOString(),kwargs:{action:e}}),await this.onAgentEnd?.(r))}_createRunForRetrieverStart(e,t,r,a,n,i,s){let o=this._getExecutionOrder(a),l=Date.now(),u={id:r,name:s??e.id[e.id.length-1],parent_run_id:a,start_time:l,serialized:e,events:[{name:"start",time:new Date(l).toISOString()}],inputs:{query:t},execution_order:o,child_execution_order:o,run_type:"retriever",child_runs:[],extra:i?{metadata:i}:{},tags:n||[]};return this._addRunToRunMap(u)}async handleRetrieverStart(e,t,r,a,n,i,s){let o=this.getRunById(r)??this._createRunForRetrieverStart(e,t,r,a,n,i,s);return await this.onRunCreate?.(o),await this.onRetrieverStart?.(o),o}async handleRetrieverEnd(e,t){let r=this.getRunById(t);if(!r||r?.run_type!=="retriever")throw Error("No retriever run to end");return r.end_time=Date.now(),r.outputs={documents:e},r.events.push({name:"end",time:new Date(r.end_time).toISOString()}),await this.onRetrieverEnd?.(r),await this._endTrace(r),r}async handleRetrieverError(e,t){let r=this.getRunById(t);if(!r||r?.run_type!=="retriever")throw Error("No retriever run to end");return r.end_time=Date.now(),r.error=this.stringifyError(e),r.events.push({name:"error",time:new Date(r.end_time).toISOString()}),await this.onRetrieverError?.(r),await this._endTrace(r),r}async handleText(e,t){let r=this.getRunById(t);r&&r?.run_type==="chain"&&(r.events.push({name:"text",time:new Date().toISOString(),kwargs:{text:e}}),await this.onText?.(r))}async handleLLMNewToken(e,t,r,a,n,i){let s=this.getRunById(r);if(!s||s?.run_type!=="llm")throw Error('Invalid "runId" provided to "handleLLMNewToken" callback.');return s.events.push({name:"new_token",time:new Date().toISOString(),kwargs:{token:e,idx:t,chunk:i?.chunk}}),await this.onLLMNewToken?.(s,e,{chunk:i?.chunk}),s}};e.s(["BaseTracer",0,t0,"base_exports",0,tY,"isBaseTracer",0,tX],191325);var t1=e.i(704567),t4=(0,l.__exportAll)({ConsoleCallbackHandler:()=>t8});function t2(e,t){return`${e.open}${t}${e.close}`}function t9(e,t){try{return JSON.stringify(e,null,2)}catch{return t}}function t6(e){return"string"==typeof e?e.trim():null==e?e:t9(e,e.toString())}function t5(e){if(!e.end_time)return"";let t=e.end_time-e.start_time;return t<1e3?`${t}ms`:`${(t/1e3).toFixed(2)}s`}let{color:t3}=t1.default;var t8=class extends t0{name="console_callback_handler";persistRun(e){return Promise.resolve()}getParents(e){let t=[],r=e;for(;r.parent_run_id;){let e=this.runMap.get(r.parent_run_id);if(e)t.push(e),r=e;else break}return t}getBreadcrumbs(e){let t=[...this.getParents(e).reverse(),e].map((e,t,r)=>{let a=`${e.execution_order}:${e.run_type}:${e.name}`;return t===r.length-1?t2(t1.default.bold,a):a}).join(" > ");return t2(t3.grey,t)}onChainStart(e){let t=this.getBreadcrumbs(e);console.log(`${t2(t3.green,"[chain/start]")} [${t}] Entering Chain run with input: ${t9(e.inputs,"[inputs]")}`)}onChainEnd(e){let t=this.getBreadcrumbs(e);console.log(`${t2(t3.cyan,"[chain/end]")} [${t}] [${t5(e)}] Exiting Chain run with output: ${t9(e.outputs,"[outputs]")}`)}onChainError(e){let t=this.getBreadcrumbs(e);console.log(`${t2(t3.red,"[chain/error]")} [${t}] [${t5(e)}] Chain run errored with error: ${t9(e.error,"[error]")}`)}onLLMStart(e){let t=this.getBreadcrumbs(e),r="prompts"in e.inputs?{prompts:e.inputs.prompts.map(e=>e.trim())}:e.inputs;console.log(`${t2(t3.green,"[llm/start]")} [${t}] Entering LLM run with input: ${t9(r,"[inputs]")}`)}onLLMEnd(e){let t=this.getBreadcrumbs(e);console.log(`${t2(t3.cyan,"[llm/end]")} [${t}] [${t5(e)}] Exiting LLM run with output: ${t9(e.outputs,"[response]")}`)}onLLMError(e){let t=this.getBreadcrumbs(e);console.log(`${t2(t3.red,"[llm/error]")} [${t}] [${t5(e)}] LLM run errored with error: ${t9(e.error,"[error]")}`)}onToolStart(e){let t=this.getBreadcrumbs(e);console.log(`${t2(t3.green,"[tool/start]")} [${t}] Entering Tool run with input: "${t6(e.inputs.input)}"`)}onToolEnd(e){let t=this.getBreadcrumbs(e);console.log(`${t2(t3.cyan,"[tool/end]")} [${t}] [${t5(e)}] Exiting Tool run with output: "${t6(e.outputs?.output)}"`)}onToolError(e){let t=this.getBreadcrumbs(e);console.log(`${t2(t3.red,"[tool/error]")} [${t}] [${t5(e)}] Tool run errored with error: ${t9(e.error,"[error]")}`)}onRetrieverStart(e){let t=this.getBreadcrumbs(e);console.log(`${t2(t3.green,"[retriever/start]")} [${t}] Entering Retriever run with input: ${t9(e.inputs,"[inputs]")}`)}onRetrieverEnd(e){let t=this.getBreadcrumbs(e);console.log(`${t2(t3.cyan,"[retriever/end]")} [${t}] [${t5(e)}] Exiting Retriever run with output: ${t9(e.outputs,"[outputs]")}`)}onRetrieverError(e){let t=this.getBreadcrumbs(e);console.log(`${t2(t3.red,"[retriever/error]")} [${t}] [${t5(e)}] Retriever run errored with error: ${t9(e.error,"[error]")}`)}onAgentAction(e){let t=this.getBreadcrumbs(e);console.log(`${t2(t3.blue,"[agent/action]")} [${t}] Agent selected action: ${t9(e.actions[e.actions.length-1],"[action]")}`)}};e.s(["ConsoleCallbackHandler",0,t8,"console_exports",0,t4],804017);var t7=e.i(367751),re=e.i(649835);e.s([],779571);let rt=()=>(void 0===i&&(i=new tL("false"===b("LANGCHAIN_CALLBACKS_BACKGROUND")?{blockOnRootRunFinalization:!0}:{})),i),rr=Symbol.for("ls:tracing_async_local_storage"),ra=new class{getStore(){}run(e,t){return t()}},rn=new class{getInstance(){return globalThis[rr]??ra}initializeGlobalInstance(e){void 0===globalThis[rr]&&(globalThis[rr]=e)}};function ri(e=!1){let t=rn.getInstance().getStore();if(!e&&void 0===t)throw 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.");return t}Symbol.for("langsmith:traceable:root"),e.s(["getCurrentRunTree",0,ri,"isTraceableFunction",0,function(e){return"function"==typeof e&&"langsmith:traceable"in e}],76719),e.s([],184698);var rs=(0,l.__exportAll)({LangChainTracer:()=>rl,OVERRIDABLE_LANGSMITH_INHERITABLE_METADATA_KEYS:()=>ro});let ro=new Set(["ls_agent_type"]);var rl=class e extends t0{name="langchain_tracer";projectName;exampleId;client;replicas;usesRunTreeMap=!0;tracingMetadata;tracingTags=[];constructor(t={}){super(t),this.fields=t;const{exampleId:r,projectName:a,client:n,replicas:i,metadata:s,tags:o}=t;this.projectName=a??G(),this.replicas=i,this.exampleId=r,this.client=n??rt(),this.tracingMetadata=s?{...s}:void 0,this.tracingTags=o??[];const l=e.getTraceableRunTree();l&&this.updateFromRunTree(l)}async persistRun(e){}async onRunCreate(e){ru(this,e),e.extra?.lc_defers_inputs||await this.getRunTreeWithTracingConfig(e.id)?.postRun()}async onRunUpdate(e){ru(this,e);let t=this.getRunTreeWithTracingConfig(e.id);e.extra?.lc_defers_inputs?await t?.postRun():await t?.patchRun()}onLLMEnd(e){let t=e.outputs;if(t?.generations){let r=function(e){let t;for(let r of e)for(let e of r)re.AIMessage.isInstance(e.message)&&void 0!==e.message.usage_metadata&&(t=(0,t7.mergeUsageMetadata)(t,e.message.usage_metadata));return t}(t.generations);if(void 0!==r){e.extra=e.extra??{};let t=e.extra.metadata??{};t.usage_metadata=r,e.extra.metadata=t}}}copyWithTracingConfig({metadata:t,tags:r}){let a;if(void 0===t)a=this.tracingMetadata?{...this.tracingMetadata}:void 0;else if(void 0===this.tracingMetadata)a={...t};else for(let[e,r]of(a={...this.tracingMetadata},Object.entries(t)))(!Object.prototype.hasOwnProperty.call(a,e)||ro.has(e))&&(a[e]=r);let n=r?Array.from(new Set([...this.tracingTags,...r])):[...this.tracingTags],i=new e({...this.fields,metadata:a,tags:n});return i.runMap=this.runMap,i.runTreeMap=this.runTreeMap,i}getRun(e){return this.runTreeMap.get(e)}updateFromRunTree(e){this.runTreeMap.set(e.id,e);let t=e,r=new Set;for(;t.parent_run&&!r.has(t.id)&&(r.add(t.id),t.parent_run);){;t=t.parent_run}r.clear();let a=[t];for(;a.length>0;){let e=a.shift();!(!e||r.has(e.id))&&(r.add(e.id),this.runTreeMap.set(e.id,e),e.child_runs&&a.push(...e.child_runs))}this.client=e.client??this.client,this.replicas=e.replicas??this.replicas,this.projectName=e.project_name??this.projectName,this.exampleId=e.reference_example_id??this.exampleId,this.fields={...this.fields,client:this.client,replicas:this.replicas,projectName:this.projectName,exampleId:this.exampleId}}getRunTreeWithTracingConfig(e){let t=this.runTreeMap.get(e);if(t)return new tW({...t,client:this.client,project_name:this.projectName,replicas:this.replicas,reference_example_id:this.exampleId,tracingEnabled:!0})}static getTraceableRunTree(){try{return ri(!0)}catch{return}}static[Symbol.hasInstance](e){return"object"==typeof e&&null!==e&&"name"in e&&"langchain_tracer"===e.name&&"copyWithTracingConfig"in e&&"function"==typeof e.copyWithTracingConfig&&"getRunTreeWithTracingConfig"in e&&"function"==typeof e.getRunTreeWithTracingConfig}};function ru(e,t){if(e.tracingMetadata){t.extra??={};let r=t.extra.metadata??{},a=!1;for(let[t,n]of Object.entries(e.tracingMetadata))(!Object.prototype.hasOwnProperty.call(r,t)||ro.has(t))&&r[t]!==n&&(r[t]=n,a=!0);a&&(t.extra.metadata=r)}e.tracingTags.length>0&&(t.tags=Array.from(new Set([...t.tags??[],...e.tracingTags])))}async function rd(e,t){if(!0===t){let t=(0,u.getGlobalAsyncLocalStorageInstance)();void 0!==t?await t.run(void 0,async()=>e()):await e()}else void 0===s&&(s=new("default"in tt.default?tt.default.default:tt.default)({autoStart:!0,concurrency:1})),s.add(async()=>{let t=(0,u.getGlobalAsyncLocalStorageInstance)();void 0!==t?await t.run(void 0,async()=>e()):await e()})}async function rc(){let e=rt();await Promise.allSettled([void 0!==s?s.onIdle():Promise.resolve(),e.awaitPendingTraceBatches()])}e.s(["LangChainTracer",0,rl,"tracer_langchain_exports",0,rs],146833);var rh=(0,l.__exportAll)({awaitAllCallbacks:()=>rc,consumeCallback:()=>rd});function rp(e){let t=(0,u.getGlobalAsyncLocalStorageInstance)();if(void 0!==t)return t.getStore()?.[u._CONTEXT_VARIABLES_KEY]?.[e]}e.s(["promises_exports",0,rh],131059);let rf=Symbol("lc:configure_hooks");var rm=(0,l.__exportAll)({BaseCallbackManager:()=>r_,BaseRunManager:()=>ry,CallbackManager:()=>rx,CallbackManagerForChainRun:()=>rw,CallbackManagerForLLMRun:()=>rb,CallbackManagerForRetrieverRun:()=>rv,CallbackManagerForToolRun:()=>rk,ensureHandler:()=>rS,parseCallbackConfigArg:()=>rg});function rg(e){return e?Array.isArray(e)||"name"in e?{callbacks:e}:e:{}}var r_=class{setHandler(e){return this.setHandlers([e])}},ry=class{constructor(e,t,r,a,n,i,s,o){this.runId=e,this.handlers=t,this.inheritableHandlers=r,this.tags=a,this.inheritableTags=n,this.metadata=i,this.inheritableMetadata=s,this._parentRunId=o}get parentRunId(){return this._parentRunId}async handleText(e){await Promise.all(this.handlers.map(t=>rd(async()=>{try{await t.handleText?.(e,this.runId,this._parentRunId,this.tags)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleText: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}async handleCustomEvent(e,t,r,a,n){await Promise.all(this.handlers.map(r=>rd(async()=>{try{await r.handleCustomEvent?.(e,t,this.runId,this.tags,this.metadata)}catch(e){if((r.raiseError?console.error:console.warn)(`Error in handler ${r.constructor.name}, handleCustomEvent: ${e}`),r.raiseError)throw e}},r.awaitHandlers)))}},rv=class extends ry{getChild(e){let t=new rx(this.runId);return t.setHandlers(this.inheritableHandlers),t.addTags(this.inheritableTags),t.addMetadata(this.inheritableMetadata),e&&t.addTags([e],!1),t}async handleRetrieverEnd(e){await Promise.all(this.handlers.map(t=>rd(async()=>{if(!t.ignoreRetriever)try{await t.handleRetrieverEnd?.(e,this.runId,this._parentRunId,this.tags)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleRetriever`),t.raiseError)throw e}},t.awaitHandlers)))}async handleRetrieverError(e){await Promise.all(this.handlers.map(t=>rd(async()=>{if(!t.ignoreRetriever)try{await t.handleRetrieverError?.(e,this.runId,this._parentRunId,this.tags)}catch(r){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleRetrieverError: ${r}`),t.raiseError)throw e}},t.awaitHandlers)))}},rb=class extends ry{async handleLLMNewToken(e,t,r,a,n,i){await Promise.all(this.handlers.map(r=>rd(async()=>{if(!r.ignoreLLM)try{await r.handleLLMNewToken?.(e,t??{prompt:0,completion:0},this.runId,this._parentRunId,this.tags,i)}catch(e){if((r.raiseError?console.error:console.warn)(`Error in handler ${r.constructor.name}, handleLLMNewToken: ${e}`),r.raiseError)throw e}},r.awaitHandlers)))}async handleChatModelStreamEvent(e){await Promise.all(this.handlers.map(t=>rd(async()=>{if(!t.ignoreLLM)try{await t.handleChatModelStreamEvent?.(e,this.runId,this._parentRunId,this.tags)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleChatModelStreamEvent: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}async handleLLMError(e,t,r,a,n){await Promise.all(this.handlers.map(t=>rd(async()=>{if(!t.ignoreLLM)try{await t.handleLLMError?.(e,this.runId,this._parentRunId,this.tags,n)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleLLMError: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}async handleLLMEnd(e,t,r,a,n){await Promise.all(this.handlers.map(t=>rd(async()=>{if(!t.ignoreLLM)try{await t.handleLLMEnd?.(e,this.runId,this._parentRunId,this.tags,n)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleLLMEnd: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}},rw=class extends ry{getChild(e){let t=new rx(this.runId);return t.setHandlers(this.inheritableHandlers),t.addTags(this.inheritableTags),t.addMetadata(this.inheritableMetadata),e&&t.addTags([e],!1),t}async handleChainError(e,t,r,a,n){await Promise.all(this.handlers.map(t=>rd(async()=>{if(!t.ignoreChain)try{await t.handleChainError?.(e,this.runId,this._parentRunId,this.tags,n)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleChainError: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}async handleChainEnd(e,t,r,a,n){await Promise.all(this.handlers.map(t=>rd(async()=>{if(!t.ignoreChain)try{await t.handleChainEnd?.(e,this.runId,this._parentRunId,this.tags,n)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleChainEnd: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}async handleAgentAction(e){await Promise.all(this.handlers.map(t=>rd(async()=>{if(!t.ignoreAgent)try{await t.handleAgentAction?.(e,this.runId,this._parentRunId,this.tags)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleAgentAction: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}async handleAgentEnd(e){await Promise.all(this.handlers.map(t=>rd(async()=>{if(!t.ignoreAgent)try{await t.handleAgentEnd?.(e,this.runId,this._parentRunId,this.tags)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleAgentEnd: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}},rk=class extends ry{getChild(e){let t=new rx(this.runId);return t.setHandlers(this.inheritableHandlers),t.addTags(this.inheritableTags),t.addMetadata(this.inheritableMetadata),e&&t.addTags([e],!1),t}async handleToolError(e){await Promise.all(this.handlers.map(t=>rd(async()=>{if(!t.ignoreAgent)try{await t.handleToolError?.(e,this.runId,this._parentRunId,this.tags)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleToolError: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}async handleToolEvent(e){await Promise.all(this.handlers.map(t=>rd(async()=>{if(!t.ignoreAgent)try{await t.handleToolEvent?.(e,this.runId,this._parentRunId,this.tags)}catch(e){if(t.raiseError)throw e}},t.awaitHandlers)))}async handleToolEnd(e){await Promise.all(this.handlers.map(t=>rd(async()=>{if(!t.ignoreAgent)try{await t.handleToolEnd?.(e,this.runId,this._parentRunId,this.tags)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleToolEnd: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}},rx=class e extends r_{handlers=[];inheritableHandlers=[];tags=[];inheritableTags=[];metadata={};inheritableMetadata={};name="callback_manager";_parentRunId;constructor(e,t){super(),this.handlers=t?.handlers??this.handlers,this.inheritableHandlers=t?.inheritableHandlers??this.inheritableHandlers,this.tags=t?.tags??this.tags,this.inheritableTags=t?.inheritableTags??this.inheritableTags,this.metadata=t?.metadata??this.metadata,this.inheritableMetadata=t?.inheritableMetadata??this.inheritableMetadata,this._parentRunId=e}getParentRunId(){return this._parentRunId}async handleLLMStart(e,t,r,a,n,i,s,o){return Promise.all(t.map(async(t,a)=>{let i=0===a&&r?r:(0,c.default)();return await Promise.all(this.handlers.map(r=>{if(!r.ignoreLLM)return tX(r)&&r._createRunForLLMStart(e,[t],i,this._parentRunId,n,this.tags,this.metadata,o),rd(async()=>{try{await r.handleLLMStart?.(e,[t],i,this._parentRunId,n,this.tags,this.metadata,o)}catch(e){if((r.raiseError?console.error:console.warn)(`Error in handler ${r.constructor.name}, handleLLMStart: ${e}`),r.raiseError)throw e}},r.awaitHandlers)})),new rb(i,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChatModelStart(e,t,r,a,n,i,s,o){return Promise.all(t.map(async(t,a)=>{let i=0===a&&r?r:(0,c.default)();return await Promise.all(this.handlers.map(r=>{if(!r.ignoreLLM)return tX(r)&&r._createRunForChatModelStart(e,[t],i,this._parentRunId,n,this.tags,this.metadata,o),rd(async()=>{try{if(r.handleChatModelStart)await r.handleChatModelStart?.(e,[t],i,this._parentRunId,n,this.tags,this.metadata,o);else if(r.handleLLMStart){let a=(0,d.getBufferString)(t);await r.handleLLMStart?.(e,[a],i,this._parentRunId,n,this.tags,this.metadata,o)}}catch(e){if((r.raiseError?console.error:console.warn)(`Error in handler ${r.constructor.name}, handleLLMStart: ${e}`),r.raiseError)throw e}},r.awaitHandlers)})),new rb(i,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChainStart(e,t,r=(0,c.default)(),a,n,i,s,o,l){return await Promise.all(this.handlers.map(n=>{if(!n.ignoreChain)return tX(n)&&n._createRunForChainStart(e,t,r,this._parentRunId,this.tags,this.metadata,a,s,l),rd(async()=>{try{await n.handleChainStart?.(e,t,r,this._parentRunId,this.tags,this.metadata,a,s,l)}catch(e){if((n.raiseError?console.error:console.warn)(`Error in handler ${n.constructor.name}, handleChainStart: ${e}`),n.raiseError)throw e}},n.awaitHandlers)})),new rw(r,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleToolStart(e,t,r=(0,c.default)(),a,n,i,s,o){return await Promise.all(this.handlers.map(a=>{if(!a.ignoreAgent)return tX(a)&&a._createRunForToolStart(e,t,r,this._parentRunId,this.tags,this.metadata,s),rd(async()=>{try{await a.handleToolStart?.(e,t,r,this._parentRunId,this.tags,this.metadata,s,o)}catch(e){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleToolStart: ${e}`),a.raiseError)throw e}},a.awaitHandlers)})),new rk(r,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleRetrieverStart(e,t,r=(0,c.default)(),a,n,i,s){return await Promise.all(this.handlers.map(a=>{if(!a.ignoreRetriever)return tX(a)&&a._createRunForRetrieverStart(e,t,r,this._parentRunId,this.tags,this.metadata,s),rd(async()=>{try{await a.handleRetrieverStart?.(e,t,r,this._parentRunId,this.tags,this.metadata,s)}catch(e){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleRetrieverStart: ${e}`),a.raiseError)throw e}},a.awaitHandlers)})),new rv(r,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleCustomEvent(e,t,r,a,n){await Promise.all(this.handlers.map(a=>rd(async()=>{if(!a.ignoreCustomEvent)try{await a.handleCustomEvent?.(e,t,r,this.tags,this.metadata)}catch(e){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleCustomEvent: ${e}`),a.raiseError)throw e}},a.awaitHandlers)))}addHandler(e,t=!0){this.handlers.push(e),t&&this.inheritableHandlers.push(e)}removeHandler(e){this.handlers=this.handlers.filter(t=>t!==e),this.inheritableHandlers=this.inheritableHandlers.filter(t=>t!==e)}setHandlers(e,t=!0){for(let r of(this.handlers=[],this.inheritableHandlers=[],e))this.addHandler(r,t)}addTags(e,t=!0){this.removeTags(e),this.tags.push(...e),t&&this.inheritableTags.push(...e)}removeTags(e){this.tags=this.tags.filter(t=>!e.includes(t)),this.inheritableTags=this.inheritableTags.filter(t=>!e.includes(t))}addMetadata(e,t=!0){this.metadata={...this.metadata,...e},t&&(this.inheritableMetadata={...this.inheritableMetadata,...e})}removeMetadata(e){for(let t of Object.keys(e))delete this.metadata[t],delete this.inheritableMetadata[t]}copy(t=[],r=!0){let a=new e(this._parentRunId);for(let e of this.handlers){let t=this.inheritableHandlers.includes(e);a.addHandler(e,t)}for(let e of this.tags){let t=this.inheritableTags.includes(e);a.addTags([e],t)}for(let e of Object.keys(this.metadata)){let t=Object.keys(this.inheritableMetadata).includes(e);a.addMetadata({[e]:this.metadata[e]},t)}for(let e of t)a.handlers.filter(e=>"console_callback_handler"===e.name).some(t=>t.name===e.name)||a.addHandler(e,r);return a}static fromHandlers(e){class t extends E{name=(0,c.default)();constructor(){super(),Object.assign(this,e)}}let r=new this;return r.addHandler(new t),r}static configure(e,t,r,a,n,i,s){return this._configureSync(e,t,r,a,n,i,s)}static _configureSync(t,r,a,n,i,s,o){var l;let u;(t||r)&&(Array.isArray(t)||!t?(u=new e).setHandlers(t?.map(rS)??[],!0):u=t,u=u.copy(Array.isArray(r)?r.map(rS):r?.handlers,!1));let d="true"===b("LANGCHAIN_VERBOSE")||o?.verbose,c=rl.getTraceableRunTree(),h=c?.tracingEnabled??(void 0!==l?l:!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find(e=>"true"===b(e)));if(c?.tracingEnabled===!1&&u)for(let e of u.handlers.filter(e=>"langchain_tracer"===e.name))u.removeHandler(e);let p=h||(b("LANGCHAIN_TRACING")??!1);if(d||p){if(u||(u=new e),d&&!u.handlers.some(e=>e.name===t8.prototype.name)){let e=new t8;u.addHandler(e,!0)}if(p&&!u.handlers.some(e=>"langchain_tracer"===e.name)&&h){let e=new rl;u.addHandler(e,!0)}h&&c&&void 0===u._parentRunId&&(u._parentRunId=c.id,u.handlers.find(e=>"langchain_tracer"===e.name)?.updateFromRunTree(c))}for(let{contextVar:t,inheritable:r=!0,handlerClass:a,envVar:n}of rp(rf)||[]){let i,s=n&&"true"===b(n)&&a,o=void 0!==t?rp(t):void 0;o&&T(o)?i=o:s&&(i=new a({})),void 0!==i&&(u||(u=new e),u.handlers.some(e=>e.name===i.name)||u.addHandler(i,r))}(a||n)&&u&&(u.addTags(a??[]),u.addTags(n??[],!1)),(i||s)&&u&&(u.addMetadata(i??{}),u.addMetadata(s??{},!1));let f=o?.tracerInheritableMetadata,m=o?.tracerInheritableTags;return u&&(f||m)&&(u.handlers=u.handlers.map(e=>e instanceof rl?e.copyWithTracingConfig({metadata:f,tags:m}):e),u.inheritableHandlers=u.inheritableHandlers.map(e=>e instanceof rl?e.copyWithTracingConfig({metadata:f,tags:m}):e)),u}};function rS(e){return"name"in e?e:E.fromMethods(e)}e.s(["CallbackManager",0,rx,"ensureHandler",0,rS,"manager_exports",0,rm,"parseCallbackConfigArg",0,rg],206696);var r$=class{getStore(){}run(e,t){return t()}enterWith(e){}};let rE=new r$,rT=Symbol.for("lc:child_config"),rA=new class{getInstance(){return(0,u.getGlobalAsyncLocalStorageInstance)()??rE}getRunnableConfig(){return this.getInstance().getStore()?.extra?.[rT]}runWithConfig(e,t,r){let a,n=rx._configureSync(e?.callbacks,void 0,e?.tags,void 0,e?.metadata),i=this.getInstance(),s=i.getStore(),o=n?.getParentRunId(),l=n?.handlers?.find(e=>e?.name==="langchain_tracer");return l&&o?a=l.getRunTreeWithTracingConfig(o):r||(a=new tW({name:"",tracingEnabled:!1})),a&&(a.extra={...a.extra,[rT]:e}),void 0!==s&&void 0!==s[u._CONTEXT_VARIABLES_KEY]&&(void 0===a&&(a={}),a[u._CONTEXT_VARIABLES_KEY]=s[u._CONTEXT_VARIABLES_KEY]),i.run(a,t)}initializeGlobalInstance(e){void 0===(0,u.getGlobalAsyncLocalStorageInstance)()&&(0,u.setGlobalAsyncLocalStorageInstance)(e)}};e.s(["AsyncLocalStorageProviderSingleton",0,rA,"MockAsyncLocalStorage",0,r$],200587);var rC=(0,l.__exportAll)({AsyncLocalStorageProviderSingleton:()=>rA,MockAsyncLocalStorage:()=>r$,_CONTEXT_VARIABLES_KEY:()=>u._CONTEXT_VARIABLES_KEY});e.s(["singletons_exports",0,rC],869070);let rO=new Set(["api_key"]),rI=new Set(["string","number","boolean"]);async function rj(e){return rx._configureSync(e?.callbacks,void 0,e?.tags,void 0,e?.metadata,void 0,{tracerInheritableMetadata:e?function(e){let t=e.configurable??{},r=e.metadata??{},a={};for(let[e,n]of Object.entries(t))!e.startsWith("__")&&!Object.prototype.hasOwnProperty.call(r,e)&&!rO.has(e)&&rI.has(typeof n)&&(a[e]=n);return Object.keys(a).length>0?a:void 0}(e):void 0})}function rP(e){let t=rA.getRunnableConfig(),r={tags:[],metadata:{},recursionLimit:25,runId:void 0};if(t){let{runId:e,runName:a,...n}=t;r=Object.entries(n).reduce((e,[t,r])=>(void 0!==r&&(e[t]=r),e),r)}if(e&&(r=Object.entries(e).reduce((e,[t,r])=>(void 0!==r&&(e[t]=r),e),r)),r?.configurable&&"string"==typeof r.configurable.model&&r.metadata?.model===void 0&&(r.metadata||(r.metadata={}),r.metadata.model=r.configurable.model),void 0!==r.timeout){if(r.timeout<=0)throw Error("Timeout must be a positive number");let e=r.timeout,t=AbortSignal.timeout(e);r.metadata||(r.metadata={}),void 0===r.metadata.timeoutMs&&(r.metadata.timeoutMs=e),void 0!==r.signal?"any"in AbortSignal&&(r.signal=AbortSignal.any([r.signal,t])):r.signal=t,delete r.timeout}return r}function rz(e){if(e)return{configurable:e.configurable,recursionLimit:e.recursionLimit,callbacks:e.callbacks,tags:e.tags,metadata:e.metadata,maxConcurrency:e.maxConcurrency,timeout:e.timeout,signal:e.signal,store:e.store}}async function rN(e,t){let r;return void 0===t?e:Promise.race([e.catch(e=>{if(!t?.aborted)throw e}),new Promise((e,a)=>{r=()=>{a(rR(t))},t.addEventListener("abort",r,{once:!0}),t.aborted&&a(rR(t))})]).finally(()=>t.removeEventListener("abort",r))}function rR(e){return e?.reason instanceof Error?e.reason:"string"==typeof e?.reason?Error(e.reason):Error("Aborted")}e.s(["ensureConfig",0,rP,"getCallbackManagerForConfig",0,rj,"mergeConfigs",0,function(...e){let t={};for(let r of e.filter(e=>!!e))for(let e of Object.keys(r))if("metadata"===e)t[e]={...t[e],...r[e]};else if("tags"===e){let a=t[e]??[];t[e]=[...new Set(a.concat(r[e]??[]))]}else if("configurable"===e)t[e]={...t[e],...r[e]};else if("timeout"===e)void 0===t.timeout?t.timeout=r.timeout:void 0!==r.timeout&&(t.timeout=Math.min(t.timeout,r.timeout));else if("signal"===e)void 0===t.signal?t.signal=r.signal:void 0!==r.signal&&("any"in AbortSignal?t.signal=AbortSignal.any([t.signal,r.signal]):t.signal=r.signal);else if("callbacks"===e){let e=t.callbacks,a=r.callbacks;if(Array.isArray(a))if(e)if(Array.isArray(e))t.callbacks=e.concat(a);else{let r=e.copy();for(let e of a)r.addHandler(rS(e),!0);t.callbacks=r}else t.callbacks=a;else if(a)if(e)if(Array.isArray(e)){let r=a.copy();for(let t of e)r.addHandler(rS(t),!0);t.callbacks=r}else t.callbacks=new rx(a._parentRunId,{handlers:e.handlers.concat(a.handlers),inheritableHandlers:e.inheritableHandlers.concat(a.inheritableHandlers),tags:Array.from(new Set(e.tags.concat(a.tags))),inheritableTags:Array.from(new Set(e.inheritableTags.concat(a.inheritableTags))),metadata:{...e.metadata,...a.metadata}});else t.callbacks=a}else t[e]=r[e]??t[e];return t},"patchConfig",0,function(e={},{callbacks:t,maxConcurrency:r,recursionLimit:a,runName:n,configurable:i,runId:s}={}){let o=rP(e);return void 0!==t&&(delete o.runName,o.callbacks=t),void 0!==a&&(o.recursionLimit=a),void 0!==r&&(o.maxConcurrency=r),void 0!==n&&(o.runName=n),void 0!==i&&(o.configurable={...o.configurable,...i}),void 0!==s&&delete o.runId,o},"pickRunnableConfigKeys",0,rz],640516),e.s(["getAbortSignalError",0,rR,"raceWithSignal",0,rN],115995);var rM=(0,l.__exportAll)({AsyncGeneratorWithSetup:()=>rU,IterableReadableStream:()=>rL,atee:()=>rZ,concat:()=>rD,pipeGeneratorWithSetup:()=>rB}),rL=class e extends ReadableStream{reader;ensureReader(){this.reader||(this.reader=this.getReader())}async next(){this.ensureReader();try{let e=await this.reader.read();if(e.done)return this.reader.releaseLock(),{done:!0,value:void 0};return{done:!1,value:e.value}}catch(e){throw this.reader.releaseLock(),e}}async return(){if(this.ensureReader(),this.locked){let e=this.reader.cancel();this.reader.releaseLock(),await e}return{done:!0,value:void 0}}async throw(e){if(this.ensureReader(),this.locked){let e=this.reader.cancel();this.reader.releaseLock(),await e}throw e}[Symbol.asyncIterator](){return this}async [Symbol.asyncDispose](){await this.return()}static fromReadableStream(t){let r=t.getReader();return new e({start:e=>(function t(){return r.read().then(({done:r,value:a})=>r?void e.close():(e.enqueue(a),t()))})(),cancel(){r.releaseLock()}})}static fromAsyncGenerator(t){return new e({async pull(e){let{value:r,done:a}=await t.next();a&&e.close(),e.enqueue(r)},async cancel(e){await t.return(e)}})}};function rZ(e,t=2){let r=Array.from({length:t},()=>[]);return r.map(async function*(t){for(;;)if(0===t.length){let t=await e.next();for(let e of r)e.push(t)}else{if(t[0].done)return;yield t.shift().value}})}function rD(e,t){if(Array.isArray(e)&&Array.isArray(t))return e.concat(t);if("string"==typeof e&&"string"==typeof t)return e+t;if("number"==typeof e&&"number"==typeof t)return e+t;if("concat"in e&&"function"==typeof e.concat)return e.concat(t);if("object"==typeof e&&"object"==typeof t){let r={...e};for(let[e,a]of Object.entries(t))e in r&&!Array.isArray(r[e])?r[e]=rD(r[e],a):r[e]=a;return r}else throw Error(`Cannot concat ${typeof e} and ${typeof t}`)}var rU=class{generator;setup;config;signal;firstResult;firstResultUsed=!1;constructor(e){this.generator=e.generator,this.config=e.config,this.signal=e.signal??this.config?.signal,this.setup=new Promise((t,r)=>{rA.runWithConfig(rz(e.config),async()=>{this.firstResult=this.signal?rN(e.generator.next(),this.signal):e.generator.next(),e.startSetup?this.firstResult.then(e.startSetup).then(t,r):this.firstResult.then(e=>t(void 0),r)},!0)})}async next(...e){return(this.signal?.throwIfAborted(),this.firstResultUsed)?rA.runWithConfig(rz(this.config),this.signal?async()=>rN(this.generator.next(...e),this.signal):async()=>this.generator.next(...e),!0):(this.firstResultUsed=!0,this.firstResult)}async return(e){return this.generator.return(e)}async throw(e){return this.generator.throw(e)}[Symbol.asyncIterator](){return this}async [Symbol.asyncDispose](){await this.return()}};async function rB(e,t,r,a,...n){let i=new rU({generator:t,startSetup:r,signal:a}),s=await i.setup;return{output:e(i,s,...n),setup:s}}e.s(["AsyncGeneratorWithSetup",0,rU,"IterableReadableStream",0,rL,"atee",0,rZ,"concat",0,rD,"pipeGeneratorWithSetup",0,rB,"stream_exports",0,rM],890406);let rF=Object.prototype.hasOwnProperty;function rH(e,t){return rF.call(e,t)}function rq(e){if(Array.isArray(e)){let t=Array(e.length);for(let e=0;e=48&&t<=57){r++;continue}return!1}return!0}function rW(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function rV(e){if(void 0===e)return!0;if(e){if(Array.isArray(e)){for(let t=0,r=e.length;t0&&"constructor"==u[c-1]))throw 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(r&&void 0===l&&(void 0===d[s]?l=u.slice(0,c).join("/"):c==h-1&&(l=t.path),void 0!==l&&o(t,0,e,l)),c++,Array.isArray(d)){if("-"===s)s=d.length;else if(r&&!rG(s))throw new rY("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",i,t,e);else rG(s)&&(s=~~s);if(c>=h){if(r&&"add"===t.op&&s>d.length)throw new rY("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",i,t,e);let a=rX[t.op].call(t,d,s,e);if(!1===a.test)throw new rY("Test operation failed","TEST_OPERATION_FAILED",i,t,e);return a}}else if(c>=h){let r=rQ[t.op].call(t,d,s,e);if(!1===r.test)throw new rY("Test operation failed","TEST_OPERATION_FAILED",i,t,e);return r}if(d=d[s],r&&c0)throw new rY('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",t,e,r);else if(("move"===e.op||"copy"===e.op)&&"string"!=typeof e.from)throw new rY("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",t,e,r);else if(("add"===e.op||"replace"===e.op||"test"===e.op)&&void 0===e.value)throw new rY("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",t,e,r);else if(("add"===e.op||"replace"===e.op||"test"===e.op)&&rV(e.value))throw new rY("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",t,e,r);else if(r){if("add"==e.op){var n=e.path.split("/").length,i=a.split("/").length;if(n!==i+1&&n!==i)throw new rY("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",t,e,r)}else if("replace"===e.op||"remove"===e.op||"_get"===e.op){if(e.path!==a)throw new rY("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",t,e,r)}else if("move"===e.op||"copy"===e.op){var s=function(e,t,r){try{if(!Array.isArray(e))throw new rY("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(t)r4(rJ(t),rJ(e),r||!0);else{r=r||r2;for(var a=0;aat,RunLog:()=>r3,RunLogPatch:()=>r5,isLogStreamHandler:()=>r8}),r5=class{ops;constructor(e){this.ops=e.ops??[]}concat(e){let t=this.ops.concat(e.ops),r=r4({},t);return new r3({ops:t,state:r[r.length-1].newDocument})}},r3=class e extends r5{state;constructor(e){super(e),this.state=e.state}concat(t){let r=this.ops.concat(t.ops),a=r4(this.state,t.ops);return new e({ops:r,state:a[a.length-1].newDocument})}static fromRunLogPatch(t){let r=r4({},t.ops);return new e({ops:t.ops,state:r[r.length-1].newDocument})}};let r8=e=>"log_stream_tracer"===e.name;async function r7(e,t){if("original"===t)throw 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.");let{inputs:r}=e;return["retriever","llm","prompt"].includes(e.run_type)?r:1!==Object.keys(r).length||r?.input!==""?r.input:void 0}async function ae(e,t){let{outputs:r}=e;return"original"===t||["retriever","llm","prompt"].includes(e.run_type)?r:void 0!==r&&1===Object.keys(r).length&&r?.output!==void 0?r.output:r}var at=class extends t0{autoClose=!0;includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;_schemaFormat="original";rootId;keyMapByRunId={};counterMapByRunName={};transformStream;writer;receiveStream;name="log_stream_tracer";lc_prefer_streaming=!0;constructor(e){super({_awaitHandler:!0,...e}),this.autoClose=e?.autoClose??!0,this.includeNames=e?.includeNames,this.includeTypes=e?.includeTypes,this.includeTags=e?.includeTags,this.excludeNames=e?.excludeNames,this.excludeTypes=e?.excludeTypes,this.excludeTags=e?.excludeTags,this._schemaFormat=e?._schemaFormat??this._schemaFormat,this.transformStream=new TransformStream,this.writer=this.transformStream.writable.getWriter(),this.receiveStream=rL.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){if(e.id===this.rootId)return!1;let t=e.tags??[],r=void 0===this.includeNames&&void 0===this.includeTags&&void 0===this.includeTypes;return void 0!==this.includeNames&&(r=r||this.includeNames.includes(e.name)),void 0!==this.includeTypes&&(r=r||this.includeTypes.includes(e.run_type)),void 0!==this.includeTags&&(r=r||void 0!==t.find(e=>this.includeTags?.includes(e))),void 0!==this.excludeNames&&(r=r&&!this.excludeNames.includes(e.name)),void 0!==this.excludeTypes&&(r=r&&!this.excludeTypes.includes(e.run_type)),void 0!==this.excludeTags&&(r=r&&t.every(e=>!this.excludeTags?.includes(e))),r}async *tapOutputIterable(e,t){for await(let r of t){if(e!==this.rootId){let t=this.keyMapByRunId[e];t&&await this.writer.write(new r5({ops:[{op:"add",path:`/logs/${t}/streamed_output/-`,value:r}]}))}yield r}}async onRunCreate(e){if(void 0===this.rootId&&(this.rootId=e.id,await this.writer.write(new r5({ops:[{op:"replace",path:"",value:{id:e.id,name:e.name,type:e.run_type,streamed_output:[],final_output:void 0,logs:{}}}]}))),!this._includeRun(e))return;void 0===this.counterMapByRunName[e.name]&&(this.counterMapByRunName[e.name]=0),this.counterMapByRunName[e.name]+=1;let t=this.counterMapByRunName[e.name];this.keyMapByRunId[e.id]=1===t?e.name:`${e.name}:${t}`;let r={id:e.id,name:e.name,type:e.run_type,tags:e.tags??[],metadata:e.extra?.metadata??{},start_time:new Date(e.start_time).toISOString(),streamed_output:[],streamed_output_str:[],final_output:void 0,end_time:void 0};"streaming_events"===this._schemaFormat&&(r.inputs=await r7(e,this._schemaFormat)),await this.writer.write(new r5({ops:[{op:"add",path:`/logs/${this.keyMapByRunId[e.id]}`,value:r}]}))}async onRunUpdate(e){try{let t=this.keyMapByRunId[e.id];if(void 0===t)return;let r=[];"streaming_events"===this._schemaFormat&&r.push({op:"replace",path:`/logs/${t}/inputs`,value:await r7(e,this._schemaFormat)}),r.push({op:"add",path:`/logs/${t}/final_output`,value:await ae(e,this._schemaFormat)}),void 0!==e.end_time&&r.push({op:"add",path:`/logs/${t}/end_time`,value:new Date(e.end_time).toISOString()});let a=new r5({ops:r});await this.writer.write(a)}finally{if(e.id===this.rootId){let t=new r5({ops:[{op:"replace",path:"/final_output",value:await ae(e,this._schemaFormat)}]});await this.writer.write(t),this.autoClose&&await this.writer.close()}}}async onLLMNewToken(e,t,r){let a,n=this.keyMapByRunId[e.id];if(void 0===n)return;if(void 0!==e.inputs.messages){var i;a=void 0!==(i=r?.chunk)&&void 0!==i.message?r?.chunk:new re.AIMessageChunk({id:`run-${e.id}`,content:t})}else a=t;let s=new r5({ops:[{op:"add",path:`/logs/${n}/streamed_output_str/-`,value:t},{op:"add",path:`/logs/${n}/streamed_output/-`,value:a}]});await this.writer.write(s)}};e.s(["LogStreamCallbackHandler",0,at,"RunLog",0,r3,"RunLogPatch",0,r5,"isLogStreamHandler",0,r8,"log_stream_exports",0,r6],99815);var ar=(0,l.__exportAll)({ChatGenerationChunk:()=>ai,GenerationChunk:()=>an,RUN_KEY:()=>aa});let aa="__run";var an=class e{text;generationInfo;constructor(e){this.text=e.text,this.generationInfo=e.generationInfo}concat(t){return new e({text:this.text+t.text,generationInfo:{...this.generationInfo,...t.generationInfo}})}},ai=class e extends an{message;constructor(e){super(e),this.message=e.message}concat(t){return new e({text:this.text+t.text,generationInfo:{...this.generationInfo,...t.generationInfo},message:this.message.concat(t.message)})}};e.s(["ChatGenerationChunk",0,ai,"GenerationChunk",0,an,"RUN_KEY",0,aa,"outputs_exports",0,ar],976044)},577284,e=>{"use strict";var t=e.i(649835),r=e.i(191325),a=e.i(890406),n=e.i(976044);function i({name:e,serialized:t}){return void 0!==e?e:t?.name!==void 0?t.name:t?.id!==void 0&&Array.isArray(t?.id)?t.id[t.id.length-1]:"Unnamed"}var s=class extends r.BaseTracer{autoClose=!0;includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;runInfoMap=new Map;tappedPromises=new Map;transformStream;writer;receiveStream;readableStreamClosed=!1;name="event_stream_tracer";lc_prefer_streaming=!0;constructor(e){super({_awaitHandler:!0,...e}),this.autoClose=e?.autoClose??!0,this.includeNames=e?.includeNames,this.includeTypes=e?.includeTypes,this.includeTags=e?.includeTags,this.excludeNames=e?.excludeNames,this.excludeTypes=e?.excludeTypes,this.excludeTags=e?.excludeTags,this.transformStream=new TransformStream({flush:()=>{this.readableStreamClosed=!0}}),this.writer=this.transformStream.writable.getWriter(),this.receiveStream=a.IterableReadableStream.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){let t=e.tags??[],r=void 0===this.includeNames&&void 0===this.includeTags&&void 0===this.includeTypes;return void 0!==this.includeNames&&(r=r||this.includeNames.includes(e.name)),void 0!==this.includeTypes&&(r=r||this.includeTypes.includes(e.runType)),void 0!==this.includeTags&&(r=r||void 0!==t.find(e=>this.includeTags?.includes(e))),void 0!==this.excludeNames&&(r=r&&!this.excludeNames.includes(e.name)),void 0!==this.excludeTypes&&(r=r&&!this.excludeTypes.includes(e.runType)),void 0!==this.excludeTags&&(r=r&&t.every(e=>!this.excludeTags?.includes(e))),r}async *tapOutputIterable(e,t){let r=await t.next();if(r.done)return;let a=this.runInfoMap.get(e);if(void 0===a)return void(yield r.value);function i(e,t){return"llm"===e&&"string"==typeof t?new n.GenerationChunk({text:t}):t}let s=this.tappedPromises.get(e);if(void 0===s){let n;s=new Promise(e=>{n=e}),this.tappedPromises.set(e,s);try{let n={event:`on_${a.runType}_stream`,run_id:e,name:a.name,tags:a.tags,metadata:a.metadata,data:{}};for await(let e of(await this.send({...n,data:{chunk:i(a.runType,r.value)}},a),yield r.value,t))"tool"!==a.runType&&"retriever"!==a.runType&&await this.send({...n,data:{chunk:i(a.runType,e)}},a),yield e}finally{n?.()}}else for await(let e of(yield r.value,t))yield e}async send(e,t){!this.readableStreamClosed&&this._includeRun(t)&&await this.writer.write(e)}async sendEndEvent(e,t){let r=this.tappedPromises.get(e.run_id);void 0!==r?r.then(()=>{this.send(e,t)}):await this.send(e,t)}async onLLMStart(e){let t=i(e),r=void 0!==e.inputs.messages?"chat_model":"llm",a={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:r,inputs:e.inputs};this.runInfoMap.set(e.id,a);let n=`on_${r}_start`;await this.send({event:n,data:{input:e.inputs},name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},a)}async onLLMNewToken(e,r,a){let i,s,o=this.runInfoMap.get(e.id);if(void 0===o)throw Error(`onLLMNewToken: Run ID ${e.id} not found in run map.`);if(1!==this.runInfoMap.size){if("chat_model"===o.runType)s="on_chat_model_stream",i=a?.chunk===void 0?new t.AIMessageChunk({content:r,id:`run-${e.id}`}):a.chunk.message;else if("llm"===o.runType)s="on_llm_stream",i=a?.chunk===void 0?new n.GenerationChunk({text:r}):a.chunk;else throw Error(`Unexpected run type ${o.runType}`);await this.send({event:s,data:{chunk:i},run_id:e.id,name:o.name,tags:o.tags,metadata:o.metadata},o)}}async onLLMEnd(e){let t,r,a=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),void 0===a)throw Error(`onLLMEnd: Run ID ${e.id} not found in run map.`);let n=e.outputs?.generations;if("chat_model"===a.runType){for(let e of n??[]){if(void 0!==r)break;r=e[0]?.message}t="on_chat_model_end"}else if("llm"===a.runType)r={generations:n?.map(e=>e.map(e=>({text:e.text,generationInfo:e.generationInfo}))),llmOutput:e.outputs?.llmOutput??{}},t="on_llm_end";else throw Error(`onLLMEnd: Unexpected run type: ${a.runType}`);await this.sendEndEvent({event:t,data:{output:r,input:a.inputs},run_id:e.id,name:a.name,tags:a.tags,metadata:a.metadata},a)}async onChainStart(e){let t=i(e),r=e.run_type??"chain",a={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:e.run_type},n={};""===e.inputs.input&&1===Object.keys(e.inputs).length?(n={},a.inputs={}):void 0!==e.inputs.input?(n.input=e.inputs.input,a.inputs=e.inputs.input):(n.input=e.inputs,a.inputs=e.inputs),this.runInfoMap.set(e.id,a),await this.send({event:`on_${r}_start`,data:n,name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},a)}async onChainEnd(e){let t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),void 0===t)throw Error(`onChainEnd: Run ID ${e.id} not found in run map.`);let r=`on_${e.run_type}_end`,a=e.inputs??t.inputs??{},n={output:e.outputs?.output??e.outputs,input:a};a.input&&1===Object.keys(a).length&&(n.input=a.input,t.inputs=a.input),await this.sendEndEvent({event:r,data:n,run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata??{}},t)}async onToolStart(e){let t=i(e),r={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:"tool",inputs:e.inputs??{}};this.runInfoMap.set(e.id,r),await this.send({event:"on_tool_start",data:{input:e.inputs??{}},name:t,run_id:e.id,tags:e.tags??[],metadata:e.extra?.metadata??{}},r)}async onToolEnd(e){let t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),void 0===t)throw Error(`onToolEnd: Run ID ${e.id} not found in run map.`);if(void 0===t.inputs)throw Error(`onToolEnd: Run ID ${e.id} is a tool call, and is expected to have traced inputs.`);let r=e.outputs?.output===void 0?e.outputs:e.outputs.output;await this.sendEndEvent({event:"on_tool_end",data:{output:r,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onToolError(e){let t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),void 0===t)throw Error(`onToolEnd: Run ID ${e.id} not found in run map.`);if(void 0===t.inputs)throw Error(`onToolEnd: Run ID ${e.id} is a tool call, and is expected to have traced inputs.`);await this.sendEndEvent({event:"on_tool_error",data:{input:t.inputs,error:e.error},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onRetrieverStart(e){let t=i(e),r={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:"retriever",inputs:{query:e.inputs.query}};this.runInfoMap.set(e.id,r),await this.send({event:"on_retriever_start",data:{input:{query:e.inputs.query}},name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},r)}async onRetrieverEnd(e){let t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),void 0===t)throw Error(`onRetrieverEnd: Run ID ${e.id} not found in run map.`);await this.sendEndEvent({event:"on_retriever_end",data:{output:e.outputs?.documents??e.outputs,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async handleCustomEvent(e,t,r){let a=this.runInfoMap.get(r);if(void 0===a)throw Error(`handleCustomEvent: Run ID ${r} not found in run map.`);await this.send({event:"on_custom_event",run_id:r,name:e,tags:a.tags,metadata:a.metadata,data:t},a)}async finish(){Promise.all([...this.tappedPromises.values()]).finally(()=>{this.writer.close()})}};e.s(["EventStreamCallbackHandler",0,s,"isStreamEventsHandler",0,e=>"event_stream_tracer"===e.name])},664527,884606,e=>{"use strict";var t=e.i(190949),r=e.i(115995);let a=Object.prototype.toString,n=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"]);function i(e,t,{min:r=0,allowInfinity:a=!1}={}){if(void 0!==t){if("number"!=typeof t||Number.isNaN(t))throw TypeError(`Expected \`${e}\` to be a number${a?" or Infinity":""}.`);if(!a&&!Number.isFinite(t))throw TypeError(`Expected \`${e}\` to be a finite number.`);if(t=o(i,p))throw c;let m=await u.shouldConsumeRetry(f),g=o(i,p);if(g<=0||h<=0)throw c;if(c instanceof TypeError&&!function(e){if(!(e&&"[object Error]"===a.call(e)&&"TypeError"===e.name&&"string"==typeof e.message))return!1;let{message:t,stack:r}=e;return"Load failed"===t?void 0===r||"__sentry_captured__"in e:!!t.startsWith("error sending request for url")||n.has(t)}(c)){if(m)throw c;return u.signal?.throwIfAborted(),!1}if(!await u.shouldRetry(f))throw c;if(!m)return u.signal?.throwIfAborted(),!1;let _=Math.min((d=Math.max(1,r+1),Math.min(Math.round((u.randomize?Math.random()+1:1)*u.minTimeout*u.factor**(d-1)),u.maxTimeout)),g);return _>0&&await new Promise((e,t)=>{let r=()=>{clearTimeout(a),u.signal?.removeEventListener("abort",r),t(u.signal.reason)},a=setTimeout(()=>{u.signal?.removeEventListener("abort",r),e()},_);u.unref&&a.unref?.(),u.signal?.addEventListener("abort",r,{once:!0})}),u.signal?.throwIfAborted(),!0}async function u(e,t={}){var r=(t={...t}).retries;if("number"==typeof r){if(r<0)throw TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(r))throw TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(void 0!==r)throw TypeError("Expected `retries` to be a number or Infinity.");if(Object.hasOwn(t,"forever"))throw Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");t.retries??=10,t.factor??=2,t.minTimeout??=1e3,t.maxTimeout??=1/0,t.maxRetryTime??=1/0,t.randomize??=!1,t.onFailedAttempt??=()=>{},t.shouldRetry??=()=>!0,t.shouldConsumeRetry??=()=>!0,i("factor",t.factor,{min:0,allowInfinity:!1}),i("minTimeout",t.minTimeout,{min:0,allowInfinity:!1}),i("maxTimeout",t.maxTimeout,{min:0,allowInfinity:!0}),i("maxRetryTime",t.maxRetryTime,{min:0,allowInfinity:!0}),t.factor>0||(t.factor=1),t.signal?.throwIfAborted();let a=0,n=0,s=performance.now();for(;!Number.isFinite(t.retries)||n<=t.retries;){a++;try{t.signal?.throwIfAborted();let r=await e(a);return t.signal?.throwIfAborted(),r}catch(e){await l({error:e,attemptNumber:a,retriesConsumed:n,startTime:s,options:t})&&n++}}throw Error("Retry attempts exhausted without throwing an error.")}e.s(["default",0,u],884606);var d=e.i(655747),c=(0,t.__exportAll)({AsyncCaller:()=>f});let h=[400,401,402,403,404,405,406,407,409],p=e=>{if("object"!=typeof e||null===e)return;if("message"in e&&"string"==typeof e.message&&(e.message.startsWith("Cancel")||e.message.startsWith("AbortError"))||"name"in e&&"string"==typeof e.name&&"AbortError"===e.name||"code"in e&&"string"==typeof e.code&&"ECONNABORTED"===e.code)throw e;let t="response"in e&&"object"==typeof e.response&&null!==e.response&&"status"in e.response&&"number"==typeof e.response.status?e.response.status:void 0,r="status"in e&&"number"==typeof e.status?e.status:void 0,a=t??r;if(a&&h.includes(+a))throw e;if(("error"in e&&"object"==typeof e.error&&null!==e.error&&"code"in e.error&&"string"==typeof e.error.code?e.error.code:void 0)==="insufficient_quota"){let t=Error("message"in e&&"string"==typeof e.message?e.message:"Insufficient quota");throw t.name="InsufficientQuotaError",t}};var f=class{maxConcurrency;maxRetries;onFailedAttempt;queue;constructor(e){this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,this.onFailedAttempt=e.onFailedAttempt??p;const t="default"in d.default?d.default.default:d.default;this.queue=new t({concurrency:this.maxConcurrency})}async call(e,...t){return this.queue.add(()=>u(()=>e(...t).catch(e=>{if(e instanceof Error)throw e;throw Error(e)}),{onFailedAttempt:({error:e})=>this.onFailedAttempt?.(e),retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(e,t,...a){if(e.signal){let n;return Promise.race([this.call(t,...a),new Promise((t,a)=>{n=()=>{a((0,r.getAbortSignalError)(e.signal))},e.signal?.addEventListener("abort",n,{once:!0})})]).finally(()=>{e.signal&&n&&e.signal.removeEventListener("abort",n)})}return this.call(t,...a)}fetch(...e){return this.call(()=>fetch(...e).then(e=>e.ok?e:Promise.reject(e)))}};e.s(["AsyncCaller",0,f,"async_caller_exports",0,c],664527)},743160,e=>{"use strict";var t=e.i(191325),r=class extends t.BaseTracer{name="RootListenersTracer";rootId;config;argOnStart;argOnEnd;argOnError;constructor({config:e,onStart:t,onEnd:r,onError:a}){super({_awaitHandler:!0}),this.config=e,this.argOnStart=t,this.argOnEnd=r,this.argOnError=a}persistRun(e){return Promise.resolve()}async onRunCreate(e){!this.rootId&&(this.rootId=e.id,this.argOnStart&&await this.argOnStart(e,this.config))}async onRunUpdate(e){e.id===this.rootId&&(e.error?this.argOnError&&await this.argOnError(e,this.config):this.argOnEnd&&await this.argOnEnd(e,this.config))}};e.s(["RootListenersTracer",0,r])},165978,e=>{"use strict";var t=class{includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;constructor(e){this.includeNames=e.includeNames,this.includeTypes=e.includeTypes,this.includeTags=e.includeTags,this.excludeNames=e.excludeNames,this.excludeTypes=e.excludeTypes,this.excludeTags=e.excludeTags}includeEvent(e,t){let r=void 0===this.includeNames&&void 0===this.includeTypes&&void 0===this.includeTags,a=e.tags??[];return void 0!==this.includeNames&&(r=r||this.includeNames.includes(e.name)),void 0!==this.includeTypes&&(r=r||this.includeTypes.includes(t)),void 0!==this.includeTags&&(r=r||a.some(e=>this.includeTags?.includes(e))),void 0!==this.excludeNames&&(r=r&&!this.excludeNames.includes(e.name)),void 0!==this.excludeTypes&&(r=r&&!this.excludeTypes.includes(t)),void 0!==this.excludeTags&&(r=r&&a.every(e=>!this.excludeTags?.includes(e))),r}};e.s(["_RootEventFilter",0,t,"isRunnableInterface",0,function(e){return!!e&&e.lc_runnable},"toBase64Url",0,e=>btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")])},238073,127438,486618,421131,236608,173911,67021,715143,622824,639510,52637,862061,628343,e=>{"use strict";let t=Object.freeze({status:"aborted"});function r(e,t,r){function a(r,a){if(r._zod||Object.defineProperty(r,"_zod",{value:{def:a,constr:s,traits:new Set},enumerable:!1}),r._zod.traits.has(e))return;r._zod.traits.add(e),t(r,a);let n=s.prototype,i=Object.keys(n);for(let e=0;e!!r?.Parent&&t instanceof r.Parent||t?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}let a=Symbol("zod_brand");class n extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class i extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}}(ah=globalThis).__zod_globalConfig??(ah.__zod_globalConfig={});let s=globalThis.__zod_globalConfig;function o(e){return e&&Object.assign(s,e),s}function l(e){let t=Object.values(e).filter(e=>"number"==typeof e);return Object.entries(e).filter(([e,r])=>-1===t.indexOf(+e)).map(([e,t])=>t)}function u(e,t){return"bigint"==typeof t?t.toString():t}function d(e){return{get value(){{let t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function c(e){return null==e}function h(e){let t=+!!e.startsWith("^"),r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function p(e,t){let r=e/t,a=Math.round(r),n=Number.EPSILON*Math.max(Math.abs(r),1);return Math.abs(r-a){};function w(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}let k=d(()=>{if(s.jitless||"u">typeof navigator&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return Function(""),!0}catch(e){return!1}});function x(e){if(!1===w(e))return!1;let t=e.constructor;if(void 0===t||"function"!=typeof t)return!0;let r=t.prototype;return!1!==w(r)&&!1!==Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")}function S(e){return x(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}let $=new Set(["string","number","symbol"]),E=new Set(["string","number","bigint","boolean","symbol","undefined"]);function T(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function A(e,t,r){let a=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(a._zod.parent=e),a}function C(e){if(!e)return{};if("string"==typeof e)return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");e.error=e.message}return(delete e.message,"string"==typeof e.error)?{...e,error:()=>e.error}:e}function O(e){return"bigint"==typeof e?e.toString()+"n":"string"==typeof e?`"${e}"`:`${e}`}function I(e){return Object.keys(e).filter(t=>"optional"===e[t]._zod.optin&&"optional"===e[t]._zod.optout)}let j={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-0x80000000,0x7fffffff],uint32:[0,0xffffffff],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},P={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function z(e,t=0){if(!0===e.aborted)return!0;for(let r=t;r(t.path??(t.path=[]),t.path.unshift(e),t))}function M(e){return"string"==typeof e?e:e?.message}function L(e,t,r){let a=e.message?e.message:M(e.inst?._zod.def?.error?.(e))??M(t?.error?.(e))??M(r.customError?.(e))??M(r.localeError?.(e))??"Invalid input",{inst:n,continue:i,input:s,...o}=e;return o.path??(o.path=[]),o.message=a,t?.reportInput&&(o.input=s),o}function Z(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function D(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}function U(...e){let[t,r,a]=e;return"string"==typeof t?{message:t,code:"custom",input:r,inst:a}:{...t}}function B(e){let t=atob(e),r=new Uint8Array(t.length);for(let e=0;eNumber.isNaN(Number.parseInt(e,10))).map(e=>e[1])},"cleanRegex",0,h,"clone",0,A,"cloneDef",0,function(e){return _(e._zod.def)},"createTransparentProxy",0,function(e){let t;return new Proxy({},{get:(r,a,n)=>(t??(t=e()),Reflect.get(t,a,n)),set:(r,a,n,i)=>(t??(t=e()),Reflect.set(t,a,n,i)),has:(r,a)=>(t??(t=e()),Reflect.has(t,a)),deleteProperty:(r,a)=>(t??(t=e()),Reflect.deleteProperty(t,a)),ownKeys:r=>(t??(t=e()),Reflect.ownKeys(t)),getOwnPropertyDescriptor:(r,a)=>(t??(t=e()),Reflect.getOwnPropertyDescriptor(t,a)),defineProperty:(r,a,n)=>(t??(t=e()),Reflect.defineProperty(t,a,n))})},"defineLazy",0,m,"esc",0,y,"escapeRegex",0,T,"explicitlyAborted",0,N,"extend",0,function(e,t){if(!x(t))throw Error("Invalid input to extend: expected a plain object");let r=e._zod.def.checks;if(r&&r.length>0){let r=e._zod.def.shape;for(let e in t)if(void 0!==Object.getOwnPropertyDescriptor(r,e))throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let a=_(e._zod.def,{get shape(){let r={...e._zod.def.shape,...t};return g(this,"shape",r),r}});return A(e,a)},"finalizeIssue",0,L,"floatSafeRemainder",0,p,"getElementAtPath",0,function(e,t){return t?t.reduce((e,t)=>e?.[t],e):e},"getEnumValues",0,l,"getLengthableOrigin",0,D,"getParsedType",0,e=>{let t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch)return"promise";if("u">typeof Map&&e instanceof Map)return"map";if("u">typeof Set&&e instanceof Set)return"set";if("u">typeof Date&&e instanceof Date)return"date";if("u">typeof File&&e instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${t}`)}},"getSizableOrigin",0,Z,"hexToUint8Array",0,function(e){let t=e.replace(/^0x/,"");if(t.length%2!=0)throw Error("Invalid hex string length");let r=new Uint8Array(t.length/2);for(let e=0;eO(e)).join(t)},"jsonStringifyReplacer",0,u,"merge",0,function(e,t){if(e._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let r=_(e._zod.def,{get shape(){let r={...e._zod.def.shape,...t._zod.def.shape};return g(this,"shape",r),r},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return A(e,r)},"mergeDefs",0,_,"normalizeParams",0,C,"nullish",0,c,"numKeys",0,function(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t},"objectClone",0,function(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))},"omit",0,function(e,t){let r=e._zod.def,a=r.checks;if(a&&a.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let n=_(e._zod.def,{get shape(){let a={...e._zod.def.shape};for(let e in t){if(!(e in r.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&delete a[e]}return g(this,"shape",a),a},checks:[]});return A(e,n)},"optionalKeys",0,I,"parsedType",0,function(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":if(null===e)return"null";if(Array.isArray(e))return"array";if(e&&Object.getPrototypeOf(e)!==Object.prototype&&"constructor"in e&&e.constructor)return e.constructor.name}return t},"partial",0,function(e,t,r){let a=t._zod.def.checks;if(a&&a.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let n=_(t._zod.def,{get shape(){let a=t._zod.def.shape,n={...a};if(r)for(let t in r){if(!(t in a))throw Error(`Unrecognized key: "${t}"`);r[t]&&(n[t]=e?new e({type:"optional",innerType:a[t]}):a[t])}else for(let t in a)n[t]=e?new e({type:"optional",innerType:a[t]}):a[t];return g(this,"shape",n),n},checks:[]});return A(t,n)},"pick",0,function(e,t){let r=e._zod.def,a=r.checks;if(a&&a.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let n=_(e._zod.def,{get shape(){let e={};for(let a in t){if(!(a in r.shape))throw Error(`Unrecognized key: "${a}"`);t[a]&&(e[a]=r.shape[a])}return g(this,"shape",e),e},checks:[]});return A(e,n)},"prefixIssues",0,R,"primitiveTypes",0,E,"promiseAllObject",0,function(e){let t=Object.keys(e);return Promise.all(t.map(t=>e[t])).then(e=>{let r={};for(let a=0;ae.toString(16).padStart(2,"0")).join("")},"unwrapMessage",0,M],486618);let H=/^[cC][0-9a-z]{6,}$/,q=/^[0-9a-z]+$/,J=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,G=/^[0-9a-vA-V]{20}$/,W=/^[A-Za-z0-9]{27}$/,V=/^[a-zA-Z0-9_-]{21}$/,K=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Y=/^([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})$/,Q=e=>e?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([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|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,X=Q(4),ee=Q(6),et=Q(7),er=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,ea=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u;function en(){return RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")}let ei=/^(?:(?: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])$/,es=/^(([0-9a-fA-F]{1,4}:){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}|:))$/,eo=e=>{let t=T(e??":");return RegExp(`^(?:[0-9A-F]{2}${t}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${t}){5}[0-9a-f]{2}$`)},el=/^((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])$/,eu=/^(([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])$/,ed=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,ec=/^[A-Za-z0-9_-]*$/,eh=/^https?$/,ep=/^\+[1-9]\d{6,14}$/,ef="(?:(?:\\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])))",em=RegExp(`^${ef}$`);function eg(e){let t="(?:[01]\\d|2[0-3]):[0-5]\\d";return"number"==typeof e.precision?-1===e.precision?`${t}`:0===e.precision?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function e_(e){return RegExp(`^${eg(e)}$`)}function ey(e){let t=eg({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let a=`${t}(?:${r.join("|")})`;return RegExp(`^${ef}T(?:${a})$`)}let ev=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return RegExp(`^${t}$`)},eb=/^-?\d+n?$/,ew=/^-?\d+$/,ek=/^-?\d+(?:\.\d+)?$/,ex=/^(?:true|false)$/i,eS=/^null$/i,e$=/^undefined$/i,eE=/^[^A-Z]*$/,eT=/^[^a-z]*$/;function eA(e,t){return RegExp(`^[A-Za-z0-9+/]{${e}}${t}$`)}function eC(e){return RegExp(`^[A-Za-z0-9_-]{${e}}$`)}let eO=eA(22,"=="),eI=eC(22),ej=eA(27,"="),eP=eC(27),ez=eA(43,"="),eN=eC(43),eR=eA(64,""),eM=eC(64),eL=eA(86,"=="),eZ=eC(86);e.s(["base64",0,ed,"base64url",0,ec,"bigint",0,eb,"boolean",0,ex,"browserEmail",0,/^[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])?)*$/,"cidrv4",0,el,"cidrv6",0,eu,"cuid",0,H,"cuid2",0,q,"date",0,em,"datetime",0,ey,"domain",0,/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,"duration",0,K,"e164",0,ep,"email",0,er,"emoji",0,en,"extendedDuration",0,/^[-+]?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)?)??$/,"guid",0,Y,"hex",0,/^[0-9a-fA-F]*$/,"hostname",0,/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,"html5Email",0,/^[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])?)*$/,"httpProtocol",0,eh,"idnEmail",0,ea,"integer",0,ew,"ipv4",0,ei,"ipv6",0,es,"ksuid",0,W,"lowercase",0,eE,"mac",0,eo,"md5_base64",0,eO,"md5_base64url",0,eI,"md5_hex",0,/^[0-9a-fA-F]{32}$/,"nanoid",0,V,"null",0,eS,"number",0,ek,"rfc5322Email",0,/^(([^<>()\[\]\\.,;:\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,}))$/,"sha1_base64",0,ej,"sha1_base64url",0,eP,"sha1_hex",0,/^[0-9a-fA-F]{40}$/,"sha256_base64",0,ez,"sha256_base64url",0,eN,"sha256_hex",0,/^[0-9a-fA-F]{64}$/,"sha384_base64",0,eR,"sha384_base64url",0,eM,"sha384_hex",0,/^[0-9a-fA-F]{96}$/,"sha512_base64",0,eL,"sha512_base64url",0,eZ,"sha512_hex",0,/^[0-9a-fA-F]{128}$/,"string",0,ev,"time",0,e_,"ulid",0,J,"undefined",0,e$,"unicodeEmail",0,ea,"uppercase",0,eT,"uuid",0,Q,"uuid4",0,X,"uuid6",0,ee,"uuid7",0,et,"xid",0,G],421131);let eD=r("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),eU={number:"number",bigint:"bigint",object:"date"},eB=r("$ZodCheckLessThan",(e,t)=>{eD.init(e,t);let r=eU[typeof t.value];e._zod.onattach.push(e=>{let r=e._zod.bag,a=(t.inclusive?r.maximum:r.exclusiveMaximum)??1/0;t.value{(t.inclusive?a.value<=t.value:a.value{eD.init(e,t);let r=eU[typeof t.value];e._zod.onattach.push(e=>{let r=e._zod.bag,a=(t.inclusive?r.minimum:r.exclusiveMinimum)??-1/0;t.value>a&&(t.inclusive?r.minimum=t.value:r.exclusiveMinimum=t.value)}),e._zod.check=a=>{(t.inclusive?a.value>=t.value:a.value>t.value)||a.issues.push({origin:r,code:"too_small",minimum:"object"==typeof t.value?t.value.getTime():t.value,input:a.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),eH=r("$ZodCheckMultipleOf",(e,t)=>{eD.init(e,t),e._zod.onattach.push(e=>{var r;(r=e._zod.bag).multipleOf??(r.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw Error("Cannot mix number and bigint in multiple_of check.");("bigint"==typeof r.value?r.value%t.value===BigInt(0):0===p(r.value,t.value))||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),eq=r("$ZodCheckNumberFormat",(e,t)=>{eD.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),a=r?"int":"number",[n,i]=j[t.format];e._zod.onattach.push(e=>{let a=e._zod.bag;a.format=t.format,a.minimum=n,a.maximum=i,r&&(a.pattern=ew)}),e._zod.check=s=>{let o=s.value;if(r){if(!Number.isInteger(o))return void s.issues.push({expected:a,format:t.format,code:"invalid_type",continue:!1,input:o,inst:e});if(!Number.isSafeInteger(o))return void(o>0?s.issues.push({input:o,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:a,inclusive:!0,continue:!t.abort}):s.issues.push({input:o,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:a,inclusive:!0,continue:!t.abort}))}oi&&s.issues.push({origin:"number",input:o,code:"too_big",maximum:i,inclusive:!0,inst:e,continue:!t.abort})}}),eJ=r("$ZodCheckBigIntFormat",(e,t)=>{eD.init(e,t);let[r,a]=P[t.format];e._zod.onattach.push(e=>{let n=e._zod.bag;n.format=t.format,n.minimum=r,n.maximum=a}),e._zod.check=n=>{let i=n.value;ia&&n.issues.push({origin:"bigint",input:i,code:"too_big",maximum:a,inclusive:!0,inst:e,continue:!t.abort})}}),eG=r("$ZodCheckMaxSize",(e,t)=>{var r;eD.init(e,t),(r=e._zod.def).when??(r.when=e=>{let t=e.value;return!c(t)&&void 0!==t.size}),e._zod.onattach.push(e=>{let r=e._zod.bag.maximum??1/0;t.maximum{let a=r.value;a.size<=t.maximum||r.issues.push({origin:Z(a),code:"too_big",maximum:t.maximum,inclusive:!0,input:a,inst:e,continue:!t.abort})}}),eW=r("$ZodCheckMinSize",(e,t)=>{var r;eD.init(e,t),(r=e._zod.def).when??(r.when=e=>{let t=e.value;return!c(t)&&void 0!==t.size}),e._zod.onattach.push(e=>{let r=e._zod.bag.minimum??-1/0;t.minimum>r&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{let a=r.value;a.size>=t.minimum||r.issues.push({origin:Z(a),code:"too_small",minimum:t.minimum,inclusive:!0,input:a,inst:e,continue:!t.abort})}}),eV=r("$ZodCheckSizeEquals",(e,t)=>{var r;eD.init(e,t),(r=e._zod.def).when??(r.when=e=>{let t=e.value;return!c(t)&&void 0!==t.size}),e._zod.onattach.push(e=>{let r=e._zod.bag;r.minimum=t.size,r.maximum=t.size,r.size=t.size}),e._zod.check=r=>{let a=r.value,n=a.size;if(n===t.size)return;let i=n>t.size;r.issues.push({origin:Z(a),...i?{code:"too_big",maximum:t.size}:{code:"too_small",minimum:t.size},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),eK=r("$ZodCheckMaxLength",(e,t)=>{var r;eD.init(e,t),(r=e._zod.def).when??(r.when=e=>{let t=e.value;return!c(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{let r=e._zod.bag.maximum??1/0;t.maximum{let a=r.value;if(a.length<=t.maximum)return;let n=D(a);r.issues.push({origin:n,code:"too_big",maximum:t.maximum,inclusive:!0,input:a,inst:e,continue:!t.abort})}}),eY=r("$ZodCheckMinLength",(e,t)=>{var r;eD.init(e,t),(r=e._zod.def).when??(r.when=e=>{let t=e.value;return!c(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{let r=e._zod.bag.minimum??-1/0;t.minimum>r&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{let a=r.value;if(a.length>=t.minimum)return;let n=D(a);r.issues.push({origin:n,code:"too_small",minimum:t.minimum,inclusive:!0,input:a,inst:e,continue:!t.abort})}}),eQ=r("$ZodCheckLengthEquals",(e,t)=>{var r;eD.init(e,t),(r=e._zod.def).when??(r.when=e=>{let t=e.value;return!c(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{let r=e._zod.bag;r.minimum=t.length,r.maximum=t.length,r.length=t.length}),e._zod.check=r=>{let a=r.value,n=a.length;if(n===t.length)return;let i=D(a),s=n>t.length;r.issues.push({origin:i,...s?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),eX=r("$ZodCheckStringFormat",(e,t)=>{var r,a;eD.init(e,t),e._zod.onattach.push(e=>{let r=e._zod.bag;r.format=t.format,t.pattern&&(r.patterns??(r.patterns=new Set),r.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=r=>{t.pattern.lastIndex=0,t.pattern.test(r.value)||r.issues.push({origin:"string",code:"invalid_format",format:t.format,input:r.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(a=e._zod).check??(a.check=()=>{})}),e0=r("$ZodCheckRegex",(e,t)=>{eX.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,t.pattern.test(r.value)||r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),e1=r("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=eE),eX.init(e,t)}),e4=r("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=eT),eX.init(e,t)}),e2=r("$ZodCheckIncludes",(e,t)=>{eD.init(e,t);let r=T(t.includes),a=new RegExp("number"==typeof t.position?`^.{${t.position}}${r}`:r);t.pattern=a,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(a)}),e._zod.check=r=>{r.value.includes(t.includes,t.position)||r.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:r.value,inst:e,continue:!t.abort})}}),e9=r("$ZodCheckStartsWith",(e,t)=>{eD.init(e,t);let r=RegExp(`^${T(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(r)}),e._zod.check=r=>{r.value.startsWith(t.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),e6=r("$ZodCheckEndsWith",(e,t)=>{eD.init(e,t);let r=RegExp(`.*${T(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(r)}),e._zod.check=r=>{r.value.endsWith(t.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}});function e5(e,t,r){e.issues.length&&t.issues.push(...R(r,e.issues))}let e3=r("$ZodCheckProperty",(e,t)=>{eD.init(e,t),e._zod.check=e=>{let r=t.schema._zod.run({value:e.value[t.property],issues:[]},{});if(r instanceof Promise)return r.then(r=>e5(r,e,t.property));e5(r,e,t.property)}}),e8=r("$ZodCheckMimeType",(e,t)=>{eD.init(e,t);let r=new Set(t.mime);e._zod.onattach.push(e=>{e._zod.bag.mime=t.mime}),e._zod.check=a=>{r.has(a.value.type)||a.issues.push({code:"invalid_value",values:t.mime,input:a.value.type,inst:e,continue:!t.abort})}}),e7=r("$ZodCheckOverwrite",(e,t)=>{eD.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});e.s(["$ZodCheck",0,eD,"$ZodCheckBigIntFormat",0,eJ,"$ZodCheckEndsWith",0,e6,"$ZodCheckGreaterThan",0,eF,"$ZodCheckIncludes",0,e2,"$ZodCheckLengthEquals",0,eQ,"$ZodCheckLessThan",0,eB,"$ZodCheckLowerCase",0,e1,"$ZodCheckMaxLength",0,eK,"$ZodCheckMaxSize",0,eG,"$ZodCheckMimeType",0,e8,"$ZodCheckMinLength",0,eY,"$ZodCheckMinSize",0,eW,"$ZodCheckMultipleOf",0,eH,"$ZodCheckNumberFormat",0,eq,"$ZodCheckOverwrite",0,e7,"$ZodCheckProperty",0,e3,"$ZodCheckRegex",0,e0,"$ZodCheckSizeEquals",0,eV,"$ZodCheckStartsWith",0,e9,"$ZodCheckStringFormat",0,eX,"$ZodCheckUpperCase",0,e4],236608);class te{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if("function"==typeof e){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let t=e.split("\n").filter(e=>e),r=Math.min(...t.map(e=>e.length-e.trimStart().length));for(let e of t.map(e=>e.slice(r)).map(e=>" ".repeat(2*this.indent)+e))this.content.push(e)}compile(){return Function(...this?.args,[...(this?.content??[""]).map(e=>` ${e}`)].join("\n"))}}e.s(["Doc",0,te],173911);let tt=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,u,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},tr=r("$ZodError",tt),ta=r("$ZodError",tt,{Parent:Error});function tn(e){let t=[];for(let r of e.map(e=>"object"==typeof e?e.key:e))"number"==typeof r?t.push(`[${r}]`):"symbol"==typeof r?t.push(`[${JSON.stringify(String(r))}]`):/[^\w$]/.test(r)?t.push(`[${JSON.stringify(r)}]`):(t.length&&t.push("."),t.push(r));return t.join("")}e.s(["$ZodError",0,tr,"$ZodRealError",0,ta,"flattenError",0,function(e,t=e=>e.message){let r={},a=[];for(let n of e.issues)n.path.length>0?(r[n.path[0]]=r[n.path[0]]||[],r[n.path[0]].push(t(n))):a.push(t(n));return{formErrors:a,fieldErrors:r}},"formatError",0,function(e,t=e=>e.message){let r={_errors:[]},a=(e,n=[])=>{for(let i of e.issues)if("invalid_union"===i.code&&i.errors.length)i.errors.map(e=>a({issues:e},[...n,...i.path]));else if("invalid_key"===i.code)a({issues:i.issues},[...n,...i.path]);else if("invalid_element"===i.code)a({issues:i.issues},[...n,...i.path]);else{let e=[...n,...i.path];if(0===e.length)r._errors.push(t(i));else{let a=r,n=0;for(;n(e.path??[]).length-(t.path??[]).length))t.push(`✖ ${r.message}`),r.path?.length&&t.push(` → at ${tn(r.path)}`);return t.join("\n")},"toDotPath",0,tn,"treeifyError",0,function(e,t=e=>e.message){let r={errors:[]},a=(e,n=[])=>{var i,s;for(let o of e.issues)if("invalid_union"===o.code&&o.errors.length)o.errors.map(e=>a({issues:e},[...n,...o.path]));else if("invalid_key"===o.code)a({issues:o.issues},[...n,...o.path]);else if("invalid_element"===o.code)a({issues:o.issues},[...n,...o.path]);else{let e=[...n,...o.path];if(0===e.length){r.errors.push(t(o));continue}let a=r,l=0;for(;l(t,r,a,i)=>{let s=a?{...a,async:!1}:{async:!1},l=t._zod.run({value:r,issues:[]},s);if(l instanceof Promise)throw new n;if(l.issues.length){let t=new(i?.Err??e)(l.issues.map(e=>L(e,s,o())));throw b(t,i?.callee),t}return l.value},ts=ti(ta),to=e=>async(t,r,a,n)=>{let i=a?{...a,async:!0}:{async:!0},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise&&(s=await s),s.issues.length){let t=new(n?.Err??e)(s.issues.map(e=>L(e,i,o())));throw b(t,n?.callee),t}return s.value},tl=to(ta),tu=e=>(t,r,a)=>{let i=a?{...a,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise)throw new n;return s.issues.length?{success:!1,error:new(e??tr)(s.issues.map(e=>L(e,i,o())))}:{success:!0,data:s.value}},td=tu(ta),tc=e=>async(t,r,a)=>{let n=a?{...a,async:!0}:{async:!0},i=t._zod.run({value:r,issues:[]},n);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new e(i.issues.map(e=>L(e,n,o())))}:{success:!0,data:i.value}},th=tc(ta),tp=e=>(t,r,a)=>{let n=a?{...a,direction:"backward"}:{direction:"backward"};return ti(e)(t,r,n)},tf=tp(ta),tm=e=>(t,r,a)=>ti(e)(t,r,a),tg=tm(ta),t_=e=>async(t,r,a)=>{let n=a?{...a,direction:"backward"}:{direction:"backward"};return to(e)(t,r,n)},ty=t_(ta),tv=e=>async(t,r,a)=>to(e)(t,r,a),tb=tv(ta),tw=e=>(t,r,a)=>{let n=a?{...a,direction:"backward"}:{direction:"backward"};return tu(e)(t,r,n)},tk=tw(ta),tx=e=>(t,r,a)=>tu(e)(t,r,a),tS=tx(ta),t$=e=>async(t,r,a)=>{let n=a?{...a,direction:"backward"}:{direction:"backward"};return tc(e)(t,r,n)},tE=t$(ta),tT=e=>async(t,r,a)=>tc(e)(t,r,a),tA=tT(ta);e.s(["_decode",0,tm,"_decodeAsync",0,tv,"_encode",0,tp,"_encodeAsync",0,t_,"_parse",0,ti,"_parseAsync",0,to,"_safeDecode",0,tx,"_safeDecodeAsync",0,tT,"_safeEncode",0,tw,"_safeEncodeAsync",0,t$,"_safeParse",0,tu,"_safeParseAsync",0,tc,"decode",0,tg,"decodeAsync",0,tb,"encode",0,tf,"encodeAsync",0,ty,"parse",0,ts,"parseAsync",0,tl,"safeDecode",0,tS,"safeDecodeAsync",0,tA,"safeEncode",0,tk,"safeEncodeAsync",0,tE,"safeParse",0,td,"safeParseAsync",0,th],715143);let tC={major:4,minor:4,patch:2};e.s(["version",0,tC],622824);let tO=r("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=tC;let a=[...e._zod.def.checks??[]];for(let t of(e._zod.traits.has("$ZodCheck")&&a.unshift(e),a))for(let r of t._zod.onattach)r(e);if(0===a.length)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(e,t,r)=>{let a,i=z(e);for(let s of t){if(s._zod.def.when){if(N(e)||!s._zod.def.when(e))continue}else if(i)continue;let t=e.issues.length,o=s._zod.check(e);if(o instanceof Promise&&r?.async===!1)throw new n;if(a||o instanceof Promise)a=(a??Promise.resolve()).then(async()=>{await o,e.issues.length!==t&&(i||(i=z(e,t)))});else{if(e.issues.length===t)continue;i||(i=z(e,t))}}return a?a.then(()=>e):e},r=(r,i,s)=>{if(z(r))return r.aborted=!0,r;let o=t(i,a,s);if(o instanceof Promise){if(!1===s.async)throw new n;return o.then(t=>e._zod.parse(t,s))}return e._zod.parse(o,s)};e._zod.run=(i,s)=>{if(s.skipChecks)return e._zod.parse(i,s);if("backward"===s.direction){let t=e._zod.parse({value:i.value,issues:[]},{...s,skipChecks:!0});return t instanceof Promise?t.then(e=>r(e,i,s)):r(t,i,s)}let o=e._zod.parse(i,s);if(o instanceof Promise){if(!1===s.async)throw new n;return o.then(e=>t(e,a,s))}return t(o,a,s)}}m(e,"~standard",()=>({validate:t=>{try{let r=td(e,t);return r.success?{value:r.data}:{issues:r.error?.issues}}catch(r){return th(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:"zod",version:1}))}),tI=r("$ZodString",(e,t)=>{tO.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??ev(e._zod.bag),e._zod.parse=(r,a)=>{if(t.coerce)try{r.value=String(r.value)}catch(e){}return"string"==typeof r.value||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),tj=r("$ZodStringFormat",(e,t)=>{eX.init(e,t),tI.init(e,t)}),tP=r("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Y),tj.init(e,t)}),tz=r("$ZodUUID",(e,t)=>{if(t.version){let e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(void 0===e)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=Q(e))}else t.pattern??(t.pattern=Q());tj.init(e,t)}),tN=r("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=er),tj.init(e,t)}),tR=r("$ZodURL",(e,t)=>{tj.init(e,t),e._zod.check=r=>{try{let a=r.value.trim();if(!t.normalize&&t.protocol?.source===eh.source&&!/^https?:\/\//i.test(a))return void r.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:r.value,inst:e,continue:!t.abort});let n=new URL(a);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(n.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:r.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(n.protocol.endsWith(":")?n.protocol.slice(0,-1):n.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})),t.normalize?r.value=n.href:r.value=a;return}catch(a){r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),tM=r("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=en()),tj.init(e,t)}),tL=r("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=V),tj.init(e,t)}),tZ=r("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=H),tj.init(e,t)}),tD=r("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=q),tj.init(e,t)}),tU=r("$ZodULID",(e,t)=>{t.pattern??(t.pattern=J),tj.init(e,t)}),tB=r("$ZodXID",(e,t)=>{t.pattern??(t.pattern=G),tj.init(e,t)}),tF=r("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=W),tj.init(e,t)}),tH=r("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=ey(t)),tj.init(e,t)}),tq=r("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=em),tj.init(e,t)}),tJ=r("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=e_(t)),tj.init(e,t)}),tG=r("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=K),tj.init(e,t)}),tW=r("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=ei),tj.init(e,t),e._zod.bag.format="ipv4"}),tV=r("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=es),tj.init(e,t),e._zod.bag.format="ipv6",e._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}}),tK=r("$ZodMAC",(e,t)=>{t.pattern??(t.pattern=eo(t.delimiter)),tj.init(e,t),e._zod.bag.format="mac"}),tY=r("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=el),tj.init(e,t)}),tQ=r("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=eu),tj.init(e,t),e._zod.check=r=>{let a=r.value.split("/");try{if(2!==a.length)throw Error();let[e,t]=a;if(!t)throw Error();let r=Number(t);if(`${r}`!==t||r<0||r>128)throw Error();new URL(`http://[${e}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function tX(e){if(""===e)return!0;if(/\s/.test(e)||e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}let t0=r("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=ed),tj.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=r=>{tX(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function t1(e){if(!ec.test(e))return!1;let t=e.replace(/[-_]/g,e=>"-"===e?"+":"/");return tX(t.padEnd(4*Math.ceil(t.length/4),"="))}let t4=r("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=ec),tj.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=r=>{t1(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),t2=r("$ZodE164",(e,t)=>{t.pattern??(t.pattern=ep),tj.init(e,t)});function t9(e,t=null){try{let r=e.split(".");if(3!==r.length)return!1;let[a]=r;if(!a)return!1;let n=JSON.parse(atob(a));if("typ"in n&&n?.typ!=="JWT"||!n.alg||t&&(!("alg"in n)||n.alg!==t))return!1;return!0}catch{return!1}}let t6=r("$ZodJWT",(e,t)=>{tj.init(e,t),e._zod.check=r=>{t9(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),t5=r("$ZodCustomStringFormat",(e,t)=>{tj.init(e,t),e._zod.check=r=>{t.fn(r.value)||r.issues.push({code:"invalid_format",format:t.format,input:r.value,inst:e,continue:!t.abort})}}),t3=r("$ZodNumber",(e,t)=>{tO.init(e,t),e._zod.pattern=e._zod.bag.pattern??ek,e._zod.parse=(r,a)=>{if(t.coerce)try{r.value=Number(r.value)}catch(e){}let n=r.value;if("number"==typeof n&&!Number.isNaN(n)&&Number.isFinite(n))return r;let i="number"==typeof n?Number.isNaN(n)?"NaN":Number.isFinite(n)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:n,inst:e,...i?{received:i}:{}}),r}}),t8=r("$ZodNumberFormat",(e,t)=>{eq.init(e,t),t3.init(e,t)}),t7=r("$ZodBoolean",(e,t)=>{tO.init(e,t),e._zod.pattern=ex,e._zod.parse=(r,a)=>{if(t.coerce)try{r.value=!!r.value}catch(e){}let n=r.value;return"boolean"==typeof n||r.issues.push({expected:"boolean",code:"invalid_type",input:n,inst:e}),r}}),re=r("$ZodBigInt",(e,t)=>{tO.init(e,t),e._zod.pattern=eb,e._zod.parse=(r,a)=>{if(t.coerce)try{r.value=BigInt(r.value)}catch(e){}return"bigint"==typeof r.value||r.issues.push({expected:"bigint",code:"invalid_type",input:r.value,inst:e}),r}}),rt=r("$ZodBigIntFormat",(e,t)=>{eJ.init(e,t),re.init(e,t)}),rr=r("$ZodSymbol",(e,t)=>{tO.init(e,t),e._zod.parse=(t,r)=>{let a=t.value;return"symbol"==typeof a||t.issues.push({expected:"symbol",code:"invalid_type",input:a,inst:e}),t}}),ra=r("$ZodUndefined",(e,t)=>{tO.init(e,t),e._zod.pattern=e$,e._zod.values=new Set([void 0]),e._zod.parse=(t,r)=>{let a=t.value;return void 0===a||t.issues.push({expected:"undefined",code:"invalid_type",input:a,inst:e}),t}}),rn=r("$ZodNull",(e,t)=>{tO.init(e,t),e._zod.pattern=eS,e._zod.values=new Set([null]),e._zod.parse=(t,r)=>{let a=t.value;return null===a||t.issues.push({expected:"null",code:"invalid_type",input:a,inst:e}),t}}),ri=r("$ZodAny",(e,t)=>{tO.init(e,t),e._zod.parse=e=>e}),rs=r("$ZodUnknown",(e,t)=>{tO.init(e,t),e._zod.parse=e=>e}),ro=r("$ZodNever",(e,t)=>{tO.init(e,t),e._zod.parse=(t,r)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e}),t)}),rl=r("$ZodVoid",(e,t)=>{tO.init(e,t),e._zod.parse=(t,r)=>{let a=t.value;return void 0===a||t.issues.push({expected:"void",code:"invalid_type",input:a,inst:e}),t}}),ru=r("$ZodDate",(e,t)=>{tO.init(e,t),e._zod.parse=(r,a)=>{if(t.coerce)try{r.value=new Date(r.value)}catch(e){}let n=r.value,i=n instanceof Date;return i&&!Number.isNaN(n.getTime())||r.issues.push({expected:"date",code:"invalid_type",input:n,...i?{received:"Invalid Date"}:{},inst:e}),r}});function rd(e,t,r){e.issues.length&&t.issues.push(...R(r,e.issues)),t.value[r]=e.value}let rc=r("$ZodArray",(e,t)=>{tO.init(e,t),e._zod.parse=(r,a)=>{let n=r.value;if(!Array.isArray(n))return r.issues.push({expected:"array",code:"invalid_type",input:n,inst:e}),r;r.value=Array(n.length);let i=[];for(let e=0;erd(t,r,e))):rd(o,r,e)}return i.length?Promise.all(i).then(()=>r):r}});function rh(e,t,r,a,n,i){let s=r in a;if(e.issues.length){if(n&&i&&!s)return;t.issues.push(...R(r,e.issues))}if(!s&&!n){e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[r]});return}void 0===e.value?s&&(t.value[r]=void 0):t.value[r]=e.value}function rp(e){let t=Object.keys(e.shape);for(let r of t)if(!e.shape?.[r]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${r}": expected a Zod schema`);let r=I(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function rf(e,t,r,a,n,i){let s=[],o=n.keySet,l=n.catchall._zod,u=l.def.type,d="optional"===l.optin,c="optional"===l.optout;for(let n in t){if("__proto__"===n||o.has(n))continue;if("never"===u){s.push(n);continue}let i=l.run({value:t[n],issues:[]},a);i instanceof Promise?e.push(i.then(e=>rh(e,r,n,t,d,c))):rh(i,r,n,t,d,c)}return(s.length&&r.issues.push({code:"unrecognized_keys",keys:s,input:t,inst:i}),e.length)?Promise.all(e).then(()=>r):r}let rm=r("$ZodObject",(e,t)=>{let r;tO.init(e,t);let a=Object.getOwnPropertyDescriptor(t,"shape");if(!a?.get){let e=t.shape;Object.defineProperty(t,"shape",{get:()=>{let r={...e};return Object.defineProperty(t,"shape",{value:r}),r}})}let n=d(()=>rp(t));m(e._zod,"propValues",()=>{let e=t.shape,r={};for(let t in e){let a=e[t]._zod;if(a.values)for(let e of(r[t]??(r[t]=new Set),a.values))r[t].add(e)}return r});let i=t.catchall;e._zod.parse=(t,a)=>{r??(r=n.value);let s=t.value;if(!w(s))return t.issues.push({expected:"object",code:"invalid_type",input:s,inst:e}),t;t.value={};let o=[],l=r.shape;for(let e of r.keys){let r=l[e],n="optional"===r._zod.optin,i="optional"===r._zod.optout,u=r._zod.run({value:s[e],issues:[]},a);u instanceof Promise?o.push(u.then(r=>rh(r,t,e,s,n,i))):rh(u,t,e,s,n,i)}return i?rf(o,s,t,a,n.value,e):o.length?Promise.all(o).then(()=>t):t}}),rg=r("$ZodObjectJIT",(e,t)=>{let r,a;rm.init(e,t);let n=e._zod.parse,i=d(()=>rp(t)),o=!s.jitless,l=o&&k.value,u=t.catchall;e._zod.parse=(s,d)=>{a??(a=i.value);let c=s.value;return w(c)?o&&l&&d?.async===!1&&!0!==d.jitless?(r||(r=(e=>{let t=new te(["shape","payload","ctx"]),r=i.value,a=e=>{let t=y(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write("const input = payload.value;");let n=Object.create(null),s=0;for(let e of r.keys)n[e]=`key_${s++}`;for(let i of(t.write("const newResult = {};"),r.keys)){let r=n[i],s=y(i),o=e[i],l=o?._zod?.optin==="optional",u=o?._zod?.optout==="optional";t.write(`const ${r} = ${a(i)};`),l&&u?t.write(` if (${r}.issues.length) { if (${s} in input) { payload.issues = payload.issues.concat(${r}.issues.map(iss => ({ ...iss, path: iss.path ? [${s}, ...iss.path] : [${s}] }))); } } if (${r}.value === undefined) { if (${s} in input) { newResult[${s}] = undefined; } } else { newResult[${s}] = ${r}.value; } `):l?t.write(` if (${r}.issues.length) { payload.issues = payload.issues.concat(${r}.issues.map(iss => ({ ...iss, path: iss.path ? [${s}, ...iss.path] : [${s}] }))); } if (${r}.value === undefined) { if (${s} in input) { newResult[${s}] = undefined; } } else { newResult[${s}] = ${r}.value; } `):t.write(` const ${r}_present = ${s} in input; if (${r}.issues.length) { payload.issues = payload.issues.concat(${r}.issues.map(iss => ({ ...iss, path: iss.path ? [${s}, ...iss.path] : [${s}] }))); } if (!${r}_present && !${r}.issues.length) { payload.issues.push({ code: "invalid_type", expected: "nonoptional", input: undefined, path: [${s}] }); } if (${r}_present) { if (${r}.value === undefined) { newResult[${s}] = undefined; } else { newResult[${s}] = ${r}.value; } } `)}t.write("payload.value = newResult;"),t.write("return payload;");let o=t.compile();return(t,r)=>o(e,t,r)})(t.shape)),s=r(s,d),u)?rf([],c,s,d,a,e):s:n(s,d):(s.issues.push({expected:"object",code:"invalid_type",input:c,inst:e}),s)}});function r_(e,t,r,a){for(let r of e)if(0===r.issues.length)return t.value=r.value,t;let n=e.filter(e=>!z(e));return 1===n.length?(t.value=n[0].value,n[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(e=>e.issues.map(e=>L(e,a,o())))}),t)}let ry=r("$ZodUnion",(e,t)=>{tO.init(e,t),m(e._zod,"optin",()=>t.options.some(e=>"optional"===e._zod.optin)?"optional":void 0),m(e._zod,"optout",()=>t.options.some(e=>"optional"===e._zod.optout)?"optional":void 0),m(e._zod,"values",()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),m(e._zod,"pattern",()=>{if(t.options.every(e=>e._zod.pattern)){let e=t.options.map(e=>e._zod.pattern);return RegExp(`^(${e.map(e=>h(e.source)).join("|")})$`)}});let r=1===t.options.length?t.options[0]._zod.run:null;e._zod.parse=(a,n)=>{if(r)return r(a,n);let i=!1,s=[];for(let e of t.options){let t=e._zod.run({value:a.value,issues:[]},n);if(t instanceof Promise)s.push(t),i=!0;else{if(0===t.issues.length)return t;s.push(t)}}return i?Promise.all(s).then(t=>r_(t,a,e,n)):r_(s,a,e,n)}});function rv(e,t,r,a){let n=e.filter(e=>0===e.issues.length);return 1===n.length?t.value=n[0].value:0===n.length?t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(e=>e.issues.map(e=>L(e,a,o())))}):t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:[],inclusive:!1}),t}let rb=r("$ZodXor",(e,t)=>{ry.init(e,t),t.inclusive=!1;let r=1===t.options.length?t.options[0]._zod.run:null;e._zod.parse=(a,n)=>{if(r)return r(a,n);let i=!1,s=[];for(let e of t.options){let t=e._zod.run({value:a.value,issues:[]},n);t instanceof Promise?(s.push(t),i=!0):s.push(t)}return i?Promise.all(s).then(t=>rv(t,a,e,n)):rv(s,a,e,n)}}),rw=r("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,ry.init(e,t);let r=e._zod.parse;m(e._zod,"propValues",()=>{let e={};for(let r of t.options){let a=r._zod.propValues;if(!a||0===Object.keys(a).length)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(r)}"`);for(let[t,r]of Object.entries(a))for(let a of(e[t]||(e[t]=new Set),r))e[t].add(a)}return e});let a=d(()=>{let e=t.options,r=new Map;for(let a of e){let e=a._zod.propValues?.[t.discriminator];if(!e||0===e.size)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(a)}"`);for(let t of e){if(r.has(t))throw Error(`Duplicate discriminator value "${String(t)}"`);r.set(t,a)}}return r});e._zod.parse=(n,i)=>{let s=n.value;if(!w(s))return n.issues.push({code:"invalid_type",expected:"object",input:s,inst:e}),n;let o=a.value.get(s?.[t.discriminator]);return o?o._zod.run(n,i):t.unionFallback||"backward"===i.direction?r(n,i):(n.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,options:Array.from(a.value.keys()),input:s,path:[t.discriminator],inst:e}),n)}}),rk=r("$ZodIntersection",(e,t)=>{tO.init(e,t),e._zod.parse=(e,r)=>{let a=e.value,n=t.left._zod.run({value:a,issues:[]},r),i=t.right._zod.run({value:a,issues:[]},r);return n instanceof Promise||i instanceof Promise?Promise.all([n,i]).then(([t,r])=>rx(e,t,r)):rx(e,n,i)}});function rx(e,t,r){let a,n=new Map;for(let r of t.issues)if("unrecognized_keys"===r.code)for(let e of(a??(a=r),r.keys))n.has(e)||n.set(e,{}),n.get(e).l=!0;else e.issues.push(r);for(let t of r.issues)if("unrecognized_keys"===t.code)for(let e of t.keys)n.has(e)||n.set(e,{}),n.get(e).r=!0;else e.issues.push(t);let i=[...n].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(i.length&&a&&e.issues.push({...a,keys:i}),z(e))return e;let s=function e(t,r){if(t===r||t instanceof Date&&r instanceof Date&&+t==+r)return{valid:!0,data:t};if(x(t)&&x(r)){let a=Object.keys(r),n=Object.keys(t).filter(e=>-1!==a.indexOf(e)),i={...t,...r};for(let a of n){let n=e(t[a],r[a]);if(!n.valid)return{valid:!1,mergeErrorPath:[a,...n.mergeErrorPath]};i[a]=n.data}return{valid:!0,data:i}}if(Array.isArray(t)&&Array.isArray(r)){if(t.length!==r.length)return{valid:!1,mergeErrorPath:[]};let a=[];for(let n=0;n{tO.init(e,t);let r=t.items;e._zod.parse=(a,n)=>{let i=a.value;if(!Array.isArray(i))return a.issues.push({input:i,inst:e,expected:"tuple",code:"invalid_type"}),a;a.value=[];let s=[],o=r$(r,"optin"),l=r$(r,"optout");if(!t.rest){if(i.lengthr.length&&a.issues.push({code:"too_big",maximum:r.length,inclusive:!0,input:i,inst:e,origin:"array"})}let u=Array(r.length);for(let e=0;e{u[e]=t})):u[e]=t}if(t.rest){let e=r.length-1;for(let o of i.slice(r.length)){e++;let r=t.rest._zod.run({value:o,issues:[]},n);r instanceof Promise?s.push(r.then(t=>rE(t,a,e))):rE(r,a,e)}}return s.length?Promise.all(s).then(()=>rT(u,a,r,i,l)):rT(u,a,r,i,l)}});function r$(e,t){for(let r=e.length-1;r>=0;r--)if("optional"!==e[r]._zod[t])return r+1;return 0}function rE(e,t,r){e.issues.length&&t.issues.push(...R(r,e.issues)),t.value[r]=e.value}function rT(e,t,r,a,n){for(let i=0;i=n){t.value.length=i;break}t.issues.push(...R(i,r.issues))}t.value[i]=r.value}for(let e=t.value.length-1;e>=a.length;e--)if("optional"===r[e]._zod.optout&&void 0===t.value[e])t.value.length=e;else break;return t}let rA=r("$ZodRecord",(e,t)=>{tO.init(e,t),e._zod.parse=(r,a)=>{let n=r.value;if(!x(n))return r.issues.push({expected:"record",code:"invalid_type",input:n,inst:e}),r;let i=[],s=t.keyType._zod.values;if(s){let l;r.value={};let u=new Set;for(let l of s)if("string"==typeof l||"number"==typeof l||"symbol"==typeof l){u.add("number"==typeof l?l.toString():l);let s=t.keyType._zod.run({value:l,issues:[]},a);if(s instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(s.issues.length){r.issues.push({code:"invalid_key",origin:"record",issues:s.issues.map(e=>L(e,a,o())),input:l,path:[l],inst:e});continue}let d=s.value,c=t.valueType._zod.run({value:n[l],issues:[]},a);c instanceof Promise?i.push(c.then(e=>{e.issues.length&&r.issues.push(...R(l,e.issues)),r.value[d]=e.value})):(c.issues.length&&r.issues.push(...R(l,c.issues)),r.value[d]=c.value)}for(let e in n)u.has(e)||(l=l??[]).push(e);l&&l.length>0&&r.issues.push({code:"unrecognized_keys",input:n,inst:e,keys:l})}else for(let s of(r.value={},Reflect.ownKeys(n))){if("__proto__"===s||!Object.prototype.propertyIsEnumerable.call(n,s))continue;let l=t.keyType._zod.run({value:s,issues:[]},a);if(l instanceof Promise)throw Error("Async schemas not supported in object keys currently");if("string"==typeof s&&ek.test(s)&&l.issues.length){let e=t.keyType._zod.run({value:Number(s),issues:[]},a);if(e instanceof Promise)throw Error("Async schemas not supported in object keys currently");0===e.issues.length&&(l=e)}if(l.issues.length){"loose"===t.mode?r.value[s]=n[s]:r.issues.push({code:"invalid_key",origin:"record",issues:l.issues.map(e=>L(e,a,o())),input:s,path:[s],inst:e});continue}let u=t.valueType._zod.run({value:n[s],issues:[]},a);u instanceof Promise?i.push(u.then(e=>{e.issues.length&&r.issues.push(...R(s,e.issues)),r.value[l.value]=e.value})):(u.issues.length&&r.issues.push(...R(s,u.issues)),r.value[l.value]=u.value)}return i.length?Promise.all(i).then(()=>r):r}}),rC=r("$ZodMap",(e,t)=>{tO.init(e,t),e._zod.parse=(r,a)=>{let n=r.value;if(!(n instanceof Map))return r.issues.push({expected:"map",code:"invalid_type",input:n,inst:e}),r;let i=[];for(let[s,o]of(r.value=new Map,n)){let l=t.keyType._zod.run({value:s,issues:[]},a),u=t.valueType._zod.run({value:o,issues:[]},a);l instanceof Promise||u instanceof Promise?i.push(Promise.all([l,u]).then(([t,i])=>{rO(t,i,r,s,n,e,a)})):rO(l,u,r,s,n,e,a)}return i.length?Promise.all(i).then(()=>r):r}});function rO(e,t,r,a,n,i,s){e.issues.length&&($.has(typeof a)?r.issues.push(...R(a,e.issues)):r.issues.push({code:"invalid_key",origin:"map",input:n,inst:i,issues:e.issues.map(e=>L(e,s,o()))})),t.issues.length&&($.has(typeof a)?r.issues.push(...R(a,t.issues)):r.issues.push({origin:"map",code:"invalid_element",input:n,inst:i,key:a,issues:t.issues.map(e=>L(e,s,o()))})),r.value.set(e.value,t.value)}let rI=r("$ZodSet",(e,t)=>{tO.init(e,t),e._zod.parse=(r,a)=>{let n=r.value;if(!(n instanceof Set))return r.issues.push({input:n,inst:e,expected:"set",code:"invalid_type"}),r;let i=[];for(let e of(r.value=new Set,n)){let n=t.valueType._zod.run({value:e,issues:[]},a);n instanceof Promise?i.push(n.then(e=>rj(e,r))):rj(n,r)}return i.length?Promise.all(i).then(()=>r):r}});function rj(e,t){e.issues.length&&t.issues.push(...e.issues),t.value.add(e.value)}let rP=r("$ZodEnum",(e,t)=>{tO.init(e,t);let r=l(t.entries),a=new Set(r);e._zod.values=a,e._zod.pattern=RegExp(`^(${r.filter(e=>$.has(typeof e)).map(e=>"string"==typeof e?T(e):e.toString()).join("|")})$`),e._zod.parse=(t,n)=>{let i=t.value;return a.has(i)||t.issues.push({code:"invalid_value",values:r,input:i,inst:e}),t}}),rz=r("$ZodLiteral",(e,t)=>{if(tO.init(e,t),0===t.values.length)throw Error("Cannot create literal schema with no valid values");let r=new Set(t.values);e._zod.values=r,e._zod.pattern=RegExp(`^(${t.values.map(e=>"string"==typeof e?T(e):e?T(e.toString()):String(e)).join("|")})$`),e._zod.parse=(a,n)=>{let i=a.value;return r.has(i)||a.issues.push({code:"invalid_value",values:t.values,input:i,inst:e}),a}}),rN=r("$ZodFile",(e,t)=>{tO.init(e,t),e._zod.parse=(t,r)=>{let a=t.value;return a instanceof File||t.issues.push({expected:"file",code:"invalid_type",input:a,inst:e}),t}}),rR=r("$ZodTransform",(e,t)=>{tO.init(e,t),e._zod.parse=(r,a)=>{if("backward"===a.direction)throw new i(e.constructor.name);let s=t.transform(r.value,r);if(a.async)return(s instanceof Promise?s:Promise.resolve(s)).then(e=>(r.value=e,r));if(s instanceof Promise)throw new n;return r.value=s,r}});function rM(e,t){return e.issues.length&&void 0===t?{issues:[],value:void 0}:e}let rL=r("$ZodOptional",(e,t)=>{tO.init(e,t),e._zod.optin="optional",e._zod.optout="optional",m(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),m(e._zod,"pattern",()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${h(e.source)})?$`):void 0}),e._zod.parse=(e,r)=>{if("optional"===t.innerType._zod.optin){let a=t.innerType._zod.run(e,r);return a instanceof Promise?a.then(t=>rM(t,e.value)):rM(a,e.value)}return void 0===e.value?e:t.innerType._zod.run(e,r)}}),rZ=r("$ZodExactOptional",(e,t)=>{rL.init(e,t),m(e._zod,"values",()=>t.innerType._zod.values),m(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(e,r)=>t.innerType._zod.run(e,r)}),rD=r("$ZodNullable",(e,t)=>{tO.init(e,t),m(e._zod,"optin",()=>t.innerType._zod.optin),m(e._zod,"optout",()=>t.innerType._zod.optout),m(e._zod,"pattern",()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${h(e.source)}|null)$`):void 0}),m(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,r)=>null===e.value?e:t.innerType._zod.run(e,r)}),rU=r("$ZodDefault",(e,t)=>{tO.init(e,t),e._zod.optin="optional",m(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,r)=>{if("backward"===r.direction)return t.innerType._zod.run(e,r);if(void 0===e.value)return e.value=t.defaultValue,e;let a=t.innerType._zod.run(e,r);return a instanceof Promise?a.then(e=>rB(e,t)):rB(a,t)}});function rB(e,t){return void 0===e.value&&(e.value=t.defaultValue),e}let rF=r("$ZodPrefault",(e,t)=>{tO.init(e,t),e._zod.optin="optional",m(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,r)=>("backward"===r.direction||void 0===e.value&&(e.value=t.defaultValue),t.innerType._zod.run(e,r))}),rH=r("$ZodNonOptional",(e,t)=>{tO.init(e,t),m(e._zod,"values",()=>{let e=t.innerType._zod.values;return e?new Set([...e].filter(e=>void 0!==e)):void 0}),e._zod.parse=(r,a)=>{let n=t.innerType._zod.run(r,a);return n instanceof Promise?n.then(t=>rq(t,e)):rq(n,e)}});function rq(e,t){return e.issues.length||void 0!==e.value||e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}let rJ=r("$ZodSuccess",(e,t)=>{tO.init(e,t),e._zod.parse=(e,r)=>{if("backward"===r.direction)throw new i("ZodSuccess");let a=t.innerType._zod.run(e,r);return a instanceof Promise?a.then(t=>(e.value=0===t.issues.length,e)):(e.value=0===a.issues.length,e)}}),rG=r("$ZodCatch",(e,t)=>{tO.init(e,t),m(e._zod,"optin",()=>t.innerType._zod.optin),m(e._zod,"optout",()=>t.innerType._zod.optout),m(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,r)=>{if("backward"===r.direction)return t.innerType._zod.run(e,r);let a=t.innerType._zod.run(e,r);return a instanceof Promise?a.then(a=>(e.value=a.value,a.issues.length&&(e.value=t.catchValue({...e,error:{issues:a.issues.map(e=>L(e,r,o()))},input:e.value}),e.issues=[]),e)):(e.value=a.value,a.issues.length&&(e.value=t.catchValue({...e,error:{issues:a.issues.map(e=>L(e,r,o()))},input:e.value}),e.issues=[]),e)}}),rW=r("$ZodNaN",(e,t)=>{tO.init(e,t),e._zod.parse=(t,r)=>("number"==typeof t.value&&Number.isNaN(t.value)||t.issues.push({input:t.value,inst:e,expected:"nan",code:"invalid_type"}),t)}),rV=r("$ZodPipe",(e,t)=>{tO.init(e,t),m(e._zod,"values",()=>t.in._zod.values),m(e._zod,"optin",()=>t.in._zod.optin),m(e._zod,"optout",()=>t.out._zod.optout),m(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(e,r)=>{if("backward"===r.direction){let a=t.out._zod.run(e,r);return a instanceof Promise?a.then(e=>rK(e,t.in,r)):rK(a,t.in,r)}let a=t.in._zod.run(e,r);return a instanceof Promise?a.then(e=>rK(e,t.out,r)):rK(a,t.out,r)}});function rK(e,t,r){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},r)}let rY=r("$ZodCodec",(e,t)=>{tO.init(e,t),m(e._zod,"values",()=>t.in._zod.values),m(e._zod,"optin",()=>t.in._zod.optin),m(e._zod,"optout",()=>t.out._zod.optout),m(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(e,r)=>{if("forward"===(r.direction||"forward")){let a=t.in._zod.run(e,r);return a instanceof Promise?a.then(e=>rQ(e,t,r)):rQ(a,t,r)}{let a=t.out._zod.run(e,r);return a instanceof Promise?a.then(e=>rQ(e,t,r)):rQ(a,t,r)}}});function rQ(e,t,r){if(e.issues.length)return e.aborted=!0,e;if("forward"===(r.direction||"forward")){let a=t.transform(e.value,e);return a instanceof Promise?a.then(a=>rX(e,a,t.out,r)):rX(e,a,t.out,r)}{let a=t.reverseTransform(e.value,e);return a instanceof Promise?a.then(a=>rX(e,a,t.in,r)):rX(e,a,t.in,r)}}function rX(e,t,r,a){return e.issues.length?(e.aborted=!0,e):r._zod.run({value:t,issues:e.issues},a)}let r0=r("$ZodPreprocess",(e,t)=>{rV.init(e,t),m(e._zod,"optin",()=>t.out._zod.optin),m(e._zod,"optout",()=>t.out._zod.optout)}),r1=r("$ZodReadonly",(e,t)=>{tO.init(e,t),m(e._zod,"propValues",()=>t.innerType._zod.propValues),m(e._zod,"values",()=>t.innerType._zod.values),m(e._zod,"optin",()=>t.innerType?._zod?.optin),m(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(e,r)=>{if("backward"===r.direction)return t.innerType._zod.run(e,r);let a=t.innerType._zod.run(e,r);return a instanceof Promise?a.then(r4):r4(a)}});function r4(e){return e.value=Object.freeze(e.value),e}let r2=r("$ZodTemplateLiteral",(e,t)=>{tO.init(e,t);let r=[];for(let e of t.parts)if("object"==typeof e&&null!==e){if(!e._zod.pattern)throw Error(`Invalid template literal part, no pattern found: ${[...e._zod.traits].shift()}`);let t=e._zod.pattern instanceof RegExp?e._zod.pattern.source:e._zod.pattern;if(!t)throw Error(`Invalid template literal part: ${e._zod.traits}`);let a=+!!t.startsWith("^"),n=t.endsWith("$")?t.length-1:t.length;r.push(t.slice(a,n))}else if(null===e||E.has(typeof e))r.push(T(`${e}`));else throw Error(`Invalid template literal part: ${e}`);e._zod.pattern=RegExp(`^${r.join("")}$`),e._zod.parse=(r,a)=>("string"!=typeof r.value?r.issues.push({input:r.value,inst:e,expected:"string",code:"invalid_type"}):(e._zod.pattern.lastIndex=0,e._zod.pattern.test(r.value)||r.issues.push({input:r.value,inst:e,code:"invalid_format",format:t.format??"template_literal",pattern:e._zod.pattern.source})),r)}),r9=r("$ZodFunction",(e,t)=>(tO.init(e,t),e._def=t,e._zod.def=t,e.implement=t=>{if("function"!=typeof t)throw Error("implement() must be called with a function");return function(...r){let a=Reflect.apply(t,this,e._def.input?ts(e._def.input,r):r);return e._def.output?ts(e._def.output,a):a}},e.implementAsync=t=>{if("function"!=typeof t)throw Error("implementAsync() must be called with a function");return async function(...r){let a=e._def.input?await tl(e._def.input,r):r,n=await Reflect.apply(t,this,a);return e._def.output?await tl(e._def.output,n):n}},e._zod.parse=(t,r)=>("function"!=typeof t.value?t.issues.push({code:"invalid_type",expected:"function",input:t.value,inst:e}):e._def.output&&"promise"===e._def.output._zod.def.type?t.value=e.implementAsync(t.value):t.value=e.implement(t.value),t),e.input=(...t)=>{let r=e.constructor;return new r(Array.isArray(t[0])?{type:"function",input:new rS({type:"tuple",items:t[0],rest:t[1]}),output:e._def.output}:{type:"function",input:t[0],output:e._def.output})},e.output=t=>new e.constructor({type:"function",input:e._def.input,output:t}),e)),r6=r("$ZodPromise",(e,t)=>{tO.init(e,t),e._zod.parse=(e,r)=>Promise.resolve(e.value).then(e=>t.innerType._zod.run({value:e,issues:[]},r))}),r5=r("$ZodLazy",(e,t)=>{tO.init(e,t),m(e._zod,"innerType",()=>(t._cachedInner||(t._cachedInner=t.getter()),t._cachedInner)),m(e._zod,"pattern",()=>e._zod.innerType?._zod?.pattern),m(e._zod,"propValues",()=>e._zod.innerType?._zod?.propValues),m(e._zod,"optin",()=>e._zod.innerType?._zod?.optin??void 0),m(e._zod,"optout",()=>e._zod.innerType?._zod?.optout??void 0),e._zod.parse=(t,r)=>e._zod.innerType._zod.run(t,r)}),r3=r("$ZodCustom",(e,t)=>{eD.init(e,t),tO.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=r=>{let a=r.value,n=t.fn(a);if(n instanceof Promise)return n.then(t=>r8(t,r,a,e));r8(n,r,a,e)}});function r8(e,t,r,a){if(!e){let e={code:"custom",input:r,inst:a,path:[...a._zod.def.path??[]],continue:!a._zod.def.abort};a._zod.def.params&&(e.params=a._zod.def.params),t.issues.push(U(e))}}e.s(["$ZodAny",0,ri,"$ZodArray",0,rc,"$ZodBase64",0,t0,"$ZodBase64URL",0,t4,"$ZodBigInt",0,re,"$ZodBigIntFormat",0,rt,"$ZodBoolean",0,t7,"$ZodCIDRv4",0,tY,"$ZodCIDRv6",0,tQ,"$ZodCUID",0,tZ,"$ZodCUID2",0,tD,"$ZodCatch",0,rG,"$ZodCodec",0,rY,"$ZodCustom",0,r3,"$ZodCustomStringFormat",0,t5,"$ZodDate",0,ru,"$ZodDefault",0,rU,"$ZodDiscriminatedUnion",0,rw,"$ZodE164",0,t2,"$ZodEmail",0,tN,"$ZodEmoji",0,tM,"$ZodEnum",0,rP,"$ZodExactOptional",0,rZ,"$ZodFile",0,rN,"$ZodFunction",0,r9,"$ZodGUID",0,tP,"$ZodIPv4",0,tW,"$ZodIPv6",0,tV,"$ZodISODate",0,tq,"$ZodISODateTime",0,tH,"$ZodISODuration",0,tG,"$ZodISOTime",0,tJ,"$ZodIntersection",0,rk,"$ZodJWT",0,t6,"$ZodKSUID",0,tF,"$ZodLazy",0,r5,"$ZodLiteral",0,rz,"$ZodMAC",0,tK,"$ZodMap",0,rC,"$ZodNaN",0,rW,"$ZodNanoID",0,tL,"$ZodNever",0,ro,"$ZodNonOptional",0,rH,"$ZodNull",0,rn,"$ZodNullable",0,rD,"$ZodNumber",0,t3,"$ZodNumberFormat",0,t8,"$ZodObject",0,rm,"$ZodObjectJIT",0,rg,"$ZodOptional",0,rL,"$ZodPipe",0,rV,"$ZodPrefault",0,rF,"$ZodPreprocess",0,r0,"$ZodPromise",0,r6,"$ZodReadonly",0,r1,"$ZodRecord",0,rA,"$ZodSet",0,rI,"$ZodString",0,tI,"$ZodStringFormat",0,tj,"$ZodSuccess",0,rJ,"$ZodSymbol",0,rr,"$ZodTemplateLiteral",0,r2,"$ZodTransform",0,rR,"$ZodTuple",0,rS,"$ZodType",0,tO,"$ZodULID",0,tU,"$ZodURL",0,tR,"$ZodUUID",0,tz,"$ZodUndefined",0,ra,"$ZodUnion",0,ry,"$ZodUnknown",0,rs,"$ZodVoid",0,rl,"$ZodXID",0,tB,"$ZodXor",0,rb,"isValidBase64",0,tX,"isValidBase64URL",0,t1,"isValidJWT",0,t9],639510);let r7=Symbol("ZodOutput"),ae=Symbol("ZodInput");class at{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let r=t[0];return this._map.set(e,r),r&&"object"==typeof r&&"id"in r&&this._idmap.set(r.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&"object"==typeof t&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let r={...this.get(t)??{}};delete r.id;let a={...r,...this._map.get(e)};return Object.keys(a).length?a:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}function ar(){return new at}(ap=globalThis).__zod_globalRegistry??(ap.__zod_globalRegistry=ar());let aa=globalThis.__zod_globalRegistry;function an(e){return new e({type:"unknown"})}function ai(e,t){return new e({type:"never",...C(t)})}function as(e,t){return new eB({check:"less_than",...C(t),value:e,inclusive:!1})}function ao(e,t){return new eB({check:"less_than",...C(t),value:e,inclusive:!0})}function al(e,t){return new eF({check:"greater_than",...C(t),value:e,inclusive:!1})}function au(e,t){return new eF({check:"greater_than",...C(t),value:e,inclusive:!0})}function ad(e){return new e7({check:"overwrite",tx:e})}function ac(e,t){let r=new eD({check:"custom",...C(t)});return r._zod.check=e,r}e.s(["$ZodRegistry",0,at,"$input",0,ae,"$output",0,r7,"globalRegistry",0,aa,"registry",0,ar],52637),e.s(["TimePrecision",0,{Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6},"_any",0,function(e){return new e({type:"any"})},"_array",0,function(e,t,r){return new e({type:"array",element:t,...C(r)})},"_base64",0,function(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...C(t)})},"_base64url",0,function(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...C(t)})},"_bigint",0,function(e,t){return new e({type:"bigint",...C(t)})},"_boolean",0,function(e,t){return new e({type:"boolean",...C(t)})},"_catch",0,function(e,t,r){return new e({type:"catch",innerType:t,catchValue:"function"==typeof r?r:()=>r})},"_check",0,ac,"_cidrv4",0,function(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...C(t)})},"_cidrv6",0,function(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...C(t)})},"_coercedBigint",0,function(e,t){return new e({type:"bigint",coerce:!0,...C(t)})},"_coercedBoolean",0,function(e,t){return new e({type:"boolean",coerce:!0,...C(t)})},"_coercedDate",0,function(e,t){return new e({type:"date",coerce:!0,...C(t)})},"_coercedNumber",0,function(e,t){return new e({type:"number",coerce:!0,checks:[],...C(t)})},"_coercedString",0,function(e,t){return new e({type:"string",coerce:!0,...C(t)})},"_cuid",0,function(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...C(t)})},"_cuid2",0,function(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...C(t)})},"_custom",0,function(e,t,r){let a=C(r);return a.abort??(a.abort=!0),new e({type:"custom",check:"custom",fn:t,...a})},"_date",0,function(e,t){return new e({type:"date",...C(t)})},"_default",0,function(e,t,r){return new e({type:"default",innerType:t,get defaultValue(){return"function"==typeof r?r():S(r)}})},"_discriminatedUnion",0,function(e,t,r,a){return new e({type:"union",options:r,discriminator:t,...C(a)})},"_e164",0,function(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...C(t)})},"_email",0,function(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...C(t)})},"_emoji",0,function(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...C(t)})},"_endsWith",0,function(e,t){return new e6({check:"string_format",format:"ends_with",...C(t),suffix:e})},"_enum",0,function(e,t,r){return new e({type:"enum",entries:Array.isArray(t)?Object.fromEntries(t.map(e=>[e,e])):t,...C(r)})},"_file",0,function(e,t){return new e({type:"file",...C(t)})},"_float32",0,function(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float32",...C(t)})},"_float64",0,function(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float64",...C(t)})},"_gt",0,al,"_gte",0,au,"_guid",0,function(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...C(t)})},"_includes",0,function(e,t){return new e2({check:"string_format",format:"includes",...C(t),includes:e})},"_int",0,function(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...C(t)})},"_int32",0,function(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"int32",...C(t)})},"_int64",0,function(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...C(t)})},"_intersection",0,function(e,t,r){return new e({type:"intersection",left:t,right:r})},"_ipv4",0,function(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...C(t)})},"_ipv6",0,function(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...C(t)})},"_isoDate",0,function(e,t){return new e({type:"string",format:"date",check:"string_format",...C(t)})},"_isoDateTime",0,function(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...C(t)})},"_isoDuration",0,function(e,t){return new e({type:"string",format:"duration",check:"string_format",...C(t)})},"_isoTime",0,function(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...C(t)})},"_jwt",0,function(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...C(t)})},"_ksuid",0,function(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...C(t)})},"_lazy",0,function(e,t){return new e({type:"lazy",getter:t})},"_length",0,function(e,t){return new eQ({check:"length_equals",...C(t),length:e})},"_literal",0,function(e,t,r){return new e({type:"literal",values:Array.isArray(t)?t:[t],...C(r)})},"_lowercase",0,function(e){return new e1({check:"string_format",format:"lowercase",...C(e)})},"_lt",0,as,"_lte",0,ao,"_mac",0,function(e,t){return new e({type:"string",format:"mac",check:"string_format",abort:!1,...C(t)})},"_map",0,function(e,t,r,a){return new e({type:"map",keyType:t,valueType:r,...C(a)})},"_max",0,ao,"_maxLength",0,function(e,t){return new eK({check:"max_length",...C(t),maximum:e})},"_maxSize",0,function(e,t){return new eG({check:"max_size",...C(t),maximum:e})},"_mime",0,function(e,t){return new e8({check:"mime_type",mime:e,...C(t)})},"_min",0,au,"_minLength",0,function(e,t){return new eY({check:"min_length",...C(t),minimum:e})},"_minSize",0,function(e,t){return new eW({check:"min_size",...C(t),minimum:e})},"_multipleOf",0,function(e,t){return new eH({check:"multiple_of",...C(t),value:e})},"_nan",0,function(e,t){return new e({type:"nan",...C(t)})},"_nanoid",0,function(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...C(t)})},"_nativeEnum",0,function(e,t,r){return new e({type:"enum",entries:t,...C(r)})},"_negative",0,function(e){return as(0,e)},"_never",0,ai,"_nonnegative",0,function(e){return au(0,e)},"_nonoptional",0,function(e,t,r){return new e({type:"nonoptional",innerType:t,...C(r)})},"_nonpositive",0,function(e){return ao(0,e)},"_normalize",0,function(e){return ad(t=>t.normalize(e))},"_null",0,function(e,t){return new e({type:"null",...C(t)})},"_nullable",0,function(e,t){return new e({type:"nullable",innerType:t})},"_number",0,function(e,t){return new e({type:"number",checks:[],...C(t)})},"_optional",0,function(e,t){return new e({type:"optional",innerType:t})},"_overwrite",0,ad,"_pipe",0,function(e,t,r){return new e({type:"pipe",in:t,out:r})},"_positive",0,function(e){return al(0,e)},"_promise",0,function(e,t){return new e({type:"promise",innerType:t})},"_property",0,function(e,t,r){return new e3({check:"property",property:e,schema:t,...C(r)})},"_readonly",0,function(e,t){return new e({type:"readonly",innerType:t})},"_record",0,function(e,t,r,a){return new e({type:"record",keyType:t,valueType:r,...C(a)})},"_refine",0,function(e,t,r){return new e({type:"custom",check:"custom",fn:t,...C(r)})},"_regex",0,function(e,t){return new e0({check:"string_format",format:"regex",...C(t),pattern:e})},"_set",0,function(e,t,r){return new e({type:"set",valueType:t,...C(r)})},"_size",0,function(e,t){return new eV({check:"size_equals",...C(t),size:e})},"_slugify",0,function(){return ad(e=>v(e))},"_startsWith",0,function(e,t){return new e9({check:"string_format",format:"starts_with",...C(t),prefix:e})},"_string",0,function(e,t){return new e({type:"string",...C(t)})},"_stringFormat",0,function(e,t,r,a={}){let n=C(a),i={...C(a),check:"string_format",type:"string",format:t,fn:"function"==typeof r?r:e=>r.test(e),...n};return r instanceof RegExp&&(i.pattern=r),new e(i)},"_stringbool",0,function(e,t){let r=C(t),a=r.truthy??["true","1","yes","on","y","enabled"],n=r.falsy??["false","0","no","off","n","disabled"];"sensitive"!==r.case&&(a=a.map(e=>"string"==typeof e?e.toLowerCase():e),n=n.map(e=>"string"==typeof e?e.toLowerCase():e));let i=new Set(a),s=new Set(n),o=e.Codec??rY,l=e.Boolean??t7,u=new o({type:"pipe",in:new(e.String??tI)({type:"string",error:r.error}),out:new l({type:"boolean",error:r.error}),transform:(e,t)=>{let a=e;return"sensitive"!==r.case&&(a=a.toLowerCase()),!!i.has(a)||!s.has(a)&&(t.issues.push({code:"invalid_value",expected:"stringbool",values:[...i,...s],input:t.value,inst:u,continue:!1}),{})},reverseTransform:(e,t)=>!0===e?a[0]||"true":n[0]||"false",error:r.error});return u},"_success",0,function(e,t){return new e({type:"success",innerType:t})},"_superRefine",0,function(e,t){let r=ac(t=>(t.addIssue=e=>{"string"==typeof e?t.issues.push(U(e,t.value,r._zod.def)):(e.fatal&&(e.continue=!1),e.code??(e.code="custom"),e.input??(e.input=t.value),e.inst??(e.inst=r),e.continue??(e.continue=!r._zod.def.abort),t.issues.push(U(e)))},e(t.value,t)),t);return r},"_symbol",0,function(e,t){return new e({type:"symbol",...C(t)})},"_templateLiteral",0,function(e,t,r){return new e({type:"template_literal",parts:t,...C(r)})},"_toLowerCase",0,function(){return ad(e=>e.toLowerCase())},"_toUpperCase",0,function(){return ad(e=>e.toUpperCase())},"_transform",0,function(e,t){return new e({type:"transform",transform:t})},"_trim",0,function(){return ad(e=>e.trim())},"_tuple",0,function(e,t,r,a){let n=r instanceof tO,i=n?a:r;return new e({type:"tuple",items:t,rest:n?r:null,...C(i)})},"_uint32",0,function(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"uint32",...C(t)})},"_uint64",0,function(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...C(t)})},"_ulid",0,function(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...C(t)})},"_undefined",0,function(e,t){return new e({type:"undefined",...C(t)})},"_union",0,function(e,t,r){return new e({type:"union",options:t,...C(r)})},"_unknown",0,an,"_uppercase",0,function(e){return new e4({check:"string_format",format:"uppercase",...C(e)})},"_url",0,function(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...C(t)})},"_uuid",0,function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...C(t)})},"_uuidv4",0,function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...C(t)})},"_uuidv6",0,function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...C(t)})},"_uuidv7",0,function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...C(t)})},"_void",0,function(e,t){return new e({type:"void",...C(t)})},"_xid",0,function(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...C(t)})},"_xor",0,function(e,t,r){return new e({type:"union",options:t,inclusive:!1,...C(r)})},"describe",0,function(e){let t=new eD({check:"describe"});return t._zod.onattach=[t=>{let r=aa.get(t)??{};aa.add(t,{...r,description:e})}],t._zod.check=()=>{},t},"meta",0,function(e){let t=new eD({check:"meta"});return t._zod.onattach=[t=>{let r=aa.get(t)??{};aa.add(t,{...r,...e})}],t._zod.check=()=>{},t}],862061);var ah,ap,af=e.i(486618);e.s(["util",0,af],628343);var af=af;function am(e){if("object"!=typeof e||null===e||!("_zod"in e))return!1;let t=e._zod;return"object"==typeof t&&null!==t&&"def"in t}function ag(e){if("object"!=typeof e||null===e||!("_def"in e)||"_zod"in e)return!1;let t=e._def;return"object"==typeof t&&null!=t&&"typeName"in t}function a_(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&!!(am(e)||ag(e))}function ay(e){return"object"==typeof e&&null!==e&&"_def"in e&&"object"==typeof e._def&&null!==e._def&&"typeName"in e._def&&"ZodLiteral"===e._def.typeName||!1}function av(e){return!!am(e)&&("object"==typeof e&&null!==e&&"_zod"in e&&"object"==typeof e._zod&&null!==e._zod&&"def"in e._zod&&"object"==typeof e._zod.def&&null!==e._zod.def&&"type"in e._zod.def&&"literal"===e._zod.def.type||!1)}async function ab(e,t){if(am(e))try{return{success:!0,data:await tl(e,t)}}catch(e){return{success:!1,error:e}}if(ag(e))return await e.safeParseAsync(t);throw Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}async function aw(e,t){if(am(e))return await tl(e,t);if(ag(e))return await e.parseAsync(t);throw Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function ak(e){return"object"==typeof e&&null!==e&&"_def"in e&&"object"==typeof e._def&&null!==e._def&&"typeName"in e._def&&"ZodObject"===e._def.typeName||!1}function ax(e){return!!am(e)&&("object"==typeof e&&null!==e&&"_zod"in e&&"object"==typeof e._zod&&null!==e._zod&&"def"in e._zod&&"object"==typeof e._zod.def&&null!==e._zod.def&&"type"in e._zod.def&&"object"===e._zod.def.type||!1)}function aS(e){return!!am(e)&&("object"==typeof e&&null!==e&&"_zod"in e&&"object"==typeof e._zod&&null!==e._zod&&"def"in e._zod&&"object"==typeof e._zod.def&&null!==e._zod.def&&"type"in e._zod.def&&"array"===e._zod.def.type||!1)}function a$(e){return!!am(e)&&("object"==typeof e&&null!==e&&"_zod"in e&&"object"==typeof e._zod&&null!==e._zod&&"def"in e._zod&&"object"==typeof e._zod.def&&null!==e._zod.def&&"type"in e._zod.def&&"optional"===e._zod.def.type||!1)}function aE(e){return!!am(e)&&("object"==typeof e&&null!==e&&"_zod"in e&&"object"==typeof e._zod&&null!==e._zod&&"def"in e._zod&&"object"==typeof e._zod.def&&null!==e._zod.def&&"type"in e._zod.def&&"nullable"===e._zod.def.type||!1)}function aT(e){if(ag(e))return e.shape;if(am(e))return e._zod.def.shape;throw Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}e.s(["extendInteropZodObject",0,function(e,t){if(ag(e))return e.extend(t);if(am(e))return af.extend(e,t);throw Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")},"getInteropZodDefaultGetter",0,function(e){if(ag(e))try{let t=e.parse(void 0);return()=>t}catch{return}if(am(e))try{let t=ts(e,void 0);return()=>t}catch{return}},"getInteropZodObjectShape",0,aT,"getSchemaDescription",0,function(e){return am(e)?aa.get(e)?.description:ag(e)||"description"in e&&"string"==typeof e.description?e.description:void 0},"interopParse",0,function(e,t){if(am(e))return ts(e,t);if(ag(e))return e.parse(t);throw Error("Schema must be an instance of z3.ZodType or z4.$ZodType")},"interopParseAsync",0,aw,"interopSafeParse",0,function(e,t){if(am(e))try{return{success:!0,data:ts(e,t)}}catch(e){return{success:!1,error:e}}if(ag(e))return e.safeParse(t);throw Error("Schema must be an instance of z3.ZodType or z4.$ZodType")},"interopSafeParseAsync",0,ab,"interopZodObjectMakeFieldsOptional",0,function(e,t){if(ag(e)){let r=aT(e),a={};for(let[e,n]of Object.entries(r))t(e,n)?a[e]=n.optional():a[e]=n;return e.extend(a)}if(am(e)){let r=aT(e),a={...e._zod.def.shape};for(let[e,n]of Object.entries(r))t(e,n)&&(a[e]=new rL({type:"optional",innerType:n}));let n=A(e,{...e._zod.def,shape:a}),i=aa.get(e);return i&&aa.add(n,i),n}throw Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")},"interopZodObjectPartial",0,function(e){if(ag(e))return e.partial();if(am(e))return af.partial(rL,e,void 0);throw Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")},"interopZodObjectPassthrough",0,function e(t,r=!1){if(ak(t))return t.passthrough();if(ax(t)){let a=t._zod.def.shape;if(r)for(let[n,i]of Object.entries(t._zod.def.shape)){if(ax(i))a[n]=e(i,r);else if(aS(i)){let t=i._zod.def.element;ax(t)&&(t=e(t,r)),a[n]=A(i,{...i._zod.def,element:t})}else a[n]=i;let t=aa.get(i);t&&aa.add(a[n],t)}let n=A(t,{...t._zod.def,shape:a,catchall:an(rs)}),i=aa.get(t);return i&&aa.add(n,i),n}throw Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")},"interopZodObjectStrict",0,function e(t,r=!1){if(ak(t))return t.strict();if(ax(t)){let a=t._zod.def.shape;if(r)for(let[n,i]of Object.entries(t._zod.def.shape)){if(ax(i))a[n]=e(i,r);else if(aS(i)){let t=i._zod.def.element;ax(t)&&(t=e(t,r)),a[n]=A(i,{...i._zod.def,element:t})}else a[n]=i;let t=aa.get(i);t&&aa.add(a[n],t)}let n=A(t,{...t._zod.def,shape:a,catchall:ai(ro)}),i=aa.get(t);return i&&aa.add(n,i),n}throw Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")},"interopZodTransformInputSchema",0,function(e,t=!1){return function e(t,r,a){let n=a.get(t);if(void 0!==n)return n;if(ag(t))return ag(t)&&"typeName"in t._def&&"ZodEffects"===t._def.typeName?e(t._def.schema,r,a):t;if(am(t)){let n=t;if(am(t)&&"pipe"===t._zod.def.type&&(n=e(t._zod.def.in,r,a)),r){if(ax(n)){let t={};for(let[i,s]of Object.entries(n._zod.def.shape))t[i]=e(s,r,a);n=A(n,{...n._zod.def,shape:t})}else if(aS(n)){let t=e(n._zod.def.element,r,a);n=A(n,{...n._zod.def,element:t})}else if(a$(n)){let t=e(n._zod.def.innerType,r,a);n=A(n,{...n._zod.def,innerType:t})}else if(aE(n)){let t=e(n._zod.def.innerType,r,a);n=A(n,{...n._zod.def,innerType:t})}}let i=aa.get(t);return i&&aa.add(n,i),a.set(t,n),n}throw Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}(e,t,new WeakMap)},"isInteropZodError",0,function(e){return e instanceof Error&&("ZodError"===e.constructor.name||"$ZodError"===e.constructor.name)},"isInteropZodLiteral",0,function(e){return!!(ay(e)||av(e))},"isInteropZodObject",0,function(e){return!!(ak(e)||ax(e))},"isInteropZodSchema",0,a_,"isShapelessZodSchema",0,function(e){if(!a_(e))return!1;if(ag(e)){let t=e._def;if("ZodObject"===t.typeName)return!e.shape||0===Object.keys(e.shape).length;if("ZodRecord"===t.typeName)return!0}if(am(e)){let t=e._zod.def;if("object"===t.type)return!e.shape||0===Object.keys(e.shape).length;if("record"===t.type)return!0}return"object"==typeof e&&null!==e&&!("shape"in e)},"isSimpleStringZodSchema",0,function(e){return!!a_(e)&&(ag(e)?"ZodString"===e._def.typeName:!!am(e)&&"string"===e._zod.def.type)},"isZodArrayV4",0,aS,"isZodLiteralV3",0,ay,"isZodLiteralV4",0,av,"isZodNullableV4",0,aE,"isZodObjectV3",0,ak,"isZodObjectV4",0,ax,"isZodOptionalV4",0,a$,"isZodSchema",0,function(e){return am(e)&&console.warn("[WARNING] Attempting to use Zod 4 schema in a context where Zod 3 schema is expected. This may cause unexpected behavior."),ag(e)},"isZodSchemaV3",0,ag,"isZodSchemaV4",0,am],238073)},959026,e=>{"use strict";var t=e.i(165978);function r(e){return e.replace(/[^a-zA-Z-_0-9]/g,"_")}let a=["*","_","`"];async function n(e,r){let a=r?.backgroundColor??"white",n=r?.imageType??"png",i=(0,t.toBase64Url)(e);void 0===a||/^#(?:[0-9a-fA-F]{3}){1,2}$/.test(a)||(a=`!${a}`);let s=`https://mermaid.ink/img/${i}?bgColor=${a}&type=${n}`,o=await fetch(s);if(!o.ok)throw Error(`Failed to render the graph using the Mermaid.INK API. Status code: ${o.status} Status text: ${o.statusText}`);return await o.blob()}e.s(["drawMermaid",0,function(e,t,n){let{firstNode:i,lastNode:s,nodeColors:o,withStyles:l=!0,curveStyle:u="linear",wrapLabelNWords:d=9}=n??{},c=l?`%%{init: {'flowchart': {'curve': '${u}'}}}%% graph TD; `:"graph TD;\n";if(l){let t="default",n={[t]:"{0}({1})"};for(let[o,l]of(void 0!==i&&(n[i]="{0}([{1}]):::first"),void 0!==s&&(n[s]="{0}([{1}]):::last"),Object.entries(e))){let e=l.name.split(":").pop()??"",i=a.some(t=>e.startsWith(t)&&e.endsWith(t))?`

${e}

`:e;Object.keys(l.metadata??{}).length&&(i+=`
${Object.entries(l.metadata??{}).map(([e,t])=>`${e} = ${t}`).join("\n")}`);let s=(n[o]??n[t]).replace("{0}",r(o)).replace("{1}",i);c+=` ${s} `}}let h={};for(let e of t){let t=e.source.split(":"),r=e.target.split(":"),a=t.filter((e,t)=>e===r[t]).join(":");h[a]||(h[a]=[]),h[a].push(e)}let p=new Set;function f(e,t){let a=1===e.length&&e[0].source===e[0].target;if(t&&!a){let e=t.split(":").pop();if(p.has(t))throw Error(`Found duplicate subgraph '${e}' at '${t} -- 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.`);p.add(t),c+=` subgraph ${e} `}for(let e of[...Object.keys(h).filter(e=>e.startsWith(`${t}:`)&&e!==t&&e.split(":").length===t.split(":").length+1)].sort((e,t)=>e.split(":").length-t.split(":").length))f(h[e],e);for(let t of e){let{source:e,target:a,data:n,conditional:i}=t,s="";if(void 0!==n){let e=n,t=e.split(" ");t.length>d&&(e=Array.from({length:Math.ceil(t.length/d)},(e,r)=>t.slice(r*d,(r+1)*d).join(" ")).join(" 
 ")),s=i?` -.  ${e}  .-> `:` --  ${e}  --> `}else s=i?" -.-> ":" --> ";c+=` ${r(e)}${s}${r(a)}; `}t&&!a&&(c+=" end\n")}for(let e in f(h[""]??[],""),h)e.includes(":")||""===e||f(h[e],e);return l&&(c+=function(e){let t="";for(let[r,a]of Object.entries(e))t+=` classDef ${r} ${a}; `;return t}(o??{})),c},"drawMermaidImage",0,n])},229335,742944,115235,880264,585676,984488,117958,e=>{"use strict";var t,r,a,n,i,s,o;let l,u,d=Symbol("Let zodToJsonSchema decide on which parser to use"),c={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},h=(e,t)=>{let r=0;for(;r{},i.assertIs=function(e){},i.assertNever=function(e){throw Error()},i.arrayToEnum=e=>{let t={};for(let r of e)t[r]=r;return t},i.getValidEnumValues=e=>{let t=i.objectKeys(e).filter(t=>"number"!=typeof e[e[t]]),r={};for(let a of t)r[a]=e[a];return i.objectValues(r)},i.objectValues=e=>i.objectKeys(e).map(function(t){return e[t]}),i.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{let t=[];for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.push(r);return t},i.find=(e,t)=>{for(let r of e)if(t(r))return r},i.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,i.joinValues=function(e,t=" | "){return e.map(e=>"string"==typeof e?`'${e}'`:e).join(t)},i.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t,(r||(r={})).mergeShapes=(e,t)=>({...e,...t});let g=t.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),_=e=>{switch(typeof e){case"undefined":return g.undefined;case"string":return g.string;case"number":return Number.isNaN(e)?g.nan:g.number;case"boolean":return g.boolean;case"function":return g.function;case"bigint":return g.bigint;case"symbol":return g.symbol;case"object":if(Array.isArray(e))return g.array;if(null===e)return g.null;if(e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch)return g.promise;if("u">typeof Map&&e instanceof Map)return g.map;if("u">typeof Set&&e instanceof Set)return g.set;if("u">typeof Date&&e instanceof Date)return g.date;return g.object;default:return g.unknown}};e.s(["ZodParsedType",0,g,"getParsedType",0,_,"objectUtil",0,r,"util",0,t],742944);let y=t.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"]);class v extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(e){return e.message},r={_errors:[]},a=e=>{for(let n of e.issues)if("invalid_union"===n.code)n.unionErrors.map(a);else if("invalid_return_type"===n.code)a(n.returnTypeError);else if("invalid_arguments"===n.code)a(n.argumentsError);else if(0===n.path.length)r._errors.push(t(n));else{let e=r,a=0;for(;ae.message){let t=Object.create(null),r=[];for(let a of this.issues)if(a.path.length>0){let r=a.path[0];t[r]=t[r]||[],t[r].push(e(a))}else r.push(e(a));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}v.create=e=>new v(e),e.s(["ZodError",0,v,"ZodIssueCode",0,y,"quotelessJson",0,e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:")],115235);let b=(e,r)=>{let a;switch(e.code){case y.invalid_type:a=e.received===g.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case y.invalid_literal:a=`Invalid literal value, expected ${JSON.stringify(e.expected,t.jsonStringifyReplacer)}`;break;case y.unrecognized_keys:a=`Unrecognized key(s) in object: ${t.joinValues(e.keys,", ")}`;break;case y.invalid_union:a="Invalid input";break;case y.invalid_union_discriminator:a=`Invalid discriminator value. Expected ${t.joinValues(e.options)}`;break;case y.invalid_enum_value:a=`Invalid enum value. Expected ${t.joinValues(e.options)}, received '${e.received}'`;break;case y.invalid_arguments:a="Invalid function arguments";break;case y.invalid_return_type:a="Invalid function return type";break;case y.invalid_date:a="Invalid date";break;case y.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(a=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(a=`${a} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?a=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?a=`Invalid input: must end with "${e.validation.endsWith}"`:t.assertNever(e.validation):a="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case y.too_small:a="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type||"bigint"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:"Invalid input";break;case y.too_big:a="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case y.custom:a="Invalid input";break;case y.invalid_intersection_types:a="Intersection results could not be merged";break;case y.not_multiple_of:a=`Number must be a multiple of ${e.multipleOf}`;break;case y.not_finite:a="Number must be finite";break;default:a=r.defaultError,t.assertNever(e)}return{message:a}};e.s(["default",0,b],880264);let w=b;function k(){return w}e.s(["getErrorMap",0,k,"setErrorMap",0,function(e){w=e}],585676),(s=a||(a={})).errToObj=e=>"string"==typeof e?{message:e}:e||{},s.toString=e=>"string"==typeof e?e:e?.message;let x=e=>{let{data:t,path:r,errorMaps:a,issueData:n}=e,i=[...r,...n.path||[]],s={...n,path:i};if(void 0!==n.message)return{...n,path:i,message:n.message};let o="";for(let e of a.filter(e=>!!e).slice().reverse())o=e(s,{data:t,defaultError:o}).message;return{...n,path:i,message:o}};function S(e,t){let r=k(),a=x({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===b?void 0:b].filter(e=>!!e)});e.common.issues.push(a)}class ${constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){let r=[];for(let a of t){if("aborted"===a.status)return E;"dirty"===a.status&&e.dirty(),r.push(a.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){let r=[];for(let e of t){let t=await e.key,a=await e.value;r.push({key:t,value:a})}return $.mergeObjectSync(e,r)}static mergeObjectSync(e,t){let r={};for(let a of t){let{key:t,value:n}=a;if("aborted"===t.status||"aborted"===n.status)return E;"dirty"===t.status&&e.dirty(),"dirty"===n.status&&e.dirty(),"__proto__"!==t.value&&(void 0!==n.value||a.alwaysSet)&&(r[t.value]=n.value)}return{status:e.value,value:r}}}let E=Object.freeze({status:"aborted"}),T=e=>({status:"dirty",value:e}),A=e=>({status:"valid",value:e}),C=e=>"aborted"===e.status,O=e=>"dirty"===e.status,I=e=>"valid"===e.status,j=e=>"u">typeof Promise&&e instanceof Promise;e.s(["DIRTY",0,T,"EMPTY_PATH",0,[],"INVALID",0,E,"OK",0,A,"ParseStatus",0,$,"addIssueToContext",0,S,"isAborted",0,C,"isAsync",0,j,"isDirty",0,O,"isValid",0,I,"makeIssue",0,x],984488);class P{constructor(e,t,r,a){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=a}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}let z=(e,t)=>{if(I(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new v(e.common.issues);return this._error=t,this._error}}};function N(e){if(!e)return{};let{errorMap:t,invalid_type_error:r,required_error:a,description:n}=e;if(t&&(r||a))throw Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');return t?{errorMap:t,description:n}:{errorMap:(t,n)=>{let{message:i}=e;return"invalid_enum_value"===t.code?{message:i??n.defaultError}:void 0===n.data?{message:i??a??n.defaultError}:"invalid_type"!==t.code?{message:n.defaultError}:{message:i??r??n.defaultError}},description:n}}class R{get description(){return this._def.description}_getType(e){return _(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:_(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new $,ctx:{common:e.parent.common,data:e.data,parsedType:_(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(j(t))throw Error("Synchronous parse encountered promise.");return t}_parseAsync(e){return Promise.resolve(this._parse(e))}parse(e,t){let r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){let r={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:_(e)},a=this._parseSync({data:e,path:r.path,parent:r});return z(r,a)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:_(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:t});return I(r)?{value:r.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>I(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){let r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){let r={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:_(e)},a=this._parse({data:e,path:r.path,parent:r});return z(r,await (j(a)?a:Promise.resolve(a)))}refine(e,t){return this._refinement((r,a)=>{let n=e(r),i=()=>a.addIssue({code:y.custom,..."string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(r):t});return"u">typeof Promise&&n instanceof Promise?n.then(e=>!!e||(i(),!1)):!!n||(i(),!1)})}refinement(e,t){return this._refinement((r,a)=>!!e(r)||(a.addIssue("function"==typeof t?t(r,a):t),!1))}_refinement(e){return new eO({schema:this,typeName:n.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,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:e=>this["~validate"](e)}}optional(){return eI.create(this,this._def)}nullable(){return ej.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ep.create(this)}promise(){return eC.create(this,this._def)}or(e){return em.create([this,e],this._def)}and(e){return ey.create(this,e,this._def)}transform(e){return new eO({...N(this._def),schema:this,typeName:n.ZodEffects,effect:{type:"transform",transform:e}})}default(e){return new eP({...N(this._def),innerType:this,defaultValue:"function"==typeof e?e:()=>e,typeName:n.ZodDefault})}brand(){return new eM({typeName:n.ZodBranded,type:this,...N(this._def)})}catch(e){return new ez({...N(this._def),innerType:this,catchValue:"function"==typeof e?e:()=>e,typeName:n.ZodCatch})}describe(e){return new this.constructor({...this._def,description:e})}pipe(e){return eL.create(this,e)}readonly(){return eZ.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}let M=/^c[^\s-]{8,}$/i,L=/^[0-9a-z]+$/,Z=/^[0-9A-HJKMNP-TV-Z]{26}$/i,D=/^[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,U=/^[a-z0-9_-]{21}$/i,B=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,F=/^[-+]?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)?)??$/,H=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,q=/^(?:(?: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])$/,J=/^(?:(?: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])$/,G=/^(([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]))$/,W=/^(([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])$/,V=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,K=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Y="((\\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])))",Q=RegExp(`^${Y}$`);function X(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`);let r=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${r}`}function ee(e){let t=`${Y}T${X(e)}`,r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,RegExp(`^${t}$`)}class et extends R{_parse(e){var r,a,n,i;let s;if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==g.string){let t=this._getOrReturnCtx(e);return S(t,{code:y.invalid_type,expected:g.string,received:t.parsedType}),E}let o=new $;for(let u of this._def.checks)if("min"===u.kind)e.data.lengthu.value&&(S(s=this._getOrReturnCtx(e,s),{code:y.too_big,maximum:u.value,type:"string",inclusive:!0,exact:!1,message:u.message}),o.dirty());else if("length"===u.kind){let t=e.data.length>u.value,r=e.data.lengthe.test(t),{validation:t,code:y.invalid_string,...a.errToObj(r)})}_addCheck(e){return new et({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...a.errToObj(e)})}url(e){return this._addCheck({kind:"url",...a.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...a.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...a.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...a.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...a.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...a.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...a.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...a.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...a.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...a.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...a.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...a.errToObj(e)})}datetime(e){return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===e?.precision?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...a.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===e?.precision?null:e?.precision,...a.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...a.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...a.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...a.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...a.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...a.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...a.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...a.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...a.errToObj(t)})}nonempty(e){return this.min(1,a.errToObj(e))}trim(){return new et({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new et({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new et({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>"datetime"===e.kind)}get isDate(){return!!this._def.checks.find(e=>"date"===e.kind)}get isTime(){return!!this._def.checks.find(e=>"time"===e.kind)}get isDuration(){return!!this._def.checks.find(e=>"duration"===e.kind)}get isEmail(){return!!this._def.checks.find(e=>"email"===e.kind)}get isURL(){return!!this._def.checks.find(e=>"url"===e.kind)}get isEmoji(){return!!this._def.checks.find(e=>"emoji"===e.kind)}get isUUID(){return!!this._def.checks.find(e=>"uuid"===e.kind)}get isNANOID(){return!!this._def.checks.find(e=>"nanoid"===e.kind)}get isCUID(){return!!this._def.checks.find(e=>"cuid"===e.kind)}get isCUID2(){return!!this._def.checks.find(e=>"cuid2"===e.kind)}get isULID(){return!!this._def.checks.find(e=>"ulid"===e.kind)}get isIP(){return!!this._def.checks.find(e=>"ip"===e.kind)}get isCIDR(){return!!this._def.checks.find(e=>"cidr"===e.kind)}get isBase64(){return!!this._def.checks.find(e=>"base64"===e.kind)}get isBase64url(){return!!this._def.checks.find(e=>"base64url"===e.kind)}get minLength(){let e=null;for(let t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)"max"===t.kind&&(null===e||t.valuenew et({checks:[],typeName:n.ZodString,coerce:e?.coerce??!1,...N(e)});class er extends R{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){let r;if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==g.number){let t=this._getOrReturnCtx(e);return S(t,{code:y.invalid_type,expected:g.number,received:t.parsedType}),E}let a=new $;for(let n of this._def.checks)"int"===n.kind?t.isInteger(e.data)||(S(r=this._getOrReturnCtx(e,r),{code:y.invalid_type,expected:"integer",received:"float",message:n.message}),a.dirty()):"min"===n.kind?(n.inclusive?e.datan.value:e.data>=n.value)&&(S(r=this._getOrReturnCtx(e,r),{code:y.too_big,maximum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),a.dirty()):"multipleOf"===n.kind?0!==function(e,t){let r=(e.toString().split(".")[1]||"").length,a=(t.toString().split(".")[1]||"").length,n=r>a?r:a;return Number.parseInt(e.toFixed(n).replace(".",""))%Number.parseInt(t.toFixed(n).replace(".",""))/10**n}(e.data,n.value)&&(S(r=this._getOrReturnCtx(e,r),{code:y.not_multiple_of,multipleOf:n.value,message:n.message}),a.dirty()):"finite"===n.kind?Number.isFinite(e.data)||(S(r=this._getOrReturnCtx(e,r),{code:y.not_finite,message:n.message}),a.dirty()):t.assertNever(n);return{status:a.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,a.toString(t))}gt(e,t){return this.setLimit("min",e,!1,a.toString(t))}lte(e,t){return this.setLimit("max",e,!0,a.toString(t))}lt(e,t){return this.setLimit("max",e,!1,a.toString(t))}setLimit(e,t,r,n){return new er({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:a.toString(n)}]})}_addCheck(e){return new er({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:a.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:a.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:a.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:a.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:a.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:a.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:a.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:a.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:a.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)"max"===t.kind&&(null===e||t.value"int"===e.kind||"multipleOf"===e.kind&&t.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let r of this._def.checks)if("finite"===r.kind||"int"===r.kind||"multipleOf"===r.kind)return!0;else"min"===r.kind?(null===t||r.value>t)&&(t=r.value):"max"===r.kind&&(null===e||r.valuenew er({checks:[],typeName:n.ZodNumber,coerce:e?.coerce||!1,...N(e)});class ea extends R{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){let r;if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==g.bigint)return this._getInvalidInput(e);let a=new $;for(let n of this._def.checks)"min"===n.kind?(n.inclusive?e.datan.value:e.data>=n.value)&&(S(r=this._getOrReturnCtx(e,r),{code:y.too_big,type:"bigint",maximum:n.value,inclusive:n.inclusive,message:n.message}),a.dirty()):"multipleOf"===n.kind?e.data%n.value!==BigInt(0)&&(S(r=this._getOrReturnCtx(e,r),{code:y.not_multiple_of,multipleOf:n.value,message:n.message}),a.dirty()):t.assertNever(n);return{status:a.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return S(t,{code:y.invalid_type,expected:g.bigint,received:t.parsedType}),E}gte(e,t){return this.setLimit("min",e,!0,a.toString(t))}gt(e,t){return this.setLimit("min",e,!1,a.toString(t))}lte(e,t){return this.setLimit("max",e,!0,a.toString(t))}lt(e,t){return this.setLimit("max",e,!1,a.toString(t))}setLimit(e,t,r,n){return new ea({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:a.toString(n)}]})}_addCheck(e){return new ea({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:a.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:a.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:a.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:a.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:a.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)"max"===t.kind&&(null===e||t.valuenew ea({checks:[],typeName:n.ZodBigInt,coerce:e?.coerce??!1,...N(e)});class en extends R{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==g.boolean){let t=this._getOrReturnCtx(e);return S(t,{code:y.invalid_type,expected:g.boolean,received:t.parsedType}),E}return A(e.data)}}en.create=e=>new en({typeName:n.ZodBoolean,coerce:e?.coerce||!1,...N(e)});class ei extends R{_parse(e){let r;if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==g.date){let t=this._getOrReturnCtx(e);return S(t,{code:y.invalid_type,expected:g.date,received:t.parsedType}),E}if(Number.isNaN(e.data.getTime()))return S(this._getOrReturnCtx(e),{code:y.invalid_date}),E;let a=new $;for(let n of this._def.checks)"min"===n.kind?e.data.getTime()n.value&&(S(r=this._getOrReturnCtx(e,r),{code:y.too_big,message:n.message,inclusive:!0,exact:!1,maximum:n.value,type:"date"}),a.dirty()):t.assertNever(n);return{status:a.value,value:new Date(e.data.getTime())}}_addCheck(e){return new ei({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:a.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:a.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)"max"===t.kind&&(null===e||t.valuenew ei({checks:[],coerce:e?.coerce||!1,typeName:n.ZodDate,...N(e)});class es extends R{_parse(e){if(this._getType(e)!==g.symbol){let t=this._getOrReturnCtx(e);return S(t,{code:y.invalid_type,expected:g.symbol,received:t.parsedType}),E}return A(e.data)}}es.create=e=>new es({typeName:n.ZodSymbol,...N(e)});class eo extends R{_parse(e){if(this._getType(e)!==g.undefined){let t=this._getOrReturnCtx(e);return S(t,{code:y.invalid_type,expected:g.undefined,received:t.parsedType}),E}return A(e.data)}}eo.create=e=>new eo({typeName:n.ZodUndefined,...N(e)});class el extends R{_parse(e){if(this._getType(e)!==g.null){let t=this._getOrReturnCtx(e);return S(t,{code:y.invalid_type,expected:g.null,received:t.parsedType}),E}return A(e.data)}}el.create=e=>new el({typeName:n.ZodNull,...N(e)});class eu extends R{constructor(){super(...arguments),this._any=!0}_parse(e){return A(e.data)}}eu.create=e=>new eu({typeName:n.ZodAny,...N(e)});class ed extends R{constructor(){super(...arguments),this._unknown=!0}_parse(e){return A(e.data)}}ed.create=e=>new ed({typeName:n.ZodUnknown,...N(e)});class ec extends R{_parse(e){let t=this._getOrReturnCtx(e);return S(t,{code:y.invalid_type,expected:g.never,received:t.parsedType}),E}}ec.create=e=>new ec({typeName:n.ZodNever,...N(e)});class eh extends R{_parse(e){if(this._getType(e)!==g.undefined){let t=this._getOrReturnCtx(e);return S(t,{code:y.invalid_type,expected:g.void,received:t.parsedType}),E}return A(e.data)}}eh.create=e=>new eh({typeName:n.ZodVoid,...N(e)});class ep extends R{_parse(e){let{ctx:t,status:r}=this._processInputParams(e),a=this._def;if(t.parsedType!==g.array)return S(t,{code:y.invalid_type,expected:g.array,received:t.parsedType}),E;if(null!==a.exactLength){let e=t.data.length>a.exactLength.value,n=t.data.lengtha.maxLength.value&&(S(t,{code:y.too_big,maximum:a.maxLength.value,type:"array",inclusive:!0,exact:!1,message:a.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((e,r)=>a.type._parseAsync(new P(t,e,t.path,r)))).then(e=>$.mergeArray(r,e));let n=[...t.data].map((e,r)=>a.type._parseSync(new P(t,e,t.path,r)));return $.mergeArray(r,n)}get element(){return this._def.type}min(e,t){return new ep({...this._def,minLength:{value:e,message:a.toString(t)}})}max(e,t){return new ep({...this._def,maxLength:{value:e,message:a.toString(t)}})}length(e,t){return new ep({...this._def,exactLength:{value:e,message:a.toString(t)}})}nonempty(e){return this.min(1,e)}}ep.create=(e,t)=>new ep({type:e,minLength:null,maxLength:null,exactLength:null,typeName:n.ZodArray,...N(t)});class ef extends R{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;let e=this._def.shape(),r=t.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==g.object){let t=this._getOrReturnCtx(e);return S(t,{code:y.invalid_type,expected:g.object,received:t.parsedType}),E}let{status:t,ctx:r}=this._processInputParams(e),{shape:a,keys:n}=this._getCached(),i=[];if(!(this._def.catchall instanceof ec&&"strip"===this._def.unknownKeys))for(let e in r.data)n.includes(e)||i.push(e);let s=[];for(let e of n){let t=a[e],n=r.data[e];s.push({key:{status:"valid",value:e},value:t._parse(new P(r,n,r.path,e)),alwaysSet:e in r.data})}if(this._def.catchall instanceof ec){let e=this._def.unknownKeys;if("passthrough"===e)for(let e of i)s.push({key:{status:"valid",value:e},value:{status:"valid",value:r.data[e]}});else if("strict"===e)i.length>0&&(S(r,{code:y.unrecognized_keys,keys:i}),t.dirty());else if("strip"===e);else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let e=this._def.catchall;for(let t of i){let a=r.data[t];s.push({key:{status:"valid",value:t},value:e._parse(new P(r,a,r.path,t)),alwaysSet:t in r.data})}}return r.common.async?Promise.resolve().then(async()=>{let e=[];for(let t of s){let r=await t.key,a=await t.value;e.push({key:r,value:a,alwaysSet:t.alwaysSet})}return e}).then(e=>$.mergeObjectSync(t,e)):$.mergeObjectSync(t,s)}get shape(){return this._def.shape()}strict(e){return a.errToObj,new ef({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,r)=>{let n=this._def.errorMap?.(t,r).message??r.defaultError;return"unrecognized_keys"===t.code?{message:a.errToObj(e).message??n}:{message:n}}}:{}})}strip(){return new ef({...this._def,unknownKeys:"strip"})}passthrough(){return new ef({...this._def,unknownKeys:"passthrough"})}extend(e){return new ef({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new ef({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:n.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new ef({...this._def,catchall:e})}pick(e){let r={};for(let a of t.objectKeys(e))e[a]&&this.shape[a]&&(r[a]=this.shape[a]);return new ef({...this._def,shape:()=>r})}omit(e){let r={};for(let a of t.objectKeys(this.shape))e[a]||(r[a]=this.shape[a]);return new ef({...this._def,shape:()=>r})}deepPartial(){return function e(t){if(t instanceof ef){let r={};for(let a in t.shape){let n=t.shape[a];r[a]=eI.create(e(n))}return new ef({...t._def,shape:()=>r})}if(t instanceof ep)return new ep({...t._def,type:e(t.element)});if(t instanceof eI)return eI.create(e(t.unwrap()));if(t instanceof ej)return ej.create(e(t.unwrap()));if(t instanceof ev)return ev.create(t.items.map(t=>e(t)));else return t}(this)}partial(e){let r={};for(let a of t.objectKeys(this.shape)){let t=this.shape[a];e&&!e[a]?r[a]=t:r[a]=t.optional()}return new ef({...this._def,shape:()=>r})}required(e){let r={};for(let a of t.objectKeys(this.shape))if(e&&!e[a])r[a]=this.shape[a];else{let e=this.shape[a];for(;e instanceof eI;)e=e._def.innerType;r[a]=e}return new ef({...this._def,shape:()=>r})}keyof(){return eE(t.objectKeys(this.shape))}}ef.create=(e,t)=>new ef({shape:()=>e,unknownKeys:"strip",catchall:ec.create(),typeName:n.ZodObject,...N(t)}),ef.strictCreate=(e,t)=>new ef({shape:()=>e,unknownKeys:"strict",catchall:ec.create(),typeName:n.ZodObject,...N(t)}),ef.lazycreate=(e,t)=>new ef({shape:e,unknownKeys:"strip",catchall:ec.create(),typeName:n.ZodObject,...N(t)});class em extends R{_parse(e){let{ctx:t}=this._processInputParams(e),r=this._def.options;if(t.common.async)return Promise.all(r.map(async e=>{let r={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:r}),ctx:r}})).then(function(e){for(let t of e)if("valid"===t.result.status)return t.result;for(let r of e)if("dirty"===r.result.status)return t.common.issues.push(...r.ctx.common.issues),r.result;let r=e.map(e=>new v(e.ctx.common.issues));return S(t,{code:y.invalid_union,unionErrors:r}),E});{let e,a=[];for(let n of r){let r={...t,common:{...t.common,issues:[]},parent:null},i=n._parseSync({data:t.data,path:t.path,parent:r});if("valid"===i.status)return i;"dirty"!==i.status||e||(e={result:i,ctx:r}),r.common.issues.length&&a.push(r.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;let n=a.map(e=>new v(e));return S(t,{code:y.invalid_union,unionErrors:n}),E}}get options(){return this._def.options}}em.create=(e,t)=>new em({options:e,typeName:n.ZodUnion,...N(t)});let eg=e=>{if(e instanceof eS)return eg(e.schema);if(e instanceof eO)return eg(e.innerType());if(e instanceof e$)return[e.value];if(e instanceof eT)return e.options;if(e instanceof eA)return t.objectValues(e.enum);else if(e instanceof eP)return eg(e._def.innerType);else if(e instanceof eo)return[void 0];else if(e instanceof el)return[null];else if(e instanceof eI)return[void 0,...eg(e.unwrap())];else if(e instanceof ej)return[null,...eg(e.unwrap())];else if(e instanceof eM)return eg(e.unwrap());else if(e instanceof eZ)return eg(e.unwrap());else if(e instanceof ez)return eg(e._def.innerType);else return[]};class e_ extends R{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==g.object)return S(t,{code:y.invalid_type,expected:g.object,received:t.parsedType}),E;let r=this.discriminator,a=t.data[r],n=this.optionsMap.get(a);return n?t.common.async?n._parseAsync({data:t.data,path:t.path,parent:t}):n._parseSync({data:t.data,path:t.path,parent:t}):(S(t,{code:y.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),E)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){let a=new Map;for(let r of t){let t=eg(r.shape[e]);if(!t.length)throw Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let n of t){if(a.has(n))throw Error(`Discriminator property ${String(e)} has duplicate value ${String(n)}`);a.set(n,r)}}return new e_({typeName:n.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:a,...N(r)})}}class ey extends R{_parse(e){let{status:r,ctx:a}=this._processInputParams(e),n=(e,n)=>{if(C(e)||C(n))return E;let i=function e(r,a){let n=_(r),i=_(a);if(r===a)return{valid:!0,data:r};if(n===g.object&&i===g.object){let n=t.objectKeys(a),i=t.objectKeys(r).filter(e=>-1!==n.indexOf(e)),s={...r,...a};for(let t of i){let n=e(r[t],a[t]);if(!n.valid)return{valid:!1};s[t]=n.data}return{valid:!0,data:s}}if(n===g.array&&i===g.array){if(r.length!==a.length)return{valid:!1};let t=[];for(let n=0;nn(e,t)):n(this._def.left._parseSync({data:a.data,path:a.path,parent:a}),this._def.right._parseSync({data:a.data,path:a.path,parent:a}))}}ey.create=(e,t,r)=>new ey({left:e,right:t,typeName:n.ZodIntersection,...N(r)});class ev extends R{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==g.array)return S(r,{code:y.invalid_type,expected:g.array,received:r.parsedType}),E;if(r.data.lengththis._def.items.length&&(S(r,{code:y.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let a=[...r.data].map((e,t)=>{let a=this._def.items[t]||this._def.rest;return a?a._parse(new P(r,e,r.path,t)):null}).filter(e=>!!e);return r.common.async?Promise.all(a).then(e=>$.mergeArray(t,e)):$.mergeArray(t,a)}get items(){return this._def.items}rest(e){return new ev({...this._def,rest:e})}}ev.create=(e,t)=>{if(!Array.isArray(e))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new ev({items:e,typeName:n.ZodTuple,rest:null,...N(t)})};class eb extends R{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==g.object)return S(r,{code:y.invalid_type,expected:g.object,received:r.parsedType}),E;let a=[],n=this._def.keyType,i=this._def.valueType;for(let e in r.data)a.push({key:n._parse(new P(r,e,r.path,e)),value:i._parse(new P(r,r.data[e],r.path,e)),alwaysSet:e in r.data});return r.common.async?$.mergeObjectAsync(t,a):$.mergeObjectSync(t,a)}get element(){return this._def.valueType}static create(e,t,r){return new eb(t instanceof R?{keyType:e,valueType:t,typeName:n.ZodRecord,...N(r)}:{keyType:et.create(),valueType:e,typeName:n.ZodRecord,...N(t)})}}class ew extends R{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==g.map)return S(r,{code:y.invalid_type,expected:g.map,received:r.parsedType}),E;let a=this._def.keyType,n=this._def.valueType,i=[...r.data.entries()].map(([e,t],i)=>({key:a._parse(new P(r,e,r.path,[i,"key"])),value:n._parse(new P(r,t,r.path,[i,"value"]))}));if(r.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let r of i){let a=await r.key,n=await r.value;if("aborted"===a.status||"aborted"===n.status)return E;("dirty"===a.status||"dirty"===n.status)&&t.dirty(),e.set(a.value,n.value)}return{status:t.value,value:e}})}{let e=new Map;for(let r of i){let a=r.key,n=r.value;if("aborted"===a.status||"aborted"===n.status)return E;("dirty"===a.status||"dirty"===n.status)&&t.dirty(),e.set(a.value,n.value)}return{status:t.value,value:e}}}}ew.create=(e,t,r)=>new ew({valueType:t,keyType:e,typeName:n.ZodMap,...N(r)});class ek extends R{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==g.set)return S(r,{code:y.invalid_type,expected:g.set,received:r.parsedType}),E;let a=this._def;null!==a.minSize&&r.data.sizea.maxSize.value&&(S(r,{code:y.too_big,maximum:a.maxSize.value,type:"set",inclusive:!0,exact:!1,message:a.maxSize.message}),t.dirty());let n=this._def.valueType;function i(e){let r=new Set;for(let a of e){if("aborted"===a.status)return E;"dirty"===a.status&&t.dirty(),r.add(a.value)}return{status:t.value,value:r}}let s=[...r.data.values()].map((e,t)=>n._parse(new P(r,e,r.path,t)));return r.common.async?Promise.all(s).then(e=>i(e)):i(s)}min(e,t){return new ek({...this._def,minSize:{value:e,message:a.toString(t)}})}max(e,t){return new ek({...this._def,maxSize:{value:e,message:a.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}ek.create=(e,t)=>new ek({valueType:e,minSize:null,maxSize:null,typeName:n.ZodSet,...N(t)});class ex extends R{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==g.function)return S(t,{code:y.invalid_type,expected:g.function,received:t.parsedType}),E;function r(e,r){return x({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,k(),b].filter(e=>!!e),issueData:{code:y.invalid_arguments,argumentsError:r}})}function a(e,r){return x({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,k(),b].filter(e=>!!e),issueData:{code:y.invalid_return_type,returnTypeError:r}})}let n={errorMap:t.common.contextualErrorMap},i=t.data;if(this._def.returns instanceof eC){let e=this;return A(async function(...t){let s=new v([]),o=await e._def.args.parseAsync(t,n).catch(e=>{throw s.addIssue(r(t,e)),s}),l=await Reflect.apply(i,this,o);return await e._def.returns._def.type.parseAsync(l,n).catch(e=>{throw s.addIssue(a(l,e)),s})})}{let e=this;return A(function(...t){let s=e._def.args.safeParse(t,n);if(!s.success)throw new v([r(t,s.error)]);let o=Reflect.apply(i,this,s.data),l=e._def.returns.safeParse(o,n);if(!l.success)throw new v([a(o,l.error)]);return l.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new ex({...this._def,args:ev.create(e).rest(ed.create())})}returns(e){return new ex({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,r){return new ex({args:e||ev.create([]).rest(ed.create()),returns:t||ed.create(),typeName:n.ZodFunction,...N(r)})}}class eS extends R{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}eS.create=(e,t)=>new eS({getter:e,typeName:n.ZodLazy,...N(t)});class e$ extends R{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return S(t,{received:t.data,code:y.invalid_literal,expected:this._def.value}),E}return{status:"valid",value:e.data}}get value(){return this._def.value}}function eE(e,t){return new eT({values:e,typeName:n.ZodEnum,...N(t)})}e$.create=(e,t)=>new e$({value:e,typeName:n.ZodLiteral,...N(t)});class eT extends R{_parse(e){if("string"!=typeof e.data){let r=this._getOrReturnCtx(e),a=this._def.values;return S(r,{expected:t.joinValues(a),received:r.parsedType,code:y.invalid_type}),E}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),r=this._def.values;return S(t,{received:t.data,code:y.invalid_enum_value,options:r}),E}return A(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return eT.create(e,{...this._def,...t})}exclude(e,t=this._def){return eT.create(this.options.filter(t=>!e.includes(t)),{...this._def,...t})}}eT.create=eE;class eA extends R{_parse(e){let r=t.getValidEnumValues(this._def.values),a=this._getOrReturnCtx(e);if(a.parsedType!==g.string&&a.parsedType!==g.number){let e=t.objectValues(r);return S(a,{expected:t.joinValues(e),received:a.parsedType,code:y.invalid_type}),E}if(this._cache||(this._cache=new Set(t.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let e=t.objectValues(r);return S(a,{received:a.data,code:y.invalid_enum_value,options:e}),E}return A(e.data)}get enum(){return this._def.values}}eA.create=(e,t)=>new eA({values:e,typeName:n.ZodNativeEnum,...N(t)});class eC extends R{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==g.promise&&!1===t.common.async?(S(t,{code:y.invalid_type,expected:g.promise,received:t.parsedType}),E):A((t.parsedType===g.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}eC.create=(e,t)=>new eC({type:e,typeName:n.ZodPromise,...N(t)});class eO extends R{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===n.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:a}=this._processInputParams(e),n=this._def.effect||null,i={addIssue:e=>{S(a,e),e.fatal?r.abort():r.dirty()},get path(){return a.path}};if(i.addIssue=i.addIssue.bind(i),"preprocess"===n.type){let e=n.transform(a.data,i);if(a.common.async)return Promise.resolve(e).then(async e=>{if("aborted"===r.value)return E;let t=await this._def.schema._parseAsync({data:e,path:a.path,parent:a});return"aborted"===t.status?E:"dirty"===t.status||"dirty"===r.value?T(t.value):t});{if("aborted"===r.value)return E;let t=this._def.schema._parseSync({data:e,path:a.path,parent:a});return"aborted"===t.status?E:"dirty"===t.status||"dirty"===r.value?T(t.value):t}}if("refinement"===n.type){let e=e=>{let t=n.refinement(e,i);if(a.common.async)return Promise.resolve(t);if(t instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1!==a.common.async)return this._def.schema._parseAsync({data:a.data,path:a.path,parent:a}).then(t=>"aborted"===t.status?E:("dirty"===t.status&&r.dirty(),e(t.value).then(()=>({status:r.value,value:t.value}))));{let t=this._def.schema._parseSync({data:a.data,path:a.path,parent:a});return"aborted"===t.status?E:("dirty"===t.status&&r.dirty(),e(t.value),{status:r.value,value:t.value})}}if("transform"===n.type)if(!1!==a.common.async)return this._def.schema._parseAsync({data:a.data,path:a.path,parent:a}).then(e=>I(e)?Promise.resolve(n.transform(e.value,i)).then(e=>({status:r.value,value:e})):E);else{let e=this._def.schema._parseSync({data:a.data,path:a.path,parent:a});if(!I(e))return E;let t=n.transform(e.value,i);if(t instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:t}}t.assertNever(n)}}eO.create=(e,t,r)=>new eO({schema:e,typeName:n.ZodEffects,effect:t,...N(r)}),eO.createWithPreprocess=(e,t,r)=>new eO({schema:t,effect:{type:"preprocess",transform:e},typeName:n.ZodEffects,...N(r)});class eI extends R{_parse(e){return this._getType(e)===g.undefined?A(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}eI.create=(e,t)=>new eI({innerType:e,typeName:n.ZodOptional,...N(t)});class ej extends R{_parse(e){return this._getType(e)===g.null?A(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ej.create=(e,t)=>new ej({innerType:e,typeName:n.ZodNullable,...N(t)});class eP extends R{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return t.parsedType===g.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}eP.create=(e,t)=>new eP({innerType:e,typeName:n.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...N(t)});class ez extends R{_parse(e){let{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},a=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return j(a)?a.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new v(r.common.issues)},input:r.data})})):{status:"valid",value:"valid"===a.status?a.value:this._def.catchValue({get error(){return new v(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}ez.create=(e,t)=>new ez({innerType:e,typeName:n.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...N(t)});class eN extends R{_parse(e){if(this._getType(e)!==g.nan){let t=this._getOrReturnCtx(e);return S(t,{code:y.invalid_type,expected:g.nan,received:t.parsedType}),E}return{status:"valid",value:e.data}}}eN.create=e=>new eN({typeName:n.ZodNaN,...N(e)});let eR=Symbol("zod_brand");class eM extends R{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}}class eL extends R{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let e=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?E:"dirty"===e.status?(t.dirty(),T(e.value)):this._def.out._parseAsync({data:e.value,path:r.path,parent:r})})();{let e=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?E:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:r.path,parent:r})}}static create(e,t){return new eL({in:e,out:t,typeName:n.ZodPipeline})}}class eZ extends R{_parse(e){let t=this._def.innerType._parse(e),r=e=>(I(e)&&(e.value=Object.freeze(e.value)),e);return j(t)?t.then(e=>r(e)):r(t)}unwrap(){return this._def.innerType}}function eD(e,t){let r="function"==typeof e?e(t):"string"==typeof e?{message:e}:e;return"string"==typeof r?{message:r}:r}function eU(e,t={},r){return e?eu.create().superRefine((a,n)=>{let i=e(a);if(i instanceof Promise)return i.then(e=>{if(!e){let e=eD(t,a),i=e.fatal??r??!0;n.addIssue({code:"custom",...e,fatal:i})}});if(!i){let e=eD(t,a),i=e.fatal??r??!0;n.addIssue({code:"custom",...e,fatal:i})}}):eu.create()}eZ.create=(e,t)=>new eZ({innerType:e,typeName:n.ZodReadonly,...N(t)});let eB={object:ef.lazycreate};(o=n||(n={})).ZodString="ZodString",o.ZodNumber="ZodNumber",o.ZodNaN="ZodNaN",o.ZodBigInt="ZodBigInt",o.ZodBoolean="ZodBoolean",o.ZodDate="ZodDate",o.ZodSymbol="ZodSymbol",o.ZodUndefined="ZodUndefined",o.ZodNull="ZodNull",o.ZodAny="ZodAny",o.ZodUnknown="ZodUnknown",o.ZodNever="ZodNever",o.ZodVoid="ZodVoid",o.ZodArray="ZodArray",o.ZodObject="ZodObject",o.ZodUnion="ZodUnion",o.ZodDiscriminatedUnion="ZodDiscriminatedUnion",o.ZodIntersection="ZodIntersection",o.ZodTuple="ZodTuple",o.ZodRecord="ZodRecord",o.ZodMap="ZodMap",o.ZodSet="ZodSet",o.ZodFunction="ZodFunction",o.ZodLazy="ZodLazy",o.ZodLiteral="ZodLiteral",o.ZodEnum="ZodEnum",o.ZodEffects="ZodEffects",o.ZodNativeEnum="ZodNativeEnum",o.ZodOptional="ZodOptional",o.ZodNullable="ZodNullable",o.ZodDefault="ZodDefault",o.ZodCatch="ZodCatch",o.ZodPromise="ZodPromise",o.ZodBranded="ZodBranded",o.ZodPipeline="ZodPipeline",o.ZodReadonly="ZodReadonly";let eF=et.create,eH=er.create,eq=eN.create,eJ=ea.create,eG=en.create,eW=ei.create,eV=es.create,eK=eo.create,eY=el.create,eQ=eu.create,eX=ed.create,e0=ec.create,e1=eh.create,e4=ep.create,e2=ef.create,e9=ef.strictCreate,e6=em.create,e5=e_.create,e3=ey.create,e8=ev.create,e7=eb.create,te=ew.create,tt=ek.create,tr=ex.create,ta=eS.create,tn=e$.create,ti=eT.create,ts=eA.create,to=eC.create,tl=eO.create,tu=eI.create,td=ej.create,tc=eO.createWithPreprocess,th=eL.create;function tp(e,t){return tz(e.type._def,t)}e.s(["BRAND",0,eR,"NEVER",0,E,"Schema",0,R,"ZodAny",0,eu,"ZodArray",0,ep,"ZodBigInt",0,ea,"ZodBoolean",0,en,"ZodBranded",0,eM,"ZodCatch",0,ez,"ZodDate",0,ei,"ZodDefault",0,eP,"ZodDiscriminatedUnion",0,e_,"ZodEffects",0,eO,"ZodEnum",0,eT,"ZodFirstPartyTypeKind",0,n,"ZodFunction",0,ex,"ZodIntersection",0,ey,"ZodLazy",0,eS,"ZodLiteral",0,e$,"ZodMap",0,ew,"ZodNaN",0,eN,"ZodNativeEnum",0,eA,"ZodNever",0,ec,"ZodNull",0,el,"ZodNullable",0,ej,"ZodNumber",0,er,"ZodObject",0,ef,"ZodOptional",0,eI,"ZodPipeline",0,eL,"ZodPromise",0,eC,"ZodReadonly",0,eZ,"ZodRecord",0,eb,"ZodSchema",0,R,"ZodSet",0,ek,"ZodString",0,et,"ZodSymbol",0,es,"ZodTransformer",0,eO,"ZodTuple",0,ev,"ZodType",0,R,"ZodUndefined",0,eo,"ZodUnion",0,em,"ZodUnknown",0,ed,"ZodVoid",0,eh,"any",0,eQ,"array",0,e4,"bigint",0,eJ,"boolean",0,eG,"coerce",0,{string:e=>et.create({...e,coerce:!0}),number:e=>er.create({...e,coerce:!0}),boolean:e=>en.create({...e,coerce:!0}),bigint:e=>ea.create({...e,coerce:!0}),date:e=>ei.create({...e,coerce:!0})},"custom",0,eU,"date",0,eW,"datetimeRegex",0,ee,"discriminatedUnion",0,e5,"effect",0,tl,"enum",0,ti,"function",0,tr,"instanceof",0,(e,t={message:`Input not instance of ${e.name}`})=>eU(t=>t instanceof e,t),"intersection",0,e3,"late",0,eB,"lazy",0,ta,"literal",0,tn,"map",0,te,"nan",0,eq,"nativeEnum",0,ts,"never",0,e0,"null",0,eY,"nullable",0,td,"number",0,eH,"object",0,e2,"oboolean",0,()=>eG().optional(),"onumber",0,()=>eH().optional(),"optional",0,tu,"ostring",0,()=>eF().optional(),"pipeline",0,th,"preprocess",0,tc,"promise",0,to,"record",0,e7,"set",0,tt,"strictObject",0,e9,"string",0,eF,"symbol",0,eV,"transformer",0,tl,"tuple",0,e8,"undefined",0,eK,"union",0,e6,"unknown",0,eX,"void",0,e1],117958);let tf=/^[cC][^\s-]{8,}$/,tm=/^[0-9a-z]+$/,tg=/^[0-9A-HJKMNP-TV-Z]{26}$/,t_=/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,ty=()=>(void 0===u&&(u=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),u),tv=/^(?:(?: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])$/,tb=/^(([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])$/,tw=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,tk=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,tx=/^[a-zA-Z0-9_-]{21}$/,tS=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;function t$(e,t){let r={type:"string"};if(e.checks)for(let a of e.checks)switch(a.kind){case"min":m(r,"minLength","number"==typeof r.minLength?Math.max(r.minLength,a.value):a.value,a.message,t);break;case"max":m(r,"maxLength","number"==typeof r.maxLength?Math.min(r.maxLength,a.value):a.value,a.message,t);break;case"email":switch(t.emailStrategy){case"format:email":tA(r,"email",a.message,t);break;case"format:idn-email":tA(r,"idn-email",a.message,t);break;case"pattern:zod":tC(r,t_,a.message,t)}break;case"url":tA(r,"uri",a.message,t);break;case"uuid":tA(r,"uuid",a.message,t);break;case"regex":tC(r,a.regex,a.message,t);break;case"cuid":tC(r,tf,a.message,t);break;case"cuid2":tC(r,tm,a.message,t);break;case"startsWith":tC(r,RegExp(`^${tE(a.value,t)}`),a.message,t);break;case"endsWith":tC(r,RegExp(`${tE(a.value,t)}$`),a.message,t);break;case"datetime":tA(r,"date-time",a.message,t);break;case"date":tA(r,"date",a.message,t);break;case"time":tA(r,"time",a.message,t);break;case"duration":tA(r,"duration",a.message,t);break;case"length":m(r,"minLength","number"==typeof r.minLength?Math.max(r.minLength,a.value):a.value,a.message,t),m(r,"maxLength","number"==typeof r.maxLength?Math.min(r.maxLength,a.value):a.value,a.message,t);break;case"includes":tC(r,RegExp(tE(a.value,t)),a.message,t);break;case"ip":"v6"!==a.version&&tA(r,"ipv4",a.message,t),"v4"!==a.version&&tA(r,"ipv6",a.message,t);break;case"base64url":tC(r,tk,a.message,t);break;case"jwt":tC(r,tS,a.message,t);break;case"cidr":"v6"!==a.version&&tC(r,tv,a.message,t),"v4"!==a.version&&tC(r,tb,a.message,t);break;case"emoji":tC(r,ty(),a.message,t);break;case"ulid":tC(r,tg,a.message,t);break;case"base64":switch(t.base64Strategy){case"format:binary":tA(r,"binary",a.message,t);break;case"contentEncoding:base64":m(r,"contentEncoding","base64",a.message,t);break;case"pattern:zod":tC(r,tw,a.message,t)}break;case"nanoid":tC(r,tx,a.message,t)}return r}function tE(e,t){return"escape"===t.patternStrategy?function(e){let t="";for(let r=0;re.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&a.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.anyOf.push({format:t,...r&&a.errorMessages&&{errorMessage:{format:r}}})):m(e,"format",t,r,a)}function tC(e,t,r,a){e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&a.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.allOf.push({pattern:tO(t,a),...r&&a.errorMessages&&{errorMessage:{pattern:r}}})):m(e,"pattern",tO(t,a),r,a)}function tO(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let r={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},a=r.i?e.source.toLowerCase():e.source,n="",i=!1,s=!1,o=!1;for(let e=0;e({...r,[a]:tz(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",a]})??p(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let r={type:"object",additionalProperties:tz(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if("openApi3"===t.target)return r;if(e.keyType?._def.typeName===n.ZodString&&e.keyType._def.checks?.length){let{type:a,...n}=t$(e.keyType._def,t);return{...r,propertyNames:n}}if(e.keyType?._def.typeName===n.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===n.ZodBranded&&e.keyType._def.type._def.typeName===n.ZodString&&e.keyType._def.type._def.checks?.length){let{type:a,...n}=tp(e.keyType._def,t);return{...r,propertyNames:n}}return r}let tj={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"},tP=(e,t)=>{let r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,r)=>tz(e._def,{...t,currentPath:[...t.currentPath,"anyOf",`${r}`]})).filter(e=>!!e&&(!t.strictUnions||"object"==typeof e&&Object.keys(e).length>0));return r.length?{anyOf:r}:void 0};function tz(e,t,r=!1){let a=t.seen.get(e);if(t.override){let n=t.override?.(e,t,a,r);if(n!==d)return n}if(a&&!r){let e=tN(a,t);if(void 0!==e)return e}let i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);let s=((e,t,r)=>{switch(t){case n.ZodString:return t$(e,r);case n.ZodNumber:let a={type:"number"};if(!e.checks)return a;for(let t of e.checks)switch(t.kind){case"int":a.type="integer",f(a,"type",t.message,r);break;case"min":"jsonSchema7"===r.target?t.inclusive?m(a,"minimum",t.value,t.message,r):m(a,"exclusiveMinimum",t.value,t.message,r):(t.inclusive||(a.exclusiveMinimum=!0),m(a,"minimum",t.value,t.message,r));break;case"max":"jsonSchema7"===r.target?t.inclusive?m(a,"maximum",t.value,t.message,r):m(a,"exclusiveMaximum",t.value,t.message,r):(t.inclusive||(a.exclusiveMaximum=!0),m(a,"maximum",t.value,t.message,r));break;case"multipleOf":m(a,"multipleOf",t.value,t.message,r)}return a;case n.ZodObject:return function(e,t){let r="openAi"===t.target,a={type:"object",properties:{}},n=[],i=e.shape();for(let e in i){let s=i[e];if(void 0===s||void 0===s._def)continue;let o=function(e){try{return e.isOptional()}catch{return!0}}(s);o&&r&&("ZodOptional"===s._def.typeName&&(s=s._def.innerType),s.isNullable()||(s=s.nullable()),o=!1);let l=tz(s._def,{...t,currentPath:[...t.currentPath,"properties",e],propertyPath:[...t.currentPath,"properties",e]});void 0!==l&&(a.properties[e]=l,o||n.push(e))}n.length&&(a.required=n);let s=function(e,t){if("ZodNever"!==e.catchall._def.typeName)return tz(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return"strict"===t.removeAdditionalStrategy?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}(e,t);return void 0!==s&&(a.additionalProperties=s),a}(e,r);case n.ZodBigInt:let i={type:"integer",format:"int64"};if(!e.checks)return i;for(let t of e.checks)switch(t.kind){case"min":"jsonSchema7"===r.target?t.inclusive?m(i,"minimum",t.value,t.message,r):m(i,"exclusiveMinimum",t.value,t.message,r):(t.inclusive||(i.exclusiveMinimum=!0),m(i,"minimum",t.value,t.message,r));break;case"max":"jsonSchema7"===r.target?t.inclusive?m(i,"maximum",t.value,t.message,r):m(i,"exclusiveMaximum",t.value,t.message,r):(t.inclusive||(i.exclusiveMaximum=!0),m(i,"maximum",t.value,t.message,r));break;case"multipleOf":m(i,"multipleOf",t.value,t.message,r)}return i;case n.ZodBoolean:return{type:"boolean"};case n.ZodDate:return function e(t,r,a){let n=a??r.dateStrategy;if(Array.isArray(n))return{anyOf:n.map(a=>e(t,r,a))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":var i=t,s=r;let o={type:"integer",format:"unix-time"};if("openApi3"===s.target)return o;for(let e of i.checks)switch(e.kind){case"min":m(o,"minimum",e.value,e.message,s);break;case"max":m(o,"maximum",e.value,e.message,s)}return o}}(e,r);case n.ZodUndefined:return{not:p(r)};case n.ZodNull:return"openApi3"===r.target?{enum:["null"],nullable:!0}:{type:"null"};case n.ZodArray:let s;return s={type:"array"},e.type?._def&&e.type?._def?.typeName!==n.ZodAny&&(s.items=tz(e.type._def,{...r,currentPath:[...r.currentPath,"items"]})),e.minLength&&m(s,"minItems",e.minLength.value,e.minLength.message,r),e.maxLength&&m(s,"maxItems",e.maxLength.value,e.maxLength.message,r),e.exactLength&&(m(s,"minItems",e.exactLength.value,e.exactLength.message,r),m(s,"maxItems",e.exactLength.value,e.exactLength.message,r)),s;case n.ZodUnion:case n.ZodDiscriminatedUnion:if("openApi3"===r.target)return tP(e,r);let o=e.options instanceof Map?Array.from(e.options.values()):e.options;if(o.every(e=>e._def.typeName in tj&&(!e._def.checks||!e._def.checks.length))){let e=o.reduce((e,t)=>{let r=tj[t._def.typeName];return r&&!e.includes(r)?[...e,r]:e},[]);return{type:e.length>1?e:e[0]}}if(o.every(e=>"ZodLiteral"===e._def.typeName&&!e.description)){let e=o.reduce((e,t)=>{let r=typeof t._def.value;switch(r){case"string":case"number":case"boolean":return[...e,r];case"bigint":return[...e,"integer"];case"object":if(null===t._def.value)return[...e,"null"];return e;default:return e}},[]);if(e.length===o.length){let t=e.filter((e,t,r)=>r.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:o.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(o.every(e=>"ZodEnum"===e._def.typeName))return{type:"string",enum:o.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return tP(e,r);case n.ZodIntersection:let l,u,d;return l=[tz(e.left._def,{...r,currentPath:[...r.currentPath,"allOf","0"]}),tz(e.right._def,{...r,currentPath:[...r.currentPath,"allOf","1"]})].filter(e=>!!e),u="jsonSchema2019-09"===r.target?{unevaluatedProperties:!1}:void 0,d=[],l.forEach(e=>{if((!("type"in e)||"string"!==e.type)&&"allOf"in e)d.push(...e.allOf),void 0===e.unevaluatedProperties&&(u=void 0);else{let t=e;if("additionalProperties"in e&&!1===e.additionalProperties){let{additionalProperties:r,...a}=e;t=a}else u=void 0;d.push(t)}}),d.length?{allOf:d,...u}:void 0;case n.ZodTuple:return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((e,t)=>tz(e._def,{...r,currentPath:[...r.currentPath,"items",`${t}`]})).reduce((e,t)=>void 0===t?e:[...e,t],[]),additionalItems:tz(e.rest._def,{...r,currentPath:[...r.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,t)=>tz(e._def,{...r,currentPath:[...r.currentPath,"items",`${t}`]})).reduce((e,t)=>void 0===t?e:[...e,t],[])};case n.ZodRecord:return tI(e,r);case n.ZodLiteral:let c;return"bigint"!=(c=typeof e.value)&&"number"!==c&&"boolean"!==c&&"string"!==c?{type:Array.isArray(e.value)?"array":"object"}:"openApi3"===r.target?{type:"bigint"===c?"integer":c,enum:[e.value]}:{type:"bigint"===c?"integer":c,const:e.value};case n.ZodEnum:return{type:"string",enum:Array.from(e.values)};case n.ZodNativeEnum:let h,g,_;return h=e.values,{type:1===(_=Array.from(new Set((g=Object.keys(e.values).filter(e=>"number"!=typeof h[h[e]]).map(e=>h[e])).map(e=>typeof e)))).length?"string"===_[0]?"string":"number":["string","number"],enum:g};case n.ZodNullable:if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return"openApi3"===r.target?{type:tj[e.innerType._def.typeName],nullable:!0}:{type:[tj[e.innerType._def.typeName],"null"]};if("openApi3"===r.target){let t=tz(e.innerType._def,{...r,currentPath:[...r.currentPath]});return t&&"$ref"in t?{allOf:[t],nullable:!0}:t&&{...t,nullable:!0}}let y=tz(e.innerType._def,{...r,currentPath:[...r.currentPath,"anyOf","0"]});return y&&{anyOf:[y,{type:"null"}]};case n.ZodOptional:if(r.currentPath.toString()===r.propertyPath?.toString())return tz(e.innerType._def,r);let v=tz(e.innerType._def,{...r,currentPath:[...r.currentPath,"anyOf","1"]});return v?{anyOf:[{not:p(r)},v]}:p(r);case n.ZodMap:return"record"===r.mapStrategy?tI(e,r):{type:"array",maxItems:125,items:{type:"array",items:[tz(e.keyType._def,{...r,currentPath:[...r.currentPath,"items","items","0"]})||p(r),tz(e.valueType._def,{...r,currentPath:[...r.currentPath,"items","items","1"]})||p(r)],minItems:2,maxItems:2}};case n.ZodSet:let b;return b={type:"array",uniqueItems:!0,items:tz(e.valueType._def,{...r,currentPath:[...r.currentPath,"items"]})},e.minSize&&m(b,"minItems",e.minSize.value,e.minSize.message,r),e.maxSize&&m(b,"maxItems",e.maxSize.value,e.maxSize.message,r),b;case n.ZodLazy:return()=>e.getter()._def;case n.ZodPromise:return tz(e.type._def,r);case n.ZodNaN:case n.ZodNever:return"openAi"===r.target?void 0:{not:p({...r,currentPath:[...r.currentPath,"not"]})};case n.ZodEffects:return"input"===r.effectStrategy?tz(e.schema._def,r):p(r);case n.ZodAny:case n.ZodUnknown:return p(r);case n.ZodDefault:return{...tz(e.innerType._def,r),default:e.defaultValue()};case n.ZodBranded:return tp(e,r);case n.ZodReadonly:case n.ZodCatch:return tz(e.innerType._def,r);case n.ZodPipeline:if("input"===r.pipeStrategy)return tz(e.in._def,r);if("output"===r.pipeStrategy)return tz(e.out._def,r);let w=tz(e.in._def,{...r,currentPath:[...r.currentPath,"allOf","0"]});return{allOf:[w,tz(e.out._def,{...r,currentPath:[...r.currentPath,"allOf",w?"1":"0"]})].filter(e=>void 0!==e)};case n.ZodFunction:case n.ZodVoid:case n.ZodSymbol:default:return}})(e,e.typeName,t),o="function"==typeof s?tz(s(),t):s;if(o&&tR(e,t,o),t.postProcess){let r=t.postProcess(o,e,t);return i.jsonSchema=o,r}return i.jsonSchema=o,o}let tN=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:h(t.currentPath,e.path)};case"none":case"seen":if(e.path.lengtht.currentPath[r]===e))return console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),p(t);return"seen"===t.$refStrategy?p(t):void 0}},tR=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r);e.s(["zodToJsonSchema",0,(e,t)=>{let r,a,n=(a=void 0!==(r="string"==typeof t?{...c,name:t}:{...c,...t}).name?[...r.basePath,r.definitionPath,r.name]:r.basePath,{...r,flags:{hasReferencedOpenAiAnyType:!1},currentPath:a,propertyPath:void 0,seen:new Map(Object.entries(r.definitions).map(([e,t])=>[t._def,{def:t._def,path:[...r.basePath,r.definitionPath,e],jsonSchema:void 0}]))}),i="object"==typeof t&&t.definitions?Object.entries(t.definitions).reduce((e,[t,r])=>({...e,[t]:tz(r._def,{...n,currentPath:[...n.basePath,n.definitionPath,t]},!0)??p(n)}),{}):void 0,s="string"==typeof t?t:t?.nameStrategy==="title"?void 0:t?.name,o=tz(e._def,void 0===s?n:{...n,currentPath:[...n.basePath,n.definitionPath,s]},!1)??p(n),l="object"==typeof t&&void 0!==t.name&&"title"===t.nameStrategy?t.name:void 0;void 0!==l&&(o.title=l),n.flags.hasReferencedOpenAiAnyType&&(i||(i={}),i[n.openAiAnyTypeName]||(i[n.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:"relative"===n.$refStrategy?"1":[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join("/")}}));let u=void 0===s?i?{...o,[n.definitionPath]:i}:o:{$ref:[..."relative"===n.$refStrategy?[]:n.basePath,n.definitionPath,s].join("/"),[n.definitionPath]:{...i,[s]:o}};return"jsonSchema7"===n.target?u.$schema="http://json-schema.org/draft-07/schema#":("jsonSchema2019-09"===n.target||"openAi"===n.target)&&(u.$schema="https://json-schema.org/draft/2019-09/schema#"),"openAi"===n.target&&("anyOf"in u||"oneOf"in u||"allOf"in u||"type"in u&&Array.isArray(u.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),u}],229335)},776401,e=>{"use strict";var t=(0,e.i(190949).__exportAll)({isSerializableSchema:()=>n,isStandardJsonSchema:()=>a,isStandardSchema:()=>r});function r(e){return("object"==typeof e||"function"==typeof e)&&null!==e&&"~standard"in e&&"object"==typeof e["~standard"]&&null!==e["~standard"]&&"validate"in e["~standard"]}function a(e){return("object"==typeof e||"function"==typeof e)&&null!==e&&"~standard"in e&&"object"==typeof e["~standard"]&&null!==e["~standard"]&&"jsonSchema"in e["~standard"]}function n(e){return r(e)&&a(e)}e.s(["isSerializableSchema",0,n,"isStandardJsonSchema",0,a,"standard_schema_exports",0,t])},785337,207159,865889,645668,370536,262144,e=>{"use strict";var t,r,a=e.i(190949),n=e.i(238073),i=e.i(229335),s=e.i(776401),o=e.i(52637);function l(e){let t=e?.target??"draft-2020-12";return"draft-4"===t&&(t="draft-04"),"draft-7"===t&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??o.globalRegistry,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function u(e,t,r={path:[],schemaPath:[]}){var a;let n=e._zod.def,i=t.seen.get(e);if(i)return i.count++,r.schemaPath.includes(e)&&(i.cycle=r.path),i.schema;let s={schema:{},count:1,cycle:void 0,path:r.path};t.seen.set(e,s);let o=e._zod.toJSONSchema?.();if(o)s.schema=o;else{let a={...r,schemaPath:[...r.schemaPath,e],path:r.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,s.schema,a);else{let r=s.schema,i=t.processors[n.type];if(!i)throw Error(`[toJSONSchema]: Non-representable type encountered: ${n.type}`);i(e,t,r,a)}let i=e._zod.parent;i&&(s.ref||(s.ref=i),u(i,t,a),t.seen.get(i).isParent=!0)}let l=t.metadataRegistry.get(e);return l&&Object.assign(s.schema,l),"input"===t.io&&function e(t,r){let a=r??{seen:new Set};if(a.seen.has(t))return!1;a.seen.add(t);let n=t._zod.def;if("transform"===n.type)return!0;if("array"===n.type)return e(n.element,a);if("set"===n.type)return e(n.valueType,a);if("lazy"===n.type)return e(n.getter(),a);if("promise"===n.type||"optional"===n.type||"nonoptional"===n.type||"nullable"===n.type||"readonly"===n.type||"default"===n.type||"prefault"===n.type)return e(n.innerType,a);if("intersection"===n.type)return e(n.left,a)||e(n.right,a);if("record"===n.type||"map"===n.type)return e(n.keyType,a)||e(n.valueType,a);if("pipe"===n.type)return!!t._zod.traits.has("$ZodCodec")||e(n.in,a)||e(n.out,a);if("object"===n.type){for(let t in n.shape)if(e(n.shape[t],a))return!0;return!1}if("union"===n.type){for(let t of n.options)if(e(t,a))return!0;return!1}if("tuple"===n.type){for(let t of n.items)if(e(t,a))return!0;if(n.rest&&e(n.rest,a))return!0}return!1}(e)&&(delete s.schema.examples,delete s.schema.default),"input"===t.io&&"_prefault"in s.schema&&((a=s.schema).default??(a.default=s.schema._prefault)),delete s.schema._prefault,t.seen.get(e).schema}function d(e,t){let r=e.seen.get(t);if(!r)throw Error("Unprocessed schema. This is a bug in Zod.");let a=new Map;for(let t of e.seen.entries()){let r=e.metadataRegistry.get(t[0])?.id;if(r){let e=a.get(r);if(e&&e!==t[0])throw Error(`Duplicate schema id "${r}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);a.set(r,t[0])}}let n=t=>{if(t[1].schema.$ref)return;let a=t[1],{ref:n,defId:i}=(t=>{let a="draft-2020-12"===e.target?"$defs":"definitions";if(e.external){let r=e.external.registry.get(t[0])?.id,n=e.external.uri??(e=>e);if(r)return{ref:n(r)};let i=t[1].defId??t[1].schema.id??`schema${e.counter++}`;return t[1].defId=i,{defId:i,ref:`${n("__shared")}#/${a}/${i}`}}if(t[1]===r)return{ref:"#"};let n=`#/${a}/`,i=t[1].schema.id??`__schema${e.counter++}`;return{defId:i,ref:n+i}})(t);a.def={...a.schema},i&&(a.defId=i);let s=a.schema;for(let e in s)delete s[e];s.$ref=n};if("throw"===e.cycles)for(let t of e.seen.entries()){let e=t[1];if(e.cycle)throw Error(`Cycle detected: #/${e.cycle?.join("/")}/ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let r of e.seen.entries()){let a=r[1];if(t===r[0]){n(r);continue}if(e.external){let a=e.external.registry.get(r[0])?.id;if(t!==r[0]&&a){n(r);continue}}if(e.metadataRegistry.get(r[0])?.id||a.cycle||a.count>1&&"ref"===e.reused){n(r);continue}}}function c(e,t){let r=e.seen.get(t);if(!r)throw Error("Unprocessed schema. This is a bug in Zod.");let a=t=>{let r=e.seen.get(t);if(null===r.ref)return;let n=r.def??r.schema,i={...n},s=r.ref;if(r.ref=null,s){a(s);let r=e.seen.get(s),o=r.schema;if(o.$ref&&("draft-07"===e.target||"draft-04"===e.target||"openapi-3.0"===e.target)?(n.allOf=n.allOf??[],n.allOf.push(o)):Object.assign(n,o),Object.assign(n,i),t._zod.parent===s)for(let e in n)"$ref"!==e&&"allOf"!==e&&(e in i||delete n[e]);if(o.$ref&&r.def)for(let e in n)"$ref"!==e&&"allOf"!==e&&e in r.def&&JSON.stringify(n[e])===JSON.stringify(r.def[e])&&delete n[e]}let o=t._zod.parent;if(o&&o!==s){a(o);let t=e.seen.get(o);if(t?.schema.$ref&&(n.$ref=t.schema.$ref,t.def))for(let e in n)"$ref"!==e&&"allOf"!==e&&e in t.def&&JSON.stringify(n[e])===JSON.stringify(t.def[e])&&delete n[e]}e.override({zodSchema:t,jsonSchema:n,path:r.path??[]})};for(let t of[...e.seen.entries()].reverse())a(t[0]);let n={};if("draft-2020-12"===e.target?n.$schema="https://json-schema.org/draft/2020-12/schema":"draft-07"===e.target?n.$schema="http://json-schema.org/draft-07/schema#":"draft-04"===e.target?n.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){let r=e.external.registry.get(t)?.id;if(!r)throw Error("Schema is missing an `id` property");n.$id=e.external.uri(r)}Object.assign(n,r.def??r.schema);let i=e.metadataRegistry.get(t)?.id;void 0!==i&&n.id===i&&delete n.id;let s=e.external?.defs??{};for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,s[e.defId]=e.def)}e.external||Object.keys(s).length>0&&("draft-2020-12"===e.target?n.$defs=s:n.definitions=s);try{let r=JSON.parse(JSON.stringify(n));return Object.defineProperty(r,"~standard",{value:{...t["~standard"],jsonSchema:{input:h(t,"input",e.processors),output:h(t,"output",e.processors)}},enumerable:!1,writable:!1}),r}catch(e){throw Error("Error converting schema to JSON.")}}let h=(e,t,r={})=>a=>{let{libraryOptions:n,target:i}=a??{},s=l({...n??{},target:i,io:t,processors:r});return u(e,s),d(s,e),c(s,e)};e.s(["createStandardJSONSchemaMethod",0,h,"createToJSONSchemaMethod",0,(e,t={})=>r=>{let a=l({...r,processors:t});return u(e,a),d(a,e),c(a,e)},"extractDefs",0,d,"finalize",0,c,"initializeContext",0,l,"process",0,u],207159);var p=e.i(486618);let f={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},m=(e,t,r,a)=>{r.type="string";let{minimum:n,maximum:i,format:s,patterns:o,contentEncoding:l}=e._zod.bag;if("number"==typeof n&&(r.minLength=n),"number"==typeof i&&(r.maxLength=i),s&&(r.format=f[s]??s,""===r.format&&delete r.format,"time"===s&&delete r.format),l&&(r.contentEncoding=l),o&&o.size>0){let e=[...o];1===e.length?r.pattern=e[0].source:e.length>1&&(r.allOf=[...e.map(e=>({..."draft-07"===t.target||"draft-04"===t.target||"openapi-3.0"===t.target?{type:"string"}:{},pattern:e.source}))])}},g=(e,t,r,a)=>{let{minimum:n,maximum:i,format:s,multipleOf:o,exclusiveMaximum:l,exclusiveMinimum:u}=e._zod.bag;"string"==typeof s&&s.includes("int")?r.type="integer":r.type="number";let d="number"==typeof u&&u>=(n??-1/0),c="number"==typeof l&&l<=(i??1/0),h="draft-04"===t.target||"openapi-3.0"===t.target;d?h?(r.minimum=u,r.exclusiveMinimum=!0):r.exclusiveMinimum=u:"number"==typeof n&&(r.minimum=n),c?h?(r.maximum=l,r.exclusiveMaximum=!0):r.exclusiveMaximum=l:"number"==typeof i&&(r.maximum=i),"number"==typeof o&&(r.multipleOf=o)},_=(e,t,r,a)=>{r.type="boolean"},y=(e,t,r,a)=>{if("throw"===t.unrepresentable)throw Error("BigInt cannot be represented in JSON Schema")},v=(e,t,r,a)=>{if("throw"===t.unrepresentable)throw Error("Symbols cannot be represented in JSON Schema")},b=(e,t,r,a)=>{"openapi-3.0"===t.target?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"},w=(e,t,r,a)=>{if("throw"===t.unrepresentable)throw Error("Undefined cannot be represented in JSON Schema")},k=(e,t,r,a)=>{if("throw"===t.unrepresentable)throw Error("Void cannot be represented in JSON Schema")},x=(e,t,r,a)=>{r.not={}},S=(e,t,r,a)=>{},$=(e,t,r,a)=>{},E=(e,t,r,a)=>{if("throw"===t.unrepresentable)throw Error("Date cannot be represented in JSON Schema")},T=(e,t,r,a)=>{let n=e._zod.def,i=(0,p.getEnumValues)(n.entries);i.every(e=>"number"==typeof e)&&(r.type="number"),i.every(e=>"string"==typeof e)&&(r.type="string"),r.enum=i},A=(e,t,r,a)=>{let n=e._zod.def,i=[];for(let e of n.values)if(void 0===e){if("throw"===t.unrepresentable)throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if("bigint"==typeof e)if("throw"===t.unrepresentable)throw Error("BigInt literals cannot be represented in JSON Schema");else i.push(Number(e));else i.push(e);if(0===i.length);else if(1===i.length){let e=i[0];r.type=null===e?"null":typeof e,"draft-04"===t.target||"openapi-3.0"===t.target?r.enum=[e]:r.const=e}else i.every(e=>"number"==typeof e)&&(r.type="number"),i.every(e=>"string"==typeof e)&&(r.type="string"),i.every(e=>"boolean"==typeof e)&&(r.type="boolean"),i.every(e=>null===e)&&(r.type="null"),r.enum=i},C=(e,t,r,a)=>{if("throw"===t.unrepresentable)throw Error("NaN cannot be represented in JSON Schema")},O=(e,t,r,a)=>{let n=e._zod.pattern;if(!n)throw Error("Pattern not found in template literal");r.type="string",r.pattern=n.source},I=(e,t,r,a)=>{let n={type:"string",format:"binary",contentEncoding:"binary"},{minimum:i,maximum:s,mime:o}=e._zod.bag;void 0!==i&&(n.minLength=i),void 0!==s&&(n.maxLength=s),o?1===o.length?(n.contentMediaType=o[0],Object.assign(r,n)):(Object.assign(r,n),r.anyOf=o.map(e=>({contentMediaType:e}))):Object.assign(r,n)},j=(e,t,r,a)=>{r.type="boolean"},P=(e,t,r,a)=>{if("throw"===t.unrepresentable)throw Error("Custom types cannot be represented in JSON Schema")},z=(e,t,r,a)=>{if("throw"===t.unrepresentable)throw Error("Function types cannot be represented in JSON Schema")},N=(e,t,r,a)=>{if("throw"===t.unrepresentable)throw Error("Transforms cannot be represented in JSON Schema")},R=(e,t,r,a)=>{if("throw"===t.unrepresentable)throw Error("Map cannot be represented in JSON Schema")},M=(e,t,r,a)=>{if("throw"===t.unrepresentable)throw Error("Set cannot be represented in JSON Schema")},L=(e,t,r,a)=>{let n=e._zod.def,{minimum:i,maximum:s}=e._zod.bag;"number"==typeof i&&(r.minItems=i),"number"==typeof s&&(r.maxItems=s),r.type="array",r.items=u(n.element,t,{...a,path:[...a.path,"items"]})},Z=(e,t,r,a)=>{let n=e._zod.def;r.type="object",r.properties={};let i=n.shape;for(let e in i)r.properties[e]=u(i[e],t,{...a,path:[...a.path,"properties",e]});let s=new Set([...new Set(Object.keys(i))].filter(e=>{let r=n.shape[e]._zod;return"input"===t.io?void 0===r.optin:void 0===r.optout}));s.size>0&&(r.required=Array.from(s)),n.catchall?._zod.def.type==="never"?r.additionalProperties=!1:n.catchall?n.catchall&&(r.additionalProperties=u(n.catchall,t,{...a,path:[...a.path,"additionalProperties"]})):"output"===t.io&&(r.additionalProperties=!1)},D=(e,t,r,a)=>{let n=e._zod.def,i=!1===n.inclusive,s=n.options.map((e,r)=>u(e,t,{...a,path:[...a.path,i?"oneOf":"anyOf",r]}));i?r.oneOf=s:r.anyOf=s},U=(e,t,r,a)=>{let n=e._zod.def,i=u(n.left,t,{...a,path:[...a.path,"allOf",0]}),s=u(n.right,t,{...a,path:[...a.path,"allOf",1]}),o=e=>"allOf"in e&&1===Object.keys(e).length;r.allOf=[...o(i)?i.allOf:[i],...o(s)?s.allOf:[s]]},B=(e,t,r,a)=>{let n=e._zod.def;r.type="array";let i="draft-2020-12"===t.target?"prefixItems":"items",s="draft-2020-12"===t.target||"openapi-3.0"===t.target?"items":"additionalItems",o=n.items.map((e,r)=>u(e,t,{...a,path:[...a.path,i,r]})),l=n.rest?u(n.rest,t,{...a,path:[...a.path,s,..."openapi-3.0"===t.target?[n.items.length]:[]]}):null;"draft-2020-12"===t.target?(r.prefixItems=o,l&&(r.items=l)):"openapi-3.0"===t.target?(r.items={anyOf:o},l&&r.items.anyOf.push(l),r.minItems=o.length,l||(r.maxItems=o.length)):(r.items=o,l&&(r.additionalItems=l));let{minimum:d,maximum:c}=e._zod.bag;"number"==typeof d&&(r.minItems=d),"number"==typeof c&&(r.maxItems=c)},F=(e,t,r,a)=>{let n=e._zod.def;r.type="object";let i=n.keyType,s=i._zod.bag,o=s?.patterns;if("loose"===n.mode&&o&&o.size>0){let e=u(n.valueType,t,{...a,path:[...a.path,"patternProperties","*"]});for(let t of(r.patternProperties={},o))r.patternProperties[t.source]=e}else("draft-07"===t.target||"draft-2020-12"===t.target)&&(r.propertyNames=u(n.keyType,t,{...a,path:[...a.path,"propertyNames"]})),r.additionalProperties=u(n.valueType,t,{...a,path:[...a.path,"additionalProperties"]});let l=i._zod.values;if(l){let e=[...l].filter(e=>"string"==typeof e||"number"==typeof e);e.length>0&&(r.required=e)}},H=(e,t,r,a)=>{let n=e._zod.def,i=u(n.innerType,t,a),s=t.seen.get(e);"openapi-3.0"===t.target?(s.ref=n.innerType,r.nullable=!0):r.anyOf=[i,{type:"null"}]},q=(e,t,r,a)=>{let n=e._zod.def;u(n.innerType,t,a),t.seen.get(e).ref=n.innerType},J=(e,t,r,a)=>{let n=e._zod.def;u(n.innerType,t,a),t.seen.get(e).ref=n.innerType,r.default=JSON.parse(JSON.stringify(n.defaultValue))},G=(e,t,r,a)=>{let n=e._zod.def;u(n.innerType,t,a),t.seen.get(e).ref=n.innerType,"input"===t.io&&(r._prefault=JSON.parse(JSON.stringify(n.defaultValue)))},W=(e,t,r,a)=>{let n,i=e._zod.def;u(i.innerType,t,a),t.seen.get(e).ref=i.innerType;try{n=i.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}r.default=n},V=(e,t,r,a)=>{let n=e._zod.def,i=n.in._zod.traits.has("$ZodTransform"),s="input"===t.io?i?n.out:n.in:n.out;u(s,t,a),t.seen.get(e).ref=s},K=(e,t,r,a)=>{let n=e._zod.def;u(n.innerType,t,a),t.seen.get(e).ref=n.innerType,r.readOnly=!0},Y=(e,t,r,a)=>{let n=e._zod.def;u(n.innerType,t,a),t.seen.get(e).ref=n.innerType},Q=(e,t,r,a)=>{let n=e._zod.def;u(n.innerType,t,a),t.seen.get(e).ref=n.innerType},X=(e,t,r,a)=>{let n=e._zod.innerType;u(n,t,a),t.seen.get(e).ref=n},ee={string:m,number:g,boolean:_,bigint:y,symbol:v,null:b,undefined:w,void:k,never:x,any:S,unknown:$,date:E,enum:T,literal:A,nan:C,template_literal:O,file:I,success:j,custom:P,function:z,transform:N,map:R,set:M,array:L,object:Z,union:D,intersection:U,tuple:B,record:F,nullable:H,nonoptional:q,default:J,prefault:G,catch:W,pipe:V,readonly:K,promise:Y,optional:Q,lazy:X};function et(e,t){if("_idmap"in e){let r=l({...t,processors:ee}),a={};for(let t of e._idmap.entries()){let[e,a]=t;u(a,r)}let n={};for(let i of(r.external={registry:e,uri:t?.uri,defs:a},e._idmap.entries())){let[e,t]=i;d(r,t),n[e]=c(r,t)}return Object.keys(a).length>0&&(n.__shared={["draft-2020-12"===r.target?"$defs":"definitions"]:a}),{schemas:n}}let r=l({...t,processors:ee});return u(e,r),d(r,e),c(r,e)}e.s(["allProcessors",0,ee,"anyProcessor",0,S,"arrayProcessor",0,L,"bigintProcessor",0,y,"booleanProcessor",0,_,"catchProcessor",0,W,"customProcessor",0,P,"dateProcessor",0,E,"defaultProcessor",0,J,"enumProcessor",0,T,"fileProcessor",0,I,"functionProcessor",0,z,"intersectionProcessor",0,U,"lazyProcessor",0,X,"literalProcessor",0,A,"mapProcessor",0,R,"nanProcessor",0,C,"neverProcessor",0,x,"nonoptionalProcessor",0,q,"nullProcessor",0,b,"nullableProcessor",0,H,"numberProcessor",0,g,"objectProcessor",0,Z,"optionalProcessor",0,Q,"pipeProcessor",0,V,"prefaultProcessor",0,G,"promiseProcessor",0,Y,"readonlyProcessor",0,K,"recordProcessor",0,F,"setProcessor",0,M,"stringProcessor",0,m,"successProcessor",0,j,"symbolProcessor",0,v,"templateLiteralProcessor",0,O,"toJSONSchema",0,et,"transformProcessor",0,N,"tupleProcessor",0,B,"undefinedProcessor",0,w,"unionProcessor",0,D,"unknownProcessor",0,$,"voidProcessor",0,k],865889);let er=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,ea=[0,31,28,31,30,31,30,31,31,30,31,30,31],en=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i;function ei(e){return e.test.bind(e)}let es={date:eo,time:el.bind(void 0,!1),"date-time":function(e){let t=e.split(eu);return 2==t.length&&eo(t[0])&&el(!0,t[1])},duration:e=>e.length>1&&e.length<80&&(/^P\d+([.,]\d+)?W$/.test(e)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(e)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(e)),uri:function(e){return ed.test(e)&&ec.test(e)},"uri-reference":ei(/^(?:[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),"uri-template":ei(/^(?:(?:[^\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),url:ei(/^(?:(?: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),email:e=>{if('"'===e[0])return!1;let[t,r,...a]=e.split("@");return!(!t||!r||0!==a.length||t.length>64||r.length>253||"."===t[0]||t.endsWith(".")||t.includes(".."))&&!!/^[a-z0-9.-]+$/i.test(r)&&!!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t)&&r.split(".").every(e=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(e))},hostname:ei(/^(?=.{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),ipv4:ei(/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/),ipv6:ei(/^((([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),regex:function(e){if(eh.test(e))return!1;try{return RegExp(e,"u"),!0}catch(e){return!1}},uuid:ei(/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i),"json-pointer":ei(/^(?:\/(?:[^~/]|~0|~1)*)*$/),"json-pointer-uri-fragment":ei(/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i),"relative-json-pointer":ei(/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/)};function eo(e){var t;let r=e.match(er);if(!r)return!1;let a=+r[1],n=+r[2],i=+r[3];return n>=1&&n<=12&&i>=1&&i<=(2==n&&(t=a)%4==0&&(t%100!=0||t%400==0)?29:ea[n])}function el(e,t){let r=t.match(en);if(!r)return!1;let a=+r[1],n=+r[2],i=+r[3],s=!!r[5];return(a<=23&&n<=59&&i<=59||23==a&&59==n&&60==i)&&(!e||s)}let eu=/t|\s/i,ed=/\/|:/,ec=/^(?:[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,eh=/[^\\]\\Z/;function ep(e,t){let r=typeof e;if(r!==typeof t)return!1;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let r=e.length;if(r!==t.length)return!1;for(let a=0;atypeof self&&self.location&&"null"!==self.location.origin?new URL(self.location.origin+self.location.pathname+location.search):new URL("https://github.com/cfworker");function ev(e,t=Object.create(null),r=ey,a=""){if(e&&"object"==typeof e&&!Array.isArray(e)){let n=e.$id||e.id;if(n){let i=new URL(n,r.href);i.hash.length>1?t[i.href]=e:(i.hash="",""===a?r=i:ev(e,t,r))}}else if(!0!==e&&!1!==e)return t;let n=r.href+(a?"#"+a:"");if(void 0!==t[n])throw Error(`Duplicate schema URI "${n}".`);if(t[n]=e,!0===e||!1===e)return t;if(void 0===e.__absolute_uri__&&Object.defineProperty(e,"__absolute_uri__",{enumerable:!1,value:n}),e.$ref&&void 0===e.__absolute_ref__){let t=new URL(e.$ref,r.href);t.hash=t.hash,Object.defineProperty(e,"__absolute_ref__",{enumerable:!1,value:t.href})}if(e.$recursiveRef&&void 0===e.__absolute_recursive_ref__){let t=new URL(e.$recursiveRef,r.href);t.hash=t.hash,Object.defineProperty(e,"__absolute_recursive_ref__",{enumerable:!1,value:t.href})}for(let n in e.$anchor&&(t[new URL("#"+e.$anchor,r.href).href]=e),e){if(e_[n])continue;let i=`${a}/${ef(n)}`,s=e[n];if(Array.isArray(s)){if(em[n]){let e=s.length;for(let a=0;aep(e,t))||er.push({instanceLocation:s,keyword:"enum",keywordLocation:`${o}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`}):g.some(t=>e===t)||er.push({instanceLocation:s,keyword:"enum",keywordLocation:`${o}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`})),void 0!==y){let t=`${o}/not`;eb(e,y,r,a,n,i,s,t).valid&&er.push({instanceLocation:s,keyword:"not",keywordLocation:t,error:'Instance matched "not" schema.'})}let ea=[];if(void 0!==v){let t=`${o}/anyOf`,u=er.length,d=!1;for(let o=0;o{let d=Object.create(l),c=eb(e,o,r,a,n,!0===p?i:null,s,`${t}/${u}`,d);return er.push(...c.errors),c.valid&&ea.push(d),c.valid}).length;1===d?er.length=u:er.splice(u,0,{instanceLocation:s,keyword:"oneOf",keywordLocation:t,error:`Instance does not match exactly one subschema (${d} matches).`})}if(("object"===u||"array"===u)&&Object.assign(l,...ea),void 0!==k){let t=`${o}/if`;if(eb(e,k,r,a,n,i,s,t,l).valid){if(void 0!==x){let u=eb(e,x,r,a,n,i,s,`${o}/then`,l);u.valid||er.push({instanceLocation:s,keyword:"if",keywordLocation:t,error:'Instance does not match "then" schema.'},...u.errors)}}else if(void 0!==S){let u=eb(e,S,r,a,n,i,s,`${o}/else`,l);u.valid||er.push({instanceLocation:s,keyword:"if",keywordLocation:t,error:'Instance does not match "else" schema.'},...u.errors)}}if("object"===u){if(void 0!==_)for(let t of _)t in e||er.push({instanceLocation:s,keyword:"required",keywordLocation:`${o}/required`,error:`Instance does not have required property "${t}".`});let t=Object.keys(e);if(void 0!==O&&t.lengthI&&er.push({instanceLocation:s,keyword:"maxProperties",keywordLocation:`${o}/maxProperties`,error:`Instance does not have at least ${I} properties.`}),void 0!==j){let t=`${o}/propertyNames`;for(let o in e){let e=`${s}/${ef(o)}`,l=eb(o,j,r,a,n,i,e,t);l.valid||er.push({instanceLocation:s,keyword:"propertyNames",keywordLocation:t,error:`Property name "${o}" does not match schema.`},...l.errors)}}if(void 0!==P){let t=`${o}/dependantRequired`;for(let r in P)if(r in e)for(let a of P[r])a in e||er.push({instanceLocation:s,keyword:"dependentRequired",keywordLocation:t,error:`Instance has "${r}" but does not have "${a}".`})}if(void 0!==z)for(let t in z){let u=`${o}/dependentSchemas`;if(t in e){let o=eb(e,z[t],r,a,n,i,s,`${u}/${ef(t)}`,l);o.valid||er.push({instanceLocation:s,keyword:"dependentSchemas",keywordLocation:u,error:`Instance has "${t}" but does not match dependant schema.`},...o.errors)}}if(void 0!==N){let t=`${o}/dependencies`;for(let o in N)if(o in e){let l=N[o];if(Array.isArray(l))for(let r of l)r in e||er.push({instanceLocation:s,keyword:"dependencies",keywordLocation:t,error:`Instance has "${o}" but does not have "${r}".`});else{let u=eb(e,l,r,a,n,i,s,`${t}/${ef(o)}`);u.valid||er.push({instanceLocation:s,keyword:"dependencies",keywordLocation:t,error:`Instance has "${o}" but does not match dependant schema.`},...u.errors)}}}let u=Object.create(null),d=!1;if(void 0!==E){let t=`${o}/properties`;for(let o in E){if(!(o in e))continue;let c=`${s}/${ef(o)}`,h=eb(e[o],E[o],r,a,n,i,c,`${t}/${ef(o)}`);if(h.valid)l[o]=u[o]=!0;else if(d=n,er.push({instanceLocation:s,keyword:"properties",keywordLocation:t,error:`Property "${o}" does not match schema.`},...h.errors),d)break}}if(!d&&void 0!==T){let t=`${o}/patternProperties`;for(let o in T){let c=RegExp(o,"u"),h=T[o];for(let p in e){if(!c.test(p))continue;let f=`${s}/${ef(p)}`,m=eb(e[p],h,r,a,n,i,f,`${t}/${ef(o)}`);m.valid?l[p]=u[p]=!0:(d=n,er.push({instanceLocation:s,keyword:"patternProperties",keywordLocation:t,error:`Property "${p}" matches pattern "${o}" but does not match associated schema.`},...m.errors))}}}if(d||void 0===A){if(!d&&void 0!==C){let t=`${o}/unevaluatedProperties`;for(let o in e)if(!l[o]){let u=`${s}/${ef(o)}`,d=eb(e[o],C,r,a,n,i,u,t);d.valid?l[o]=!0:er.push({instanceLocation:s,keyword:"unevaluatedProperties",keywordLocation:t,error:`Property "${o}" does not match unevaluated properties schema.`},...d.errors)}}}else{let t=`${o}/additionalProperties`;for(let o in e){if(u[o])continue;let c=`${s}/${ef(o)}`,h=eb(e[o],A,r,a,n,i,c,t);h.valid?l[o]=!0:(d=n,er.push({instanceLocation:s,keyword:"additionalProperties",keywordLocation:t,error:`Property "${o}" does not match additional properties schema.`},...h.errors))}}}else if("array"===u){void 0!==H&&e.length>H&&er.push({instanceLocation:s,keyword:"maxItems",keywordLocation:`${o}/maxItems`,error:`Array has too many items (${e.length} > ${H}).`}),void 0!==F&&e.length=(U||0)&&(er.length=d),void 0===U&&void 0===B&&0===c?er.splice(d,0,{instanceLocation:s,keyword:"contains",keywordLocation:u,error:"Array does not contain item matching schema."}):void 0!==U&&cB&&er.push({instanceLocation:s,keyword:"maxContains",keywordLocation:`${o}/maxContains`,error:`Array may contain at most ${B} items matching schema. ${c} items were found.`})}if(!d&&void 0!==Z){let d=`${o}/unevaluatedItems`;for(;u=G||e>G)&&er.push({instanceLocation:s,keyword:"maximum",keywordLocation:`${o}/maximum`,error:`${e} is greater than ${V?"or equal to ":""} ${G}.`})):(void 0!==J&&eG&&er.push({instanceLocation:s,keyword:"maximum",keywordLocation:`${o}/maximum`,error:`${e} is greater than ${G}.`}),void 0!==W&&e<=W&&er.push({instanceLocation:s,keyword:"exclusiveMinimum",keywordLocation:`${o}/exclusiveMinimum`,error:`${e} is less than ${W}.`}),void 0!==V&&e>=V&&er.push({instanceLocation:s,keyword:"exclusiveMaximum",keywordLocation:`${o}/exclusiveMaximum`,error:`${e} is greater than or equal to ${V}.`})),void 0!==K){let t=e%K;Math.abs(0-t)>=11920929e-14&&Math.abs(K-t)>=11920929e-14&&er.push({instanceLocation:s,keyword:"multipleOf",keywordLocation:`${o}/multipleOf`,error:`${e} is not a multiple of ${K}.`})}}else if("string"===u){let t=void 0===Y&&void 0===Q?0:function(e){let t,r=0,a=e.length,n=0;for(;n=55296&&t<=56319&&nQ&&er.push({instanceLocation:s,keyword:"maxLength",keywordLocation:`${o}/maxLength`,error:`String is too long (${t} > ${Q}).`}),void 0===X||RegExp(X,"u").test(e)||er.push({instanceLocation:s,keyword:"pattern",keywordLocation:`${o}/pattern`,error:"String does not match pattern."}),void 0!==$&&es[$]&&!es[$](e)&&er.push({instanceLocation:s,keyword:"format",keywordLocation:`${o}/format`,error:`String does not match format "${$}".`})}return{valid:0===er.length,errors:er}}e.s(["validate",0,eb],370536);class ew{schema;draft;shortCircuit;lookup;constructor(e,t="2019-09",r=!0){this.schema=e,this.draft=t,this.shortCircuit=r,this.lookup=ev(e)}validate(e){return eb(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,t){t&&(e={...e,$id:t}),ev(e,this.lookup)}}e.s([],262144);var ek=(0,a.__exportAll)({Validator:()=>ew,deepCompareStrict:()=>ep,toJsonSchema:()=>eS,validatesOnlyStrings:()=>e$});let ex=new WeakMap;function eS(e,t){let r,a=!t&&null!=e&&"object"==typeof e;if(a){let t=ex.get(e);if(t)return t}if((0,s.isStandardJsonSchema)(e)&&!(0,n.isZodSchemaV4)(e))r=e["~standard"].jsonSchema.input({target:"draft-07"});else if((0,n.isZodSchemaV4)(e)){let a=(0,n.interopZodTransformInputSchema)(e,!0);r=(0,n.isZodObjectV4)(a)?et((0,n.interopZodObjectStrict)(a,!0),t):et(e,t)}else r=(0,n.isZodSchemaV3)(e)?(0,i.zodToJsonSchema)(e):e;return a&&null!=r&&"object"==typeof r&&ex.set(e,r),r}function e$(e){if(!e||"object"!=typeof e||0===Object.keys(e).length||Array.isArray(e))return!1;if("type"in e)return"string"==typeof e.type?"string"===e.type:!!Array.isArray(e.type)&&e.type.every(e=>"string"===e);if("enum"in e)return Array.isArray(e.enum)&&e.enum.length>0&&e.enum.every(e=>"string"==typeof e);if("const"in e)return"string"==typeof e.const;if("allOf"in e&&Array.isArray(e.allOf))return e.allOf.some(e=>e$(e));if("anyOf"in e&&Array.isArray(e.anyOf)||"oneOf"in e&&Array.isArray(e.oneOf)){let t="anyOf"in e?e.anyOf:e.oneOf;return t.length>0&&t.every(e=>e$(e))}if("not"in e)return!1;if("$ref"in e&&"string"==typeof e.$ref){let t=e.$ref,r=ev(e);if(r[t])return e$(r[t])}return!1}e.s(["json_schema_exports",0,ek,"toJsonSchema",0,eS,"validatesOnlyStrings",0,e$],785337)},98034,e=>{"use strict";var t=e.i(190949),r=e.i(818154),a=e.i(444303);e.i(827007);var n=e.i(165978),i=e.i(959026),s=e.i(785337),o=(0,t.__exportAll)({Graph:()=>l}),l=class e{nodes={};edges=[];constructor(e){this.nodes=e?.nodes??this.nodes,this.edges=e?.edges??this.edges}toJSON(){let e={};return Object.values(this.nodes).forEach((t,a)=>{e[t.id]=(0,r.default)(t.id)?a:t.id}),{nodes:Object.values(this.nodes).map(t=>({id:e[t.id],...(0,n.isRunnableInterface)(t.data)?{type:"runnable",data:{id:t.data.lc_id,name:t.data.getName()}}:{type:"schema",data:{...(0,s.toJsonSchema)(t.data.schema),title:t.data.name}}})),edges:this.edges.map(t=>{let r={source:e[t.source],target:e[t.target]};return void 0!==t.data&&(r.data=t.data),void 0!==t.conditional&&(r.conditional=t.conditional),r})}}addNode(e,t,i){if(void 0!==t&&void 0!==this.nodes[t])throw Error(`Node with id ${t} already exists`);let s=t??(0,a.default)(),o={id:s,data:e,name:function(e,t){if(void 0!==e&&!(0,r.default)(e))return e;if(!(0,n.isRunnableInterface)(t))return t.name??"UnknownSchema";try{let e=t.getName();return e=e.startsWith("Runnable")?e.slice(8):e}catch{return t.getName()}}(t,e),metadata:i};return this.nodes[s]=o,o}removeNode(e){delete this.nodes[e.id],this.edges=this.edges.filter(t=>t.source!==e.id&&t.target!==e.id)}addEdge(e,t,r,a){if(void 0===this.nodes[e.id])throw Error(`Source node ${e.id} not in graph`);if(void 0===this.nodes[t.id])throw Error(`Target node ${t.id} not in graph`);let n={source:e.id,target:t.id,data:r,conditional:a};return this.edges.push(n),n}firstNode(){return u(this)}lastNode(){return d(this)}extend(e,t=""){let a=t;Object.values(e.nodes).map(e=>e.id).every(r.default)&&(a="");let n=e=>a?`${a}:${e}`:e;Object.entries(e.nodes).forEach(([e,t])=>{this.nodes[n(e)]={...t,id:n(e)}});let i=e.edges.map(e=>({...e,source:n(e.source),target:n(e.target)}));this.edges=[...this.edges,...i];let s=e.firstNode(),o=e.lastNode();return[s?{id:n(s.id),data:s.data}:void 0,o?{id:n(o.id),data:o.data}:void 0]}trimFirstNode(){let e=this.firstNode();e&&u(this,[e.id])&&this.removeNode(e)}trimLastNode(){let e=this.lastNode();e&&d(this,[e.id])&&this.removeNode(e)}reid(){let t=Object.fromEntries(Object.values(this.nodes).map(e=>[e.id,e.name])),a=new Map;Object.values(t).forEach(e=>{a.set(e,(a.get(e)||0)+1)});let n=e=>{let n=t[e];return(0,r.default)(e)&&1===a.get(n)?n:e};return new e({nodes:Object.fromEntries(Object.entries(this.nodes).map(([e,t])=>[n(e),{...t,id:n(e)}])),edges:this.edges.map(e=>({...e,source:n(e.source),target:n(e.target)}))})}drawMermaid(e){let{withStyles:t,curveStyle:r,nodeColors:a={default:"fill:#f2f0ff,line-height:1.2",first:"fill-opacity:0",last:"fill:#bfb6fc"},wrapLabelNWords:n}=e??{},s=this.reid(),o=s.firstNode(),l=s.lastNode();return(0,i.drawMermaid)(s.nodes,s.edges,{firstNode:o?.id,lastNode:l?.id,withStyles:t,curveStyle:r,nodeColors:a,wrapLabelNWords:n})}async drawMermaidPng(e){return(0,i.drawMermaidImage)(this.drawMermaid(e),{backgroundColor:e?.backgroundColor})}};function u(e,t=[]){let r=new Set(e.edges.filter(e=>!t.includes(e.source)).map(e=>e.target)),a=[];for(let n of Object.values(e.nodes))t.includes(n.id)||r.has(n.id)||a.push(n);return 1===a.length?a[0]:void 0}function d(e,t=[]){let r=new Set(e.edges.filter(e=>!t.includes(e.target)).map(e=>e.source)),a=[];for(let n of Object.values(e.nodes))t.includes(n.id)||r.has(n.id)||a.push(n);return 1===a.length?a[0]:void 0}e.s(["Graph",0,l,"graph_exports",0,o])},637253,3487,322632,420204,692660,209387,e=>{"use strict";var t=e.i(190949),r=e.i(507577),a=e.i(403929),n=e.i(640470),i=e.i(367751),s=e.i(771863),o=e.i(649835),l=e.i(151191),u=e.i(622480),d=e.i(60427),c=e.i(65955),h=e.i(211614),p=e.i(329494),f=e.i(642416),m=e.i(756740),g=e.i(738573);e.i(827007);var _=e.i(200587);e.i(869070);var y=e.i(640516),v=e.i(115995),b=e.i(890406),w=e.i(99815),k=e.i(577284),x=e.i(884606),S=e.i(664527),$=e.i(743160),E=e.i(165978),T=e.i(238073),A=e.i(98034);function C(e){return"object"==typeof e&&null!==e&&"function"==typeof e[Symbol.iterator]&&"function"==typeof e.next}let O=e=>null!=e&&"object"==typeof e&&"next"in e&&"function"==typeof e.next;function I(e){return"object"==typeof e&&null!==e&&"function"==typeof e[Symbol.asyncIterator]}async function j(e,t){try{let r=await e.next();for(;!r.done;)await t?.(r.value),r=await e.next();return r.value}finally{await e.return?.(void 0)}}function*P(e,t){for(;;){let{value:r,done:a}=_.AsyncLocalStorageProviderSingleton.runWithConfig((0,y.pickRunnableConfigKeys)(e),t.next.bind(t),!0);if(a)break;yield r}}async function*z(e,t){let r=t[Symbol.asyncIterator]();for(;;){let{value:a,done:n}=await _.AsyncLocalStorageProviderSingleton.runWithConfig((0,y.pickRunnableConfigKeys)(e),r.next.bind(t),!0);if(n)break;yield a}}e.s(["consumeAsyncGenerator",0,j,"consumeAsyncIterableInContext",0,z,"consumeIteratorInContext",0,P,"isAsyncGenerator",0,function(e){return null!=e&&"object"==typeof e&&"function"==typeof e.next},"isAsyncIterable",0,I,"isIterableIterator",0,C,"isIterator",0,O],3487),e.i(184698);var N=e.i(76719);e.s([],254033),e.i(254033);var R=e.i(585676),M=e.i(880264);e.s(["defaultErrorMap",()=>M.default,"getErrorMap",()=>R.getErrorMap,"setErrorMap",()=>R.setErrorMap],676733),e.i(676733);var L=e.i(984488);e.s([],91316),e.i(91316);var Z=e.i(742944),D=e.i(117958),U=e.i(115235);e.s(["BRAND",()=>D.BRAND,"DIRTY",()=>L.DIRTY,"EMPTY_PATH",()=>L.EMPTY_PATH,"INVALID",()=>L.INVALID,"NEVER",()=>D.NEVER,"OK",()=>L.OK,"ParseStatus",()=>L.ParseStatus,"Schema",()=>D.Schema,"ZodAny",()=>D.ZodAny,"ZodArray",()=>D.ZodArray,"ZodBigInt",()=>D.ZodBigInt,"ZodBoolean",()=>D.ZodBoolean,"ZodBranded",()=>D.ZodBranded,"ZodCatch",()=>D.ZodCatch,"ZodDate",()=>D.ZodDate,"ZodDefault",()=>D.ZodDefault,"ZodDiscriminatedUnion",()=>D.ZodDiscriminatedUnion,"ZodEffects",()=>D.ZodEffects,"ZodEnum",()=>D.ZodEnum,"ZodError",()=>U.ZodError,"ZodFirstPartyTypeKind",()=>D.ZodFirstPartyTypeKind,"ZodFunction",()=>D.ZodFunction,"ZodIntersection",()=>D.ZodIntersection,"ZodIssueCode",()=>U.ZodIssueCode,"ZodLazy",()=>D.ZodLazy,"ZodLiteral",()=>D.ZodLiteral,"ZodMap",()=>D.ZodMap,"ZodNaN",()=>D.ZodNaN,"ZodNativeEnum",()=>D.ZodNativeEnum,"ZodNever",()=>D.ZodNever,"ZodNull",()=>D.ZodNull,"ZodNullable",()=>D.ZodNullable,"ZodNumber",()=>D.ZodNumber,"ZodObject",()=>D.ZodObject,"ZodOptional",()=>D.ZodOptional,"ZodParsedType",()=>Z.ZodParsedType,"ZodPipeline",()=>D.ZodPipeline,"ZodPromise",()=>D.ZodPromise,"ZodReadonly",()=>D.ZodReadonly,"ZodRecord",()=>D.ZodRecord,"ZodSchema",()=>D.ZodSchema,"ZodSet",()=>D.ZodSet,"ZodString",()=>D.ZodString,"ZodSymbol",()=>D.ZodSymbol,"ZodTransformer",()=>D.ZodTransformer,"ZodTuple",()=>D.ZodTuple,"ZodType",()=>D.ZodType,"ZodUndefined",()=>D.ZodUndefined,"ZodUnion",()=>D.ZodUnion,"ZodUnknown",()=>D.ZodUnknown,"ZodVoid",()=>D.ZodVoid,"addIssueToContext",()=>L.addIssueToContext,"any",()=>D.any,"array",()=>D.array,"bigint",()=>D.bigint,"boolean",()=>D.boolean,"coerce",()=>D.coerce,"custom",()=>D.custom,"date",()=>D.date,"datetimeRegex",()=>D.datetimeRegex,"defaultErrorMap",()=>M.default,"discriminatedUnion",()=>D.discriminatedUnion,"effect",()=>D.effect,"enum",()=>D.enum,"function",()=>D.function,"getErrorMap",()=>R.getErrorMap,"getParsedType",()=>Z.getParsedType,"instanceof",()=>D.instanceof,"intersection",()=>D.intersection,"isAborted",()=>L.isAborted,"isAsync",()=>L.isAsync,"isDirty",()=>L.isDirty,"isValid",()=>L.isValid,"late",()=>D.late,"lazy",()=>D.lazy,"literal",()=>D.literal,"makeIssue",()=>L.makeIssue,"map",()=>D.map,"nan",()=>D.nan,"nativeEnum",()=>D.nativeEnum,"never",()=>D.never,"null",()=>D.null,"nullable",()=>D.nullable,"number",()=>D.number,"object",()=>D.object,"objectUtil",()=>Z.objectUtil,"oboolean",()=>D.oboolean,"onumber",()=>D.onumber,"optional",()=>D.optional,"ostring",()=>D.ostring,"pipeline",()=>D.pipeline,"preprocess",()=>D.preprocess,"promise",()=>D.promise,"quotelessJson",()=>U.quotelessJson,"record",()=>D.record,"set",()=>D.set,"setErrorMap",()=>R.setErrorMap,"strictObject",()=>D.strictObject,"string",()=>D.string,"symbol",()=>D.symbol,"transformer",()=>D.transformer,"tuple",()=>D.tuple,"undefined",()=>D.undefined,"union",()=>D.union,"unknown",()=>D.unknown,"util",()=>Z.util,"void",()=>D.void],735907);var B=e.i(735907);e.s(["z",0,B],322632);var B=B;function F(e,t){return!e||Array.isArray(e)||e instanceof Date||"object"!=typeof e?{[t]:e}:e}var H=class extends m.Serializable{lc_runnable=!0;name;getName(e){let t=this.name??this.constructor.lc_name()??this.constructor.name;return e?`${t}${e}`:t}withRetry(e){return new G({bound:this,kwargs:{},config:{},maxAttemptNumber:e?.stopAfterAttempt,...e})}withConfig(e){return new q({bound:this,config:e,kwargs:{}})}withFallbacks(e){return new X({runnable:this,fallbacks:Array.isArray(e)?e:e.fallbacks})}_getOptionsList(e,t=0){if(Array.isArray(e)&&e.length!==t)throw Error(`Passed "options" must be an array with the same length as the inputs, but got ${e.length} options for ${t} inputs`);if(Array.isArray(e))return e.map(y.ensureConfig);if(t>1&&!Array.isArray(e)&&e.runId){console.warn("Provided runId will be used only for the first element of the batch.");let r=Object.fromEntries(Object.entries(e).filter(([e])=>"runId"!==e));return Array.from({length:t},(t,a)=>(0,y.ensureConfig)(0===a?e:r))}return Array.from({length:t},()=>(0,y.ensureConfig)(e))}async batch(e,t,r){let a=this._getOptionsList(t??{},e.length),n=new S.AsyncCaller({maxConcurrency:a[0]?.maxConcurrency??r?.maxConcurrency,onFailedAttempt:e=>{throw e}});return Promise.all(e.map((e,t)=>n.call(async()=>{try{return await this.invoke(e,a[t])}catch(e){if(r?.returnExceptions)return e;throw e}})))}async *_streamIterator(e,t){yield this.invoke(e,t)}async stream(e,t){let r=(0,y.ensureConfig)(t),a=new b.AsyncGeneratorWithSetup({generator:this._streamIterator(e,r),config:r});return await a.setup,b.IterableReadableStream.fromAsyncGenerator(a)}_separateRunnableConfigFromCallOptions(e){let t;t=void 0===e?(0,y.ensureConfig)(e):(0,y.ensureConfig)({callbacks:e.callbacks,tags:e.tags,metadata:e.metadata,runName:e.runName,configurable:e.configurable,recursionLimit:e.recursionLimit,maxConcurrency:e.maxConcurrency,runId:e.runId,timeout:e.timeout,signal:e.signal});let r={...e};return delete r.callbacks,delete r.tags,delete r.metadata,delete r.runName,delete r.configurable,delete r.recursionLimit,delete r.maxConcurrency,delete r.runId,delete r.timeout,delete r.signal,[t,r]}async _callWithConfig(e,t,r){let a,n=(0,y.ensureConfig)(r),i=await (await (0,y.getCallbackManagerForConfig)(n))?.handleChainStart(this.toJSON(),F(t,"input"),n.runId,n?.runType,void 0,void 0,n?.runName??this.getName());delete n.runId;try{a=await (0,v.raceWithSignal)(e.call(this,t,n,i),n.signal)}catch(e){throw await i?.handleChainError(e),e}return await i?.handleChainEnd(F(a,"output")),a}async _batchWithConfig(e,t,r,a){let n,i=this._getOptionsList(r??{},t.length),s=await Promise.all(i.map(y.getCallbackManagerForConfig)),o=await Promise.all(s.map(async(e,r)=>{let a=await e?.handleChainStart(this.toJSON(),F(t[r],"input"),i[r].runId,i[r].runType,void 0,void 0,i[r].runName??this.getName());return delete i[r].runId,a}));try{n=await (0,v.raceWithSignal)(e.call(this,t,i,o,a),i?.[0]?.signal)}catch(e){throw await Promise.all(o.map(t=>t?.handleChainError(e))),e}return await Promise.all(o.map(e=>e?.handleChainEnd(F(n,"output")))),n}_concatOutputChunks(e,t){return(0,b.concat)(e,t)}async *_transformStreamWithConfig(e,t,r){let a,n,i,s=!0,o=!0,l=(0,y.ensureConfig)(r),u=await (0,y.getCallbackManagerForConfig)(l),d=this;async function*c(){for await(let t of e){if(s)if(void 0===a)a=t;else try{a=d._concatOutputChunks(a,t)}catch{a=void 0,s=!1}yield t}}try{let e=await (0,b.pipeGeneratorWithSetup)(t.bind(this),c(),async()=>u?.handleChainStart(this.toJSON(),{input:""},l.runId,l.runType,void 0,void 0,l.runName??this.getName(),void 0,{lc_defers_inputs:!0}),l.signal,l);delete l.runId,i=e.setup;let r=i?.handlers.find(k.isStreamEventsHandler),a=e.output;void 0!==r&&void 0!==i&&(a=r.tapOutputIterable(i.runId,a));let s=i?.handlers.find(w.isLogStreamHandler);for await(let e of(void 0!==s&&void 0!==i&&(a=s.tapOutputIterable(i.runId,a)),a))if(yield e,o)if(void 0===n)n=e;else try{n=this._concatOutputChunks(n,e)}catch{n=void 0,o=!1}}catch(e){throw await i?.handleChainError(e,void 0,void 0,void 0,{inputs:F(a,"input")}),e}await i?.handleChainEnd(n??{},void 0,void 0,void 0,{inputs:F(a,"input")})}getGraph(e){let t=new A.Graph,r=t.addNode({name:`${this.getName()}Input`,schema:B.any()}),a=t.addNode(this),n=t.addNode({name:`${this.getName()}Output`,schema:B.any()});return t.addEdge(r,a),t.addEdge(a,n),t}pipe(e){return new W({first:this,last:ee(e)})}pick(e){return this.pipe(new er(e))}assign(e){return this.pipe(new et(new V({steps:e})))}async *transform(e,t){let r;for await(let t of e)r=void 0===r?t:this._concatOutputChunks(r,t);yield*this._streamIterator(r,(0,y.ensureConfig)(t))}async *streamLog(e,t,r){let a=new w.LogStreamCallbackHandler({...r,autoClose:!1,_schemaFormat:"original"}),n=(0,y.ensureConfig)(t);yield*this._streamLog(e,a,n)}async *_streamLog(e,t,r){let{callbacks:a}=r;if(void 0===a)r.callbacks=[t];else if(Array.isArray(a))r.callbacks=a.concat([t]);else{let e=a.copy();e.addHandler(t,!0),r.callbacks=e}let n=this.stream(e,r),i=async function(){try{for await(let e of(await n)){let r=new w.RunLogPatch({ops:[{op:"add",path:"/streamed_output/-",value:e}]});await t.writer.write(r)}}finally{await t.writer.close()}}();try{for await(let e of t)yield e}finally{await i}}streamEvents(e,t,r){var a;let n,i,s;if("v1"===t.version)n=this._streamEventsV1(e,t,r);else if("v2"===t.version)n=this._streamEventsV2(e,t,r);else throw Error('Only versions "v1" and "v2" of the schema are currently supported.');if("text/event-stream"!==t.encoding)return b.IterableReadableStream.fromAsyncGenerator(n);return a=n,i=new TextEncoder,s=new ReadableStream({async start(e){for await(let t of a)e.enqueue(i.encode(`event: data data: ${JSON.stringify(t)} `));e.enqueue(i.encode("event: end\n\n")),e.close()}}),b.IterableReadableStream.fromReadableStream(s)}async *_streamEventsV2(e,t,r){let a,n=new k.EventStreamCallbackHandler({...r,autoClose:!1}),i=(0,y.ensureConfig)(t),s=i.runId??(0,g.default)();i.runId=s;let o=i.callbacks;if(void 0===o)i.callbacks=[n];else if(Array.isArray(o))i.callbacks=o.concat(n);else{let e=o.copy();e.addHandler(n,!0),i.callbacks=e}let l=new AbortController,u=this,d=async function(){let t;try{if(i.signal)if("any"in AbortSignal)t=AbortSignal.any([l.signal,i.signal]);else{let e=new AbortController;i.signal.addEventListener("abort",()=>e.abort(),{once:!0}),l.signal.addEventListener("abort",()=>e.abort(),{once:!0}),t=e.signal}else t=l.signal;let r=await u.stream(e,{...i,signal:t});for await(let e of n.tapOutputIterable(s,r))if(l.signal.aborted)break}finally{await n.finish()}}(),c=!1;try{for await(let t of n){if(!c){t.data.input=e,c=!0,a=t.run_id,yield t;continue}t.run_id===a&&t.event.endsWith("_end")&&t.data?.input&&delete t.data.input,yield t}}finally{l.abort(),await d}}async *_streamEventsV1(e,t,r){let a,n=!1,i=(0,y.ensureConfig)(t),s=i.tags??[],o=i.metadata??{},l=i.runName??this.getName(),u=new w.LogStreamCallbackHandler({...r,autoClose:!1,_schemaFormat:"streaming_events"}),d=new E._RootEventFilter({...r});for await(let t of this._streamLog(e,u,i)){if(void 0===(a=a?a.concat(t):w.RunLog.fromRunLogPatch(t)).state)throw Error('Internal error: "streamEvents" state is missing. Please open a bug report.');if(!n){n=!0;let t={...a.state},r={run_id:t.id,event:`on_${t.type}_start`,name:l,tags:s,metadata:o,data:{input:e}};d.includeEvent(r,t.type)&&(yield r)}for(let e of[...new Set(t.ops.filter(e=>e.path.startsWith("/logs/")).map(e=>e.path.split("/")[2]))]){let t,r={},n=a.state.logs[e];if("start"==(t=void 0===n.end_time?n.streamed_output.length>0?"stream":"start":"end"))void 0!==n.inputs&&(r.input=n.inputs);else if("end"===t)void 0!==n.inputs&&(r.input=n.inputs),r.output=n.final_output;else if("stream"===t){let e=n.streamed_output.length;if(1!==e)throw Error(`Expected exactly one chunk of streamed output, got ${e} instead. Encountered in: "${n.name}"`);r={chunk:n.streamed_output[0]},n.streamed_output=[]}yield{event:`on_${n.type}_${t}`,name:n.name,run_id:n.id,tags:n.tags,metadata:n.metadata,data:r}}let{state:r}=a;if(r.streamed_output.length>0){let e=r.streamed_output.length;if(1!==e)throw Error(`Expected exactly one chunk of streamed output, got ${e} instead. Encountered in: "${r.name}"`);let t={chunk:r.streamed_output[0]};r.streamed_output=[];let a={event:`on_${r.type}_stream`,run_id:r.id,tags:s,metadata:o,name:l,data:t};d.includeEvent(a,r.type)&&(yield a)}}let c=a?.state;if(void 0!==c){let e={event:`on_${c.type}_end`,name:l,run_id:c.id,tags:s,metadata:o,data:{output:c.final_output}};d.includeEvent(e,c.type)&&(yield e)}}static isRunnable(e){return(0,E.isRunnableInterface)(e)}withListeners({onStart:e,onEnd:t,onError:r}){return new q({bound:this,config:{},configFactories:[a=>({callbacks:[new $.RootListenersTracer({config:a,onStart:e,onEnd:t,onError:r})]})]})}asTool(e){var t,r;let a,n;return t=this,a=(r=e).name??t.getName(),n=r.description??(0,T.getSchemaDescription)(r.schema),new ea((0,T.isSimpleStringZodSchema)(r.schema)?{name:a,description:n,schema:B.object({input:B.string()}).transform(e=>e.input),bound:t}:{name:a,description:n,schema:r.schema,bound:t})}},q=class e extends H{static lc_name(){return"RunnableBinding"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;bound;config;kwargs;configFactories;constructor(e){super(e),this.bound=e.bound,this.kwargs=e.kwargs,this.config=e.config,this.configFactories=e.configFactories}getName(e){return this.bound.getName(e)}async _mergeConfig(...e){let t=(0,y.mergeConfigs)(this.config,...e);return(0,y.mergeConfigs)(t,...this.configFactories?await Promise.all(this.configFactories.map(async e=>await e(t))):[])}withConfig(e){return new this.constructor({bound:this.bound,kwargs:this.kwargs,config:{...this.config,...e}})}withRetry(e){return new G({bound:this.bound,kwargs:this.kwargs,config:this.config,maxAttemptNumber:e?.stopAfterAttempt,...e})}async invoke(e,t){return this.bound.invoke(e,await this._mergeConfig(t,this.kwargs))}async batch(e,t,r){let a=Array.isArray(t)?await Promise.all(t.map(async e=>this._mergeConfig((0,y.ensureConfig)(e),this.kwargs))):await this._mergeConfig((0,y.ensureConfig)(t),this.kwargs);return this.bound.batch(e,a,r)}_concatOutputChunks(e,t){return this.bound._concatOutputChunks(e,t)}async *_streamIterator(e,t){yield*this.bound._streamIterator(e,await this._mergeConfig((0,y.ensureConfig)(t),this.kwargs))}async stream(e,t){return this.bound.stream(e,await this._mergeConfig((0,y.ensureConfig)(t),this.kwargs))}async *transform(e,t){yield*this.bound.transform(e,await this._mergeConfig((0,y.ensureConfig)(t),this.kwargs))}streamEvents(e,t,r){let a=this,n=async function*(){yield*a.bound.streamEvents(e,{...await a._mergeConfig((0,y.ensureConfig)(t),a.kwargs),version:t.version},r)};return b.IterableReadableStream.fromAsyncGenerator(n())}static isRunnableBinding(e){return e.bound&&H.isRunnable(e.bound)}withListeners({onStart:t,onEnd:r,onError:a}){return new e({bound:this.bound,kwargs:this.kwargs,config:this.config,configFactories:[e=>({callbacks:[new $.RootListenersTracer({config:e,onStart:t,onEnd:r,onError:a})]})]})}},J=class e extends H{static lc_name(){return"RunnableEach"}lc_serializable=!0;lc_namespace=["langchain_core","runnables"];bound;constructor(e){super(e),this.bound=e.bound}async invoke(e,t){return this._callWithConfig(this._invoke.bind(this),e,t)}async _invoke(e,t,r){return this.bound.batch(e,(0,y.patchConfig)(t,{callbacks:r?.getChild()}))}withListeners({onStart:t,onEnd:r,onError:a}){return new e({bound:this.bound.withListeners({onStart:t,onEnd:r,onError:a})})}},G=class extends q{static lc_name(){return"RunnableRetry"}lc_namespace=["langchain_core","runnables"];maxAttemptNumber=3;onFailedAttempt=()=>{};constructor(e){super(e),this.maxAttemptNumber=e.maxAttemptNumber??this.maxAttemptNumber,this.onFailedAttempt=e.onFailedAttempt??this.onFailedAttempt}_patchConfigForRetry(e,t,r){let a=e>1?`retry:attempt:${e}`:void 0;return(0,y.patchConfig)(t,{callbacks:r?.getChild(a)})}async _invoke(e,t,r){return(0,x.default)(a=>super.invoke(e,this._patchConfigForRetry(a,t,r)),{onFailedAttempt:({error:t})=>this.onFailedAttempt(t,e),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}async invoke(e,t){return this._callWithConfig(this._invoke.bind(this),e,t)}async _batch(e,t,r,a){let n={};try{await (0,x.default)(async i=>{let s,o=e.map((e,t)=>t).filter(e=>void 0===n[e.toString()]||n[e.toString()]instanceof Error),l=o.map(t=>e[t]),u=o.map(e=>this._patchConfigForRetry(i,t?.[e],r?.[e])),d=await super.batch(l,u,{...a,returnExceptions:!0});for(let e=0;ethis.onFailedAttempt(e,e.input),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}catch(e){if(a?.returnExceptions!==!0)throw e}return Object.keys(n).sort((e,t)=>parseInt(e,10)-parseInt(t,10)).map(e=>n[parseInt(e,10)])}async batch(e,t,r){return this._batchWithConfig(this._batch.bind(this),e,t,r)}},W=class e extends H{static lc_name(){return"RunnableSequence"}first;middle=[];last;omitSequenceTags=!1;lc_serializable=!0;lc_namespace=["langchain_core","runnables"];constructor(e){super(e),this.first=e.first,this.middle=e.middle??this.middle,this.last=e.last,this.name=e.name,this.omitSequenceTags=e.omitSequenceTags??this.omitSequenceTags}get steps(){return[this.first,...this.middle,this.last]}async invoke(e,t){let r,a=(0,y.ensureConfig)(t),n=await (await (0,y.getCallbackManagerForConfig)(a))?.handleChainStart(this.toJSON(),F(e,"input"),a.runId,void 0,void 0,void 0,a?.runName);delete a.runId;let i=e;try{let e=[this.first,...this.middle];for(let t=0;t{let n=await t?.handleChainStart(this.toJSON(),F(e[r],"input"),a[r].runId,void 0,void 0,void 0,a[r].runName);return delete a[r].runId,n})),s=e;try{for(let e=0;e{let n=t?.getChild(this.omitSequenceTags?void 0:`seq:step:${e+1}`);return(0,y.patchConfig)(a[r],{callbacks:n})}),r),a[0]?.signal)}catch(e){throw await Promise.all(i.map(t=>t?.handleChainError(e))),e}return await Promise.all(i.map(e=>e?.handleChainEnd(F(s,"output")))),s}_concatOutputChunks(e,t){return this.last._concatOutputChunks(e,t)}async *_streamIterator(e,t){let r,a=await (0,y.getCallbackManagerForConfig)(t),{runId:n,...i}=t??{},s=await a?.handleChainStart(this.toJSON(),F(e,"input"),n,void 0,void 0,void 0,i?.runName),o=[this.first,...this.middle,this.last],l=!0;async function*u(){yield e}try{let e=o[0].transform(u(),(0,y.patchConfig)(i,{callbacks:s?.getChild(this.omitSequenceTags?void 0:"seq:step:1")}));for(let t=1;t{let i=a.getGraph(e);0!==n&&i.trimFirstNode(),n!==this.steps.length-1&&i.trimLastNode(),t.extend(i);let s=i.firstNode();if(!s)throw Error(`Runnable ${a} has no first node`);r&&t.addEdge(r,s),r=i.lastNode()}),t}pipe(t){return new e(e.isRunnableSequence(t)?{first:this.first,middle:this.middle.concat([this.last,t.first,...t.middle]),last:t.last,name:this.name??t.name}:{first:this.first,middle:[...this.middle,this.last],last:ee(t),name:this.name})}static isRunnableSequence(e){return Array.isArray(e.middle)&&H.isRunnable(e)}static from([t,...r],a){let n={};return"string"==typeof a?n.name=a:void 0!==a&&(n=a),new e({...n,first:ee(t),middle:r.slice(0,-1).map(ee),last:ee(r[r.length-1])})}},V=class e extends H{static lc_name(){return"RunnableMap"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;steps;getStepsKeys(){return Object.keys(this.steps)}constructor(e){for(const[t,r]of(super(e),this.steps={},Object.entries(e.steps)))this.steps[t]=ee(r)}static from(t){return new e({steps:t})}async invoke(e,t){let r=(0,y.ensureConfig)(t),a=await (await (0,y.getCallbackManagerForConfig)(r))?.handleChainStart(this.toJSON(),{input:e},r.runId,void 0,void 0,void 0,r?.runName);delete r.runId;let n={};try{let t=Object.entries(this.steps).map(async([t,i])=>{n[t]=await i.invoke(e,(0,y.patchConfig)(r,{callbacks:a?.getChild(`map:key:${t}`)}))});await (0,v.raceWithSignal)(Promise.all(t),r.signal)}catch(e){throw await a?.handleChainError(e),e}return await a?.handleChainEnd(n),n}async *_transform(e,t,r){let a={...this.steps},n=(0,b.atee)(e,Object.keys(a).length),i=new Map(Object.entries(a).map(([e,a],i)=>{let s=a.transform(n[i],(0,y.patchConfig)(r,{callbacks:t?.getChild(`map:key:${e}`)}));return[e,s.next().then(t=>({key:e,gen:s,result:t}))]}));for(;i.size;){let{key:e,result:t,gen:a}=await (0,v.raceWithSignal)(Promise.race(i.values()),r?.signal);i.delete(e),t.done||(yield{[e]:t.value},i.set(e,a.next().then(t=>({key:e,gen:a,result:t}))))}}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*r(){yield e}let a=(0,y.ensureConfig)(t),n=new b.AsyncGeneratorWithSetup({generator:this.transform(r(),a),config:a});return await n.setup,b.IterableReadableStream.fromAsyncGenerator(n)}},K=class e extends H{lc_serializable=!1;lc_namespace=["langchain_core","runnables"];func;constructor(e){if(super(e),!(0,N.isTraceableFunction)(e.func))throw Error("RunnableTraceable requires a function that is wrapped in traceable higher-order function");this.func=e.func}async invoke(e,t){let[r]=this._getOptionsList(t??{},1),a=await (0,y.getCallbackManagerForConfig)(r);return(0,v.raceWithSignal)(this.func((0,y.patchConfig)(r,{callbacks:a}),e),r?.signal)}async *_streamIterator(e,t){let[r]=this._getOptionsList(t??{},1),a=await this.invoke(e,t);if(I(a)){for await(let e of a)r?.signal?.throwIfAborted(),yield e;return}if(O(a)){for(;;){r?.signal?.throwIfAborted();let e=a.next();if(e.done)break;yield e.value}return}yield a}static from(t){return new e({func:t})}},Y=class e extends H{static lc_name(){return"RunnableLambda"}lc_namespace=["langchain_core","runnables"];func;constructor(e){if((0,N.isTraceableFunction)(e.func))return K.from(e.func);super(e),function(e){if((0,N.isTraceableFunction)(e))throw Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.")}(e.func),this.func=e.func}static from(t){return new e({func:t})}async _invoke(e,t,r){return new Promise((a,n)=>{let i=(0,y.patchConfig)(t,{callbacks:r?.getChild(),recursionLimit:(t?.recursionLimit??25)-1});_.AsyncLocalStorageProviderSingleton.runWithConfig((0,y.pickRunnableConfigKeys)(i),async()=>{try{let r=await this.func(e,{...i});if(r&&H.isRunnable(r)){if(t?.recursionLimit===0)throw Error("Recursion limit reached.");r=await r.invoke(e,{...i,recursionLimit:(i.recursionLimit??25)-1})}else if(I(r)){let e;for await(let a of z(i,r))if(t?.signal?.throwIfAborted(),void 0===e)e=a;else try{e=this._concatOutputChunks(e,a)}catch{e=a}r=e}else if(C(r)){let e;for(let a of P(i,r))if(t?.signal?.throwIfAborted(),void 0===e)e=a;else try{e=this._concatOutputChunks(e,a)}catch{e=a}r=e}a(r)}catch(e){n(e)}})})}async invoke(e,t){return this._callWithConfig(this._invoke.bind(this),e,t)}async *_transform(e,t,r){let a;for await(let t of e)if(void 0===a)a=t;else try{a=this._concatOutputChunks(a,t)}catch{a=t}let n=(0,y.patchConfig)(r,{callbacks:t?.getChild(),recursionLimit:(r?.recursionLimit??25)-1}),i=await new Promise((e,t)=>{_.AsyncLocalStorageProviderSingleton.runWithConfig((0,y.pickRunnableConfigKeys)(n),async()=>{try{e(await this.func(a,{...n,config:n}))}catch(e){t(e)}})});if(i&&H.isRunnable(i)){if(r?.recursionLimit===0)throw Error("Recursion limit reached.");for await(let e of(await i.stream(a,n)))yield e}else if(I(i))for await(let e of z(n,i))r?.signal?.throwIfAborted(),yield e;else if(C(i))for(let e of P(n,i))r?.signal?.throwIfAborted(),yield e;else yield i}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*r(){yield e}let a=(0,y.ensureConfig)(t),n=new b.AsyncGeneratorWithSetup({generator:this.transform(r(),a),config:a});return await n.setup,b.IterableReadableStream.fromAsyncGenerator(n)}},Q=class extends V{},X=class extends H{static lc_name(){return"RunnableWithFallbacks"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;runnable;fallbacks;constructor(e){super(e),this.runnable=e.runnable,this.fallbacks=e.fallbacks}*runnables(){for(let e of(yield this.runnable,this.fallbacks))yield e}async invoke(e,t){let r=(0,y.ensureConfig)(t),a=await (0,y.getCallbackManagerForConfig)(r),{runId:n,...i}=r,s=await a?.handleChainStart(this.toJSON(),F(e,"input"),n,void 0,void 0,void 0,i?.runName),o=(0,y.patchConfig)(i,{callbacks:s?.getChild()});return await _.AsyncLocalStorageProviderSingleton.runWithConfig(o,async()=>{let t;for(let a of this.runnables()){r?.signal?.throwIfAborted();try{let t=await a.invoke(e,o);return await s?.handleChainEnd(F(t,"output")),t}catch(e){void 0===t&&(t=e)}}if(void 0===t)throw Error("No error stored at end of fallback.");throw await s?.handleChainError(t),t})}async *_streamIterator(e,t){let r,a,n,i=(0,y.ensureConfig)(t),s=await (0,y.getCallbackManagerForConfig)(i),{runId:o,...l}=i,u=await s?.handleChainStart(this.toJSON(),F(e,"input"),o,void 0,void 0,void 0,l?.runName);for(let t of this.runnables()){i?.signal?.throwIfAborted();let n=(0,y.patchConfig)(l,{callbacks:u?.getChild()});try{a=z(n,await t.stream(e,n));break}catch(e){void 0===r&&(r=e)}}if(void 0===a){let e=r??Error("No error stored at end of fallback.");throw await u?.handleChainError(e),e}try{for await(let e of a){yield e;try{n=void 0===n?n:this._concatOutputChunks(n,e)}catch{n=void 0}}}catch(e){throw await u?.handleChainError(e),e}await u?.handleChainEnd(F(n,"output"))}async batch(e,t,r){let a;if(r?.returnExceptions)throw Error("Not implemented.");let n=this._getOptionsList(t??{},e.length),i=await Promise.all(n.map(e=>(0,y.getCallbackManagerForConfig)(e))),s=await Promise.all(i.map(async(t,r)=>{let a=await t?.handleChainStart(this.toJSON(),F(e[r],"input"),n[r].runId,void 0,void 0,void 0,n[r].runName);return delete n[r].runId,a}));for(let t of this.runnables()){n[0].signal?.throwIfAborted();try{let a=await t.batch(e,s.map((e,t)=>(0,y.patchConfig)(n[t],{callbacks:e?.getChild()})),r);return await Promise.all(s.map((e,t)=>e?.handleChainEnd(F(a[t],"output")))),a}catch(e){void 0===a&&(a=e)}}if(!a)throw Error("No error stored at end of fallbacks.");throw await Promise.all(s.map(e=>e?.handleChainError(a))),a}};function ee(e){if("function"==typeof e)return new Y({func:e});if(H.isRunnable(e))return e;if(Array.isArray(e)||"object"!=typeof e)throw Error(`Expected a Runnable, function or object. Instead got an unsupported type.`);{let t={};for(let[r,a]of Object.entries(e))t[r]=ee(a);return new V({steps:t})}}var et=class extends H{static lc_name(){return"RunnableAssign"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;mapper;constructor(e){e instanceof V&&(e={mapper:e}),super(e),this.mapper=e.mapper}async invoke(e,t){let r=await this.mapper.invoke(e,t);return{...e,...r}}async *_transform(e,t,r){let a=this.mapper.getStepsKeys(),[n,i]=(0,b.atee)(e),s=this.mapper.transform(i,(0,y.patchConfig)(r,{callbacks:t?.getChild()})),o=s.next();for await(let e of n){if("object"!=typeof e||Array.isArray(e))throw Error(`RunnableAssign can only be used with objects as input, got ${typeof e}`);let t=Object.fromEntries(Object.entries(e).filter(([e])=>!a.includes(e)));Object.keys(t).length>0&&(yield t)}for await(let e of(yield(await o).value,s))yield e}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*r(){yield e}let a=(0,y.ensureConfig)(t),n=new b.AsyncGeneratorWithSetup({generator:this.transform(r(),a),config:a});return await n.setup,b.IterableReadableStream.fromAsyncGenerator(n)}},er=class extends H{static lc_name(){return"RunnablePick"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;keys;constructor(e){("string"==typeof e||Array.isArray(e))&&(e={keys:e}),super(e),this.keys=e.keys}async _pick(e){if("string"==typeof this.keys)return e[this.keys];{let t=this.keys.map(t=>[t,e[t]]).filter(e=>void 0!==e[1]);return 0===t.length?void 0:Object.fromEntries(t)}}async invoke(e,t){return this._callWithConfig(this._pick.bind(this),e,t)}async *_transform(e){for await(let t of e){let e=await this._pick(t);void 0!==e&&(yield e)}}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*r(){yield e}let a=(0,y.ensureConfig)(t),n=new b.AsyncGeneratorWithSetup({generator:this.transform(r(),a),config:a});return await n.setup,b.IterableReadableStream.fromAsyncGenerator(n)}},ea=class extends q{name;description;schema;constructor(e){super({bound:W.from([Y.from(async e=>{let t;if((0,f._isToolCall)(e))try{t=await (0,T.interopParseAsync)(this.schema,e.args)}catch{throw new f.ToolInputParsingException("Received tool input did not match expected schema",JSON.stringify(e.args))}else t=e;return t}).withConfig({runName:`${e.name}:parse_input`}),e.bound]).withConfig({runName:e.name}),config:e.config??{}}),this.name=e.name,this.description=e.description,this.schema=e.schema}static lc_name(){return"RunnableToolLike"}};e.s(["Runnable",0,H,"RunnableAssign",0,et,"RunnableBinding",0,q,"RunnableEach",0,J,"RunnableLambda",0,Y,"RunnableMap",0,V,"RunnableParallel",0,Q,"RunnablePick",0,er,"RunnableRetry",0,G,"RunnableSequence",0,W,"RunnableToolLike",0,ea,"RunnableWithFallbacks",0,X,"_coerceToDict",0,F,"_coerceToRunnable",0,ee],420204);let en=(e,t)=>{let r=[...new Set(t?.map(e=>{if("string"==typeof e)return e;let t=new e({});if(!("getType"in t)||"function"!=typeof t.getType)throw Error("Invalid type provided.");return t.getType()}))],a=e.getType();return r.some(e=>e===a)};function ei(e,t){return Array.isArray(e)?es(e,t):Y.from(t=>es(t,e))}function es(e,t={}){let{includeNames:r,excludeNames:a,includeTypes:n,excludeTypes:i,includeIds:s,excludeIds:o}=t,l=[];for(let t of e)if(!(a&&t.name&&a.includes(t.name))){if(i&&en(t,i))continue;if(o&&t.id&&o.includes(t.id))continue;n||s||r?r&&t.name&&r.some(e=>e===t.name)||n&&en(t,n)?l.push(t):s&&t.id&&s.some(e=>e===t.id)&&l.push(t):l.push(t)}return l}function eo(e){return Array.isArray(e)?el(e):Y.from(el)}function el(e){if(!e.length)return[];let t=[];for(let r of e){let e=t.pop();if(e)if("tool"===r.getType()||r.getType()!==e.getType())t.push(e,r);else{let a=(0,p.convertToChunk)(e),n=(0,p.convertToChunk)(r),i=a.concat(n);"string"==typeof a.content&&"string"==typeof n.content&&(i.content=`${a.content} ${n.content}`),t.push(function(e){let t,r=e.getType(),a=Object.fromEntries(Object.entries(e).filter(([e])=>!["type","tool_call_chunks"].includes(e)&&!e.startsWith("lc_")));if(r in ep&&(t=ef(r,a)),!t)throw Error(`Unrecognized message chunk class ${r}. Supported classes are ${Object.keys(ep)}`);return t}(i))}else t.push(r)}return t}function eu(e,t){if(!Array.isArray(e))return Y.from(t=>ed(t,e)).withConfig({runName:"trim_messages"});if(!t)throw Error("Options parameter is required when providing messages.");return ed(e,t)}async function ed(e,t){let r,{maxTokens:a,tokenCounter:n,strategy:i="last",allowPartial:s=!1,endOn:o,startOn:l,includeSystem:u=!1,textSplitter:d}=t;if(l&&"first"===i)throw Error("`startOn` should only be specified if `strategy` is 'last'.");if(u&&"first"===i)throw Error("`includeSystem` should only be specified if `strategy` is 'last'.");r="getNumTokens"in n?async e=>(await Promise.all(e.map(e=>n.getNumTokens(e.content)))).reduce((e,t)=>e+t,0):async e=>n(e);let c=em;if(d&&(c="splitText"in d?d.splitText:async e=>d(e)),"first"===i)return ec(e,{maxTokens:a,tokenCounter:r,textSplitter:c,partialStrategy:s?"first":void 0,endOn:o});if("last"===i)return eh(e,{maxTokens:a,tokenCounter:r,textSplitter:c,allowPartial:s,includeSystem:u,startOn:l,endOn:o});throw Error(`Unrecognized strategy: '${i}'. Must be one of 'first' or 'last'.`)}async function ec(e,t){let{maxTokens:r,tokenCounter:a,textSplitter:n,partialStrategy:i,endOn:s}=t,o=[...e],l=0;for(let e=0;e0?o.slice(0,-e):o)<=r){l=o.length-e;break}if(l"type"!==e&&!e.startsWith("lc_"))),c=ef(t.getType(),{...d,content:n}),h=[...o.slice(0,l),c];if(await a(h)<=r)o=h,l+=1,e=!0;else break}e&&"last"===i&&(t.content=[...s].reverse())}if(!e){let e,t=o[l];if(Array.isArray(t.content)&&t.content.some(e=>"string"==typeof e||"text"===e.type)?e=t.content.find(e=>"text"===e.type&&e.text)?.text:"string"==typeof t.content&&(e=t.content),e){let s=await n(e),u=s.length;"last"===i&&s.reverse();for(let e=0;e0&&!en(o[l-1],e);)l-=1}return o.slice(0,l)}async function eh(e,t){let{allowPartial:r=!1,includeSystem:a=!1,endOn:i,startOn:s,...o}=t,l=e.map(e=>{let t=Object.fromEntries(Object.entries(e).filter(([e])=>"type"!==e&&!e.startsWith("lc_")));return ef(e.getType(),t,(0,n.isBaseMessageChunk)(e))});if(i){let e=Array.isArray(i)?i:[i];for(;l.length>0&&!en(l[l.length-1],e);)l=l.slice(0,-1)}let u=a&&l[0]?.getType()==="system",d=u?l.slice(0,1).concat(l.slice(1).reverse()):l.reverse();return(d=await ec(d,{...o,partialStrategy:r?"last":void 0,endOn:s}),u)?[d[0],...d.slice(1).reverse()]:d.reverse()}let ep={human:{message:d.HumanMessage,messageChunk:d.HumanMessageChunk},ai:{message:o.AIMessage,messageChunk:o.AIMessageChunk},system:{message:h.SystemMessage,messageChunk:h.SystemMessageChunk},developer:{message:h.SystemMessage,messageChunk:h.SystemMessageChunk},tool:{message:s.ToolMessage,messageChunk:s.ToolMessageChunk},function:{message:u.FunctionMessage,messageChunk:u.FunctionMessageChunk},generic:{message:l.ChatMessage,messageChunk:l.ChatMessageChunk},remove:{message:c.RemoveMessage,messageChunk:c.RemoveMessage}};function ef(e,t,r){let a,n;switch(e){case"human":r?a=new d.HumanMessageChunk(t):n=new d.HumanMessage(t);break;case"ai":if(r){let e={...t};"tool_calls"in e&&(e={...e,tool_call_chunks:e.tool_calls?.map(e=>({...e,type:"tool_call_chunk",index:void 0,args:JSON.stringify(e.args)}))}),a=new o.AIMessageChunk(e)}else n=new o.AIMessage(t);break;case"system":r?a=new h.SystemMessageChunk(t):n=new h.SystemMessage(t);break;case"developer":r?a=new h.SystemMessageChunk({...t,additional_kwargs:{...t.additional_kwargs,__openai_role__:"developer"}}):n=new h.SystemMessage({...t,additional_kwargs:{...t.additional_kwargs,__openai_role__:"developer"}});break;case"tool":if("tool_call_id"in t)r?a=new s.ToolMessageChunk(t):n=new s.ToolMessage(t);else throw Error("Can not convert ToolMessage to ToolMessageChunk if 'tool_call_id' field is not defined.");break;case"function":if(r)a=new u.FunctionMessageChunk(t);else{if(!t.name)throw Error("FunctionMessage must have a 'name' field");n=new u.FunctionMessage(t)}break;case"generic":if("role"in t)r?a=new l.ChatMessageChunk(t):n=new l.ChatMessage(t);else throw Error("Can not convert ChatMessage to ChatMessageChunk if 'role' field is not defined.");break;default:throw Error(`Unrecognized message type ${e}`)}if(r&&a)return a;if(n)return n;throw Error(`Unrecognized message type ${e}`)}function em(e){let t=e.split("\n");return Promise.resolve([...t.slice(0,-1).map(e=>`${e} `),t[t.length-1]])}e.s(["defaultTextSplitter",0,em,"filterMessages",0,ei,"mergeMessageRuns",0,eo,"trimMessages",0,eu],692660);let eg=["text","reasoning","tool_call","tool_call_chunk","invalid_tool_call","server_tool_call","server_tool_call_chunk","server_tool_call_result","image","video","audio","text-plain","file"];e.s(["KNOWN_BLOCK_TYPES",0,eg],209387);var e_=(0,t.__exportAll)({AIMessage:()=>o.AIMessage,AIMessageChunk:()=>o.AIMessageChunk,BaseMessage:()=>n.BaseMessage,BaseMessageChunk:()=>n.BaseMessageChunk,ChatMessage:()=>l.ChatMessage,ChatMessageChunk:()=>l.ChatMessageChunk,DEFAULT_MERGE_IGNORE_KEYS:()=>n.DEFAULT_MERGE_IGNORE_KEYS,FunctionMessage:()=>u.FunctionMessage,FunctionMessageChunk:()=>u.FunctionMessageChunk,HumanMessage:()=>d.HumanMessage,HumanMessageChunk:()=>d.HumanMessageChunk,KNOWN_BLOCK_TYPES:()=>eg,RemoveMessage:()=>c.RemoveMessage,SystemMessage:()=>h.SystemMessage,SystemMessageChunk:()=>h.SystemMessageChunk,ToolMessage:()=>s.ToolMessage,ToolMessageChunk:()=>s.ToolMessageChunk,_isMessageFieldWithRole:()=>n._isMessageFieldWithRole,_mergeDicts:()=>n._mergeDicts,_mergeLists:()=>n._mergeLists,_mergeObj:()=>n._mergeObj,_mergeStatus:()=>n._mergeStatus,coerceMessageLikeToMessage:()=>p.coerceMessageLikeToMessage,collapseToolCallChunks:()=>p.collapseToolCallChunks,convertToChunk:()=>p.convertToChunk,convertToOpenAIImageBlock:()=>r.convertToOpenAIImageBlock,convertToProviderContentBlock:()=>r.convertToProviderContentBlock,defaultTextSplitter:()=>em,defaultToolCallParser:()=>s.defaultToolCallParser,filterMessages:()=>ei,getBufferString:()=>p.getBufferString,iife:()=>p.iife,isAIMessage:()=>o.isAIMessage,isAIMessageChunk:()=>o.isAIMessageChunk,isBase64ContentBlock:()=>r.isBase64ContentBlock,isBaseMessage:()=>n.isBaseMessage,isBaseMessageChunk:()=>n.isBaseMessageChunk,isChatMessage:()=>l.isChatMessage,isChatMessageChunk:()=>l.isChatMessageChunk,isDataContentBlock:()=>r.isDataContentBlock,isDirectToolOutput:()=>s.isDirectToolOutput,isFunctionMessage:()=>u.isFunctionMessage,isFunctionMessageChunk:()=>u.isFunctionMessageChunk,isHumanMessage:()=>d.isHumanMessage,isHumanMessageChunk:()=>d.isHumanMessageChunk,isIDContentBlock:()=>r.isIDContentBlock,isMessage:()=>a.isMessage,isOpenAIToolCallArray:()=>n.isOpenAIToolCallArray,isPlainTextContentBlock:()=>r.isPlainTextContentBlock,isSystemMessage:()=>h.isSystemMessage,isSystemMessageChunk:()=>h.isSystemMessageChunk,isToolMessage:()=>s.isToolMessage,isToolMessageChunk:()=>s.isToolMessageChunk,isURLContentBlock:()=>r.isURLContentBlock,mapChatMessagesToStoredMessages:()=>p.mapChatMessagesToStoredMessages,mapStoredMessageToChatMessage:()=>p.mapStoredMessageToChatMessage,mapStoredMessagesToChatMessages:()=>p.mapStoredMessagesToChatMessages,mergeContent:()=>n.mergeContent,mergeMessageRuns:()=>eo,mergeResponseMetadata:()=>i.mergeResponseMetadata,mergeUsageMetadata:()=>i.mergeUsageMetadata,parseBase64DataUrl:()=>r.parseBase64DataUrl,parseMimeType:()=>r.parseMimeType,trimMessages:()=>eu});e.s(["messages_exports",0,e_],637253)}]; //# sourceMappingURL=node_modules_09gr7yb._.js.map