@arcgis/ai-components 5.0.0-next.146 → 5.0.0-next.147
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cdn/32RHG3TZ.js +2 -0
- package/dist/cdn/4OI2H5S3.js +2 -0
- package/dist/cdn/4XCE2WFV.js +239 -0
- package/dist/cdn/BJWHZ3FS.js +2 -0
- package/dist/cdn/DI5BLAXO.js +2 -0
- package/dist/cdn/HNKWDK3D.js +2 -0
- package/dist/cdn/{WACZ5XRA.js → JCZAM66N.js} +2 -2
- package/dist/cdn/LI7VOWXM.js +267 -0
- package/dist/cdn/QZJ4SRT5.js +5 -0
- package/dist/cdn/SOPVTUE3.js +2 -0
- package/dist/cdn/index.js +1 -1
- package/dist/components/arcgis-assistant/customElement.d.ts +5 -5
- package/dist/components/arcgis-assistant-data-exploration-agent/customElement.d.ts +2 -2
- package/dist/components/arcgis-assistant-navigation-agent/customElement.d.ts +1 -1
- package/dist/docs/api.json +1 -1
- package/dist/docs/docs.json +1 -1
- package/dist/docs/vscode.html-custom-data.json +1 -1
- package/dist/docs/web-types.json +1 -1
- package/package.json +7 -7
- package/dist/cdn/6XEDIXV6.js +0 -2
- package/dist/cdn/COWIXD4Q.js +0 -223
- package/dist/cdn/CSFLVW7O.js +0 -2
- package/dist/cdn/CSKRXBVL.js +0 -85
- package/dist/cdn/CYROVXBC.js +0 -2
- package/dist/cdn/DCXWRVNH.js +0 -2
- package/dist/cdn/JPUY3X54.js +0 -2
- package/dist/cdn/KRDVOF7K.js +0 -15
- package/dist/cdn/OV52XKSU.js +0 -2
- package/dist/cdn/QWJL7VTJ.js +0 -132
- package/dist/cdn/WZKKSDIC.js +0 -2
- package/dist/cdn/YRUSAZLS.js +0 -2
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
/* COPYRIGHT Esri - https://js.arcgis.com/5.0/LICENSE.txt */
|
|
2
|
+
import{a as ae,b as Cs,c as Ps}from"./2GMCG6SX.js";export default $arcgis.t(([QE,$_,yq])=>{var yk=ae((WH,_k)=>{"use strict";_k.exports=function(e,t){if(typeof e!="string")throw new TypeError("Expected a string");return t=typeof t>"u"?"_":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()}});var Ek=ae((JH,q_)=>{"use strict";var Yz=/[\p{Lu}]/u,Qz=/[\p{Ll}]/u,vk=/^[\p{Lu}](?![\p{Lu}])/gu,xk=/([\p{Alpha}\p{N}_]|$)/u,Ik=/[_.\- ]+/,eL=new RegExp("^"+Ik.source),bk=new RegExp(Ik.source+xk.source,"gu"),wk=new RegExp("\\d+"+xk.source,"gu"),tL=(e,t,r)=>{let n=!1,i=!1,s=!1;for(let o=0;o<e.length;o++){let a=e[o];n&&Yz.test(a)?(e=e.slice(0,o)+"-"+e.slice(o),n=!1,s=i,i=!0,o++):i&&s&&Qz.test(a)?(e=e.slice(0,o-1)+"-"+e.slice(o-1),s=i,i=!1,n=!0):(n=t(a)===a&&r(a)!==a,s=i,i=r(a)===a&&t(a)!==a)}return e},rL=(e,t)=>(vk.lastIndex=0,e.replace(vk,r=>t(r))),nL=(e,t)=>(bk.lastIndex=0,wk.lastIndex=0,e.replace(bk,(r,n)=>t(n)).replace(wk,r=>t(r))),Sk=(e,t)=>{if(!(typeof e=="string"||Array.isArray(e)))throw new TypeError("Expected the input to be `string | string[]`");if(t={pascalCase:!1,preserveConsecutiveUppercase:!1,...t},Array.isArray(e)?e=e.map(s=>s.trim()).filter(s=>s.length).join("-"):e=e.trim(),e.length===0)return"";let r=t.locale===!1?s=>s.toLowerCase():s=>s.toLocaleLowerCase(t.locale),n=t.locale===!1?s=>s.toUpperCase():s=>s.toLocaleUpperCase(t.locale);return e.length===1?t.pascalCase?n(e):r(e):(e!==r(e)&&(e=tL(e,r,n)),e=e.replace(eL,""),t.preserveConsecutiveUppercase?e=rL(e,r):e=r(e),t.pascalCase&&(e=n(e.charAt(0))+e.slice(1)),nL(e,n))};q_.exports=Sk;q_.exports.default=Sk});var DA=ae((_8,Ey)=>{"use strict";var UL=Object.prototype.hasOwnProperty,lr="~";function Il(){}Object.create&&(Il.prototype=Object.create(null),new Il().__proto__||(lr=!1));function FL(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function jA(e,t,r,n,i){if(typeof r!="function")throw new TypeError("The listener must be a function");var s=new FL(r,n||e,i),o=lr?lr+t:t;return e._events[o]?e._events[o].fn?e._events[o]=[e._events[o],s]:e._events[o].push(s):(e._events[o]=s,e._eventsCount++),e}function Af(e,t){--e._eventsCount===0?e._events=new Il:delete e._events[t]}function Jt(){this._events=new Il,this._eventsCount=0}Jt.prototype.eventNames=function(){var t=[],r,n;if(this._eventsCount===0)return t;for(n in r=this._events)UL.call(r,n)&&t.push(lr?n.slice(1):n);return Object.getOwnPropertySymbols?t.concat(Object.getOwnPropertySymbols(r)):t};Jt.prototype.listeners=function(t){var r=lr?lr+t:t,n=this._events[r];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,s=n.length,o=new Array(s);i<s;i++)o[i]=n[i].fn;return o};Jt.prototype.listenerCount=function(t){var r=lr?lr+t:t,n=this._events[r];return n?n.fn?1:n.length:0};Jt.prototype.emit=function(t,r,n,i,s,o){var a=lr?lr+t:t;if(!this._events[a])return!1;var c=this._events[a],u=arguments.length,l,p;if(c.fn){switch(c.once&&this.removeListener(t,c.fn,void 0,!0),u){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,r),!0;case 3:return c.fn.call(c.context,r,n),!0;case 4:return c.fn.call(c.context,r,n,i),!0;case 5:return c.fn.call(c.context,r,n,i,s),!0;case 6:return c.fn.call(c.context,r,n,i,s,o),!0}for(p=1,l=new Array(u-1);p<u;p++)l[p-1]=arguments[p];c.fn.apply(c.context,l)}else{var f=c.length,d;for(p=0;p<f;p++)switch(c[p].once&&this.removeListener(t,c[p].fn,void 0,!0),u){case 1:c[p].fn.call(c[p].context);break;case 2:c[p].fn.call(c[p].context,r);break;case 3:c[p].fn.call(c[p].context,r,n);break;case 4:c[p].fn.call(c[p].context,r,n,i);break;default:if(!l)for(d=1,l=new Array(u-1);d<u;d++)l[d-1]=arguments[d];c[p].fn.apply(c[p].context,l)}}return!0};Jt.prototype.on=function(t,r,n){return jA(this,t,r,n,!1)};Jt.prototype.once=function(t,r,n){return jA(this,t,r,n,!0)};Jt.prototype.removeListener=function(t,r,n,i){var s=lr?lr+t:t;if(!this._events[s])return this;if(!r)return Af(this,s),this;var o=this._events[s];if(o.fn)o.fn===r&&(!i||o.once)&&(!n||o.context===n)&&Af(this,s);else{for(var a=0,c=[],u=o.length;a<u;a++)(o[a].fn!==r||i&&!o[a].once||n&&o[a].context!==n)&&c.push(o[a]);c.length?this._events[s]=c.length===1?c[0]:c:Af(this,s)}return this};Jt.prototype.removeAllListeners=function(t){var r;return t?(r=lr?lr+t:t,this._events[r]&&Af(this,r)):(this._events=new Il,this._eventsCount=0),this};Jt.prototype.off=Jt.prototype.removeListener;Jt.prototype.addListener=Jt.prototype.on;Jt.prefixed=lr;Jt.EventEmitter=Jt;typeof Ey<"u"&&(Ey.exports=Jt)});var LA=ae((y8,zA)=>{"use strict";zA.exports=(e,t)=>(t=t||(()=>{}),e.then(r=>new Promise(n=>{n(t())}).then(()=>r),r=>new Promise(n=>{n(t())}).then(()=>{throw r})))});var FA=ae((v8,Of)=>{"use strict";var BL=LA(),Tf=class extends Error{constructor(t){super(t),this.name="TimeoutError"}},UA=(e,t,r)=>new Promise((n,i)=>{if(typeof t!="number"||t<0)throw new TypeError("Expected `milliseconds` to be a positive number");if(t===1/0){n(e);return}let s=setTimeout(()=>{if(typeof r=="function"){try{n(r())}catch(c){i(c)}return}let o=typeof r=="string"?r:`Promise timed out after ${t} milliseconds`,a=r instanceof Error?r:new Tf(o);typeof e.cancel=="function"&&e.cancel(),i(a)},t);BL(e.then(n,i),()=>{clearTimeout(s)})});Of.exports=UA;Of.exports.default=UA;Of.exports.TimeoutError=Tf});var BA=ae(ky=>{"use strict";Object.defineProperty(ky,"__esModule",{value:!0});function VL(e,t,r){let n=0,i=e.length;for(;i>0;){let s=i/2|0,o=n+s;r(e[o],t)<=0?(n=++o,i-=s+1):i=s}return n}ky.default=VL});var VA=ae(Ty=>{"use strict";Object.defineProperty(Ty,"__esModule",{value:!0});var ZL=BA(),Ay=class{constructor(){this._queue=[]}enqueue(t,r){r=Object.assign({priority:0},r);let n={priority:r.priority,run:t};if(this.size&&this._queue[this.size-1].priority>=r.priority){this._queue.push(n);return}let i=ZL.default(this._queue,n,(s,o)=>o.priority-s.priority);this._queue.splice(i,0,n)}dequeue(){let t=this._queue.shift();return t?.run}filter(t){return this._queue.filter(r=>r.priority===t.priority).map(r=>r.run)}get size(){return this._queue.length}};Ty.default=Ay});var Cf=ae($y=>{"use strict";Object.defineProperty($y,"__esModule",{value:!0});var GL=DA(),ZA=FA(),KL=VA(),$f=()=>{},qL=new ZA.TimeoutError,Oy=class extends GL{constructor(t){var r,n,i,s;if(super(),this._intervalCount=0,this._intervalEnd=0,this._pendingCount=0,this._resolveEmpty=$f,this._resolveIdle=$f,t=Object.assign({carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:KL.default},t),!(typeof t.intervalCap=="number"&&t.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(n=(r=t.intervalCap)===null||r===void 0?void 0:r.toString())!==null&&n!==void 0?n:""}\` (${typeof t.intervalCap})`);if(t.interval===void 0||!(Number.isFinite(t.interval)&&t.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(s=(i=t.interval)===null||i===void 0?void 0:i.toString())!==null&&s!==void 0?s:""}\` (${typeof t.interval})`);this._carryoverConcurrencyCount=t.carryoverConcurrencyCount,this._isIntervalIgnored=t.intervalCap===1/0||t.interval===0,this._intervalCap=t.intervalCap,this._interval=t.interval,this._queue=new t.queueClass,this._queueClass=t.queueClass,this.concurrency=t.concurrency,this._timeout=t.timeout,this._throwOnTimeout=t.throwOnTimeout===!0,this._isPaused=t.autoStart===!1}get _doesIntervalAllowAnother(){return this._isIntervalIgnored||this._intervalCount<this._intervalCap}get _doesConcurrentAllowAnother(){return this._pendingCount<this._concurrency}_next(){this._pendingCount--,this._tryToStartAnother(),this.emit("next")}_resolvePromises(){this._resolveEmpty(),this._resolveEmpty=$f,this._pendingCount===0&&(this._resolveIdle(),this._resolveIdle=$f,this.emit("idle"))}_onResumeInterval(){this._onInterval(),this._initializeIntervalIfNeeded(),this._timeoutId=void 0}_isIntervalPaused(){let t=Date.now();if(this._intervalId===void 0){let r=this._intervalEnd-t;if(r<0)this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0;else return this._timeoutId===void 0&&(this._timeoutId=setTimeout(()=>{this._onResumeInterval()},r)),!0}return!1}_tryToStartAnother(){if(this._queue.size===0)return this._intervalId&&clearInterval(this._intervalId),this._intervalId=void 0,this._resolvePromises(),!1;if(!this._isPaused){let t=!this._isIntervalPaused();if(this._doesIntervalAllowAnother&&this._doesConcurrentAllowAnother){let r=this._queue.dequeue();return r?(this.emit("active"),r(),t&&this._initializeIntervalIfNeeded(),!0):!1}}return!1}_initializeIntervalIfNeeded(){this._isIntervalIgnored||this._intervalId!==void 0||(this._intervalId=setInterval(()=>{this._onInterval()},this._interval),this._intervalEnd=Date.now()+this._interval)}_onInterval(){this._intervalCount===0&&this._pendingCount===0&&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(t){if(!(typeof t=="number"&&t>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${t}\` (${typeof t})`);this._concurrency=t,this._processQueue()}async add(t,r={}){return new Promise((n,i)=>{let s=async()=>{this._pendingCount++,this._intervalCount++;try{let o=this._timeout===void 0&&r.timeout===void 0?t():ZA.default(Promise.resolve(t()),r.timeout===void 0?this._timeout:r.timeout,()=>{(r.throwOnTimeout===void 0?this._throwOnTimeout:r.throwOnTimeout)&&i(qL)});n(await o)}catch(o){i(o)}this._next()};this._queue.enqueue(s,r),this._tryToStartAnother(),this.emit("add")})}async addAll(t,r){return Promise.all(t.map(async n=>this.add(n,r)))}start(){return this._isPaused?(this._isPaused=!1,this._processQueue(),this):this}pause(){this._isPaused=!0}clear(){this._queue=new this._queueClass}async onEmpty(){if(this._queue.size!==0)return new Promise(t=>{let r=this._resolveEmpty;this._resolveEmpty=()=>{r(),t()}})}async onIdle(){if(!(this._pendingCount===0&&this._queue.size===0))return new Promise(t=>{let r=this._resolveIdle;this._resolveIdle=()=>{r(),t()}})}get size(){return this._queue.size}sizeBy(t){return this._queue.filter(t).length}get pending(){return this._pendingCount}get isPaused(){return this._isPaused}get timeout(){return this._timeout}set timeout(t){this._timeout=t}};$y.default=Oy});var El=ae((k8,GA)=>{"use strict";var WL="2.0.0",JL=Number.MAX_SAFE_INTEGER||9007199254740991,XL=16,YL=250,QL=["major","premajor","minor","preminor","patch","prepatch","prerelease"];GA.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:XL,MAX_SAFE_BUILD_LENGTH:YL,MAX_SAFE_INTEGER:JL,RELEASE_TYPES:QL,SEMVER_SPEC_VERSION:WL,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var kl=ae((A8,KA)=>{"use strict";var eU=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error("SEMVER",...e):()=>{};KA.exports=eU});var fc=ae((si,qA)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:Ny,MAX_SAFE_BUILD_LENGTH:tU,MAX_LENGTH:rU}=El(),nU=kl();si=qA.exports={};var iU=si.re=[],sU=si.safeRe=[],Y=si.src=[],oU=si.safeSrc=[],Q=si.t={},aU=0,Ry="[a-zA-Z0-9-]",cU=[["\\s",1],["\\d",rU],[Ry,tU]],uU=e=>{for(let[t,r]of cU)e=e.split(`${t}*`).join(`${t}{0,${r}}`).split(`${t}+`).join(`${t}{1,${r}}`);return e},be=(e,t,r)=>{let n=uU(t),i=aU++;nU(e,i,t),Q[e]=i,Y[i]=t,oU[i]=n,iU[i]=new RegExp(t,r?"g":void 0),sU[i]=new RegExp(n,r?"g":void 0)};be("NUMERICIDENTIFIER","0|[1-9]\\d*");be("NUMERICIDENTIFIERLOOSE","\\d+");be("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${Ry}*`);be("MAINVERSION",`(${Y[Q.NUMERICIDENTIFIER]})\\.(${Y[Q.NUMERICIDENTIFIER]})\\.(${Y[Q.NUMERICIDENTIFIER]})`);be("MAINVERSIONLOOSE",`(${Y[Q.NUMERICIDENTIFIERLOOSE]})\\.(${Y[Q.NUMERICIDENTIFIERLOOSE]})\\.(${Y[Q.NUMERICIDENTIFIERLOOSE]})`);be("PRERELEASEIDENTIFIER",`(?:${Y[Q.NONNUMERICIDENTIFIER]}|${Y[Q.NUMERICIDENTIFIER]})`);be("PRERELEASEIDENTIFIERLOOSE",`(?:${Y[Q.NONNUMERICIDENTIFIER]}|${Y[Q.NUMERICIDENTIFIERLOOSE]})`);be("PRERELEASE",`(?:-(${Y[Q.PRERELEASEIDENTIFIER]}(?:\\.${Y[Q.PRERELEASEIDENTIFIER]})*))`);be("PRERELEASELOOSE",`(?:-?(${Y[Q.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${Y[Q.PRERELEASEIDENTIFIERLOOSE]})*))`);be("BUILDIDENTIFIER",`${Ry}+`);be("BUILD",`(?:\\+(${Y[Q.BUILDIDENTIFIER]}(?:\\.${Y[Q.BUILDIDENTIFIER]})*))`);be("FULLPLAIN",`v?${Y[Q.MAINVERSION]}${Y[Q.PRERELEASE]}?${Y[Q.BUILD]}?`);be("FULL",`^${Y[Q.FULLPLAIN]}$`);be("LOOSEPLAIN",`[v=\\s]*${Y[Q.MAINVERSIONLOOSE]}${Y[Q.PRERELEASELOOSE]}?${Y[Q.BUILD]}?`);be("LOOSE",`^${Y[Q.LOOSEPLAIN]}$`);be("GTLT","((?:<|>)?=?)");be("XRANGEIDENTIFIERLOOSE",`${Y[Q.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);be("XRANGEIDENTIFIER",`${Y[Q.NUMERICIDENTIFIER]}|x|X|\\*`);be("XRANGEPLAIN",`[v=\\s]*(${Y[Q.XRANGEIDENTIFIER]})(?:\\.(${Y[Q.XRANGEIDENTIFIER]})(?:\\.(${Y[Q.XRANGEIDENTIFIER]})(?:${Y[Q.PRERELEASE]})?${Y[Q.BUILD]}?)?)?`);be("XRANGEPLAINLOOSE",`[v=\\s]*(${Y[Q.XRANGEIDENTIFIERLOOSE]})(?:\\.(${Y[Q.XRANGEIDENTIFIERLOOSE]})(?:\\.(${Y[Q.XRANGEIDENTIFIERLOOSE]})(?:${Y[Q.PRERELEASELOOSE]})?${Y[Q.BUILD]}?)?)?`);be("XRANGE",`^${Y[Q.GTLT]}\\s*${Y[Q.XRANGEPLAIN]}$`);be("XRANGELOOSE",`^${Y[Q.GTLT]}\\s*${Y[Q.XRANGEPLAINLOOSE]}$`);be("COERCEPLAIN",`(^|[^\\d])(\\d{1,${Ny}})(?:\\.(\\d{1,${Ny}}))?(?:\\.(\\d{1,${Ny}}))?`);be("COERCE",`${Y[Q.COERCEPLAIN]}(?:$|[^\\d])`);be("COERCEFULL",Y[Q.COERCEPLAIN]+`(?:${Y[Q.PRERELEASE]})?(?:${Y[Q.BUILD]})?(?:$|[^\\d])`);be("COERCERTL",Y[Q.COERCE],!0);be("COERCERTLFULL",Y[Q.COERCEFULL],!0);be("LONETILDE","(?:~>?)");be("TILDETRIM",`(\\s*)${Y[Q.LONETILDE]}\\s+`,!0);si.tildeTrimReplace="$1~";be("TILDE",`^${Y[Q.LONETILDE]}${Y[Q.XRANGEPLAIN]}$`);be("TILDELOOSE",`^${Y[Q.LONETILDE]}${Y[Q.XRANGEPLAINLOOSE]}$`);be("LONECARET","(?:\\^)");be("CARETTRIM",`(\\s*)${Y[Q.LONECARET]}\\s+`,!0);si.caretTrimReplace="$1^";be("CARET",`^${Y[Q.LONECARET]}${Y[Q.XRANGEPLAIN]}$`);be("CARETLOOSE",`^${Y[Q.LONECARET]}${Y[Q.XRANGEPLAINLOOSE]}$`);be("COMPARATORLOOSE",`^${Y[Q.GTLT]}\\s*(${Y[Q.LOOSEPLAIN]})$|^$`);be("COMPARATOR",`^${Y[Q.GTLT]}\\s*(${Y[Q.FULLPLAIN]})$|^$`);be("COMPARATORTRIM",`(\\s*)${Y[Q.GTLT]}\\s*(${Y[Q.LOOSEPLAIN]}|${Y[Q.XRANGEPLAIN]})`,!0);si.comparatorTrimReplace="$1$2$3";be("HYPHENRANGE",`^\\s*(${Y[Q.XRANGEPLAIN]})\\s+-\\s+(${Y[Q.XRANGEPLAIN]})\\s*$`);be("HYPHENRANGELOOSE",`^\\s*(${Y[Q.XRANGEPLAINLOOSE]})\\s+-\\s+(${Y[Q.XRANGEPLAINLOOSE]})\\s*$`);be("STAR","(<|>)?=?\\s*\\*");be("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");be("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var Nf=ae((T8,HA)=>{"use strict";var lU=Object.freeze({loose:!0}),pU=Object.freeze({}),dU=e=>e?typeof e!="object"?lU:e:pU;HA.exports=dU});var My=ae((O8,XA)=>{"use strict";var WA=/^[0-9]+$/,JA=(e,t)=>{if(typeof e=="number"&&typeof t=="number")return e===t?0:e<t?-1:1;let r=WA.test(e),n=WA.test(t);return r&&n&&(e=+e,t=+t),e===t?0:r&&!n?-1:n&&!r?1:e<t?-1:1},fU=(e,t)=>JA(t,e);XA.exports={compareIdentifiers:JA,rcompareIdentifiers:fU}});var Xt=ae(($8,QA)=>{"use strict";var Rf=kl(),{MAX_LENGTH:YA,MAX_SAFE_INTEGER:Mf}=El(),{safeRe:jf,t:Df}=fc(),mU=Nf(),{compareIdentifiers:jy}=My(),Dy=class e{constructor(t,r){if(r=mU(r),t instanceof e){if(t.loose===!!r.loose&&t.includePrerelease===!!r.includePrerelease)return t;t=t.version}else if(typeof t!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof t}".`);if(t.length>YA)throw new TypeError(`version is longer than ${YA} characters`);Rf("SemVer",t,r),this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease;let n=t.trim().match(r.loose?jf[Df.LOOSE]:jf[Df.FULL]);if(!n)throw new TypeError(`Invalid Version: ${t}`);if(this.raw=t,this.major=+n[1],this.minor=+n[2],this.patch=+n[3],this.major>Mf||this.major<0)throw new TypeError("Invalid major version");if(this.minor>Mf||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>Mf||this.patch<0)throw new TypeError("Invalid patch version");n[4]?this.prerelease=n[4].split(".").map(i=>{if(/^[0-9]+$/.test(i)){let s=+i;if(s>=0&&s<Mf)return s}return i}):this.prerelease=[],this.build=n[5]?n[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(t){if(Rf("SemVer.compare",this.version,this.options,t),!(t instanceof e)){if(typeof t=="string"&&t===this.version)return 0;t=new e(t,this.options)}return t.version===this.version?0:this.compareMain(t)||this.comparePre(t)}compareMain(t){return t instanceof e||(t=new e(t,this.options)),this.major<t.major?-1:this.major>t.major?1:this.minor<t.minor?-1:this.minor>t.minor?1:this.patch<t.patch?-1:this.patch>t.patch?1:0}comparePre(t){if(t instanceof e||(t=new e(t,this.options)),this.prerelease.length&&!t.prerelease.length)return-1;if(!this.prerelease.length&&t.prerelease.length)return 1;if(!this.prerelease.length&&!t.prerelease.length)return 0;let r=0;do{let n=this.prerelease[r],i=t.prerelease[r];if(Rf("prerelease compare",r,n,i),n===void 0&&i===void 0)return 0;if(i===void 0)return 1;if(n===void 0)return-1;if(n===i)continue;return jy(n,i)}while(++r)}compareBuild(t){t instanceof e||(t=new e(t,this.options));let r=0;do{let n=this.build[r],i=t.build[r];if(Rf("build compare",r,n,i),n===void 0&&i===void 0)return 0;if(i===void 0)return 1;if(n===void 0)return-1;if(n===i)continue;return jy(n,i)}while(++r)}inc(t,r,n){if(t.startsWith("pre")){if(!r&&n===!1)throw new Error("invalid increment argument: identifier is empty");if(r){let i=`-${r}`.match(this.options.loose?jf[Df.PRERELEASELOOSE]:jf[Df.PRERELEASE]);if(!i||i[1]!==r)throw new Error(`invalid identifier: ${r}`)}}switch(t){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",r,n);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",r,n);break;case"prepatch":this.prerelease.length=0,this.inc("patch",r,n),this.inc("pre",r,n);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",r,n),this.inc("pre",r,n);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{let i=Number(n)?1:0;if(this.prerelease.length===0)this.prerelease=[i];else{let s=this.prerelease.length;for(;--s>=0;)typeof this.prerelease[s]=="number"&&(this.prerelease[s]++,s=-2);if(s===-1){if(r===this.prerelease.join(".")&&n===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(i)}}if(r){let s=[r,i];n===!1&&(s=[r]),jy(this.prerelease[0],r)===0?isNaN(this.prerelease[1])&&(this.prerelease=s):this.prerelease=s}break}default:throw new Error(`invalid increment argument: ${t}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};QA.exports=Dy});var Do=ae((C8,tT)=>{"use strict";var eT=Xt(),hU=(e,t,r=!1)=>{if(e instanceof eT)return e;try{return new eT(e,t)}catch(n){if(!r)return null;throw n}};tT.exports=hU});var nT=ae((P8,rT)=>{"use strict";var gU=Do(),_U=(e,t)=>{let r=gU(e,t);return r?r.version:null};rT.exports=_U});var sT=ae((N8,iT)=>{"use strict";var yU=Do(),vU=(e,t)=>{let r=yU(e.trim().replace(/^[=v]+/,""),t);return r?r.version:null};iT.exports=vU});var cT=ae((R8,aT)=>{"use strict";var oT=Xt(),bU=(e,t,r,n,i)=>{typeof r=="string"&&(i=n,n=r,r=void 0);try{return new oT(e instanceof oT?e.version:e,r).inc(t,n,i).version}catch{return null}};aT.exports=bU});var pT=ae((M8,lT)=>{"use strict";var uT=Do(),wU=(e,t)=>{let r=uT(e,null,!0),n=uT(t,null,!0),i=r.compare(n);if(i===0)return null;let s=i>0,o=s?r:n,a=s?n:r,c=!!o.prerelease.length;if(!!a.prerelease.length&&!c){if(!a.patch&&!a.minor)return"major";if(a.compareMain(o)===0)return a.minor&&!a.patch?"minor":"patch"}let l=c?"pre":"";return r.major!==n.major?l+"major":r.minor!==n.minor?l+"minor":r.patch!==n.patch?l+"patch":"prerelease"};lT.exports=wU});var fT=ae((j8,dT)=>{"use strict";var xU=Xt(),IU=(e,t)=>new xU(e,t).major;dT.exports=IU});var hT=ae((D8,mT)=>{"use strict";var SU=Xt(),EU=(e,t)=>new SU(e,t).minor;mT.exports=EU});var _T=ae((z8,gT)=>{"use strict";var kU=Xt(),AU=(e,t)=>new kU(e,t).patch;gT.exports=AU});var vT=ae((L8,yT)=>{"use strict";var TU=Do(),OU=(e,t)=>{let r=TU(e,t);return r&&r.prerelease.length?r.prerelease:null};yT.exports=OU});var on=ae((U8,wT)=>{"use strict";var bT=Xt(),$U=(e,t,r)=>new bT(e,r).compare(new bT(t,r));wT.exports=$U});var IT=ae((F8,xT)=>{"use strict";var CU=on(),PU=(e,t,r)=>CU(t,e,r);xT.exports=PU});var ET=ae((B8,ST)=>{"use strict";var NU=on(),RU=(e,t)=>NU(e,t,!0);ST.exports=RU});var zf=ae((V8,AT)=>{"use strict";var kT=Xt(),MU=(e,t,r)=>{let n=new kT(e,r),i=new kT(t,r);return n.compare(i)||n.compareBuild(i)};AT.exports=MU});var OT=ae((Z8,TT)=>{"use strict";var jU=zf(),DU=(e,t)=>e.sort((r,n)=>jU(r,n,t));TT.exports=DU});var CT=ae((G8,$T)=>{"use strict";var zU=zf(),LU=(e,t)=>e.sort((r,n)=>zU(n,r,t));$T.exports=LU});var Al=ae((K8,PT)=>{"use strict";var UU=on(),FU=(e,t,r)=>UU(e,t,r)>0;PT.exports=FU});var Lf=ae((q8,NT)=>{"use strict";var BU=on(),VU=(e,t,r)=>BU(e,t,r)<0;NT.exports=VU});var zy=ae((H8,RT)=>{"use strict";var ZU=on(),GU=(e,t,r)=>ZU(e,t,r)===0;RT.exports=GU});var Ly=ae((W8,MT)=>{"use strict";var KU=on(),qU=(e,t,r)=>KU(e,t,r)!==0;MT.exports=qU});var Uf=ae((J8,jT)=>{"use strict";var HU=on(),WU=(e,t,r)=>HU(e,t,r)>=0;jT.exports=WU});var Ff=ae((X8,DT)=>{"use strict";var JU=on(),XU=(e,t,r)=>JU(e,t,r)<=0;DT.exports=XU});var Uy=ae((Y8,zT)=>{"use strict";var YU=zy(),QU=Ly(),e4=Al(),t4=Uf(),r4=Lf(),n4=Ff(),i4=(e,t,r,n)=>{switch(t){case"===":return typeof e=="object"&&(e=e.version),typeof r=="object"&&(r=r.version),e===r;case"!==":return typeof e=="object"&&(e=e.version),typeof r=="object"&&(r=r.version),e!==r;case"":case"=":case"==":return YU(e,r,n);case"!=":return QU(e,r,n);case">":return e4(e,r,n);case">=":return t4(e,r,n);case"<":return r4(e,r,n);case"<=":return n4(e,r,n);default:throw new TypeError(`Invalid operator: ${t}`)}};zT.exports=i4});var UT=ae((Q8,LT)=>{"use strict";var s4=Xt(),o4=Do(),{safeRe:Bf,t:Vf}=fc(),a4=(e,t)=>{if(e instanceof s4)return e;if(typeof e=="number"&&(e=String(e)),typeof e!="string")return null;t=t||{};let r=null;if(!t.rtl)r=e.match(t.includePrerelease?Bf[Vf.COERCEFULL]:Bf[Vf.COERCE]);else{let c=t.includePrerelease?Bf[Vf.COERCERTLFULL]:Bf[Vf.COERCERTL],u;for(;(u=c.exec(e))&&(!r||r.index+r[0].length!==e.length);)(!r||u.index+u[0].length!==r.index+r[0].length)&&(r=u),c.lastIndex=u.index+u[1].length+u[2].length;c.lastIndex=-1}if(r===null)return null;let n=r[2],i=r[3]||"0",s=r[4]||"0",o=t.includePrerelease&&r[5]?`-${r[5]}`:"",a=t.includePrerelease&&r[6]?`+${r[6]}`:"";return o4(`${n}.${i}.${s}${o}${a}`,t)};LT.exports=a4});var BT=ae((eJ,FT)=>{"use strict";var Fy=class{constructor(){this.max=1e3,this.map=new Map}get(t){let r=this.map.get(t);if(r!==void 0)return this.map.delete(t),this.map.set(t,r),r}delete(t){return this.map.delete(t)}set(t,r){if(!this.delete(t)&&r!==void 0){if(this.map.size>=this.max){let i=this.map.keys().next().value;this.delete(i)}this.map.set(t,r)}return this}};FT.exports=Fy});var an=ae((tJ,KT)=>{"use strict";var c4=/\s+/g,By=class e{constructor(t,r){if(r=l4(r),t instanceof e)return t.loose===!!r.loose&&t.includePrerelease===!!r.includePrerelease?t:new e(t.raw,r);if(t instanceof Vy)return this.raw=t.value,this.set=[[t]],this.formatted=void 0,this;if(this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease,this.raw=t.trim().replace(c4," "),this.set=this.raw.split("||").map(n=>this.parseRange(n.trim())).filter(n=>n.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let n=this.set[0];if(this.set=this.set.filter(i=>!ZT(i[0])),this.set.length===0)this.set=[n];else if(this.set.length>1){for(let i of this.set)if(i.length===1&&_4(i[0])){this.set=[i];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let t=0;t<this.set.length;t++){t>0&&(this.formatted+="||");let r=this.set[t];for(let n=0;n<r.length;n++)n>0&&(this.formatted+=" "),this.formatted+=r[n].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(t){let n=((this.options.includePrerelease&&h4)|(this.options.loose&&g4))+":"+t,i=VT.get(n);if(i)return i;let s=this.options.loose,o=s?pr[Yt.HYPHENRANGELOOSE]:pr[Yt.HYPHENRANGE];t=t.replace(o,A4(this.options.includePrerelease)),rt("hyphen replace",t),t=t.replace(pr[Yt.COMPARATORTRIM],d4),rt("comparator trim",t),t=t.replace(pr[Yt.TILDETRIM],f4),rt("tilde trim",t),t=t.replace(pr[Yt.CARETTRIM],m4),rt("caret trim",t);let a=t.split(" ").map(p=>y4(p,this.options)).join(" ").split(/\s+/).map(p=>k4(p,this.options));s&&(a=a.filter(p=>(rt("loose invalid filter",p,this.options),!!p.match(pr[Yt.COMPARATORLOOSE])))),rt("range list",a);let c=new Map,u=a.map(p=>new Vy(p,this.options));for(let p of u){if(ZT(p))return[p];c.set(p.value,p)}c.size>1&&c.has("")&&c.delete("");let l=[...c.values()];return VT.set(n,l),l}intersects(t,r){if(!(t instanceof e))throw new TypeError("a Range is required");return this.set.some(n=>GT(n,r)&&t.set.some(i=>GT(i,r)&&n.every(s=>i.every(o=>s.intersects(o,r)))))}test(t){if(!t)return!1;if(typeof t=="string")try{t=new p4(t,this.options)}catch{return!1}for(let r=0;r<this.set.length;r++)if(T4(this.set[r],t,this.options))return!0;return!1}};KT.exports=By;var u4=BT(),VT=new u4,l4=Nf(),Vy=Tl(),rt=kl(),p4=Xt(),{safeRe:pr,t:Yt,comparatorTrimReplace:d4,tildeTrimReplace:f4,caretTrimReplace:m4}=fc(),{FLAG_INCLUDE_PRERELEASE:h4,FLAG_LOOSE:g4}=El(),ZT=e=>e.value==="<0.0.0-0",_4=e=>e.value==="",GT=(e,t)=>{let r=!0,n=e.slice(),i=n.pop();for(;r&&n.length;)r=n.every(s=>i.intersects(s,t)),i=n.pop();return r},y4=(e,t)=>(e=e.replace(pr[Yt.BUILD],""),rt("comp",e,t),e=w4(e,t),rt("caret",e),e=v4(e,t),rt("tildes",e),e=I4(e,t),rt("xrange",e),e=E4(e,t),rt("stars",e),e),dr=e=>!e||e.toLowerCase()==="x"||e==="*",v4=(e,t)=>e.trim().split(/\s+/).map(r=>b4(r,t)).join(" "),b4=(e,t)=>{let r=t.loose?pr[Yt.TILDELOOSE]:pr[Yt.TILDE];return e.replace(r,(n,i,s,o,a)=>{rt("tilde",e,n,i,s,o,a);let c;return dr(i)?c="":dr(s)?c=`>=${i}.0.0 <${+i+1}.0.0-0`:dr(o)?c=`>=${i}.${s}.0 <${i}.${+s+1}.0-0`:a?(rt("replaceTilde pr",a),c=`>=${i}.${s}.${o}-${a} <${i}.${+s+1}.0-0`):c=`>=${i}.${s}.${o} <${i}.${+s+1}.0-0`,rt("tilde return",c),c})},w4=(e,t)=>e.trim().split(/\s+/).map(r=>x4(r,t)).join(" "),x4=(e,t)=>{rt("caret",e,t);let r=t.loose?pr[Yt.CARETLOOSE]:pr[Yt.CARET],n=t.includePrerelease?"-0":"";return e.replace(r,(i,s,o,a,c)=>{rt("caret",e,i,s,o,a,c);let u;return dr(s)?u="":dr(o)?u=`>=${s}.0.0${n} <${+s+1}.0.0-0`:dr(a)?s==="0"?u=`>=${s}.${o}.0${n} <${s}.${+o+1}.0-0`:u=`>=${s}.${o}.0${n} <${+s+1}.0.0-0`:c?(rt("replaceCaret pr",c),s==="0"?o==="0"?u=`>=${s}.${o}.${a}-${c} <${s}.${o}.${+a+1}-0`:u=`>=${s}.${o}.${a}-${c} <${s}.${+o+1}.0-0`:u=`>=${s}.${o}.${a}-${c} <${+s+1}.0.0-0`):(rt("no pr"),s==="0"?o==="0"?u=`>=${s}.${o}.${a}${n} <${s}.${o}.${+a+1}-0`:u=`>=${s}.${o}.${a}${n} <${s}.${+o+1}.0-0`:u=`>=${s}.${o}.${a} <${+s+1}.0.0-0`),rt("caret return",u),u})},I4=(e,t)=>(rt("replaceXRanges",e,t),e.split(/\s+/).map(r=>S4(r,t)).join(" ")),S4=(e,t)=>{e=e.trim();let r=t.loose?pr[Yt.XRANGELOOSE]:pr[Yt.XRANGE];return e.replace(r,(n,i,s,o,a,c)=>{rt("xRange",e,n,i,s,o,a,c);let u=dr(s),l=u||dr(o),p=l||dr(a),f=p;return i==="="&&f&&(i=""),c=t.includePrerelease?"-0":"",u?i===">"||i==="<"?n="<0.0.0-0":n="*":i&&f?(l&&(o=0),a=0,i===">"?(i=">=",l?(s=+s+1,o=0,a=0):(o=+o+1,a=0)):i==="<="&&(i="<",l?s=+s+1:o=+o+1),i==="<"&&(c="-0"),n=`${i+s}.${o}.${a}${c}`):l?n=`>=${s}.0.0${c} <${+s+1}.0.0-0`:p&&(n=`>=${s}.${o}.0${c} <${s}.${+o+1}.0-0`),rt("xRange return",n),n})},E4=(e,t)=>(rt("replaceStars",e,t),e.trim().replace(pr[Yt.STAR],"")),k4=(e,t)=>(rt("replaceGTE0",e,t),e.trim().replace(pr[t.includePrerelease?Yt.GTE0PRE:Yt.GTE0],"")),A4=e=>(t,r,n,i,s,o,a,c,u,l,p,f)=>(dr(n)?r="":dr(i)?r=`>=${n}.0.0${e?"-0":""}`:dr(s)?r=`>=${n}.${i}.0${e?"-0":""}`:o?r=`>=${r}`:r=`>=${r}${e?"-0":""}`,dr(u)?c="":dr(l)?c=`<${+u+1}.0.0-0`:dr(p)?c=`<${u}.${+l+1}.0-0`:f?c=`<=${u}.${l}.${p}-${f}`:e?c=`<${u}.${l}.${+p+1}-0`:c=`<=${c}`,`${r} ${c}`.trim()),T4=(e,t,r)=>{for(let n=0;n<e.length;n++)if(!e[n].test(t))return!1;if(t.prerelease.length&&!r.includePrerelease){for(let n=0;n<e.length;n++)if(rt(e[n].semver),e[n].semver!==Vy.ANY&&e[n].semver.prerelease.length>0){let i=e[n].semver;if(i.major===t.major&&i.minor===t.minor&&i.patch===t.patch)return!0}return!1}return!0}});var Tl=ae((rJ,YT)=>{"use strict";var Ol=Symbol("SemVer ANY"),Ky=class e{static get ANY(){return Ol}constructor(t,r){if(r=qT(r),t instanceof e){if(t.loose===!!r.loose)return t;t=t.value}t=t.trim().split(/\s+/).join(" "),Gy("comparator",t,r),this.options=r,this.loose=!!r.loose,this.parse(t),this.semver===Ol?this.value="":this.value=this.operator+this.semver.version,Gy("comp",this)}parse(t){let r=this.options.loose?HT[WT.COMPARATORLOOSE]:HT[WT.COMPARATOR],n=t.match(r);if(!n)throw new TypeError(`Invalid comparator: ${t}`);this.operator=n[1]!==void 0?n[1]:"",this.operator==="="&&(this.operator=""),n[2]?this.semver=new JT(n[2],this.options.loose):this.semver=Ol}toString(){return this.value}test(t){if(Gy("Comparator.test",t,this.options.loose),this.semver===Ol||t===Ol)return!0;if(typeof t=="string")try{t=new JT(t,this.options)}catch{return!1}return Zy(t,this.operator,this.semver,this.options)}intersects(t,r){if(!(t instanceof e))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new XT(t.value,r).test(this.value):t.operator===""?t.value===""?!0:new XT(this.value,r).test(t.semver):(r=qT(r),r.includePrerelease&&(this.value==="<0.0.0-0"||t.value==="<0.0.0-0")||!r.includePrerelease&&(this.value.startsWith("<0.0.0")||t.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&t.operator.startsWith(">")||this.operator.startsWith("<")&&t.operator.startsWith("<")||this.semver.version===t.semver.version&&this.operator.includes("=")&&t.operator.includes("=")||Zy(this.semver,"<",t.semver,r)&&this.operator.startsWith(">")&&t.operator.startsWith("<")||Zy(this.semver,">",t.semver,r)&&this.operator.startsWith("<")&&t.operator.startsWith(">")))}};YT.exports=Ky;var qT=Nf(),{safeRe:HT,t:WT}=fc(),Zy=Uy(),Gy=kl(),JT=Xt(),XT=an()});var $l=ae((nJ,QT)=>{"use strict";var O4=an(),$4=(e,t,r)=>{try{t=new O4(t,r)}catch{return!1}return t.test(e)};QT.exports=$4});var tO=ae((iJ,eO)=>{"use strict";var C4=an(),P4=(e,t)=>new C4(e,t).set.map(r=>r.map(n=>n.value).join(" ").trim().split(" "));eO.exports=P4});var nO=ae((sJ,rO)=>{"use strict";var N4=Xt(),R4=an(),M4=(e,t,r)=>{let n=null,i=null,s=null;try{s=new R4(t,r)}catch{return null}return e.forEach(o=>{s.test(o)&&(!n||i.compare(o)===-1)&&(n=o,i=new N4(n,r))}),n};rO.exports=M4});var sO=ae((oJ,iO)=>{"use strict";var j4=Xt(),D4=an(),z4=(e,t,r)=>{let n=null,i=null,s=null;try{s=new D4(t,r)}catch{return null}return e.forEach(o=>{s.test(o)&&(!n||i.compare(o)===1)&&(n=o,i=new j4(n,r))}),n};iO.exports=z4});var cO=ae((aJ,aO)=>{"use strict";var qy=Xt(),L4=an(),oO=Al(),U4=(e,t)=>{e=new L4(e,t);let r=new qy("0.0.0");if(e.test(r)||(r=new qy("0.0.0-0"),e.test(r)))return r;r=null;for(let n=0;n<e.set.length;++n){let i=e.set[n],s=null;i.forEach(o=>{let a=new qy(o.semver.version);switch(o.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!s||oO(a,s))&&(s=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${o.operator}`)}}),s&&(!r||oO(r,s))&&(r=s)}return r&&e.test(r)?r:null};aO.exports=U4});var lO=ae((cJ,uO)=>{"use strict";var F4=an(),B4=(e,t)=>{try{return new F4(e,t).range||"*"}catch{return null}};uO.exports=B4});var Zf=ae((uJ,mO)=>{"use strict";var V4=Xt(),fO=Tl(),{ANY:Z4}=fO,G4=an(),K4=$l(),pO=Al(),dO=Lf(),q4=Ff(),H4=Uf(),W4=(e,t,r,n)=>{e=new V4(e,n),t=new G4(t,n);let i,s,o,a,c;switch(r){case">":i=pO,s=q4,o=dO,a=">",c=">=";break;case"<":i=dO,s=H4,o=pO,a="<",c="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(K4(e,t,n))return!1;for(let u=0;u<t.set.length;++u){let l=t.set[u],p=null,f=null;if(l.forEach(d=>{d.semver===Z4&&(d=new fO(">=0.0.0")),p=p||d,f=f||d,i(d.semver,p.semver,n)?p=d:o(d.semver,f.semver,n)&&(f=d)}),p.operator===a||p.operator===c||(!f.operator||f.operator===a)&&s(e,f.semver))return!1;if(f.operator===c&&o(e,f.semver))return!1}return!0};mO.exports=W4});var gO=ae((lJ,hO)=>{"use strict";var J4=Zf(),X4=(e,t,r)=>J4(e,t,">",r);hO.exports=X4});var yO=ae((pJ,_O)=>{"use strict";var Y4=Zf(),Q4=(e,t,r)=>Y4(e,t,"<",r);_O.exports=Q4});var wO=ae((dJ,bO)=>{"use strict";var vO=an(),e2=(e,t,r)=>(e=new vO(e,r),t=new vO(t,r),e.intersects(t,r));bO.exports=e2});var IO=ae((fJ,xO)=>{"use strict";var t2=$l(),r2=on();xO.exports=(e,t,r)=>{let n=[],i=null,s=null,o=e.sort((l,p)=>r2(l,p,r));for(let l of o)t2(l,t,r)?(s=l,i||(i=l)):(s&&n.push([i,s]),s=null,i=null);i&&n.push([i,null]);let a=[];for(let[l,p]of n)l===p?a.push(l):!p&&l===o[0]?a.push("*"):p?l===o[0]?a.push(`<=${p}`):a.push(`${l} - ${p}`):a.push(`>=${l}`);let c=a.join(" || "),u=typeof t.raw=="string"?t.raw:String(t);return c.length<u.length?c:t}});var OO=ae((mJ,TO)=>{"use strict";var SO=an(),Wy=Tl(),{ANY:Hy}=Wy,Cl=$l(),Jy=on(),n2=(e,t,r={})=>{if(e===t)return!0;e=new SO(e,r),t=new SO(t,r);let n=!1;e:for(let i of e.set){for(let s of t.set){let o=s2(i,s,r);if(n=n||o!==null,o)continue e}if(n)return!1}return!0},i2=[new Wy(">=0.0.0-0")],EO=[new Wy(">=0.0.0")],s2=(e,t,r)=>{if(e===t)return!0;if(e.length===1&&e[0].semver===Hy){if(t.length===1&&t[0].semver===Hy)return!0;r.includePrerelease?e=i2:e=EO}if(t.length===1&&t[0].semver===Hy){if(r.includePrerelease)return!0;t=EO}let n=new Set,i,s;for(let d of e)d.operator===">"||d.operator===">="?i=kO(i,d,r):d.operator==="<"||d.operator==="<="?s=AO(s,d,r):n.add(d.semver);if(n.size>1)return null;let o;if(i&&s){if(o=Jy(i.semver,s.semver,r),o>0)return null;if(o===0&&(i.operator!==">="||s.operator!=="<="))return null}for(let d of n){if(i&&!Cl(d,String(i),r)||s&&!Cl(d,String(s),r))return null;for(let m of t)if(!Cl(d,String(m),r))return!1;return!0}let a,c,u,l,p=s&&!r.includePrerelease&&s.semver.prerelease.length?s.semver:!1,f=i&&!r.includePrerelease&&i.semver.prerelease.length?i.semver:!1;p&&p.prerelease.length===1&&s.operator==="<"&&p.prerelease[0]===0&&(p=!1);for(let d of t){if(l=l||d.operator===">"||d.operator===">=",u=u||d.operator==="<"||d.operator==="<=",i){if(f&&d.semver.prerelease&&d.semver.prerelease.length&&d.semver.major===f.major&&d.semver.minor===f.minor&&d.semver.patch===f.patch&&(f=!1),d.operator===">"||d.operator===">="){if(a=kO(i,d,r),a===d&&a!==i)return!1}else if(i.operator===">="&&!Cl(i.semver,String(d),r))return!1}if(s){if(p&&d.semver.prerelease&&d.semver.prerelease.length&&d.semver.major===p.major&&d.semver.minor===p.minor&&d.semver.patch===p.patch&&(p=!1),d.operator==="<"||d.operator==="<="){if(c=AO(s,d,r),c===d&&c!==s)return!1}else if(s.operator==="<="&&!Cl(s.semver,String(d),r))return!1}if(!d.operator&&(s||i)&&o!==0)return!1}return!(i&&u&&!s&&o!==0||s&&l&&!i&&o!==0||f||p)},kO=(e,t,r)=>{if(!e)return t;let n=Jy(e.semver,t.semver,r);return n>0?e:n<0||t.operator===">"&&e.operator===">="?t:e},AO=(e,t,r)=>{if(!e)return t;let n=Jy(e.semver,t.semver,r);return n<0?e:n>0||t.operator==="<"&&e.operator==="<="?t:e};TO.exports=n2});var NO=ae((hJ,PO)=>{"use strict";var Xy=fc(),$O=El(),o2=Xt(),CO=My(),a2=Do(),c2=nT(),u2=sT(),l2=cT(),p2=pT(),d2=fT(),f2=hT(),m2=_T(),h2=vT(),g2=on(),_2=IT(),y2=ET(),v2=zf(),b2=OT(),w2=CT(),x2=Al(),I2=Lf(),S2=zy(),E2=Ly(),k2=Uf(),A2=Ff(),T2=Uy(),O2=UT(),$2=Tl(),C2=an(),P2=$l(),N2=tO(),R2=nO(),M2=sO(),j2=cO(),D2=lO(),z2=Zf(),L2=gO(),U2=yO(),F2=wO(),B2=IO(),V2=OO();PO.exports={parse:a2,valid:c2,clean:u2,inc:l2,diff:p2,major:d2,minor:f2,patch:m2,prerelease:h2,compare:g2,rcompare:_2,compareLoose:y2,compareBuild:v2,sort:b2,rsort:w2,gt:x2,lt:I2,eq:S2,neq:E2,gte:k2,lte:A2,cmp:T2,coerce:O2,Comparator:$2,Range:C2,satisfies:P2,toComparators:N2,maxSatisfying:R2,minSatisfying:M2,minVersion:j2,validRange:D2,outside:z2,gtr:L2,ltr:U2,intersects:F2,simplifyRange:B2,subset:V2,SemVer:o2,re:Xy.re,src:Xy.src,tokens:Xy.t,SEMVER_SPEC_VERSION:$O.SEMVER_SPEC_VERSION,RELEASE_TYPES:$O.RELEASE_TYPES,compareIdentifiers:CO.compareIdentifiers,rcompareIdentifiers:CO.rcompareIdentifiers}});var QO=ae((o7,YO)=>{"use strict";var JO=(e=0)=>t=>`\x1B[${38+e};5;${t}m`,XO=(e=0)=>(t,r,n)=>`\x1B[${38+e};2;${t};${r};${n}m`;function dF(){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]}};t.color.gray=t.color.blackBright,t.bgColor.bgGray=t.bgColor.bgBlackBright,t.color.grey=t.color.blackBright,t.bgColor.bgGrey=t.bgColor.bgBlackBright;for(let[r,n]of Object.entries(t)){for(let[i,s]of Object.entries(n))t[i]={open:`\x1B[${s[0]}m`,close:`\x1B[${s[1]}m`},n[i]=t[i],e.set(s[0],s[1]);Object.defineProperty(t,r,{value:n,enumerable:!1})}return Object.defineProperty(t,"codes",{value:e,enumerable:!1}),t.color.close="\x1B[39m",t.bgColor.close="\x1B[49m",t.color.ansi256=JO(),t.color.ansi16m=XO(),t.bgColor.ansi256=JO(10),t.bgColor.ansi16m=XO(10),Object.defineProperties(t,{rgbToAnsi256:{value:(r,n,i)=>r===n&&n===i?r<8?16:r>248?231:Math.round((r-8)/247*24)+232:16+36*Math.round(r/255*5)+6*Math.round(n/255*5)+Math.round(i/255*5),enumerable:!1},hexToRgb:{value:r=>{let n=/(?<colorString>[a-f\d]{6}|[a-f\d]{3})/i.exec(r.toString(16));if(!n)return[0,0,0];let{colorString:i}=n.groups;i.length===3&&(i=i.split("").map(o=>o+o).join(""));let s=Number.parseInt(i,16);return[s>>16&255,s>>8&255,s&255]},enumerable:!1},hexToAnsi256:{value:r=>t.rgbToAnsi256(...t.hexToRgb(r)),enumerable:!1}}),t}Object.defineProperty(YO,"exports",{enumerable:!0,get:dF})});var XN=ae($h=>{"use strict";$h.byteLength=GZ;$h.toByteArray=qZ;$h.fromByteArray=JZ;var yi=[],_n=[],ZZ=typeof Uint8Array<"u"?Uint8Array:Array,$0="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(va=0,WN=$0.length;va<WN;++va)yi[va]=$0[va],_n[$0.charCodeAt(va)]=va;var va,WN;_n[45]=62;_n[95]=63;function JN(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");r===-1&&(r=t);var n=r===t?0:4-r%4;return[r,n]}function GZ(e){var t=JN(e),r=t[0],n=t[1];return(r+n)*3/4-n}function KZ(e,t,r){return(t+r)*3/4-r}function qZ(e){var t,r=JN(e),n=r[0],i=r[1],s=new ZZ(KZ(e,n,i)),o=0,a=i>0?n-4:n,c;for(c=0;c<a;c+=4)t=_n[e.charCodeAt(c)]<<18|_n[e.charCodeAt(c+1)]<<12|_n[e.charCodeAt(c+2)]<<6|_n[e.charCodeAt(c+3)],s[o++]=t>>16&255,s[o++]=t>>8&255,s[o++]=t&255;return i===2&&(t=_n[e.charCodeAt(c)]<<2|_n[e.charCodeAt(c+1)]>>4,s[o++]=t&255),i===1&&(t=_n[e.charCodeAt(c)]<<10|_n[e.charCodeAt(c+1)]<<4|_n[e.charCodeAt(c+2)]>>2,s[o++]=t>>8&255,s[o++]=t&255),s}function HZ(e){return yi[e>>18&63]+yi[e>>12&63]+yi[e>>6&63]+yi[e&63]}function WZ(e,t,r){for(var n,i=[],s=t;s<r;s+=3)n=(e[s]<<16&16711680)+(e[s+1]<<8&65280)+(e[s+2]&255),i.push(HZ(n));return i.join("")}function JZ(e){for(var t,r=e.length,n=r%3,i=[],s=16383,o=0,a=r-n;o<a;o+=s)i.push(WZ(e,o,o+s>a?a:o+s));return n===1?(t=e[r-1],i.push(yi[t>>2]+yi[t<<4&63]+"==")):n===2&&(t=(e[r-2]<<8)+e[r-1],i.push(yi[t>>10]+yi[t>>4&63]+yi[t<<2&63]+"=")),i.join("")}});var Mi=class extends Error{lc_error_code;constructor(e,t){let r=e??"";t?.lc_error_code&&(r=`${r}
|
|
3
|
+
|
|
4
|
+
Troubleshooting URL: https://docs.langchain.com/oss/javascript/langgraph/${t.lc_error_code}/
|
|
5
|
+
`),super(r),this.lc_error_code=t?.lc_error_code}},C_=class extends Mi{get is_bubble_up(){return!0}},P_=class extends Mi{constructor(e,t){super(e,t),this.name="GraphRecursionError"}static get unminifiable_name(){return"GraphRecursionError"}},Co=class extends Mi{constructor(e,t){super(e,t),this.name="GraphValueError"}static get unminifiable_name(){return"GraphValueError"}},ji=class extends C_{interrupts;constructor(e,t){super(JSON.stringify(e,null,2),t),this.name="GraphInterrupt",this.interrupts=e??[]}static get unminifiable_name(){return"GraphInterrupt"}},Jd=class extends ji{constructor(e,t){super([{value:e}],t),this.name="NodeInterrupt"}static get unminifiable_name(){return"NodeInterrupt"}},Xd=class extends C_{command;constructor(e){super(),this.name="ParentCommand",this.command=e}static get unminifiable_name(){return"ParentCommand"}};function N_(e){return e!==void 0&&e.name===Xd.unminifiable_name}function Po(e){return e!==void 0&&e.is_bubble_up===!0}function Di(e){return e!==void 0&&[ji.unminifiable_name,Jd.unminifiable_name].includes(e.name)}var Yd=class extends Mi{constructor(e,t){super(e,t),this.name="EmptyInputError"}static get unminifiable_name(){return"EmptyInputError"}},Ve=class extends Mi{constructor(e,t){super(e,t),this.name="EmptyChannelError"}static get unminifiable_name(){return"EmptyChannelError"}},De=class extends Mi{constructor(e,t){super(e,t),this.name="InvalidUpdateError"}static get unminifiable_name(){return"InvalidUpdateError"}};var R_=class extends Mi{constructor(e,t){super(e,t),this.name="UnreachableNodeError"}static get unminifiable_name(){return"UnreachableNodeError"}};var fl=class extends Mi{constructor(e,t){super(e,t),this.name="StateGraphInputError",this.message="Invalid StateGraph input. Make sure to pass a valid StateDefinition, Annotation.Root, or Zod schema."}static get unminifiable_name(){return"StateGraphInputError"}};var ak=/^(?:[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 Pz(e){return typeof e=="string"&&ak.test(e)}var kn=Pz;function Nz(e){if(!kn(e))throw TypeError("Invalid UUID");var t,r=new Uint8Array(16);return r[0]=(t=parseInt(e.slice(0,8),16))>>>24,r[1]=t>>>16&255,r[2]=t>>>8&255,r[3]=t&255,r[4]=(t=parseInt(e.slice(9,13),16))>>>8,r[5]=t&255,r[6]=(t=parseInt(e.slice(14,18),16))>>>8,r[7]=t&255,r[8]=(t=parseInt(e.slice(19,23),16))>>>8,r[9]=t&255,r[10]=(t=parseInt(e.slice(24,36),16))/1099511627776&255,r[11]=t/4294967296&255,r[12]=t>>>24&255,r[13]=t>>>16&255,r[14]=t>>>8&255,r[15]=t&255,r}var Qd=Nz;var Vt=[];for(ef=0;ef<256;++ef)Vt.push((ef+256).toString(16).slice(1));var ef;function rn(e,t=0){return(Vt[e[t+0]]+Vt[e[t+1]]+Vt[e[t+2]]+Vt[e[t+3]]+"-"+Vt[e[t+4]]+Vt[e[t+5]]+"-"+Vt[e[t+6]]+Vt[e[t+7]]+"-"+Vt[e[t+8]]+Vt[e[t+9]]+"-"+Vt[e[t+10]]+Vt[e[t+11]]+Vt[e[t+12]]+Vt[e[t+13]]+Vt[e[t+14]]+Vt[e[t+15]]).toLowerCase()}var tf,Rz=new Uint8Array(16);function No(){if(!tf&&(tf=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!tf))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return tf(Rz)}var M_,rf,j_=0,D_=0;function Mz(e,t,r){var n=t&&r||0,i=t||new Array(16);e=e||{};var s=e.node,o=e.clockseq;if(e._v6||(s||(s=M_),o==null&&(o=rf)),s==null||o==null){var a=e.random||(e.rng||No)();s==null&&(s=[a[0],a[1],a[2],a[3],a[4],a[5]],!M_&&!e._v6&&(s[0]|=1,M_=s)),o==null&&(o=(a[6]<<8|a[7])&16383,rf===void 0&&!e._v6&&(rf=o))}var c=e.msecs!==void 0?e.msecs:Date.now(),u=e.nsecs!==void 0?e.nsecs:D_+1,l=c-j_+(u-D_)/1e4;if(l<0&&e.clockseq===void 0&&(o=o+1&16383),(l<0||c>j_)&&e.nsecs===void 0&&(u=0),u>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");j_=c,D_=u,rf=o,c+=122192928e5;var p=((c&268435455)*1e4+u)%4294967296;i[n++]=p>>>24&255,i[n++]=p>>>16&255,i[n++]=p>>>8&255,i[n++]=p&255;var f=c/4294967296*1e4&268435455;i[n++]=f>>>8&255,i[n++]=f&255,i[n++]=f>>>24&15|16,i[n++]=f>>>16&255,i[n++]=o>>>8|128,i[n++]=o&255;for(var d=0;d<6;++d)i[n+d]=s[d];return t||rn(i)}var ck=Mz;function z_(e){var t=typeof e=="string"?Qd(e):e,r=jz(t);return typeof e=="string"?rn(r):r}function jz(e,t=!1){return Uint8Array.of((e[6]&15)<<4|e[7]>>4&15,(e[7]&15)<<4|(e[4]&240)>>4,(e[4]&15)<<4|(e[5]&240)>>4,(e[5]&15)<<4|(e[0]&240)>>4,(e[0]&15)<<4|(e[1]&240)>>4,(e[1]&15)<<4|(e[2]&240)>>4,96|e[2]&15,e[3],e[8],e[9],e[10],e[11],e[12],e[13],e[14],e[15])}function Dz(e){e=unescape(encodeURIComponent(e));for(var t=[],r=0;r<e.length;++r)t.push(e.charCodeAt(r));return t}var zz="6ba7b810-9dad-11d1-80b4-00c04fd430c8",Lz="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function L_(e,t,r){function n(i,s,o,a){var c;if(typeof i=="string"&&(i=Dz(i)),typeof s=="string"&&(s=Qd(s)),((c=s)===null||c===void 0?void 0:c.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");var u=new Uint8Array(16+i.length);if(u.set(s),u.set(i,s.length),u=r(u),u[6]=u[6]&15|t,u[8]=u[8]&63|128,o){a=a||0;for(var l=0;l<16;++l)o[a+l]=u[l];return o}return rn(u)}try{n.name=e}catch{}return n.DNS=zz,n.URL=Lz,n}var Uz=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),U_={randomUUID:Uz};function Fz(e,t,r){if(U_.randomUUID&&!t&&!e)return U_.randomUUID();e=e||{};var n=e.random||(e.rng||No)();if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,t){r=r||0;for(var i=0;i<16;++i)t[r+i]=n[i];return t}return rn(n)}var Ar=Fz;function Bz(e,t,r,n){switch(e){case 0:return t&r^~t&n;case 1:return t^r^n;case 2:return t&r^t&n^r&n;case 3:return t^r^n}}function F_(e,t){return e<<t|e>>>32-t}function Vz(e){var t=[1518500249,1859775393,2400959708,3395469782],r=[1732584193,4023233417,2562383102,271733878,3285377520];if(typeof e=="string"){var n=unescape(encodeURIComponent(e));e=[];for(var i=0;i<n.length;++i)e.push(n.charCodeAt(i))}else Array.isArray(e)||(e=Array.prototype.slice.call(e));e.push(128);for(var s=e.length/4+2,o=Math.ceil(s/16),a=new Array(o),c=0;c<o;++c){for(var u=new Uint32Array(16),l=0;l<16;++l)u[l]=e[c*64+l*4]<<24|e[c*64+l*4+1]<<16|e[c*64+l*4+2]<<8|e[c*64+l*4+3];a[c]=u}a[o-1][14]=(e.length-1)*8/Math.pow(2,32),a[o-1][14]=Math.floor(a[o-1][14]),a[o-1][15]=(e.length-1)*8&4294967295;for(var p=0;p<o;++p){for(var f=new Uint32Array(80),d=0;d<16;++d)f[d]=a[p][d];for(var m=16;m<80;++m)f[m]=F_(f[m-3]^f[m-8]^f[m-14]^f[m-16],1);for(var h=r[0],b=r[1],_=r[2],y=r[3],x=r[4],I=0;I<80;++I){var A=Math.floor(I/20),j=F_(h,5)+Bz(A,b,_,y)+x+t[A]+f[I]>>>0;x=y,y=_,_=F_(b,30)>>>0,b=h,h=j}r[0]=r[0]+h>>>0,r[1]=r[1]+b>>>0,r[2]=r[2]+_>>>0,r[3]=r[3]+y>>>0,r[4]=r[4]+x>>>0}return[r[0]>>24&255,r[0]>>16&255,r[0]>>8&255,r[0]&255,r[1]>>24&255,r[1]>>16&255,r[1]>>8&255,r[1]&255,r[2]>>24&255,r[2]>>16&255,r[2]>>8&255,r[2]&255,r[3]>>24&255,r[3]>>16&255,r[3]>>8&255,r[3]&255,r[4]>>24&255,r[4]>>16&255,r[4]>>8&255,r[4]&255]}var uk=Vz;var Zz=L_("v5",80,uk),nn=Zz;function lk(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function pk(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?lk(Object(r),!0).forEach(function(n){Gz(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):lk(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function Gz(e,t,r){return(t=Kz(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function Kz(e){var t=qz(e,"string");return typeof t=="symbol"?t:t+""}function qz(e,t){if(typeof e!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function nf(e={},t,r=0){var n=ck(pk(pk({},e),{},{_v6:!0}),new Uint8Array(16));if(n=z_(n),t){for(var i=0;i<16;i++)t[r+i]=n[i];return t}return rn(n)}var dk=null,fk=null,An=0;function Hz(e,t,r){e=e||{};var n=t&&r||0,i=t||new Uint8Array(16),s=e.random||(e.rng||No)(),o=e.msecs!==void 0?e.msecs:Date.now(),a=e.seq!==void 0?e.seq:null,c=fk,u=dk;return o>An&&e.msecs===void 0&&(An=o,a!==null&&(c=null,u=null)),a!==null&&(a>2147483647&&(a=2147483647),c=a>>>19&4095,u=a&524287),(c===null||u===null)&&(c=s[6]&127,c=c<<8|s[7],u=s[8]&63,u=u<<8|s[9],u=u<<5|s[10]>>>3),o+1e4>An&&a===null?++u>524287&&(u=0,++c>4095&&(c=0,An++)):An=o,fk=c,dk=u,i[n++]=An/1099511627776&255,i[n++]=An/4294967296&255,i[n++]=An/16777216&255,i[n++]=An/65536&255,i[n++]=An/256&255,i[n++]=An&255,i[n++]=c>>>4&15|112,i[n++]=c&255,i[n++]=u>>>13&63|128,i[n++]=u>>>5&255,i[n++]=u<<3&255|s[10]&7,i[n++]=s[11],i[n++]=s[12],i[n++]=s[13],i[n++]=s[14],i[n++]=s[15],t||rn(i)}var sn=Hz;function ml(e){return nf({clockseq:e})}function zi(e,t){let r=t.replace(/-/g,"").match(/.{2}/g).map(n=>parseInt(n,16));return nn(e,new Uint8Array(r))}var hl="__pregel_tasks",B_="__error__",Ro="__scheduled__",V_="__interrupt__",Z_="__resume__";var hk="[...]",Wz="[Circular]",sf=[],cc=[];function Jz(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function gk(e,t,r,n){typeof n>"u"&&(n=Jz()),K_(e,"",0,[],void 0,0,n);var i;try{cc.length===0?i=JSON.stringify(e,t,r):i=JSON.stringify(e,Xz(t),r)}catch{return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;sf.length!==0;){var s=sf.pop();s.length===4?Object.defineProperty(s[0],s[1],s[3]):s[0][s[1]]=s[2]}}return i}function G_(e,t,r,n){var i=Object.getOwnPropertyDescriptor(n,r);i.get!==void 0?i.configurable?(Object.defineProperty(n,r,{value:e}),sf.push([n,r,t,i])):cc.push([t,r,e]):(n[r]=e,sf.push([n,r,t]))}function K_(e,t,r,n,i,s,o){s+=1;var a;if(typeof e=="object"&&e!==null){for(a=0;a<n.length;a++)if(n[a]===e){G_(Wz,e,t,i);return}if(typeof o.depthLimit<"u"&&s>o.depthLimit){G_(hk,e,t,i);return}if(typeof o.edgesLimit<"u"&&r+1>o.edgesLimit){G_(hk,e,t,i);return}if(n.push(e),Array.isArray(e))for(a=0;a<e.length;a++)K_(e[a],a,a,n,e,s,o);else{var c=Object.keys(e);for(a=0;a<c.length;a++){var u=c[a];K_(e[u],u,a,n,e,s,o)}}n.pop()}}function Xz(e){return e=typeof e<"u"?e:function(t,r){return r},function(t,r){if(cc.length>0)for(var n=0;n<cc.length;n++){var i=cc[n];if(i[1]===t&&i[0]===r){r=i[2],cc.splice(n,1);break}}return e.call(this,t,r)}}var kk=Ps(yk(),1),Ak=Ps(Ek(),1);function Tk(e,t){return t?.[e]||(0,kk.default)(e)}function Ok(e,t){return t?.[e]||(0,Ak.default)(e)}function of(e,t,r){let n={};for(let i in e)Object.hasOwn(e,i)&&(n[t(i,r)]=e[i]);return n}var uf="__lc_escaped__";function iL(e){return"lc"in e||Object.keys(e).length===1&&uf in e}function sL(e){return{[uf]:e}}function H_(e){return Object.keys(e).length===1&&uf in e}function oL(e){return e!==null&&typeof e=="object"&&"lc_serializable"in e&&typeof e.toJSON=="function"}function aL(e){let t;return e!==null&&typeof e=="object"?"lc_id"in e&&Array.isArray(e.lc_id)?t=e.lc_id:t=[e.constructor?.name??"Object"]:t=[typeof e],{lc:1,type:"not_implemented",id:t}}function af(e,t=new WeakSet){if(e!==null&&typeof e=="object"&&!Array.isArray(e)){if(t.has(e))return aL(e);if(oL(e))return e;t.add(e);let r=e;if(iL(r))return t.delete(e),sL(r);let n={};for(let[i,s]of Object.entries(r))n[i]=af(s,t);return t.delete(e),n}return Array.isArray(e)?e.map(r=>af(r,t)):e}function cf(e){if(e!==null&&typeof e=="object"&&!Array.isArray(e)){let t=e;if(H_(t))return t[uf];let r={};for(let[n,i]of Object.entries(t))r[n]=cf(i);return r}return Array.isArray(e)?e.map(t=>cf(t)):e}var cL=Object.defineProperty,M=(e,t)=>{for(var r in t)cL(e,r,{get:t[r],enumerable:!0})};var W_={};M(W_,{Serializable:()=>vt,get_lc_unique_name:()=>uc});function $k(e){return Array.isArray(e)?[...e]:{...e}}function uL(e,t){let r=$k(e);for(let[n,i]of Object.entries(t)){let[s,...o]=n.split(".").reverse(),a=r;for(let c of o.reverse()){if(a[c]===void 0)break;a[c]=$k(a[c]),a=a[c]}a[s]!==void 0&&(a[s]={lc:1,type:"secret",id:[i]})}return r}function uc(e){let t=Object.getPrototypeOf(e);return typeof e.lc_name=="function"&&(typeof t.lc_name!="function"||e.lc_name()!==t.lc_name())?e.lc_name():e.name}var vt=class Ck{lc_serializable=!1;lc_kwargs;static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,uc(this.constructor)]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}constructor(t,...r){this.lc_serializable_keys!==void 0?this.lc_kwargs=Object.fromEntries(Object.entries(t||{}).filter(([n])=>this.lc_serializable_keys?.includes(n))):this.lc_kwargs=t??{}}toJSON(){if(!this.lc_serializable)return this.toJSONNotImplemented();if(this.lc_kwargs instanceof Ck||typeof this.lc_kwargs!="object"||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();let t={},r={},n=Object.keys(this.lc_kwargs).reduce((c,u)=>(c[u]=u in this?this[u]:this.lc_kwargs[u],c),{});for(let c=Object.getPrototypeOf(this);c;c=Object.getPrototypeOf(c))Object.assign(t,Reflect.get(c,"lc_aliases",this)),Object.assign(r,Reflect.get(c,"lc_secrets",this)),Object.assign(n,Reflect.get(c,"lc_attributes",this));Object.keys(r).forEach(c=>{let u=this,l=n,[p,...f]=c.split(".").reverse();for(let d of f.reverse()){if(!(d in u)||u[d]===void 0)return;(!(d in l)||l[d]===void 0)&&(typeof u[d]=="object"&&u[d]!=null?l[d]={}:Array.isArray(u[d])&&(l[d]=[])),u=u[d],l=l[d]}p in u&&u[p]!==void 0&&(l[p]=l[p]||u[p])});let i={},s=new WeakSet;s.add(this);for(let[c,u]of Object.entries(n))i[c]=af(u,s);let o=Object.keys(r).length?uL(i,r):i,a=of(o,Tk,t);return{lc:1,type:"constructor",id:this.lc_id,kwargs:a}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}};var X_={};M(X_,{getEnv:()=>pf,getEnvironmentVariable:()=>Pe,getRuntimeEnvironment:()=>Y_,isBrowser:()=>Pk,isDeno:()=>lf,isJsDom:()=>Rk,isNode:()=>Mk,isWebWorker:()=>Nk});var Pk=()=>typeof window<"u"&&typeof window.document<"u",Nk=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",Rk=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),lf=()=>typeof Deno<"u",Mk=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!lf(),pf=()=>{let e;return Pk()?e="browser":Mk()?e="node":Nk()?e="webworker":Rk()?e="jsdom":lf()?e="deno":e="other",e},J_;function Y_(){return J_===void 0&&(J_={library:"langchain-js",runtime:pf()}),J_}function Pe(e){try{return typeof process<"u"?process.env?.[e]:lf()?Deno?.env.get(e):void 0}catch{return}}var jk=[];var Dk={};function Tr(e){return typeof e=="object"&&e!==null&&"type"in e&&typeof e.type=="string"&&"source_type"in e&&(e.source_type==="url"||e.source_type==="base64"||e.source_type==="text"||e.source_type==="id")}function lc(e){return Tr(e)&&e.source_type==="url"&&"url"in e&&typeof e.url=="string"}function pc(e){return Tr(e)&&e.source_type==="base64"&&"data"in e&&typeof e.data=="string"}function zk(e){return Tr(e)&&e.source_type==="text"&&"text"in e&&typeof e.text=="string"}function df(e){return Tr(e)&&e.source_type==="id"&&"id"in e&&typeof e.id=="string"}function ff(e){if(Tr(e)){if(e.source_type==="url")return{type:"image_url",image_url:{url:e.url}};if(e.source_type==="base64"){if(!e.mime_type)throw new Error("mime_type key is required for base64 data.");return{type:"image_url",image_url:{url:`data:${e.mime_type};base64,${e.data}`}}}}throw new Error("Unsupported source type. Only 'url' and 'base64' are supported.")}function gl(e){let t=e.split(";")[0].split("/");if(t.length!==2)throw new Error(`Invalid mime type: "${e}" - does not match type/subtype format.`);let r=t[0].trim(),n=t[1].trim();if(r===""||n==="")throw new Error(`Invalid mime type: "${e}" - type or subtype is empty.`);let i={};for(let s of e.split(";").slice(1)){let o=s.split("=");if(o.length!==2)throw new Error(`Invalid parameter syntax in mime type: "${e}".`);let a=o[0].trim(),c=o[1].trim();if(a==="")throw new Error(`Invalid parameter syntax in mime type: "${e}".`);i[a]=c}return{type:r,subtype:n,parameters:i}}function Ns({dataUrl:e,asTypedArray:t=!1}){let r=e.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/),n;if(r){n=r[1].toLowerCase();let i=t?Uint8Array.from(atob(r[2]),s=>s.charCodeAt(0)):r[2];return{mime_type:n,data:i}}}function dc(e,t){if(e.type==="text"){if(!t.fromStandardTextBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardTextBlock\` method.`);return t.fromStandardTextBlock(e)}if(e.type==="image"){if(!t.fromStandardImageBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardImageBlock\` method.`);return t.fromStandardImageBlock(e)}if(e.type==="audio"){if(!t.fromStandardAudioBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardAudioBlock\` method.`);return t.fromStandardAudioBlock(e)}if(e.type==="file"){if(!t.fromStandardFileBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardFileBlock\` method.`);return t.fromStandardFileBlock(e)}throw new Error(`Unable to convert content block type '${e.type}' to provider-specific format: not recognized.`)}function re(e,t){return ue(e)&&e.type===t}function ue(e){return typeof e=="object"&&e!==null}function qt(e){return Array.isArray(e)}function z(e){return typeof e=="string"}function Ur(e){return typeof e=="number"}function mf(e){return e instanceof Uint8Array}function Q_(e){try{return JSON.parse(e)}catch{return}}var Li=e=>e();function lL(e){if(e.type==="char_location"&&z(e.document_title)&&Ur(e.start_char_index)&&Ur(e.end_char_index)&&z(e.cited_text)){let{document_title:t,start_char_index:r,end_char_index:n,cited_text:i,...s}=e;return{...s,type:"citation",source:"char",title:t??void 0,startIndex:r,endIndex:n,citedText:i}}if(e.type==="page_location"&&z(e.document_title)&&Ur(e.start_page_number)&&Ur(e.end_page_number)&&z(e.cited_text)){let{document_title:t,start_page_number:r,end_page_number:n,cited_text:i,...s}=e;return{...s,type:"citation",source:"page",title:t??void 0,startIndex:r,endIndex:n,citedText:i}}if(e.type==="content_block_location"&&z(e.document_title)&&Ur(e.start_block_index)&&Ur(e.end_block_index)&&z(e.cited_text)){let{document_title:t,start_block_index:r,end_block_index:n,cited_text:i,...s}=e;return{...s,type:"citation",source:"block",title:t??void 0,startIndex:r,endIndex:n,citedText:i}}if(e.type==="web_search_result_location"&&z(e.url)&&z(e.title)&&z(e.encrypted_index)&&z(e.cited_text)){let{url:t,title:r,encrypted_index:n,cited_text:i,...s}=e;return{...s,type:"citation",source:"url",url:t,title:r,startIndex:Number(n),endIndex:Number(n),citedText:i}}if(e.type==="search_result_location"&&z(e.source)&&z(e.title)&&Ur(e.start_block_index)&&Ur(e.end_block_index)&&z(e.cited_text)){let{source:t,title:r,start_block_index:n,end_block_index:i,cited_text:s,...o}=e;return{...o,type:"citation",source:"search",url:t,title:r??void 0,startIndex:n,endIndex:i,citedText:s}}}function Uk(e){if(re(e,"document")&&ue(e.source)&&"type"in e.source){if(e.source.type==="base64"&&z(e.source.media_type)&&z(e.source.data))return{type:"file",mimeType:e.source.media_type,data:e.source.data};if(e.source.type==="url"&&z(e.source.url))return{type:"file",url:e.source.url};if(e.source.type==="file"&&z(e.source.file_id))return{type:"file",fileId:e.source.file_id};if(e.source.type==="text"&&z(e.source.data))return{type:"file",mimeType:String(e.source.media_type??"text/plain"),data:e.source.data}}else if(re(e,"image")&&ue(e.source)&&"type"in e.source){if(e.source.type==="base64"&&z(e.source.media_type)&&z(e.source.data))return{type:"image",mimeType:e.source.media_type,data:e.source.data};if(e.source.type==="url"&&z(e.source.url))return{type:"image",url:e.source.url};if(e.source.type==="file"&&z(e.source.file_id))return{type:"image",fileId:e.source.file_id}}}function Fk(e){function*t(){for(let r of e){let n=Uk(r);n?yield n:yield r}}return Array.from(t())}function Lk(e){function*t(){let r=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content;for(let n of r){if(re(n,"text")&&z(n.text)){let{text:i,citations:s,...o}=n;if(qt(s)&&s.length){let a=s.reduce((c,u)=>{let l=lL(u);return l?[...c,l]:c},[]);yield{...o,type:"text",text:i,annotations:a};continue}else{yield{...o,type:"text",text:i};continue}}else if(re(n,"thinking")&&z(n.thinking)){let{thinking:i,signature:s,...o}=n;yield{...o,type:"reasoning",reasoning:i,signature:s};continue}else if(re(n,"redacted_thinking")){yield{type:"non_standard",value:n};continue}else if(re(n,"tool_use")&&z(n.name)&&z(n.id)){yield{type:"tool_call",id:n.id,name:n.name,args:n.input};continue}else if(re(n,"input_json_delta")){if(pL(e)&&e.tool_call_chunks?.length){let i=e.tool_call_chunks[0];yield{type:"tool_call_chunk",id:i.id,name:i.name,args:i.args,index:i.index};continue}}else if(re(n,"server_tool_use")&&z(n.name)&&z(n.id)){let{name:i,id:s}=n;if(i==="web_search"){let o=Li(()=>{if(typeof n.input=="string")return n.input;if(ue(n.input)&&z(n.input.query))return n.input.query;if(z(n.partial_json)){let a=Q_(n.partial_json);if(a?.query)return a.query}return""});yield{id:s,type:"server_tool_call",name:"web_search",args:{query:o}};continue}else if(n.name==="code_execution"){let o=Li(()=>{if(typeof n.input=="string")return n.input;if(ue(n.input)&&z(n.input.code))return n.input.code;if(z(n.partial_json)){let a=Q_(n.partial_json);if(a?.code)return a.code}return""});yield{id:s,type:"server_tool_call",name:"code_execution",args:{code:o}};continue}}else if(re(n,"web_search_tool_result")&&z(n.tool_use_id)&&qt(n.content)){let{content:i,tool_use_id:s}=n,o=i.reduce((a,c)=>re(c,"web_search_result")?[...a,c.url]:a,[]);yield{type:"server_tool_call_result",name:"web_search",toolCallId:s,status:"success",output:{urls:o}};continue}else if(re(n,"code_execution_tool_result")&&z(n.tool_use_id)&&ue(n.content)){yield{type:"server_tool_call_result",name:"code_execution",toolCallId:n.tool_use_id,status:"success",output:n.content};continue}else if(re(n,"mcp_tool_use")){yield{id:n.id,type:"server_tool_call",name:"mcp_tool_use",args:n.input};continue}else if(re(n,"mcp_tool_result")&&z(n.tool_use_id)&&ue(n.content)){yield{type:"server_tool_call_result",name:"mcp_tool_use",toolCallId:n.tool_use_id,status:"success",output:n.content};continue}else if(re(n,"container_upload")){yield{type:"server_tool_call",name:"container_upload",args:n.input};continue}else if(re(n,"search_result")){yield{id:n.id,type:"non_standard",value:n};continue}else if(re(n,"tool_result")){yield{id:n.id,type:"non_standard",value:n};continue}else{let i=Uk(n);if(i){yield i;continue}}yield{type:"non_standard",value:n}}}return Array.from(t())}var Bk={translateContent:Lk,translateContentChunk:Lk};function pL(e){return typeof e?._getType=="function"&&typeof e.concat=="function"&&e._getType()==="ai"}function dL(e){return lc(e)?{type:e.type,mimeType:e.mime_type,url:e.url,metadata:e.metadata}:pc(e)?{type:e.type,mimeType:e.mime_type??"application/octet-stream",data:e.data,metadata:e.metadata}:df(e)?{type:e.type,mimeType:e.mime_type,fileId:e.id,metadata:e.metadata}:e}function Vk(e){return e.map(dL)}function Zk(e){return!!(re(e,"image_url")&&ue(e.image_url)||re(e,"input_audio")&&ue(e.input_audio)||re(e,"file")&&ue(e.file))}function Gk(e){if(re(e,"image_url")&&ue(e.image_url)&&z(e.image_url.url)){let t=Ns({dataUrl:e.image_url.url});return t?{type:"image",mimeType:t.mime_type,data:t.data}:{type:"image",url:e.image_url.url}}else{if(re(e,"input_audio")&&ue(e.input_audio)&&z(e.input_audio.data)&&z(e.input_audio.format))return{type:"audio",data:e.input_audio.data,mimeType:`audio/${e.input_audio.format}`};if(re(e,"file")&&ue(e.file)&&z(e.file.data)){let t=Ns({dataUrl:e.file.data});if(t)return{type:"file",data:t.data,mimeType:t.mime_type};if(z(e.file.file_id))return{type:"file",fileId:e.file.file_id}}}return e}function fL(e){let t=[];typeof e.content=="string"?t.push({type:"text",text:e.content}):t.push(...hf(e.content));for(let r of e.tool_calls??[])t.push({type:"tool_call",id:r.id,name:r.name,args:r.args});return t}function mL(e){let t=[];typeof e.content=="string"?t.push({type:"text",text:e.content}):t.push(...hf(e.content));for(let r of e.tool_calls??[])t.push({type:"tool_call",id:r.id,name:r.name,args:r.args});return t}function hf(e){let t=[];for(let r of e)Zk(r)?t.push(Gk(r)):t.push(r);return t}function hL(e){if(e.type==="url_citation"){let{url:t,title:r,start_index:n,end_index:i}=e;return{type:"citation",url:t,title:r,startIndex:n,endIndex:i}}if(e.type==="file_citation"){let{file_id:t,filename:r,index:n}=e;return{type:"citation",title:r,startIndex:n,endIndex:n,fileId:t}}return e}function Kk(e){function*t(){ue(e.additional_kwargs?.reasoning)&&qt(e.additional_kwargs.reasoning.summary)&&(yield{type:"reasoning",reasoning:e.additional_kwargs.reasoning.summary.reduce((i,s)=>ue(s)&&z(s.text)?`${i}${s.text}`:i,"")});let r=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content;for(let n of r)if(re(n,"text")){let{text:i,annotations:s,...o}=n;Array.isArray(s)?yield{...o,type:"text",text:String(i),annotations:s.map(hL)}:yield{...o,type:"text",text:String(i)}}for(let n of e.tool_calls??[])yield{type:"tool_call",id:n.id,name:n.name,args:n.args};if(ue(e.additional_kwargs)&&qt(e.additional_kwargs.tool_outputs))for(let n of e.additional_kwargs.tool_outputs){if(re(n,"web_search_call")){yield{id:n.id,type:"server_tool_call",name:"web_search",args:{query:n.query}};continue}else if(re(n,"file_search_call")){yield{id:n.id,type:"server_tool_call",name:"file_search",args:{query:n.query}};continue}else if(re(n,"computer_call")){yield{type:"non_standard",value:n};continue}else if(re(n,"code_interpreter_call")){if(z(n.code)&&(yield{id:n.id,type:"server_tool_call",name:"code_interpreter",args:{code:n.code}}),qt(n.outputs)){let i=Li(()=>{if(n.status!=="in_progress"){if(n.status==="completed")return 0;if(n.status==="incomplete")return 127;if(n.status!=="interpreting"&&n.status==="failed")return 1}});for(let s of n.outputs)if(re(s,"logs")){yield{type:"server_tool_call_result",toolCallId:n.id??"",status:"success",output:{type:"code_interpreter_output",returnCode:i??0,stderr:[0,void 0].includes(i)?void 0:String(s.logs),stdout:[0,void 0].includes(i)?String(s.logs):void 0}};continue}}continue}else if(re(n,"mcp_call")){yield{id:n.id,type:"server_tool_call",name:"mcp_call",args:n.input};continue}else if(re(n,"mcp_list_tools")){yield{id:n.id,type:"server_tool_call",name:"mcp_list_tools",args:n.input};continue}else if(re(n,"mcp_approval_request")){yield{type:"non_standard",value:n};continue}else if(re(n,"image_generation_call")){z(n.result)&&(yield{type:"image",mimeType:"image/png",data:n.result,id:z(n.id)?n.id:void 0,metadata:{status:z(n.status)?n.status:void 0}}),yield{type:"non_standard",value:n};continue}ue(n)&&(yield{type:"non_standard",value:n})}}return Array.from(t())}function gL(e){function*t(){yield*Kk(e);for(let r of e.tool_call_chunks??[])yield{type:"tool_call_chunk",id:r.id,name:r.name,args:r.args}}return Array.from(t())}var qk={translateContent:e=>typeof e.content=="string"?fL(e):Kk(e),translateContentChunk:e=>typeof e.content=="string"?mL(e):gL(e)};function gf(e){return typeof e=="object"&&e!==null&&"type"in e&&"content"in e&&(typeof e.content=="string"||Array.isArray(e.content))}function Hk(e,t="pretty"){return t==="pretty"?_L(e):JSON.stringify(e)}function _L(e){let t=[],r=` ${e.type.charAt(0).toUpperCase()+e.type.slice(1)} Message `,n=Math.floor((80-r.length)/2),i="=".repeat(n),s=r.length%2===0?i:`${i}=`;if(t.push(`${i}${r}${s}`),e.type==="ai"){let o=e;if(o.tool_calls&&o.tool_calls.length>0){t.push("Tool Calls:");for(let a of o.tool_calls){t.push(` ${a.name} (${a.id})`),t.push(` Call ID: ${a.id}`),t.push(" Args:");for(let[c,u]of Object.entries(a.args))t.push(` ${c}: ${typeof u=="object"?JSON.stringify(u):u}`)}}}if(e.type==="tool"){let o=e;o.name&&t.push(`Name: ${o.name}`)}return typeof e.content=="string"&&e.content.trim()&&(t.length>1&&t.push(""),t.push(e.content)),t.join(`
|
|
6
|
+
`)}var ey=Symbol.for("langchain.message");function Ht(e,t){return typeof e=="string"?e===""?t:typeof t=="string"?e+t:Array.isArray(t)&&t.length===0?e:Array.isArray(t)&&t.some(r=>Tr(r))?[{type:"text",source_type:"text",text:e},...t]:[{type:"text",text:e},...t]:Array.isArray(t)?Mo(e,t)??[...e,...t]:t===""?e:Array.isArray(e)&&e.some(r=>Tr(r))?[...e,{type:"file",source_type:"text",text:t}]:[...e,{type:"text",text:t}]}function _f(e,t){return e==="error"||t==="error"?"error":"success"}function yL(e,t){function r(n,i){if(typeof n!="object"||n===null||n===void 0)return n;if(i>=t)return Array.isArray(n)?"[Array]":"[Object]";if(Array.isArray(n))return n.map(o=>r(o,i+1));let s={};for(let o of Object.keys(n))s[o]=r(n[o],i+1);return s}return JSON.stringify(r(e,0),null,2)}var bt=class extends vt{lc_namespace=["langchain_core","messages"];lc_serializable=!0;get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}[ey]=!0;id;name;content;additional_kwargs;response_metadata;_getType(){return this.type}getType(){return this._getType()}constructor(e){let t=typeof e=="string"||Array.isArray(e)?{content:e}:e;t.additional_kwargs||(t.additional_kwargs={}),t.response_metadata||(t.response_metadata={}),super(t),this.name=t.name,t.content===void 0&&t.contentBlocks!==void 0?(this.content=t.contentBlocks,this.response_metadata={output_version:"v1",...t.response_metadata}):t.content!==void 0?(this.content=t.content??[],this.response_metadata=t.response_metadata):(this.content=[],this.response_metadata=t.response_metadata),this.additional_kwargs=t.additional_kwargs,this.id=t.id}get text(){return typeof this.content=="string"?this.content:Array.isArray(this.content)?this.content.map(e=>typeof e=="string"?e:e.type==="text"?e.text:"").join(""):""}get contentBlocks(){let e=typeof this.content=="string"?[{type:"text",text:this.content}]:this.content;return[Vk,hf,Fk].reduce((n,i)=>i(n),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 typeof e=="object"&&e!==null&&ey in e&&e[ey]===!0&&gf(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){if(e===null)return this;let t=yL(this._printableFields,Math.max(4,e));return`${this.constructor.lc_name()} ${t}`}toFormattedString(e="pretty"){return Hk(this,e)}};function Wk(e){return Array.isArray(e)&&e.every(t=>typeof t.index=="number")}var ty=["index","created","timestamp"];function st(e,t,r){let n=r?.ignoreKeys??ty;if(e==null&&t==null)return;if(e==null||t==null)return e??t;let i={...e};for(let[s,o]of Object.entries(t))if(i[s]==null)i[s]=o;else{if(o==null)continue;if(typeof i[s]!=typeof o||Array.isArray(i[s])!==Array.isArray(o))throw new Error(`field[${s}] already exists in the message chunk, but with a different type.`);if(typeof i[s]=="string"){if(s==="type")continue;if(["id","name","output_version","model_provider"].includes(s))o&&(i[s]=o);else{if(n.includes(s))continue;i[s]+=o}}else if(typeof i[s]=="number"){if(n.includes(s))continue;i[s]=i[s]+o}else if(typeof i[s]=="object"&&!Array.isArray(i[s]))i[s]=st(i[s],o,r);else if(Array.isArray(i[s]))i[s]=Mo(i[s],o,r);else{if(i[s]===o)continue;console.warn(`field[${s}] already exists in this message chunk and value has unsupported type.`)}}return i}function Mo(e,t,r){if(!(e==null&&t==null)){if(e==null||t==null)return e||t;{let n=[...e];for(let i of t)if(typeof i=="object"&&i!==null&&"index"in i&&typeof i.index=="number"){let s=n.findIndex(o=>{let a=typeof o=="object",c="index"in o&&o.index===i.index,u="id"in o&&"id"in i&&o?.id===i?.id,l=!("id"in o)||!o?.id||!("id"in i)||!i?.id;return a&&c&&(u||l)});s!==-1&&typeof n[s]=="object"&&n[s]!==null?n[s]=st(n[s],i,r):n.push(i)}else{if(typeof i=="object"&&i!==null&&"text"in i&&i.text==="")continue;n.push(i)}return n}}}function yf(e,t,r){if(!(e==null&&t==null)){if(e==null||t==null)return e??t;if(typeof e!=typeof t)throw new Error(`Cannot merge objects of different types.
|
|
7
|
+
Left ${typeof e}
|
|
8
|
+
Right ${typeof t}`);if(typeof e=="string"&&typeof t=="string")return e+t;if(Array.isArray(e)&&Array.isArray(t))return Mo(e,t,r);if(typeof e=="object"&&typeof t=="object")return st(e,t,r);if(e===t)return e;throw new Error(`Can not merge objects of different types.
|
|
9
|
+
Left ${e}
|
|
10
|
+
Right ${t}`)}}var ur=class Jk extends bt{static isInstance(t){if(!super.isInstance(t))return!1;let r=Object.getPrototypeOf(t);for(;r!==null;){if(r===Jk.prototype)return!0;r=Object.getPrototypeOf(r)}return!1}};function vf(e){return typeof e.role=="string"}function ot(e){return typeof e?._getType=="function"}function Ui(e){return ur.isInstance(e)}var ry={};M(ry,{ToolMessage:()=>Wt,ToolMessageChunk:()=>Rs,defaultToolCallParser:()=>yl,isDirectToolOutput:()=>_l,isToolMessage:()=>jo,isToolMessageChunk:()=>ny});function _l(e){return e!=null&&typeof e=="object"&&"lc_direct_tool_output"in e&&e.lc_direct_tool_output===!0}var Wt=class extends bt{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){let n=typeof e=="string"||Array.isArray(e)?{content:e,name:r,tool_call_id:t}:e;super(n),this.tool_call_id=n.tool_call_id,this.artifact=n.artifact,this.status=n.status,this.metadata=n.metadata}static isInstance(e){return super.isInstance(e)&&e.type==="tool"}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}},Rs=class extends ur{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){let t=this.constructor;return new t({content:Ht(this.content,e.content),additional_kwargs:st(this.additional_kwargs,e.additional_kwargs),response_metadata:st(this.response_metadata,e.response_metadata),artifact:yf(this.artifact,e.artifact),tool_call_id:this.tool_call_id,id:this.id??e.id,status:_f(this.status,e.status)})}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}};function yl(e){let t=[],r=[];for(let n of e)if(n.function){let i=n.function.name;try{let s=JSON.parse(n.function.arguments);t.push({name:i||"",args:s||{},id:n.id})}catch{r.push({name:i,args:n.function.arguments,id:n.id,error:"Malformed args."})}}else continue;return[t,r]}function jo(e){return typeof e=="object"&&e!==null&&"getType"in e&&typeof e.getType=="function"&&e.getType()==="tool"}function ny(e){return e._getType()==="tool"}var iy={};M(iy,{BaseCallbackHandler:()=>Fi,callbackHandlerPrefersStreaming:()=>vl,isBaseCallbackHandler:()=>sy});var vL=class{};function vl(e){return"lc_prefer_streaming"in e&&e.lc_prefer_streaming}var Fi=class extends vL{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,uc(this.constructor)]}lc_kwargs;ignoreLLM=!1;ignoreChain=!1;ignoreAgent=!1;ignoreRetriever=!1;ignoreCustomEvent=!1;raiseError=!1;awaitHandlers=Pe("LANGCHAIN_CALLBACKS_BACKGROUND")==="false";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 vt.prototype.toJSON.call(this)}toJSONNotImplemented(){return vt.prototype.toJSONNotImplemented.call(this)}static fromMethods(e){class t extends Fi{name=sn();constructor(){super(),Object.assign(this,e)}}return new t}},sy=e=>{let t=e;return t!==void 0&&typeof t.copy=="function"&&typeof t.name=="string"&&typeof t.awaitHandlers=="boolean"};var Xk="gen_ai.operation.name",Yk="gen_ai.system",oy="gen_ai.request.model",Qk="gen_ai.response.model",ay="gen_ai.usage.input_tokens",cy="gen_ai.usage.output_tokens",uy="gen_ai.usage.total_tokens",eA="gen_ai.request.max_tokens",tA="gen_ai.request.temperature",rA="gen_ai.request.top_p",nA="gen_ai.request.frequency_penalty",iA="gen_ai.request.presence_penalty",sA="gen_ai.response.finish_reasons",oA="gen_ai.prompt",aA="gen_ai.completion",cA="gen_ai.request.extra_query",uA="gen_ai.request.extra_body",lA="gen_ai.serialized.name",pA="gen_ai.serialized.signature",dA="gen_ai.serialized.doc",fA="gen_ai.response.id",mA="gen_ai.response.service_tier",hA="gen_ai.response.system_fingerprint",gA="gen_ai.usage.input_token_details",_A="gen_ai.usage.output_token_details",yA="langsmith.trace.session_id",vA="langsmith.trace.session_name",bA="langsmith.span.kind",wA="langsmith.trace.name",xA="langsmith.metadata",ly="langsmith.span.tags";var IA="langsmith.request.streaming",SA="langsmith.request.headers";var wL=(...e)=>fetch(...e),EA=Symbol.for("ls:fetch_implementation");var kA=()=>{let e=globalThis[EA];return e?typeof e=="function"&&"Headers"in e&&"Request"in e&&"Response"in e:!1},AA=e=>async(...t)=>{if(e||wt("DEBUG")==="true"){let[n,i]=t;console.log(`\u2192 ${i?.method||"GET"} ${n}`)}let r=await(globalThis[EA]??wL)(...t);return(e||wt("DEBUG")==="true")&&console.log(`\u2190 ${r.status} ${r.statusText} ${r.url}`),r};var bl=()=>wt("PROJECT")??Fr("LANGCHAIN_SESSION")??"default";var TA={};function wl(e){TA[e]||(console.warn(e),TA[e]=!0)}var xL=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function ve(e,t){if(!xL.test(e)){let r=t!==void 0?`Invalid UUID for ${t}: ${e}`:`Invalid UUID: ${e}`;throw new Error(r)}return e}function bf(e){let t=typeof e=="string"?Date.parse(e):e;return sn({msecs:t,seq:0})}function OA(e,t){throw new Error("dump() is not supported in browser environments.")}function $A(e){throw new Error("load() is not supported in browser environments.")}function IL(e,t){return t===null?!1:Date.now()-e.createdAt>t*1e3}var xl=class{constructor(t={}){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,"fetchFunc",{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.maxSize=t.maxSize??100,this.ttlSeconds=t.ttlSeconds??3600,this.refreshIntervalSeconds=t.refreshIntervalSeconds??60,this.fetchFunc=t.fetchFunc,this.fetchFunc&&this.ttlSeconds!==null&&this.startRefreshLoop()}get metrics(){return{...this._metrics}}get totalRequests(){return this._metrics.hits+this._metrics.misses}get hitRate(){let t=this.totalRequests;return t>0?this._metrics.hits/t:0}resetMetrics(){this._metrics={hits:0,misses:0,refreshes:0,refreshErrors:0}}get(t){let r=this.cache.get(t);if(!r){this._metrics.misses+=1;return}return this.cache.delete(t),this.cache.set(t,r),this._metrics.hits+=1,r.value}set(t,r){if(!this.cache.has(t)&&this.cache.size>=this.maxSize){let i=this.cache.keys().next().value;i!==void 0&&this.cache.delete(i)}let n={value:r,createdAt:Date.now()};this.cache.delete(t),this.cache.set(t,n)}invalidate(t){this.cache.delete(t)}clear(){this.cache.clear()}get size(){return this.cache.size}stop(){this.refreshTimer&&(clearInterval(this.refreshTimer),this.refreshTimer=void 0)}dump(t){let r={};for(let[n,i]of this.cache.entries())r[n]=i.value;OA(t,r)}load(t){let r=$A(t);if(!r)return 0;let n=0,i=Date.now();for(let[s,o]of Object.entries(r)){if(this.cache.size>=this.maxSize)break;let a={value:o,createdAt:i};this.cache.set(s,a),n+=1}return n}startRefreshLoop(){this.refreshTimer=setInterval(()=>{this.refreshStaleEntries().catch(t=>{console.warn("Unexpected error in cache refresh loop:",t)})},this.refreshIntervalSeconds*1e3),this.refreshTimer.unref&&this.refreshTimer.unref()}getStaleKeys(){let t=[];for(let[r,n]of this.cache.entries())IL(n,this.ttlSeconds)&&t.push(r);return t}async refreshStaleEntries(){if(!this.fetchFunc)return;let t=this.getStaleKeys();if(t.length!==0)for(let r of t)try{let n=await this.fetchFunc(r);this.set(r,n),this._metrics.refreshes+=1}catch(n){this._metrics.refreshErrors+=1,console.warn(`Failed to refresh cache entry ${r}:`,n)}}};var wf="0.4.8";var ii,SL=()=>typeof window<"u"&&typeof window.document<"u",EL=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",kL=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),CA=()=>typeof Deno<"u",AL=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!CA(),fy=()=>ii||(typeof Bun<"u"?ii="bun":SL()?ii="browser":AL()?ii="node":EL()?ii="webworker":kL()?ii="jsdom":CA()?ii="deno":ii="other",ii),py;function xf(){if(py===void 0){let e=fy(),t=OL();py={library:"langsmith",runtime:e,sdk:"langsmith-js",sdk_version:wf,...t}}return py}function my(){let e=TL(),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[n,i]of Object.entries(e))typeof i=="string"&&!r.includes(n)&&!n.toLowerCase().includes("key")&&!n.toLowerCase().includes("secret")&&!n.toLowerCase().includes("token")&&(n==="LANGCHAIN_REVISION_ID"?t.revision_id=i:t[n]=i);return t}function TL(){let e={};try{if(typeof process<"u"&&process.env)for(let[t,r]of Object.entries(process.env))(t.startsWith("LANGCHAIN_")||t.startsWith("LANGSMITH_"))&&r!=null&&((t.toLowerCase().includes("key")||t.toLowerCase().includes("secret")||t.toLowerCase().includes("token"))&&typeof r=="string"?e[t]=r.slice(0,2)+"*".repeat(r.length-4)+r.slice(-2):e[t]=r)}catch{}return e}function Fr(e){try{return typeof process<"u"?process.env?.[e]:void 0}catch{return}}function wt(e){return Fr(`LANGSMITH_${e}`)||Fr(`LANGCHAIN_${e}`)}var dy;function OL(){if(dy!==void 0)return dy;let e=["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"],t={};for(let r of e){let n=Fr(r);n!==void 0&&(t[r]=n)}return dy=t,t}function If(){return Fr("OTEL_ENABLED")==="true"||wt("OTEL_ENABLED")==="true"}var _y=class{constructor(){Object.defineProperty(this,"hasWarned",{enumerable:!0,configurable:!0,writable:!0,value:!1})}startActiveSpan(t,...r){!this.hasWarned&&If()&&(console.warn('You have enabled OTEL export via the `OTEL_ENABLED` or `LANGSMITH_OTEL_ENABLED` environment variable, but have not initialized the required OTEL instances. Please add:\n```\nimport { initializeOTEL } from "langsmith/experimental/otel/setup";\ninitializeOTEL();\n```\nat the beginning of your code.'),this.hasWarned=!0);let n;if(r.length===1&&typeof r[0]=="function"?n=r[0]:r.length===2&&typeof r[1]=="function"?n=r[1]:r.length===3&&typeof r[2]=="function"&&(n=r[2]),typeof n=="function")return n()}},yy=class{constructor(){Object.defineProperty(this,"mockTracer",{enumerable:!0,configurable:!0,writable:!0,value:new _y})}getTracer(t,r){return this.mockTracer}getActiveSpan(){}setSpan(t,r){return t}getSpan(t){}setSpanContext(t,r){return t}getTracerProvider(){}setGlobalTracerProvider(t){return!1}},vy=class{active(){return{}}with(t,r){return r()}},hy=Symbol.for("ls:otel_trace"),gy=Symbol.for("ls:otel_context"),PA=Symbol.for("ls:otel_get_default_otlp_tracer_provider"),$L=new yy,CL=new vy,by=class{getTraceInstance(){return globalThis[hy]??$L}getContextInstance(){return globalThis[gy]??CL}initializeGlobalInstances(t){globalThis[hy]===void 0&&(globalThis[hy]=t.trace),globalThis[gy]===void 0&&(globalThis[gy]=t.context)}setDefaultOTLPTracerComponents(t){globalThis[PA]=t}getDefaultOTLPTracerComponents(){return globalThis[PA]??void 0}},wy=new by;function Sf(){return wy.getTraceInstance()}function NA(){return wy.getContextInstance()}function RA(){return wy.getDefaultOTLPTracerComponents()}var PL={llm:"chat",tool:"execute_tool",retriever:"embeddings",embedding:"embeddings",prompt:"chat"};function NL(e){return PL[e]||e}var Ef=class{constructor(){Object.defineProperty(this,"spans",{enumerable:!0,configurable:!0,writable:!0,value:new Map})}exportBatch(t,r){for(let n of t)try{if(!n.run)continue;if(n.operation==="post"){let i=this.createSpanForRun(n,n.run,r.get(n.id));i&&!n.run.end_time&&this.spans.set(n.id,i)}else this.updateSpanForRun(n,n.run)}catch(i){console.error(`Error processing operation ${n.id}:`,i)}}createSpanForRun(t,r,n){let i=n&&Sf().getSpan(n);if(i)try{return this.finishSpanSetup(i,r,t)}catch(s){console.error(`Failed to create span for run ${t.id}:`,s);return}}finishSpanSetup(t,r,n){return this.setSpanAttributes(t,r,n),r.error?(t.setStatus({code:2}),t.recordException(new Error(r.error))):t.setStatus({code:1}),r.end_time&&t.end(new Date(r.end_time)),t}updateSpanForRun(t,r){try{let n=this.spans.get(t.id);if(!n){console.debug(`No span found for run ${t.id} during update`);return}this.setSpanAttributes(n,r,t),r.error?(n.setStatus({code:2}),n.recordException(new Error(r.error))):n.setStatus({code:1});let i=r.end_time;i&&(n.end(new Date(i)),this.spans.delete(t.id))}catch(n){console.error(`Failed to update span for run ${t.id}:`,n)}}extractModelName(t){if(t.extra?.metadata){let r=t.extra.metadata;if(r.ls_model_name)return r.ls_model_name;if(r.invocation_params){let n=r.invocation_params;if(n.model)return n.model;if(n.model_name)return n.model_name}}}setSpanAttributes(t,r,n){if("run_type"in r&&r.run_type){t.setAttribute(bA,r.run_type);let a=NL(r.run_type||"chain");t.setAttribute(Xk,a)}"name"in r&&r.name&&t.setAttribute(wA,r.name),"session_id"in r&&r.session_id&&t.setAttribute(yA,r.session_id),"session_name"in r&&r.session_name&&t.setAttribute(vA,r.session_name),this.setGenAiSystem(t,r);let i=this.extractModelName(r);i&&t.setAttribute(oy,i),"prompt_tokens"in r&&typeof r.prompt_tokens=="number"&&t.setAttribute(ay,r.prompt_tokens),"completion_tokens"in r&&typeof r.completion_tokens=="number"&&t.setAttribute(cy,r.completion_tokens),"total_tokens"in r&&typeof r.total_tokens=="number"&&t.setAttribute(uy,r.total_tokens),this.setInvocationParameters(t,r);let s=r.extra?.metadata||{};for(let[a,c]of Object.entries(s))c!=null&&t.setAttribute(`${xA}.${a}`,String(c));let o=r.tags;if(o&&Array.isArray(o)?t.setAttribute(ly,o.join(", ")):o&&t.setAttribute(ly,String(o)),"serialized"in r&&typeof r.serialized=="object"){let a=r.serialized;a.name&&t.setAttribute(lA,String(a.name)),a.signature&&t.setAttribute(pA,String(a.signature)),a.doc&&t.setAttribute(dA,String(a.doc))}this.setIOAttributes(t,n)}setGenAiSystem(t,r){let n="langchain",i=this.extractModelName(r);if(i){let s=i.toLowerCase();s.includes("anthropic")||s.startsWith("claude")?n="anthropic":s.includes("bedrock")?n="aws.bedrock":s.includes("azure")&&s.includes("openai")?n="az.ai.openai":s.includes("azure")&&s.includes("inference")?n="az.ai.inference":s.includes("cohere")?n="cohere":s.includes("deepseek")?n="deepseek":s.includes("gemini")?n="gemini":s.includes("groq")?n="groq":s.includes("watson")||s.includes("ibm")?n="ibm.watsonx.ai":s.includes("mistral")?n="mistral_ai":s.includes("gpt")||s.includes("openai")?n="openai":s.includes("perplexity")||s.includes("sonar")?n="perplexity":s.includes("vertex")?n="vertex_ai":(s.includes("xai")||s.includes("grok"))&&(n="xai")}t.setAttribute(Yk,n)}setInvocationParameters(t,r){if(!r.extra?.metadata?.invocation_params)return;let n=r.extra.metadata.invocation_params;n.max_tokens!==void 0&&t.setAttribute(eA,n.max_tokens),n.temperature!==void 0&&t.setAttribute(tA,n.temperature),n.top_p!==void 0&&t.setAttribute(rA,n.top_p),n.frequency_penalty!==void 0&&t.setAttribute(nA,n.frequency_penalty),n.presence_penalty!==void 0&&t.setAttribute(iA,n.presence_penalty)}setIOAttributes(t,r){if(r.run.inputs)try{let n=r.run.inputs;typeof n=="object"&&n!==null&&(n.model&&Array.isArray(n.messages)&&t.setAttribute(oy,n.model),n.stream!==void 0&&t.setAttribute(IA,n.stream),n.extra_headers&&t.setAttribute(SA,JSON.stringify(n.extra_headers)),n.extra_query&&t.setAttribute(cA,JSON.stringify(n.extra_query)),n.extra_body&&t.setAttribute(uA,JSON.stringify(n.extra_body))),t.setAttribute(oA,JSON.stringify(n))}catch(n){console.debug(`Failed to process inputs for run ${r.id}`,n)}if(r.run.outputs)try{let n=r.run.outputs,i=this.getUnifiedRunTokens(n);if(i&&(t.setAttribute(ay,i[0]),t.setAttribute(cy,i[1]),t.setAttribute(uy,i[0]+i[1])),n&&typeof n=="object"){if(n.model&&t.setAttribute(Qk,String(n.model)),n.id&&t.setAttribute(fA,n.id),n.choices&&Array.isArray(n.choices)){let s=n.choices.map(o=>o.finish_reason).filter(o=>o).map(String);s.length>0&&t.setAttribute(sA,s.join(", "))}if(n.service_tier&&t.setAttribute(mA,n.service_tier),n.system_fingerprint&&t.setAttribute(hA,n.system_fingerprint),n.usage_metadata&&typeof n.usage_metadata=="object"){let s=n.usage_metadata;s.input_token_details&&t.setAttribute(gA,JSON.stringify(s.input_token_details)),s.output_token_details&&t.setAttribute(_A,JSON.stringify(s.output_token_details))}}t.setAttribute(aA,JSON.stringify(n))}catch(n){console.debug(`Failed to process outputs for run ${r.id}`,n)}}getUnifiedRunTokens(t){if(!t)return null;let r=this.extractUnifiedRunTokens(t.usage_metadata);if(r)return r;let n=Object.keys(t);for(let o of n){let a=t[o];if(!(!a||typeof a!="object")&&(r=this.extractUnifiedRunTokens(a.usage_metadata),r||a.lc===1&&a.kwargs&&typeof a.kwargs=="object"&&(r=this.extractUnifiedRunTokens(a.kwargs.usage_metadata),r)))return r}let i=t.generations||[];if(!Array.isArray(i))return null;let s=Array.isArray(i[0])?i.flat():i;for(let o of s)if(typeof o=="object"&&o.message&&typeof o.message=="object"&&o.message.kwargs&&typeof o.message.kwargs=="object"&&(r=this.extractUnifiedRunTokens(o.message.kwargs.usage_metadata),r))return r;return null}extractUnifiedRunTokens(t){return!t||typeof t!="object"||typeof t.input_tokens!="number"||typeof t.output_tokens!="number"?null:[t.input_tokens,t.output_tokens]}};var RL=Object.prototype.toString,ML=e=>RL.call(e)==="[object Error]",jL=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 xy(e){if(!(e&&ML(e)&&e.name==="TypeError"&&typeof e.message=="string"))return!1;let{message:r,stack:n}=e;return r==="Load failed"?n===void 0||"__sentry_captured__"in e:r.startsWith("error sending request for url")?!0:jL.has(r)}function DL(e){if(typeof e=="number"){if(e<0)throw new TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(e))throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(e!==void 0)throw new TypeError("Expected `retries` to be a number or Infinity.")}function kf(e,t,{min:r=0,allowInfinity:n=!1}={}){if(t!==void 0){if(typeof t!="number"||Number.isNaN(t))throw new TypeError(`Expected \`${e}\` to be a number${n?" or Infinity":""}.`);if(!n&&!Number.isFinite(t))throw new TypeError(`Expected \`${e}\` to be a finite number.`);if(t<r)throw new TypeError(`Expected \`${e}\` to be \u2265 ${r}.`)}}var Iy=class extends Error{constructor(t){super(),t instanceof Error?(this.originalError=t,{message:t}=t):(this.originalError=new Error(t),this.originalError.stack=this.stack),this.name="AbortError",this.message=t}};function zL(e,t){let r=Math.max(1,e+1),n=t.randomize?Math.random()+1:1,i=Math.round(n*t.minTimeout*t.factor**(r-1));return i=Math.min(i,t.maxTimeout),i}function MA(e,t){return Number.isFinite(t)?t-(performance.now()-e):t}async function LL({error:e,attemptNumber:t,retriesConsumed:r,startTime:n,options:i}){let s=e instanceof Error?e:new TypeError(`Non-error was thrown: "${e}". You should only throw errors.`);if(s instanceof Iy)throw s.originalError;let o=Number.isFinite(i.retries)?Math.max(0,i.retries-r):i.retries,a=i.maxRetryTime??Number.POSITIVE_INFINITY,c=Object.freeze({error:s,attemptNumber:t,retriesLeft:o,retriesConsumed:r});if(await i.onFailedAttempt(c),MA(n,a)<=0)throw s;let u=await i.shouldConsumeRetry(c),l=MA(n,a);if(l<=0||o<=0)throw s;if(s instanceof TypeError&&!xy(s)){if(u)throw s;return i.signal?.throwIfAborted(),!1}if(!await i.shouldRetry(c))throw s;if(!u)return i.signal?.throwIfAborted(),!1;let p=zL(r,i),f=Math.min(p,l);return f>0&&await new Promise((d,m)=>{let h=()=>{clearTimeout(b),i.signal?.removeEventListener("abort",h),m(i.signal.reason)},b=setTimeout(()=>{i.signal?.removeEventListener("abort",h),d()},f);i.unref&&b.unref?.(),i.signal?.addEventListener("abort",h,{once:!0})}),i.signal?.throwIfAborted(),!0}async function Sy(e,t={}){if(t={...t},DL(t.retries),Object.hasOwn(t,"forever"))throw new 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??=Number.POSITIVE_INFINITY,t.maxRetryTime??=Number.POSITIVE_INFINITY,t.randomize??=!1,t.onFailedAttempt??=()=>{},t.shouldRetry??=()=>!0,t.shouldConsumeRetry??=()=>!0,kf("factor",t.factor,{min:0,allowInfinity:!1}),kf("minTimeout",t.minTimeout,{min:0,allowInfinity:!1}),kf("maxTimeout",t.maxTimeout,{min:0,allowInfinity:!0}),kf("maxRetryTime",t.maxRetryTime,{min:0,allowInfinity:!0}),t.factor>0||(t.factor=1),t.signal?.throwIfAborted();let r=0,n=0,i=performance.now();for(;!Number.isFinite(t.retries)||n<=t.retries;){r++;try{t.signal?.throwIfAborted();let s=await e(r);return t.signal?.throwIfAborted(),s}catch(s){await LL({error:s,attemptNumber:r,retriesConsumed:n,startTime:i,options:t})&&n++}}throw new Error("Retry attempts exhausted without throwing an error.")}var Pf=Ps(Cf(),1),HL=[408,425,429,500,502,503,504],Sl=class{constructor(t){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=t.maxConcurrency??1/0,this.maxRetries=t.maxRetries??6,this.maxQueueSizeBytes=t.maxQueueSizeBytes,"default"in Pf.default?this.queue=new Pf.default.default({concurrency:this.maxConcurrency}):this.queue=new Pf.default({concurrency:this.maxConcurrency}),this.onFailedResponseHook=t?.onFailedResponseHook}call(t,...r){return this.callWithOptions({},t,...r)}callWithOptions(t,r,...n){let i=t.sizeBytes??0;if(this.maxQueueSizeBytes!==void 0&&i>0&&this.queueSizeBytes+i>this.maxQueueSizeBytes)return Promise.reject(new Error(`Queue size limit (${this.maxQueueSizeBytes} bytes) exceeded. Current queue size: ${this.queueSizeBytes} bytes, attempted addition: ${i} bytes.`));i>0&&(this.queueSizeBytes+=i);let s=this.onFailedResponseHook,o=this.queue.add(()=>Sy(()=>r(...n).catch(a=>{throw a instanceof Error?a:new Error(a)}),{async onFailedAttempt({error:a}){if(typeof a!="object"||a==null)throw a;let c="message"in a&&typeof a.message=="string"?a.message:void 0;if(c?.startsWith("Cancel")||c?.startsWith("TimeoutError")||c?.startsWith("AbortError")||"name"in a&&a.name==="TimeoutError"||"code"in a&&a.code==="ECONNABORTED")throw a;let u="response"in a?a.response:void 0;if(s&&await s(u))return;let l=u?.status??("status"in a?a.status:void 0);if(l!=null&&(typeof l=="number"||typeof l=="string")&&!HL.includes(+l))throw a},retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0});return i>0&&(o=o.finally(()=>{this.queueSizeBytes-=i})),t.signal?Promise.race([o,new Promise((a,c)=>{t.signal?.addEventListener("abort",()=>{c(new Error("AbortError"))})})]):o}};function Cy(e){return typeof e?._getType=="function"}function Py(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}var Z2=Ps(NO(),1);function Vi(e){if(!e||e.split("/").length>2||e.startsWith("/")||e.endsWith("/")||e.split(":").length>2)throw new Error(`Invalid identifier format: ${e}`);let[t,r]=e.split(":"),n=r||"latest";if(t.includes("/")){let[i,s]=t.split("/",2);if(!i||!s)throw new Error(`Invalid identifier format: ${e}`);return[i,s,n]}else{if(!t)throw new Error(`Invalid identifier format: ${e}`);return["-",t,n]}}var Yy=class extends Error{constructor(t){super(t),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="LangSmithConflictError",this.status=409}},Qy=class extends Error{constructor(t){super(t),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="LangSmithNotFoundError",this.status=404}};function ev(e){return e!=null&&typeof e=="object"&&"name"in e&&e?.name==="LangSmithNotFoundError"}async function ie(e,t,r){let n;if(e.ok){r&&(n=await e.text());return}if(e.status===403)try{(await e.json())?.error==="org_scoped_key_requires_workspace"&&(n="This API key is org-scoped and requires workspace specification. Please provide 'workspaceId' parameter, or set LANGSMITH_WORKSPACE_ID environment variable.")}catch{let a=new Error(`${e.status} ${e.statusText}`);throw a.status=e?.status,a}if(n===void 0)try{n=await e.text()}catch{n=""}let i=`Failed to ${t}. Received status [${e.status}]: ${e.statusText}. Message: ${n}`;if(e.status===404)throw new Qy(i);if(e.status===409)throw new Yy(i);let s=new Error(i);throw s.status=e.status,s}var RO="ERR_CONFLICTING_ENDPOINTS",Gf=class 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:RO}),this.name="ConflictingEndpointsError"}};function MO(e){return typeof e=="object"&&e!==null&&e.code===RO}var jO="[...]",G2={result:"[Circular]"},qf=[],mc=[],K2=new TextEncoder;function q2(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function Kf(e){return K2.encode(e)}function DO(e){if(e&&typeof e=="object"&&e!==null){if(e instanceof Map)return Object.fromEntries(e);if(e instanceof Set)return Array.from(e);if(e instanceof Date)return e.toISOString();if(e instanceof RegExp)return e.toString();if(e instanceof Error)return{name:e.name,message:e.message}}else if(typeof e=="bigint")return e.toString();return e}function H2(e){return function(t,r){if(e){let n=e.call(this,t,r);if(n!==void 0)return n}return DO(r)}}function Or(e,t,r,n,i){try{let s=JSON.stringify(e,H2(r),n);return Kf(s)}catch(s){if(!s.message?.includes("Converting circular structure to JSON"))return console.warn(`[WARNING]: LangSmith received unserializable value.${t?`
|
|
11
|
+
Context: ${t}`:""}`),Kf("[Unserializable]");wt("SUPPRESS_CIRCULAR_JSON_WARNINGS")!=="true"&&console.warn(`[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. ${t?`
|
|
12
|
+
Context: ${t}`:""}`),typeof i>"u"&&(i=q2()),rv(e,"",0,[],void 0,0,i);let o;try{mc.length===0?o=JSON.stringify(e,r,n):o=JSON.stringify(e,W2(r),n)}catch{return Kf("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;qf.length!==0;){let a=qf.pop();a.length===4?Object.defineProperty(a[0],a[1],a[3]):a[0][a[1]]=a[2]}}return Kf(o)}}function tv(e,t,r,n){var i=Object.getOwnPropertyDescriptor(n,r);i.get!==void 0?i.configurable?(Object.defineProperty(n,r,{value:e}),qf.push([n,r,t,i])):mc.push([t,r,e]):(n[r]=e,qf.push([n,r,t]))}function rv(e,t,r,n,i,s,o){s+=1;var a;if(typeof e=="object"&&e!==null){for(a=0;a<n.length;a++)if(n[a]===e){tv(G2,e,t,i);return}if(typeof o.depthLimit<"u"&&s>o.depthLimit){tv(jO,e,t,i);return}if(typeof o.edgesLimit<"u"&&r+1>o.edgesLimit){tv(jO,e,t,i);return}if(n.push(e),Array.isArray(e))for(a=0;a<e.length;a++)rv(e[a],a,a,n,e,s,o);else{e=DO(e);var c=Object.keys(e);for(a=0;a<c.length;a++){var u=c[a];rv(e[u],u,a,n,e,s,o)}}n.pop()}}function W2(e){return e=typeof e<"u"?e:function(t,r){return r},function(t,r){if(mc.length>0)for(var n=0;n<mc.length;n++){var i=mc[n];if(i[1]===t&&i[0]===r){r=i[2],mc.splice(n,1);break}}return e.call(this,t,r)}}function zO(e,t,r){if(r)return e;let n=xf(),i=t??my(),s=e.extra??{},o=s.metadata;return e.extra={...s,runtime:{...n,...s?.runtime},metadata:{...i,...i.revision_id||"revision_id"in e&&e.revision_id?{revision_id:("revision_id"in e?e.revision_id:void 0)??i.revision_id}:{},...o}},e}var J2=e=>{let t=e?.toString()??wt("TRACING_SAMPLING_RATE");if(t===void 0)return;let r=parseFloat(t);if(r<0||r>1)throw new Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${r}`);return r},X2=e=>{let r=e.replace("http://","").replace("https://","").split("/")[0].split(":")[0];return r==="localhost"||r==="127.0.0.1"||r==="::1"};async function Y2(e){let t=[];for await(let r of e)t.push(r);return t}function Hf(e){if(e!==void 0)return e.trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}var Q2=async e=>{if(e?.status===429){let t=parseInt(e.headers.get("retry-after")??"10",10)*1e3;if(t>0)return await new Promise(r=>setTimeout(r,t)),!0}return!1};function LO(e){return typeof e=="number"?Number(e.toFixed(4)):e}var eF=24*1024*1024,BO=1024*1024*1024,tF=1e4,rF=100,UO="https://api.smith.langchain.com",nv=class{constructor(t){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=t??BO}peek(){return this.items[0]}push(t){let r,n=new Promise(s=>{r=s}),i=Or(t.item,`Serializing run with id: ${t.item.id}`).length;return this.sizeBytes+i>this.maxSizeBytes&&this.items.length>0?(console.warn(`AutoBatchQueue size limit (${this.maxSizeBytes} bytes) exceeded. Dropping run with id: ${t.item.id}. Current queue size: ${this.sizeBytes} bytes, attempted addition: ${i} bytes.`),r(),n):(this.items.push({action:t.action,payload:t.item,otelContext:t.otelContext,apiKey:t.apiKey,apiUrl:t.apiUrl,itemPromiseResolve:r,itemPromise:n,size:i}),this.sizeBytes+=i,n)}pop({upToSizeBytes:t,upToSize:r}){if(t<1)throw new Error("Number of bytes to pop off may not be less than 1.");let n=[],i=0;for(;i+(this.peek()?.size??0)<t&&this.items.length>0&&n.length<r;){let s=this.items.shift();s&&(n.push(s),i+=s.size,this.sizeBytes-=s.size)}if(n.length===0&&this.items.length>0){let s=this.items.shift();n.push(s),i+=s.size,this.sizeBytes-=s.size}return[n.map(s=>({action:s.action,item:s.payload,otelContext:s.otelContext,apiKey:s.apiKey,apiUrl:s.apiUrl,size:s.size})),()=>n.forEach(s=>s.itemPromiseResolve())]}},Bi=class e{get _fetch(){return this.fetchImplementation||AA(this.debug)}constructor(t={}){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,"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:Fr("LANGSMITH_TRACING_BACKGROUND")==="false"}),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,"langSmithToOTELTranslator",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),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,"_cache",{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:wt("DISABLE_RUN_COMPRESSION")==="true"}),Object.defineProperty(this,"debug",{enumerable:!0,configurable:!0,writable:!0,value:Fr("LANGSMITH_DEBUG")==="true"});let r=e.getDefaultClientConfig();if(this.tracingSampleRate=J2(t.tracingSamplingRate),this.apiUrl=Hf(t.apiUrl??r.apiUrl)??"",this.apiUrl.endsWith("/")&&(this.apiUrl=this.apiUrl.slice(0,-1)),this.apiKey=Hf(t.apiKey??r.apiKey),this.webUrl=Hf(t.webUrl??r.webUrl),this.webUrl?.endsWith("/")&&(this.webUrl=this.webUrl.slice(0,-1)),this.workspaceId=Hf(t.workspaceId??wt("WORKSPACE_ID")),this.timeout_ms=t.timeout_ms??9e4,this.caller=new Sl({...t.callerOptions??{},maxRetries:4,debug:t.debug??this.debug}),this.traceBatchConcurrency=t.traceBatchConcurrency??this.traceBatchConcurrency,this.traceBatchConcurrency<1)throw new Error("Trace batch concurrency must be positive.");this.debug=t.debug??this.debug,this.fetchImplementation=t.fetchImplementation;let n=t.maxIngestMemoryBytes??BO;this.batchIngestCaller=new Sl({maxRetries:4,maxConcurrency:this.traceBatchConcurrency,maxQueueSizeBytes:n,...t.callerOptions??{},onFailedResponseHook:Q2,debug:t.debug??this.debug}),this.hideInputs=t.hideInputs??t.anonymizer??r.hideInputs,this.hideOutputs=t.hideOutputs??t.anonymizer??r.hideOutputs,this.omitTracedRuntimeInfo=t.omitTracedRuntimeInfo??!1,this.autoBatchTracing=t.autoBatchTracing??this.autoBatchTracing,this.autoBatchQueue=new nv(n),this.blockOnRootRunFinalization=t.blockOnRootRunFinalization??this.blockOnRootRunFinalization,this.batchSizeBytesLimit=t.batchSizeBytesLimit,this.batchSizeLimit=t.batchSizeLimit,this.fetchOptions=t.fetchOptions||{},this.manualFlushMode=t.manualFlushMode??this.manualFlushMode,If()&&(this.langSmithToOTELTranslator=new Ef),this.cachedLSEnvVarsForMetadata=my(),t.cache===!0?this._cache=new xl:t.cache&&typeof t.cache=="object"?this._cache=t.cache:this._cache=void 0}static getDefaultClientConfig(){let t=wt("API_KEY"),r=wt("ENDPOINT")??UO,n=wt("HIDE_INPUTS")==="true",i=wt("HIDE_OUTPUTS")==="true";return{apiUrl:r,apiKey:t,webUrl:void 0,hideInputs:n,hideOutputs:i}}getHostUrl(){return this.webUrl?this.webUrl:X2(this.apiUrl)?(this.webUrl="http://localhost:3000",this.webUrl):this.apiUrl.endsWith("/api/v1")?(this.webUrl=this.apiUrl.replace("/api/v1",""),this.webUrl):this.apiUrl.includes("/api")&&!this.apiUrl.split(".",1)[0].endsWith("api")?(this.webUrl=this.apiUrl.replace("/api",""),this.webUrl):this.apiUrl.split(".",1)[0].includes("dev")?(this.webUrl="https://dev.smith.langchain.com",this.webUrl):this.apiUrl.split(".",1)[0].includes("eu")?(this.webUrl="https://eu.smith.langchain.com",this.webUrl):this.apiUrl.split(".",1)[0].includes("beta")?(this.webUrl="https://beta.smith.langchain.com",this.webUrl):(this.webUrl="https://smith.langchain.com",this.webUrl)}get headers(){let t={"User-Agent":`langsmith-js/${wf}`};return this.apiKey&&(t["x-api-key"]=`${this.apiKey}`),this.workspaceId&&(t["x-tenant-id"]=this.workspaceId),t}_getPlatformEndpointPath(t){return this.apiUrl.slice(-3)!=="/v1"&&this.apiUrl.slice(-4)!=="/v1/"?`/v1/platform/${t}`:`/platform/${t}`}async processInputs(t){return this.hideInputs===!1?t:this.hideInputs===!0?{}:typeof this.hideInputs=="function"?this.hideInputs(t):t}async processOutputs(t){return this.hideOutputs===!1?t:this.hideOutputs===!0?{}:typeof this.hideOutputs=="function"?this.hideOutputs(t):t}async prepareRunCreateOrUpdateInputs(t){let r={...t};return r.inputs!==void 0&&(r.inputs=await this.processInputs(r.inputs)),r.outputs!==void 0&&(r.outputs=await this.processOutputs(r.outputs)),r}async _getResponse(t,r){let n=r?.toString()??"",i=`${this.apiUrl}${t}?${n}`;return await this.caller.call(async()=>{let o=await this._fetch(i,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ie(o,`fetch ${t}`),o})}async _get(t,r){return(await this._getResponse(t,r)).json()}async*_getPaginated(t,r=new URLSearchParams,n){let i=Number(r.get("offset"))||0,s=Number(r.get("limit"))||100;for(;;){r.set("offset",String(i)),r.set("limit",String(s));let o=`${this.apiUrl}${t}?${r}`,a=await this.caller.call(async()=>{let u=await this._fetch(o,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ie(u,`fetch ${t}`),u}),c=n?n(await a.json()):await a.json();if(c.length===0||(yield c,c.length<s))break;i+=c.length}}async*_getCursorPaginatedList(t,r=null,n="POST",i="runs"){let s=r?{...r}:{};for(;;){let o=JSON.stringify(s),c=await(await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}${t}`,{method:n,headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await ie(l,`fetch ${t}`),l})).json();if(!c||!c[i])break;yield c[i];let u=c.cursors;if(!u||!u.next)break;s.cursor=u.next}}_shouldSample(){return this.tracingSampleRate===void 0?!0:Math.random()<this.tracingSampleRate}_filterForSampling(t,r=!1){if(this.tracingSampleRate===void 0)return t;if(r){let n=[];for(let i of t)this.filteredPostUuids.has(i.trace_id)?i.id===i.trace_id&&this.filteredPostUuids.delete(i.trace_id):n.push(i);return n}else{let n=[];for(let i of t){let s=i.trace_id??i.id;this.filteredPostUuids.has(s)||(i.id===s?this._shouldSample()?n.push(i):this.filteredPostUuids.add(s):n.push(i))}return n}}async _getBatchSizeLimitBytes(){let t=await this._ensureServerInfo();return this.batchSizeBytesLimit??t?.batch_ingest_config?.size_limit_bytes??eF}async _getBatchSizeLimit(){let t=await this._ensureServerInfo();return this.batchSizeLimit??t?.batch_ingest_config?.size_limit??rF}async _getDatasetExamplesMultiPartSupport(){return(await this._ensureServerInfo()).instance_flags?.dataset_examples_multipart_enabled??!1}drainAutoBatchQueue({batchSizeLimitBytes:t,batchSizeLimit:r}){let n=[];for(;this.autoBatchQueue.items.length>0;){let[i,s]=this.autoBatchQueue.pop({upToSizeBytes:t,upToSize:r});if(!i.length){s();break}let o=i.reduce((u,l)=>{let p=l.apiUrl??this.apiUrl,f=l.apiKey??this.apiKey,m=l.apiKey===this.apiKey&&l.apiUrl===this.apiUrl?"default":`${p}|${f}`;return u[m]||(u[m]=[]),u[m].push(l),u},{}),a=[];for(let[u,l]of Object.entries(o)){let p=this._processBatch(l,{apiUrl:u==="default"?void 0:u.split("|")[0],apiKey:u==="default"?void 0:u.split("|")[1]});a.push(p)}let c=Promise.all(a).finally(s);n.push(c)}return Promise.all(n)}async _processBatch(t,r){if(!t.length)return;let n=t.reduce((i,s)=>i+(s.size??0),0);try{if(this.langSmithToOTELTranslator!==void 0)this._sendBatchToOTELTranslator(t);else{let i={runCreates:t.filter(a=>a.action==="create").map(a=>a.item),runUpdates:t.filter(a=>a.action==="update").map(a=>a.item)},s=await this._ensureServerInfo();if(!this._multipartDisabled&&(s?.batch_ingest_config?.use_multipart_endpoint??!0)){let a=!this._runCompressionDisabled&&s?.instance_flags?.gzip_body_enabled;try{await this.multipartIngestRuns(i,{...r,useGzip:a,sizeBytes:n})}catch(c){if(ev(c))this._multipartDisabled=!0,await this.batchIngestRuns(i,{...r,sizeBytes:n});else throw c}}else await this.batchIngestRuns(i,{...r,sizeBytes:n})}}catch(i){console.error("Error exporting batch:",i)}}_sendBatchToOTELTranslator(t){if(this.langSmithToOTELTranslator!==void 0){let r=new Map,n=[];for(let i of t)i.item.id&&i.otelContext&&(r.set(i.item.id,i.otelContext),i.action==="create"?n.push({operation:"post",id:i.item.id,trace_id:i.item.trace_id??i.item.id,run:i.item}):n.push({operation:"patch",id:i.item.id,trace_id:i.item.trace_id??i.item.id,run:i.item}));this.langSmithToOTELTranslator.exportBatch(n,r)}}async processRunOperation(t){clearTimeout(this.autoBatchTimeout),this.autoBatchTimeout=void 0,t.item=zO(t.item,this.cachedLSEnvVarsForMetadata,this.omitTracedRuntimeInfo);let r=this.autoBatchQueue.push(t);if(this.manualFlushMode)return r;let n=await this._getBatchSizeLimitBytes(),i=await this._getBatchSizeLimit();return(this.autoBatchQueue.sizeBytes>n||this.autoBatchQueue.items.length>i)&&this.drainAutoBatchQueue({batchSizeLimitBytes:n,batchSizeLimit:i}),this.autoBatchQueue.items.length>0&&(this.autoBatchTimeout=setTimeout(()=>{this.autoBatchTimeout=void 0,this.drainAutoBatchQueue({batchSizeLimitBytes:n,batchSizeLimit:i})},this.autoBatchAggregationDelayMs)),r}async _getServerInfo(){let r=await(await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/info`,{method:"GET",headers:{Accept:"application/json"},signal:AbortSignal.timeout(tF),...this.fetchOptions});return await ie(n,"get server info"),n})).json();return this.debug&&console.log(`
|
|
13
|
+
=== LangSmith Server Configuration ===
|
|
14
|
+
`+JSON.stringify(r,null,2)+`
|
|
15
|
+
`),r}async _ensureServerInfo(){return this._getServerInfoPromise===void 0&&(this._getServerInfoPromise=(async()=>{if(this._serverInfo===void 0)try{this._serverInfo=await this._getServerInfo()}catch(t){console.warn(`[LANGSMITH]: Failed to fetch info on supported operations. Falling back to batch operations and default limits. Info: ${t.status??"Unspecified status code"} ${t.message}`)}return this._serverInfo??{}})()),this._getServerInfoPromise.then(t=>(this._serverInfo===void 0&&(this._getServerInfoPromise=void 0),t))}async _getSettings(){return this.settings||(this.settings=this._get("/settings")),await this.settings}async flush(){let t=await this._getBatchSizeLimitBytes(),r=await this._getBatchSizeLimit();await this.drainAutoBatchQueue({batchSizeLimitBytes:t,batchSizeLimit:r})}_cloneCurrentOTELContext(){let t=Sf(),r=NA();if(this.langSmithToOTELTranslator!==void 0){let n=t.getActiveSpan();if(n)return t.setSpan(r.active(),n)}}async createRun(t,r){if(!this._filterForSampling([t]).length)return;let n={...this.headers,"Content-Type":"application/json"},i=t.project_name;delete t.project_name;let s=await this.prepareRunCreateOrUpdateInputs({session_name:i,...t,start_time:t.start_time??Date.now()});if(this.autoBatchTracing&&s.trace_id!==void 0&&s.dotted_order!==void 0){let c=this._cloneCurrentOTELContext();this.processRunOperation({action:"create",item:s,otelContext:c,apiKey:r?.apiKey,apiUrl:r?.apiUrl}).catch(console.error);return}let o=zO(s,this.cachedLSEnvVarsForMetadata,this.omitTracedRuntimeInfo);r?.apiKey!==void 0&&(n["x-api-key"]=r.apiKey),r?.workspaceId!==void 0&&(n["x-tenant-id"]=r.workspaceId);let a=Or(o,`Creating run with id: ${o.id}`);await this.caller.call(async()=>{let c=await this._fetch(`${r?.apiUrl??this.apiUrl}/runs`,{method:"POST",headers:n,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await ie(c,"create run",!0),c})}async batchIngestRuns({runCreates:t,runUpdates:r},n){if(t===void 0&&r===void 0)return;let i=await Promise.all(t?.map(c=>this.prepareRunCreateOrUpdateInputs(c))??[]),s=await Promise.all(r?.map(c=>this.prepareRunCreateOrUpdateInputs(c))??[]);if(i.length>0&&s.length>0){let c=i.reduce((l,p)=>(p.id&&(l[p.id]=p),l),{}),u=[];for(let l of s)l.id!==void 0&&c[l.id]?c[l.id]={...c[l.id],...l}:u.push(l);i=Object.values(c),s=u}let o={post:i,patch:s};if(!o.post.length&&!o.patch.length)return;let a={post:[],patch:[]};for(let c of["post","patch"]){let u=c,l=o[u].reverse(),p=l.pop();for(;p!==void 0;)a[u].push(p),p=l.pop()}if(a.post.length>0||a.patch.length>0){let c=a.post.map(u=>u.id).concat(a.patch.map(u=>u.id)).join(",");await this._postBatchIngestRuns(Or(a,`Ingesting runs with ids: ${c}`),n)}}async _postBatchIngestRuns(t,r){let n={...this.headers,"Content-Type":"application/json",Accept:"application/json"};r?.apiKey!==void 0&&(n["x-api-key"]=r.apiKey),await this.batchIngestCaller.callWithOptions({sizeBytes:r?.sizeBytes},async()=>{let i=await this._fetch(`${r?.apiUrl??this.apiUrl}/runs/batch`,{method:"POST",headers:n,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:t});return await ie(i,"batch create run",!0),i})}async multipartIngestRuns({runCreates:t,runUpdates:r},n){if(t===void 0&&r===void 0)return;let i={},s=[];for(let p of t??[]){let f=await this.prepareRunCreateOrUpdateInputs(p);f.id!==void 0&&f.attachments!==void 0&&(i[f.id]=f.attachments),delete f.attachments,s.push(f)}let o=[];for(let p of r??[])o.push(await this.prepareRunCreateOrUpdateInputs(p));if(s.find(p=>p.trace_id===void 0||p.dotted_order===void 0)!==void 0)throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when creating a run');if(o.find(p=>p.trace_id===void 0||p.dotted_order===void 0)!==void 0)throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when updating a run');if(s.length>0&&o.length>0){let p=s.reduce((d,m)=>(m.id&&(d[m.id]=m),d),{}),f=[];for(let d of o)d.id!==void 0&&p[d.id]?p[d.id]={...p[d.id],...d}:f.push(d);s=Object.values(p),o=f}if(s.length===0&&o.length===0)return;let u=[],l=[];for(let[p,f]of[["post",s],["patch",o]])for(let d of f){let{inputs:m,outputs:h,events:b,extra:_,error:y,serialized:x,attachments:I,...A}=d,j={inputs:m,outputs:h,events:b,extra:_,error:y,serialized:x},O=Or(A,`Serializing for multipart ingestion of run with id: ${A.id}`);l.push({name:`${p}.${A.id}`,payload:new Blob([O],{type:`application/json; length=${O.length}`})});for(let[w,F]of Object.entries(j)){if(F===void 0)continue;let P=Or(F,`Serializing ${w} for multipart ingestion of run with id: ${A.id}`);l.push({name:`${p}.${A.id}.${w}`,payload:new Blob([P],{type:`application/json; length=${P.length}`})})}if(A.id!==void 0){let w=i[A.id];if(w){delete i[A.id];for(let[F,P]of Object.entries(w)){let V,Te;if(Array.isArray(P)?[V,Te]=P:(V=P.mimeType,Te=P.data),F.includes(".")){console.warn(`Skipping attachment '${F}' for run ${A.id}: Invalid attachment name. Attachment names must not contain periods ('.'). Please rename the attachment and try again.`);continue}l.push({name:`attachment.${A.id}.${F}`,payload:new Blob([Te],{type:`${V}; length=${Te.byteLength}`})})}}}u.push(`trace=${A.trace_id},id=${A.id}`)}await this._sendMultipartRequest(l,u.join("; "),n)}async _createNodeFetchBody(t,r){let n=[];for(let o of t)n.push(new Blob([`--${r}\r
|
|
16
|
+
`])),n.push(new Blob([`Content-Disposition: form-data; name="${o.name}"\r
|
|
17
|
+
`,`Content-Type: ${o.payload.type}\r
|
|
18
|
+
\r
|
|
19
|
+
`])),n.push(o.payload),n.push(new Blob([`\r
|
|
20
|
+
`]));return n.push(new Blob([`--${r}--\r
|
|
21
|
+
`])),await new Blob(n).arrayBuffer()}async _createMultipartStream(t,r){let n=new TextEncoder;return new ReadableStream({async start(s){let o=async a=>{typeof a=="string"?s.enqueue(n.encode(a)):s.enqueue(a)};for(let a of t){await o(`--${r}\r
|
|
22
|
+
`),await o(`Content-Disposition: form-data; name="${a.name}"\r
|
|
23
|
+
`),await o(`Content-Type: ${a.payload.type}\r
|
|
24
|
+
\r
|
|
25
|
+
`);let u=a.payload.stream().getReader();try{let l;for(;!(l=await u.read()).done;)s.enqueue(l.value)}finally{u.releaseLock()}await o(`\r
|
|
26
|
+
`)}await o(`--${r}--\r
|
|
27
|
+
`),s.close()}})}async _sendMultipartRequest(t,r,n){let i="----LangSmithFormBoundary"+Math.random().toString(36).slice(2),s=kA(),o=()=>this._createNodeFetchBody(t,i),a=()=>this._createMultipartStream(t,i),c=async u=>this.batchIngestCaller.callWithOptions({sizeBytes:n?.sizeBytes},async()=>{let l=await u(),p={...this.headers,"Content-Type":`multipart/form-data; boundary=${i}`};n?.apiKey!==void 0&&(p["x-api-key"]=n.apiKey);let f=l;n?.useGzip&&typeof l=="object"&&"pipeThrough"in l&&(f=l.pipeThrough(new CompressionStream("gzip")),p["Content-Encoding"]="gzip");let d=await this._fetch(`${n?.apiUrl??this.apiUrl}/runs/multipart`,{method:"POST",headers:p,body:f,duplex:"half",signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ie(d,"Failed to send multipart request",!0),d});try{let u,l=!1;!s&&!this.multipartStreamingDisabled&&fy()!=="bun"?(l=!0,u=await c(a)):u=await c(o),(!this.multipartStreamingDisabled||l)&&u.status===422&&(n?.apiUrl??this.apiUrl)!==UO&&(console.warn(`Streaming multipart upload to ${n?.apiUrl??this.apiUrl}/runs/multipart failed. This usually means the host does not support chunked uploads. Retrying with a buffered upload for operation "${r}".`),this.multipartStreamingDisabled=!0,u=await c(o))}catch(u){if(ev(u))throw u;console.warn(`${u.message.trim()}
|
|
28
|
+
|
|
29
|
+
Context: ${r}`)}}async updateRun(t,r,n){ve(t),r.inputs&&(r.inputs=await this.processInputs(r.inputs)),r.outputs&&(r.outputs=await this.processOutputs(r.outputs));let i={...r,id:t};if(!this._filterForSampling([i],!0).length)return;if(this.autoBatchTracing&&i.trace_id!==void 0&&i.dotted_order!==void 0){let a=this._cloneCurrentOTELContext();if(r.end_time!==void 0&&i.parent_run_id===void 0&&this.blockOnRootRunFinalization&&!this.manualFlushMode){await this.processRunOperation({action:"update",item:i,otelContext:a,apiKey:n?.apiKey,apiUrl:n?.apiUrl}).catch(console.error);return}else this.processRunOperation({action:"update",item:i,otelContext:a,apiKey:n?.apiKey,apiUrl:n?.apiUrl}).catch(console.error);return}let s={...this.headers,"Content-Type":"application/json"};n?.apiKey!==void 0&&(s["x-api-key"]=n.apiKey),n?.workspaceId!==void 0&&(s["x-tenant-id"]=n.workspaceId);let o=Or(r,`Serializing payload to update run with id: ${t}`);await this.caller.call(async()=>{let a=await this._fetch(`${n?.apiUrl??this.apiUrl}/runs/${t}`,{method:"PATCH",headers:s,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await ie(a,"update run",!0),a})}async readRun(t,{loadChildRuns:r}={loadChildRuns:!1}){ve(t);let n=await this._get(`/runs/${t}`);return r&&(n=await this._loadChildRuns(n)),n}async getRunUrl({runId:t,run:r,projectOpts:n}){if(r!==void 0){let i;r.session_id?i=r.session_id:n?.projectName?i=(await this.readProject({projectName:n?.projectName})).id:n?.projectId?i=n?.projectId:i=(await this.readProject({projectName:wt("PROJECT")||"default"})).id;let s=await this._getTenantId();return`${this.getHostUrl()}/o/${s}/projects/p/${i}/r/${r.id}?poll=true`}else if(t!==void 0){let i=await this.readRun(t);if(!i.app_path)throw new Error(`Run ${t} has no app_path`);return`${this.getHostUrl()}${i.app_path}`}else throw new Error("Must provide either runId or run")}async _loadChildRuns(t){let r=await Y2(this.listRuns({isRoot:!1,projectId:t.session_id,traceId:t.trace_id})),n={},i={};r.sort((s,o)=>(s?.dotted_order??"").localeCompare(o?.dotted_order??""));for(let s of r){if(s.parent_run_id===null||s.parent_run_id===void 0)throw new Error(`Child run ${s.id} has no parent`);s.dotted_order?.startsWith(t.dotted_order??"")&&s.id!==t.id&&(s.parent_run_id in n||(n[s.parent_run_id]=[]),n[s.parent_run_id].push(s),i[s.id]=s)}t.child_runs=n[t.id]||[];for(let s in n)s!==t.id&&(i[s].child_runs=n[s]);return t}async*listRuns(t){let{projectId:r,projectName:n,parentRunId:i,traceId:s,referenceExampleId:o,startTime:a,executionOrder:c,isRoot:u,runType:l,error:p,id:f,query:d,filter:m,traceFilter:h,treeFilter:b,limit:_,select:y,order:x}=t,I=[];if(r&&(I=Array.isArray(r)?r:[r]),n){let w=Array.isArray(n)?n:[n],F=await Promise.all(w.map(P=>this.readProject({projectName:P}).then(V=>V.id)));I.push(...F)}let A=["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"],j={session:I.length?I:null,run_type:l,reference_example:o,query:d,filter:m,trace_filter:h,tree_filter:b,execution_order:c,parent_run:i,start_time:a?a.toISOString():null,error:p,id:f,limit:_,trace:s,select:y||A,is_root:u,order:x};j.select.includes("child_run_ids")&&wl("Deprecated: 'child_run_ids' in the listRuns select parameter is deprecated and will be removed in a future version.");let O=0;for await(let w of this._getCursorPaginatedList("/runs/query",j))if(_){if(O>=_)break;if(w.length+O>_){yield*w.slice(0,_-O);break}O+=w.length,yield*w}else yield*w}async*listGroupRuns(t){let{projectId:r,projectName:n,groupBy:i,filter:s,startTime:o,endTime:a,limit:c,offset:u}=t,p={session_id:r||(await this.readProject({projectName:n})).id,group_by:i,filter:s,start_time:o?o.toISOString():null,end_time:a?a.toISOString():null,limit:Number(c)||100},f=Number(u)||0,d="/runs/group",m=`${this.apiUrl}${d}`;for(;;){let h={...p,offset:f},b=Object.fromEntries(Object.entries(h).filter(([j,O])=>O!==void 0)),_=JSON.stringify(b),x=await(await this.caller.call(async()=>{let j=await this._fetch(m,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:_});return await ie(j,`Failed to fetch ${d}`),j})).json(),{groups:I,total:A}=x;if(I.length===0)break;for(let j of I)yield j;if(f+=I.length,f>=A)break}}async getRunStats({id:t,trace:r,parentRun:n,runType:i,projectNames:s,projectIds:o,referenceExampleIds:a,startTime:c,endTime:u,error:l,query:p,filter:f,traceFilter:d,treeFilter:m,isRoot:h,dataSourceType:b}){let _=o||[];s&&(_=[...o||[],...await Promise.all(s.map(O=>this.readProject({projectName:O}).then(w=>w.id)))]);let x=Object.fromEntries(Object.entries({id:t,trace:r,parent_run:n,run_type:i,session:_,reference_example:a,start_time:c,end_time:u,error:l,query:p,filter:f,trace_filter:d,tree_filter:m,is_root:h,data_source_type:b}).filter(([O,w])=>w!==void 0)),I=JSON.stringify(x);return await(await this.caller.call(async()=>{let O=await this._fetch(`${this.apiUrl}/runs/stats`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:I});return await ie(O,"get run stats"),O})).json()}async shareRun(t,{shareId:r}={}){let n={run_id:t,share_token:r||Ar()};ve(t);let i=JSON.stringify(n),o=await(await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}/runs/${t}/share`,{method:"PUT",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await ie(a,"share run"),a})).json();if(o===null||!("share_token"in o))throw new Error("Invalid response from server");return`${this.getHostUrl()}/public/${o.share_token}/r`}async unshareRun(t){ve(t),await this.caller.call(async()=>{let r=await this._fetch(`${this.apiUrl}/runs/${t}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ie(r,"unshare run",!0),r})}async readRunSharedLink(t){ve(t);let n=await(await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}/runs/${t}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ie(i,"read run shared link"),i})).json();if(!(n===null||!("share_token"in n)))return`${this.getHostUrl()}/public/${n.share_token}/r`}async listSharedRuns(t,{runIds:r}={}){let n=new URLSearchParams({share_token:t});if(r!==void 0)for(let o of r)n.append("id",o);return ve(t),await(await this.caller.call(async()=>{let o=await this._fetch(`${this.apiUrl}/public/${t}/runs${n}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ie(o,"list shared runs"),o})).json()}async readDatasetSharedSchema(t,r){if(!t&&!r)throw new Error("Either datasetId or datasetName must be given");t||(t=(await this.readDataset({datasetName:r})).id),ve(t);let i=await(await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}/datasets/${t}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ie(s,"read dataset shared schema"),s})).json();return i.url=`${this.getHostUrl()}/public/${i.share_token}/d`,i}async shareDataset(t,r){if(!t&&!r)throw new Error("Either datasetId or datasetName must be given");t||(t=(await this.readDataset({datasetName:r})).id);let n={dataset_id:t};ve(t);let i=JSON.stringify(n),o=await(await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}/datasets/${t}/share`,{method:"PUT",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await ie(a,"share dataset"),a})).json();return o.url=`${this.getHostUrl()}/public/${o.share_token}/d`,o}async unshareDataset(t){ve(t),await this.caller.call(async()=>{let r=await this._fetch(`${this.apiUrl}/datasets/${t}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ie(r,"unshare dataset",!0),r})}async readSharedDataset(t){return ve(t),await(await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}/public/${t}/datasets`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ie(i,"read shared dataset"),i})).json()}async listSharedExamples(t,r){let n={};r?.exampleIds&&(n.id=r.exampleIds);let i=new URLSearchParams;Object.entries(n).forEach(([a,c])=>{Array.isArray(c)?c.forEach(u=>i.append(a,u)):i.append(a,c)});let s=await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}/public/${t}/examples?${i.toString()}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ie(a,"list shared examples"),a}),o=await s.json();if(!s.ok)throw"detail"in o?new Error(`Failed to list shared examples.
|
|
30
|
+
Status: ${s.status}
|
|
31
|
+
Message: ${Array.isArray(o.detail)?o.detail.join(`
|
|
32
|
+
`):"Unspecified error"}`):new Error(`Failed to list shared examples: ${s.status} ${s.statusText}`);return o.map(a=>({...a,_hostUrl:this.getHostUrl()}))}async createProject({projectName:t,description:r=null,metadata:n=null,upsert:i=!1,projectExtra:s=null,referenceDatasetId:o=null}){let a=i?"?upsert=true":"",c=`${this.apiUrl}/sessions${a}`,u=s||{};n&&(u.metadata=n);let l={name:t,extra:u,description:r};o!==null&&(l.reference_dataset_id=o);let p=JSON.stringify(l);return await(await this.caller.call(async()=>{let m=await this._fetch(c,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:p});return await ie(m,"create project"),m})).json()}async updateProject(t,{name:r=null,description:n=null,metadata:i=null,projectExtra:s=null,endTime:o=null}){let a=`${this.apiUrl}/sessions/${t}`,c=s;i&&(c={...c||{},metadata:i});let u=JSON.stringify({name:r,extra:c,description:n,end_time:o?new Date(o).toISOString():null});return await(await this.caller.call(async()=>{let f=await this._fetch(a,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await ie(f,"update project"),f})).json()}async hasProject({projectId:t,projectName:r}){let n="/sessions",i=new URLSearchParams;if(t!==void 0&&r!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(t!==void 0)ve(t),n+=`/${t}`;else if(r!==void 0)i.append("name",r);else throw new Error("Must provide projectName or projectId");let s=await this.caller.call(async()=>{let o=await this._fetch(`${this.apiUrl}${n}?${i}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ie(o,"has project"),o});try{let o=await s.json();return s.ok?Array.isArray(o)?o.length>0:!0:!1}catch{return!1}}async readProject({projectId:t,projectName:r,includeStats:n}){let i="/sessions",s=new URLSearchParams;if(t!==void 0&&r!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(t!==void 0)ve(t),i+=`/${t}`;else if(r!==void 0)s.append("name",r);else throw new Error("Must provide projectName or projectId");n!==void 0&&s.append("include_stats",n.toString());let o=await this._get(i,s),a;if(Array.isArray(o)){if(o.length===0)throw new Error(`Project[id=${t}, name=${r}] not found`);a=o[0]}else a=o;return a}async getProjectUrl({projectId:t,projectName:r}){if(t===void 0&&r===void 0)throw new Error("Must provide either projectName or projectId");let n=await this.readProject({projectId:t,projectName:r}),i=await this._getTenantId();return`${this.getHostUrl()}/o/${i}/projects/p/${n.id}`}async getDatasetUrl({datasetId:t,datasetName:r}){if(t===void 0&&r===void 0)throw new Error("Must provide either datasetName or datasetId");let n=await this.readDataset({datasetId:t,datasetName:r}),i=await this._getTenantId();return`${this.getHostUrl()}/o/${i}/datasets/${n.id}`}async _getTenantId(){if(this._tenantId!==null)return this._tenantId;let t=new URLSearchParams({limit:"1"});for await(let r of this._getPaginated("/sessions",t))return this._tenantId=r[0].tenant_id,r[0].tenant_id;throw new Error("No projects found to resolve tenant.")}async*listProjects({projectIds:t,name:r,nameContains:n,referenceDatasetId:i,referenceDatasetName:s,includeStats:o,datasetVersion:a,referenceFree:c,metadata:u}={}){let l=new URLSearchParams;if(t!==void 0)for(let p of t)l.append("id",p);if(r!==void 0&&l.append("name",r),n!==void 0&&l.append("name_contains",n),i!==void 0)l.append("reference_dataset",i);else if(s!==void 0){let p=await this.readDataset({datasetName:s});l.append("reference_dataset",p.id)}o!==void 0&&l.append("include_stats",o.toString()),a!==void 0&&l.append("dataset_version",a),c!==void 0&&l.append("reference_free",c.toString()),u!==void 0&&l.append("metadata",JSON.stringify(u));for await(let p of this._getPaginated("/sessions",l))yield*p}async deleteProject({projectId:t,projectName:r}){let n;if(t===void 0&&r===void 0)throw new Error("Must provide projectName or projectId");if(t!==void 0&&r!==void 0)throw new Error("Must provide either projectName or projectId, not both");t===void 0?n=(await this.readProject({projectName:r})).id:n=t,ve(n),await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}/sessions/${n}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ie(i,`delete session ${n} (${r})`,!0),i})}async uploadCsv({csvFile:t,fileName:r,inputKeys:n,outputKeys:i,description:s,dataType:o,name:a}){let c=`${this.apiUrl}/datasets/upload`,u=new FormData,l=new Blob([t],{type:"text/csv"});return u.append("file",l,r),n.forEach(d=>{u.append("input_keys",d)}),i.forEach(d=>{u.append("output_keys",d)}),s&&u.append("description",s),o&&u.append("data_type",o),a&&u.append("name",a),await(await this.caller.call(async()=>{let d=await this._fetch(c,{method:"POST",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await ie(d,"upload CSV"),d})).json()}async createDataset(t,{description:r,dataType:n,inputsSchema:i,outputsSchema:s,metadata:o}={}){let a={name:t,description:r,extra:o?{metadata:o}:void 0};n&&(a.data_type=n),i&&(a.inputs_schema_definition=i),s&&(a.outputs_schema_definition=s);let c=JSON.stringify(a);return await(await this.caller.call(async()=>{let p=await this._fetch(`${this.apiUrl}/datasets`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await ie(p,"create dataset"),p})).json()}async readDataset({datasetId:t,datasetName:r}){let n="/datasets",i=new URLSearchParams({limit:"1"});if(t&&r)throw new Error("Must provide either datasetName or datasetId, not both");if(t)ve(t),n+=`/${t}`;else if(r)i.append("name",r);else throw new Error("Must provide datasetName or datasetId");let s=await this._get(n,i),o;if(Array.isArray(s)){if(s.length===0)throw new Error(`Dataset[id=${t}, name=${r}] not found`);o=s[0]}else o=s;return o}async hasDataset({datasetId:t,datasetName:r}){try{return await this.readDataset({datasetId:t,datasetName:r}),!0}catch(n){if(n instanceof Error&&n.message.toLocaleLowerCase().includes("not found"))return!1;throw n}}async diffDatasetVersions({datasetId:t,datasetName:r,fromVersion:n,toVersion:i}){let s=t;if(s===void 0&&r===void 0)throw new Error("Must provide either datasetName or datasetId");if(s!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");s===void 0&&(s=(await this.readDataset({datasetName:r})).id);let o=new URLSearchParams({from_version:typeof n=="string"?n:n.toISOString(),to_version:typeof i=="string"?i:i.toISOString()});return await this._get(`/datasets/${s}/versions/diff`,o)}async readDatasetOpenaiFinetuning({datasetId:t,datasetName:r}){let n="/datasets";if(t===void 0)if(r!==void 0)t=(await this.readDataset({datasetName:r})).id;else throw new Error("Must provide either datasetName or datasetId");return(await(await this._getResponse(`${n}/${t}/openai_ft`)).text()).trim().split(`
|
|
33
|
+
`).map(a=>JSON.parse(a))}async*listDatasets({limit:t=100,offset:r=0,datasetIds:n,datasetName:i,datasetNameContains:s,metadata:o}={}){let a="/datasets",c=new URLSearchParams({limit:t.toString(),offset:r.toString()});if(n!==void 0)for(let u of n)c.append("id",u);i!==void 0&&c.append("name",i),s!==void 0&&c.append("name_contains",s),o!==void 0&&c.append("metadata",JSON.stringify(o));for await(let u of this._getPaginated(a,c))yield*u}async updateDataset(t){let{datasetId:r,datasetName:n,...i}=t;if(!r&&!n)throw new Error("Must provide either datasetName or datasetId");let s=r??(await this.readDataset({datasetName:n})).id;ve(s);let o=JSON.stringify(i);return await(await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/datasets/${s}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await ie(c,"update dataset"),c})).json()}async updateDatasetTag(t){let{datasetId:r,datasetName:n,asOf:i,tag:s}=t;if(!r&&!n)throw new Error("Must provide either datasetName or datasetId");let o=r??(await this.readDataset({datasetName:n})).id;ve(o);let a=JSON.stringify({as_of:typeof i=="string"?i:i.toISOString(),tag:s});await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/datasets/${o}/tags`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await ie(c,"update dataset tags",!0),c})}async deleteDataset({datasetId:t,datasetName:r}){let n="/datasets",i=t;if(t!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(r!==void 0&&(i=(await this.readDataset({datasetName:r})).id),i!==void 0)ve(i),n+=`/${i}`;else throw new Error("Must provide datasetName or datasetId");await this.caller.call(async()=>{let s=await this._fetch(this.apiUrl+n,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ie(s,`delete ${n}`,!0),s})}async indexDataset({datasetId:t,datasetName:r,tag:n}){let i=t;if(!i&&!r)throw new Error("Must provide either datasetName or datasetId");if(i&&r)throw new Error("Must provide either datasetName or datasetId, not both");i||(i=(await this.readDataset({datasetName:r})).id),ve(i);let o=JSON.stringify({tag:n});await(await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/datasets/${i}/index`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await ie(c,"index dataset"),c})).json()}async similarExamples(t,r,n,{filter:i}={}){let s={limit:n,inputs:t};i!==void 0&&(s.filter=i),ve(r);let o=JSON.stringify(s);return(await(await this.caller.call(async()=>{let u=await this._fetch(`${this.apiUrl}/datasets/${r}/search`,{headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,method:"POST",body:o});return await ie(u,"fetch similar examples"),u})).json()).examples}async createExample(t,r,n){if(FO(t)&&(r!==void 0||n!==void 0))throw new Error("Cannot provide outputs or options when using ExampleCreate object");let i=r?n?.datasetId:t.dataset_id,s=r?n?.datasetName:t.dataset_name;if(i===void 0&&s===void 0)throw new Error("Must provide either datasetName or datasetId");if(i!==void 0&&s!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");i===void 0&&(i=(await this.readDataset({datasetName:s})).id);let o=(r?n?.createdAt:t.created_at)||new Date,a;FO(t)?a=t:a={inputs:t,outputs:r,created_at:o?.toISOString(),id:n?.exampleId,metadata:n?.metadata,split:n?.split,source_run_id:n?.sourceRunId,use_source_run_io:n?.useSourceRunIO,use_source_run_attachments:n?.useSourceRunAttachments,attachments:n?.attachments};let c=await this._uploadExamplesMultipart(i,[a]);return await this.readExample(c.example_ids?.[0]??Ar())}async createExamples(t){if(Array.isArray(t)){if(t.length===0)return[];let y=t,x=y[0].dataset_id,I=y[0].dataset_name;if(x===void 0&&I===void 0)throw new Error("Must provide either datasetName or datasetId");if(x!==void 0&&I!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");x===void 0&&(x=(await this.readDataset({datasetName:I})).id);let A=await this._uploadExamplesMultipart(x,y);return await Promise.all(A.example_ids.map(O=>this.readExample(O)))}let{inputs:r,outputs:n,metadata:i,splits:s,sourceRunIds:o,useSourceRunIOs:a,useSourceRunAttachments:c,attachments:u,exampleIds:l,datasetId:p,datasetName:f}=t;if(r===void 0)throw new Error("Must provide inputs when using legacy parameters");let d=p,m=f;if(d===void 0&&m===void 0)throw new Error("Must provide either datasetName or datasetId");if(d!==void 0&&m!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");d===void 0&&(d=(await this.readDataset({datasetName:m})).id);let h=r.map((y,x)=>({dataset_id:d,inputs:y,outputs:n?.[x],metadata:i?.[x],split:s?.[x],id:l?.[x],attachments:u?.[x],source_run_id:o?.[x],use_source_run_io:a?.[x],use_source_run_attachments:c?.[x]})),b=await this._uploadExamplesMultipart(d,h);return await Promise.all(b.example_ids.map(y=>this.readExample(y)))}async createLLMExample(t,r,n){return this.createExample({input:t},{output:r},n)}async createChatExample(t,r,n){let i=t.map(o=>Cy(o)?Py(o):o),s=Cy(r)?Py(r):r;return this.createExample({input:i},{output:s},n)}async readExample(t){ve(t);let r=`/examples/${t}`,n=await this._get(r),{attachment_urls:i,...s}=n,o=s;return i&&(o.attachments=Object.entries(i).reduce((a,[c,u])=>(a[c.slice(11)]={presigned_url:u.presigned_url,mime_type:u.mime_type},a),{})),o}async*listExamples({datasetId:t,datasetName:r,exampleIds:n,asOf:i,splits:s,inlineS3Urls:o,metadata:a,limit:c,offset:u,filter:l,includeAttachments:p}={}){let f;if(t!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(t!==void 0)f=t;else if(r!==void 0)f=(await this.readDataset({datasetName:r})).id;else throw new Error("Must provide a datasetName or datasetId");let d=new URLSearchParams({dataset:f}),m=i?typeof i=="string"?i:i?.toISOString():void 0;m&&d.append("as_of",m);let h=o??!0;if(d.append("inline_s3_urls",h.toString()),n!==void 0)for(let _ of n)d.append("id",_);if(s!==void 0)for(let _ of s)d.append("splits",_);if(a!==void 0){let _=JSON.stringify(a);d.append("metadata",_)}c!==void 0&&d.append("limit",c.toString()),u!==void 0&&d.append("offset",u.toString()),l!==void 0&&d.append("filter",l),p===!0&&["attachment_urls","outputs","metadata"].forEach(_=>d.append("select",_));let b=0;for await(let _ of this._getPaginated("/examples",d)){for(let y of _){let{attachment_urls:x,...I}=y,A=I;x&&(A.attachments=Object.entries(x).reduce((j,[O,w])=>(j[O.slice(11)]={presigned_url:w.presigned_url,mime_type:w.mime_type||void 0},j),{})),yield A,b++}if(c!==void 0&&b>=c)break}}async deleteExample(t){ve(t);let r=`/examples/${t}`;await this.caller.call(async()=>{let n=await this._fetch(this.apiUrl+r,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ie(n,`delete ${r}`,!0),n})}async deleteExamples(t,r){if(t.forEach(n=>ve(n)),r?.hardDelete){let n=this._getPlatformEndpointPath("datasets/examples/delete");await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}${n}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify({example_ids:t,hard_delete:!0}),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ie(i,"hard delete examples",!0),i})}else{let n=new URLSearchParams;t.forEach(i=>n.append("example_ids",i)),await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}/examples?${n.toString()}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ie(i,"delete examples",!0),i})}}async updateExample(t,r){let n;r?n=t:n=t.id,ve(n);let i;r?i={id:n,...r}:i=t;let s;return i.dataset_id!==void 0?s=i.dataset_id:s=(await this.readExample(n)).dataset_id,this._updateExamplesMultipart(s,[i])}async updateExamples(t){let r;return t[0].dataset_id===void 0?r=(await this.readExample(t[0].id)).dataset_id:r=t[0].dataset_id,this._updateExamplesMultipart(r,t)}async readDatasetVersion({datasetId:t,datasetName:r,asOf:n,tag:i}){let s;if(t?s=t:s=(await this.readDataset({datasetName:r})).id,ve(s),n&&i||!n&&!i)throw new Error("Exactly one of asOf and tag must be specified.");let o=new URLSearchParams;return n!==void 0&&o.append("as_of",typeof n=="string"?n:n.toISOString()),i!==void 0&&o.append("tag",i),await(await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/datasets/${s}/version?${o.toString()}`,{method:"GET",headers:{...this.headers},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ie(c,"read dataset version"),c})).json()}async listDatasetSplits({datasetId:t,datasetName:r,asOf:n}){let i;if(t===void 0&&r===void 0)throw new Error("Must provide dataset name or ID");if(t!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");t===void 0?i=(await this.readDataset({datasetName:r})).id:i=t,ve(i);let s=new URLSearchParams,o=n?typeof n=="string"?n:n?.toISOString():void 0;return o&&s.append("as_of",o),await this._get(`/datasets/${i}/splits`,s)}async updateDatasetSplits({datasetId:t,datasetName:r,splitName:n,exampleIds:i,remove:s=!1}){let o;if(t===void 0&&r===void 0)throw new Error("Must provide dataset name or ID");if(t!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");t===void 0?o=(await this.readDataset({datasetName:r})).id:o=t,ve(o);let a={split_name:n,examples:i.map(u=>(ve(u),u)),remove:s},c=JSON.stringify(a);await this.caller.call(async()=>{let u=await this._fetch(`${this.apiUrl}/datasets/${o}/splits`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await ie(u,"update dataset splits",!0),u})}async createFeedback(t,r,{score:n,value:i,correction:s,comment:o,sourceInfo:a,feedbackSourceType:c="api",sourceRunId:u,feedbackId:l,feedbackConfig:p,projectId:f,comparativeExperimentId:d}){if(!t&&!f)throw new Error("One of runId or projectId must be provided");if(t&&f)throw new Error("Only one of runId or projectId can be provided");let m={type:c??"api",metadata:a??{}};u!==void 0&&m?.metadata!==void 0&&!m.metadata.__run&&(m.metadata.__run={run_id:u}),m?.metadata!==void 0&&m.metadata.__run?.run_id!==void 0&&ve(m.metadata.__run.run_id);let h={id:l??Ar(),run_id:t,key:r,score:LO(n),value:i,correction:s,comment:o,feedback_source:m,comparative_experiment_id:d,feedbackConfig:p,session_id:f},b=JSON.stringify(h),_=`${this.apiUrl}/feedback`;return await this.caller.call(async()=>{let y=await this._fetch(_,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:b});return await ie(y,"create feedback",!0),y}),h}async updateFeedback(t,{score:r,value:n,correction:i,comment:s}){let o={};r!=null&&(o.score=LO(r)),n!=null&&(o.value=n),i!=null&&(o.correction=i),s!=null&&(o.comment=s),ve(t);let a=JSON.stringify(o);await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/feedback/${t}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await ie(c,"update feedback",!0),c})}async readFeedback(t){ve(t);let r=`/feedback/${t}`;return await this._get(r)}async deleteFeedback(t){ve(t);let r=`/feedback/${t}`;await this.caller.call(async()=>{let n=await this._fetch(this.apiUrl+r,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ie(n,`delete ${r}`,!0),n})}async*listFeedback({runIds:t,feedbackKeys:r,feedbackSourceTypes:n}={}){let i=new URLSearchParams;if(t)for(let s of t)ve(s),i.append("run",s);if(r)for(let s of r)i.append("key",s);if(n)for(let s of n)i.append("source",s);for await(let s of this._getPaginated("/feedback",i))yield*s}async createPresignedFeedbackToken(t,r,{expiration:n,feedbackConfig:i}={}){let s={run_id:t,feedback_key:r,feedback_config:i};n?typeof n=="string"?s.expires_at=n:(n?.hours||n?.minutes||n?.days)&&(s.expires_in=n):s.expires_in={hours:3};let o=JSON.stringify(s);return await(await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/feedback/tokens`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await ie(c,"create presigned feedback token"),c})).json()}async createComparativeExperiment({name:t,experimentIds:r,referenceDatasetId:n,createdAt:i,description:s,metadata:o,id:a}){if(r.length===0)throw new Error("At least one experiment is required");if(n||(n=(await this.readProject({projectId:r[0]})).reference_dataset_id),!n==null)throw new Error("A reference dataset is required");let c={id:a,name:t,experiment_ids:r,reference_dataset_id:n,description:s,created_at:(i??new Date)?.toISOString(),extra:{}};o&&(c.extra.metadata=o);let u=JSON.stringify(c);return(await this.caller.call(async()=>{let p=await this._fetch(`${this.apiUrl}/datasets/comparative`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await ie(p,"create comparative experiment"),p})).json()}async*listPresignedFeedbackTokens(t){ve(t);let r=new URLSearchParams({run_id:t});for await(let n of this._getPaginated("/feedback/tokens",r))yield*n}_selectEvalResults(t){let r;return"results"in t?r=t.results:Array.isArray(t)?r=t:r=[t],r}async _logEvaluationFeedback(t,r,n){let i=this._selectEvalResults(t),s=[];for(let o of i){let a=n||{};o.evaluatorInfo&&(a={...o.evaluatorInfo,...a});let c=null;o.targetRunId?c=o.targetRunId:r&&(c=r.id),s.push(await this.createFeedback(c,o.key,{score:o.score,value:o.value,comment:o.comment,correction:o.correction,sourceInfo:a,sourceRunId:o.sourceRunId,feedbackConfig:o.feedbackConfig,feedbackSourceType:"model"}))}return[i,s]}async logEvaluationFeedback(t,r,n){let[i]=await this._logEvaluationFeedback(t,r,n);return i}async*listAnnotationQueues(t={}){let{queueIds:r,name:n,nameContains:i,limit:s}=t,o=new URLSearchParams;r&&r.forEach((c,u)=>{ve(c,`queueIds[${u}]`),o.append("ids",c)}),n&&o.append("name",n),i&&o.append("name_contains",i),o.append("limit",(s!==void 0?Math.min(s,100):100).toString());let a=0;for await(let c of this._getPaginated("/annotation-queues",o))if(yield*c,a++,s!==void 0&&a>=s)break}async createAnnotationQueue(t){let{name:r,description:n,queueId:i,rubricInstructions:s}=t,o={name:r,description:n,id:i||Ar(),rubric_instructions:s},a=JSON.stringify(Object.fromEntries(Object.entries(o).filter(([u,l])=>l!==void 0)));return(await this.caller.call(async()=>{let u=await this._fetch(`${this.apiUrl}/annotation-queues`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await ie(u,"create annotation queue"),u})).json()}async readAnnotationQueue(t){return(await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/annotation-queues/${ve(t,"queueId")}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ie(n,"read annotation queue"),n})).json()}async updateAnnotationQueue(t,r){let{name:n,description:i,rubricInstructions:s}=r,o=JSON.stringify({name:n,description:i,rubric_instructions:s});await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}/annotation-queues/${ve(t,"queueId")}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await ie(a,"update annotation queue",!0),a})}async deleteAnnotationQueue(t){await this.caller.call(async()=>{let r=await this._fetch(`${this.apiUrl}/annotation-queues/${ve(t,"queueId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ie(r,"delete annotation queue",!0),r})}async addRunsToAnnotationQueue(t,r){let n=JSON.stringify(r.map((i,s)=>ve(i,`runIds[${s}]`).toString()));await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}/annotation-queues/${ve(t,"queueId")}/runs`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await ie(i,"add runs to annotation queue",!0),i})}async getRunFromAnnotationQueue(t,r){let n=`/annotation-queues/${ve(t,"queueId")}/run`;return(await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}${n}/${r}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ie(s,"get run from annotation queue"),s})).json()}async deleteRunFromAnnotationQueue(t,r){await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/annotation-queues/${ve(t,"queueId")}/runs/${ve(r,"queueRunId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ie(n,"delete run from annotation queue",!0),n})}async getSizeFromAnnotationQueue(t){return(await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/annotation-queues/${ve(t,"queueId")}/size`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ie(n,"get size from annotation queue"),n})).json()}async _currentTenantIsOwner(t){let r=await this._getSettings();return t=="-"||r.tenant_handle===t}async _ownerConflictError(t,r){let n=await this._getSettings();return new Error(`Cannot ${t} for another tenant.
|
|
34
|
+
|
|
35
|
+
Current tenant: ${n.tenant_handle}
|
|
36
|
+
|
|
37
|
+
Requested tenant: ${r}`)}async _getLatestCommitHash(t){let n=await(await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}/commits/${t}/?limit=1&offset=0`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ie(i,"get latest commit hash"),i})).json();if(n.commits.length!==0)return n.commits[0].commit_hash}async _likeOrUnlikePrompt(t,r){let[n,i,s]=Vi(t),o=JSON.stringify({like:r});return(await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/likes/${n}/${i}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await ie(c,`${r?"like":"unlike"} prompt`),c})).json()}async _getPromptUrl(t){let[r,n,i]=Vi(t);if(await this._currentTenantIsOwner(r)){let s=await this._getSettings();return i!=="latest"?`${this.getHostUrl()}/prompts/${n}/${i.substring(0,8)}?organizationId=${s.id}`:`${this.getHostUrl()}/prompts/${n}?organizationId=${s.id}`}else return i!=="latest"?`${this.getHostUrl()}/hub/${r}/${n}/${i.substring(0,8)}`:`${this.getHostUrl()}/hub/${r}/${n}`}async promptExists(t){return!!await this.getPrompt(t)}async likePrompt(t){return this._likeOrUnlikePrompt(t,!0)}async unlikePrompt(t){return this._likeOrUnlikePrompt(t,!1)}async*listCommits(t){for await(let r of this._getPaginated(`/commits/${t}/`,new URLSearchParams,n=>n.commits))yield*r}async*listPrompts(t){let r=new URLSearchParams;r.append("sort_field",t?.sortField??"updated_at"),r.append("sort_direction","desc"),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);for await(let n of this._getPaginated("/repos",r,i=>i.repos))yield*n}async getPrompt(t){let[r,n,i]=Vi(t),o=await(await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}/repos/${r}/${n}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return a?.status===404?null:(await ie(a,"get prompt"),a)}))?.json();return o?.repo?o.repo:null}async createPrompt(t,r){let n=await this._getSettings();if(r?.isPublic&&!n.tenant_handle)throw new Error(`Cannot create a public prompt without first
|
|
38
|
+
|
|
39
|
+
creating a LangChain Hub handle.
|
|
40
|
+
You can add a handle by creating a public prompt at:
|
|
41
|
+
|
|
42
|
+
https://smith.langchain.com/prompts`);let[i,s,o]=Vi(t);if(!await this._currentTenantIsOwner(i))throw await this._ownerConflictError("create a prompt",i);let a={repo_handle:s,...r?.description&&{description:r.description},...r?.readme&&{readme:r.readme},...r?.tags&&{tags:r.tags},is_public:!!r?.isPublic},c=JSON.stringify(a),u=await this.caller.call(async()=>{let p=await this._fetch(`${this.apiUrl}/repos/`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await ie(p,"create prompt"),p}),{repo:l}=await u.json();return l}async createCommit(t,r,n){if(!await this.promptExists(t))throw new Error("Prompt does not exist, you must create it first.");let[i,s,o]=Vi(t),a=n?.parentCommitHash==="latest"||!n?.parentCommitHash?await this._getLatestCommitHash(`${i}/${s}`):n?.parentCommitHash,c={manifest:JSON.parse(JSON.stringify(r)),parent_commit:a},u=JSON.stringify(c),p=await(await this.caller.call(async()=>{let f=await this._fetch(`${this.apiUrl}/commits/${i}/${s}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await ie(f,"create commit"),f})).json();return this._getPromptUrl(`${i}/${s}${p.commit_hash?`:${p.commit_hash}`:""}`)}async updateExamplesMultipart(t,r=[]){return this._updateExamplesMultipart(t,r)}async _updateExamplesMultipart(t,r=[]){if(!await this._getDatasetExamplesMultiPartSupport())throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");let n=new FormData;for(let o of r){let a=o.id,c={...o.metadata&&{metadata:o.metadata},...o.split&&{split:o.split}},u=Or(c,`Serializing body for example with id: ${a}`),l=new Blob([u],{type:"application/json"});if(n.append(a,l),o.inputs){let p=Or(o.inputs,`Serializing inputs for example with id: ${a}`),f=new Blob([p],{type:"application/json"});n.append(`${a}.inputs`,f)}if(o.outputs){let p=Or(o.outputs,`Serializing outputs whle updating example with id: ${a}`),f=new Blob([p],{type:"application/json"});n.append(`${a}.outputs`,f)}if(o.attachments)for(let[p,f]of Object.entries(o.attachments)){let d,m;Array.isArray(f)?[d,m]=f:(d=f.mimeType,m=f.data);let h=new Blob([m],{type:`${d}; length=${m.byteLength}`});n.append(`${a}.attachment.${p}`,h)}if(o.attachments_operations){let p=Or(o.attachments_operations,`Serializing attachments while updating example with id: ${a}`),f=new Blob([p],{type:"application/json"});n.append(`${a}.attachments_operations`,f)}}let i=t??r[0]?.dataset_id;return(await this.caller.call(async()=>{let o=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${i}/examples`)}`,{method:"PATCH",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await ie(o,"update examples"),o})).json()}async uploadExamplesMultipart(t,r=[]){return this._uploadExamplesMultipart(t,r)}async _uploadExamplesMultipart(t,r=[]){if(!await this._getDatasetExamplesMultiPartSupport())throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");let n=new FormData;for(let s of r){let o=(s.id??Ar()).toString(),a={created_at:s.created_at,...s.metadata&&{metadata:s.metadata},...s.split&&{split:s.split},...s.source_run_id&&{source_run_id:s.source_run_id},...s.use_source_run_io&&{use_source_run_io:s.use_source_run_io},...s.use_source_run_attachments&&{use_source_run_attachments:s.use_source_run_attachments}},c=Or(a,`Serializing body for uploaded example with id: ${o}`),u=new Blob([c],{type:"application/json"});if(n.append(o,u),s.inputs){let l=Or(s.inputs,`Serializing inputs for uploaded example with id: ${o}`),p=new Blob([l],{type:"application/json"});n.append(`${o}.inputs`,p)}if(s.outputs){let l=Or(s.outputs,`Serializing outputs for uploaded example with id: ${o}`),p=new Blob([l],{type:"application/json"});n.append(`${o}.outputs`,p)}if(s.attachments)for(let[l,p]of Object.entries(s.attachments)){let f,d;Array.isArray(p)?[f,d]=p:(f=p.mimeType,d=p.data);let m=new Blob([d],{type:`${f}; length=${d.byteLength}`});n.append(`${o}.attachment.${l}`,m)}}return(await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${t}/examples`)}`,{method:"POST",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await ie(s,"upload examples"),s})).json()}async updatePrompt(t,r){if(!await this.promptExists(t))throw new Error("Prompt does not exist, you must create it first.");let[n,i]=Vi(t);if(!await this._currentTenantIsOwner(n))throw await this._ownerConflictError("update a prompt",n);let s={};if(r?.description!==void 0&&(s.description=r.description),r?.readme!==void 0&&(s.readme=r.readme),r?.tags!==void 0&&(s.tags=r.tags),r?.isPublic!==void 0&&(s.is_public=r.isPublic),r?.isArchived!==void 0&&(s.is_archived=r.isArchived),Object.keys(s).length===0)throw new Error("No valid update options provided");let o=JSON.stringify(s);return(await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/repos/${n}/${i}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await ie(c,"update prompt"),c})).json()}async deletePrompt(t){if(!await this.promptExists(t))throw new Error("Prompt does not exist, you must create it first.");let[r,n,i]=Vi(t);if(!await this._currentTenantIsOwner(r))throw await this._ownerConflictError("delete a prompt",r);return(await this.caller.call(async()=>{let o=await this._fetch(`${this.apiUrl}/repos/${r}/${n}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ie(o,"delete prompt"),o})).json()}_getPromptCacheKey(t,r){return`${t}${r?":with_model":""}`}async _fetchPromptFromApi(t,r){let[n,i,s]=Vi(t),a=await(await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/commits/${n}/${i}/${s}${r?.includeModel?"?include_model=true":""}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await ie(c,"pull prompt commit"),c})).json();return{owner:n,repo:i,commit_hash:a.commit_hash,manifest:a.manifest,examples:a.examples}}async pullPromptCommit(t,r){if(!r?.skipCache&&this._cache){let n=this._getPromptCacheKey(t,r?.includeModel),i=this._cache.get(n);if(i)return i;let s=await this._fetchPromptFromApi(t,r);return this._cache.set(n,s),s}return this._fetchPromptFromApi(t,r)}async _pullPrompt(t,r){let n=await this.pullPromptCommit(t,{includeModel:r?.includeModel,skipCache:r?.skipCache});return JSON.stringify(n.manifest)}async pushPrompt(t,r){return await this.promptExists(t)?r&&Object.keys(r).some(i=>i!=="object")&&await this.updatePrompt(t,{description:r?.description,readme:r?.readme,tags:r?.tags,isPublic:r?.isPublic}):await this.createPrompt(t,{description:r?.description,readme:r?.readme,tags:r?.tags,isPublic:r?.isPublic}),r?.object?await this.createCommit(t,r?.object,{parentCommitHash:r?.parentCommitHash}):await this._getPromptUrl(t)}async clonePublicDataset(t,r={}){let{sourceApiUrl:n=this.apiUrl,datasetName:i}=r,[s,o]=this.parseTokenOrUrl(t,n),a=new e({apiUrl:s,apiKey:"placeholder"}),c=await a.readSharedDataset(o),u=i||c.name;try{if(await this.hasDataset({datasetId:u})){console.log(`Dataset ${u} already exists in your tenant. Skipping.`);return}}catch{}let l=await a.listSharedExamples(o),p=await this.createDataset(u,{description:c.description,dataType:c.data_type||"kv",inputsSchema:c.inputs_schema_definition??void 0,outputsSchema:c.outputs_schema_definition??void 0});try{await this.createExamples({inputs:l.map(f=>f.inputs),outputs:l.flatMap(f=>f.outputs?[f.outputs]:[]),datasetId:p.id})}catch(f){throw console.error(`An error occurred while creating dataset ${u}. You should delete it manually.`),f}}parseTokenOrUrl(t,r,n=2,i="dataset"){try{return ve(t),[r,t]}catch{}try{let o=new URL(t).pathname.split("/").filter(a=>a!=="");if(o.length>=n){let a=o[o.length-n];return[r,a]}else throw new Error(`Invalid public ${i} URL: ${t}`)}catch{throw new Error(`Invalid public ${i} URL or token: ${t}`)}}get cache(){return this._cache}cleanup(){this._cache&&this._cache.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();await new Promise(t=>setTimeout(t,1)),await Promise.all([...this.autoBatchQueue.items.map(({itemPromise:t})=>t),this.batchIngestCaller.queue.onIdle()]),this.langSmithToOTELTranslator!==void 0&&await RA()?.DEFAULT_LANGSMITH_SPAN_PROCESSOR?.forceFlush()}};function FO(e){return"dataset_id"in e||"dataset_name"in e}var VO=e=>e!==void 0?e:!!["TRACING_V2","TRACING"].find(r=>wt(r)==="true");var oi=Symbol.for("lc:context_variables"),jJ=Symbol.for("lc:child_run_end_promises"),Wf=Symbol.for("langsmith:replica_trace_roots");function iv(e,t){if(oi in e)return e[oi][t]}function ZO(e,t,r){let n=oi in e?e[oi]:{};n[t]=r,e[oi]=n}var Pl=36,Nl="6ba7b810-9dad-11d1-80b4-00c04fd430c8";function GO(e){let r=Object.keys(e).sort().map(n=>`${n}:${e[n]??""}`).join("|");return nn(r,Nl)}function nF(e){return e.replace(/[-:.]/g,"")}function qO(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 sv(e,t,r=1){let n=qO(e,r);return{dottedOrder:nF(n)+t,microsecondPrecisionDatestring:n}}var iF=new Set(["projectName","updates","reroot"]);function sF(e){let t={};for(let r of Object.keys(e))iF.has(r)&&(t[r]=e[r]);return t}var Jf=class e{constructor(t,r,n,i){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=t,this.tags=r,this.project_name=n,this.replicas=i}static fromHeader(t){let r=t.split(","),n={},i=[],s,o;for(let a of r){let[c,u]=a.split("="),l=decodeURIComponent(u);c==="langsmith-metadata"?n=JSON.parse(l):c==="langsmith-tags"?i=l.split(","):c==="langsmith-project"?s=l:c==="langsmith-replicas"&&(o=JSON.parse(l).map(f=>Array.isArray(f)?f:sF(f)))}return new e(n,i,s,o)}toHeader(){let t=[];return this.metadata&&Object.keys(this.metadata).length>0&&t.push(`langsmith-metadata=${encodeURIComponent(JSON.stringify(this.metadata))}`),this.tags&&this.tags.length>0&&t.push(`langsmith-tags=${encodeURIComponent(this.tags.join(","))}`),this.project_name&&t.push(`langsmith-project=${encodeURIComponent(this.project_name)}`),t.join(",")}},Tn=class e{constructor(t){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}),HO(t)){Object.assign(this,{...t});return}let r=e.getDefaultConfig(),{metadata:n,...i}=t,s=i.client??e.getSharedClient(),o={...n,...i?.extra?.metadata};if(i.extra={...i.extra,metadata:o},"id"in i&&i.id==null&&delete i.id,Object.assign(this,{...r,...i,client:s}),this.execution_order??=1,this.child_execution_order??=1,this.dotted_order||(this._serialized_start_time=qO(this.start_time,this.execution_order)),this.id||(this.id=bf(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=uF(this.replicas),!this.dotted_order){let{dottedOrder:a}=sv(this.start_time,this.id,this.execution_order);this.parent_run?this.dotted_order=this.parent_run.dotted_order+"."+a:this.dotted_order=a}}set metadata(t){this.extra={...this.extra,metadata:{...this.extra?.metadata,...t}}}get metadata(){return this.extra?.metadata}static getDefaultConfig(){let t=Date.now();return{run_type:"chain",project_name:bl(),child_runs:[],api_url:Fr("LANGCHAIN_ENDPOINT")??"http://localhost:1984",api_key:Fr("LANGCHAIN_API_KEY"),caller_options:{},start_time:t,serialized:{},inputs:{},extra:{}}}static getSharedClient(){return e.sharedClient||(e.sharedClient=new Bi),e.sharedClient}createChild(t){let r=this.child_execution_order+1,n=this.replicas?.map(l=>{let{reroot:p,...f}=l;return f}),i=t.replicas??n,s=new e({...t,parent_run:this,project_name:this.project_name,replicas:i,client:this.client,tracingEnabled:this.tracingEnabled,execution_order:r,child_execution_order:r});oi in this&&(s[oi]=this[oi]);let o=Symbol.for("lc:child_config"),a=t.extra?.[o]??this.extra[o];if(aF(a)){let l={...a},p=oF(l.callbacks)?l.callbacks.copy?.():void 0;p&&(Object.assign(p,{_parentRunId:s.id}),p.handlers?.find(WO)?.updateFromRunTree?.(s),l.callbacks=p),s.extra[o]=l}let c=new Set,u=this;for(;u!=null&&!c.has(u.id);)c.add(u.id),u.child_execution_order=Math.max(u.child_execution_order,r),u=u.parent_run;return this.child_runs.push(s),s}async end(t,r,n=Date.now(),i){this.outputs=this.outputs??t,this.error=this.error??r,this.end_time=this.end_time??n,i&&Object.keys(i).length>0&&(this.extra=this.extra?{...this.extra,metadata:{...this.extra.metadata,...i}}:{metadata:i})}_convertToCreate(t,r,n=!0){let i=t.extra??{};if(i?.runtime?.library===void 0&&(i.runtime||(i.runtime={}),r))for(let[a,c]of Object.entries(r))i.runtime[a]||(i.runtime[a]=c);let s,o;return n?(o=t.parent_run?.id??t.parent_run_id,s=[]):(s=t.child_runs.map(a=>this._convertToCreate(a,r,n)),o=void 0),{id:t.id,name:t.name,start_time:t._serialized_start_time??t.start_time,end_time:t.end_time,run_type:t.run_type,reference_example_id:t.reference_example_id,extra:i,serialized:t.serialized,error:t.error,inputs:t.inputs,outputs:t.outputs,session_name:t.project_name,child_runs:s,parent_run_id:o,trace_id:t.trace_id,dotted_order:t.dotted_order,tags:t.tags,attachments:t.attachments,events:t.events}}_sliceParentId(t,r){if(r.dotted_order){let n=r.dotted_order.split("."),i=null;for(let s=0;s<n.length;s++)if(n[s].slice(-Pl)===t){i=s;break}if(i!==null){let s=n.slice(i+1);r.dotted_order=s.join("."),s.length>0?r.trace_id=s[0].slice(-Pl):r.trace_id=r.id}}r.parent_run_id===t&&(r.parent_run_id=void 0)}_setReplicaTraceRoot(t,r){let n=iv(this,Wf)??{};n[t]=r,ZO(this,Wf,n);for(let i of this.child_runs)i._setReplicaTraceRoot(t,r)}_remapForProject(t){let{projectName:r,runtimeEnv:n,excludeChildRuns:i=!0,reroot:s=!1,distributedParentId:o,apiUrl:a,apiKey:c,workspaceId:u}=t,l=this._convertToCreate(this,n,i);if(r===this.project_name)return{...l,session_name:r};if(s){if(o)this._sliceParentId(o,l);else if(l.parent_run_id=void 0,l.dotted_order){let y=l.dotted_order.split(".");y.length>0&&(l.dotted_order=y[y.length-1],l.trace_id=l.id)}let _=GO({projectName:r,apiUrl:a,apiKey:c,workspaceId:u});this._setReplicaTraceRoot(_,l.id)}let p;if(!s){let _=iv(this,Wf)??{},y=GO({projectName:r,apiUrl:a,apiKey:c,workspaceId:u});if(p=_[y],p&&(l.trace_id=p,l.dotted_order)){let x=l.dotted_order.split("."),I=null;for(let A=0;A<x.length;A++)if(x[A].slice(-Pl)===p){I=A;break}if(I!==null){let A=x.slice(I);l.dotted_order=A.join(".")}}}let f=l.id,d=nn(`${f}:${r}`,Nl),m;l.trace_id?m=nn(`${l.trace_id}:${r}`,Nl):m=d;let h;l.parent_run_id&&(h=nn(`${l.parent_run_id}:${r}`,Nl));let b;return l.dotted_order&&(b=l.dotted_order.split(".").map(x=>{let I=x.slice(-Pl),A=nn(`${I}:${r}`,Nl);return x.slice(0,-Pl)+A}).join(".")),{...l,id:d,trace_id:m,parent_run_id:h,dotted_order:b,session_name:r}}async postRun(t=!0){this._awaitInputsOnPost&&(this.inputs=await this.inputs);try{let r=xf();if(this.replicas&&this.replicas.length>0)for(let{projectName:n,apiKey:i,apiUrl:s,workspaceId:o,reroot:a}of this.replicas){let c=this._remapForProject({projectName:n??this.project_name,runtimeEnv:r,excludeChildRuns:!0,reroot:a,distributedParentId:this.distributedParentId,apiUrl:s,apiKey:i,workspaceId:o});await this.client.createRun(c,{apiKey:i,apiUrl:s,workspaceId:o})}else{let n=this._convertToCreate(this,r,t);await this.client.createRun(n)}if(!t){wl("Posting with excludeChildRuns=false is deprecated and will be removed in a future version.");for(let n of this.child_runs)await n.postRun(!1)}this.child_runs=[]}catch(r){console.error(`Error in postRun for run ${this.id}:`,r)}}async patchRun(t){if(this.replicas&&this.replicas.length>0)for(let{projectName:r,apiKey:n,apiUrl:i,workspaceId:s,updates:o,reroot:a}of this.replicas){let c=this._remapForProject({projectName:r??this.project_name,runtimeEnv:void 0,excludeChildRuns:!0,reroot:a,distributedParentId:this.distributedParentId,apiUrl:i,apiKey:n,workspaceId:s}),u={id:c.id,name:c.name,run_type:c.run_type,start_time:c.start_time,outputs:c.outputs,error:c.error,parent_run_id:c.parent_run_id,session_name:c.session_name,reference_example_id:c.reference_example_id,end_time:c.end_time,dotted_order:c.dotted_order,trace_id:c.trace_id,events:c.events,tags:c.tags,extra:c.extra,attachments:this.attachments,...o};t?.excludeInputs||(u.inputs=c.inputs),await this.client.updateRun(c.id,u,{apiKey:n,apiUrl:i,workspaceId:s})}else try{let r={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};t?.excludeInputs||(r.inputs=this.inputs),await this.client.updateRun(this.id,r)}catch(r){console.error(`Error in patchRun for run ${this.id}`,r)}this.child_runs=[]}toJSON(){return this._convertToCreate(this,void 0,!1)}addEvent(t){this.events||(this.events=[]),typeof t=="string"?this.events.push({name:"event",time:new Date().toISOString(),message:t}):this.events.push({...t,time:t.time??new Date().toISOString()})}static fromRunnableConfig(t,r){let n=t?.callbacks,i,s,o,a=VO();if(n){let u=n?.getParentRunId?.()??"",l=n?.handlers?.find(p=>p?.name=="langchain_tracer");i=l?.getRun?.(u),s=l?.projectName,o=l?.client,a=a||!!l}return i?new e({name:i.name,id:i.id,trace_id:i.trace_id,dotted_order:i.dotted_order,client:o,tracingEnabled:a,project_name:s,tags:[...new Set((i?.tags??[]).concat(t?.tags??[]))],extra:{metadata:{...i?.extra?.metadata,...t?.metadata}}}).createChild(r):new e({...r,client:o,tracingEnabled:a,project_name:s})}static fromDottedOrder(t){return this.fromHeaders({"langsmith-trace":t})}static fromHeaders(t,r){let n="get"in t&&typeof t.get=="function"?{"langsmith-trace":t.get("langsmith-trace"),baggage:t.get("baggage")}:t,i=n["langsmith-trace"];if(!i||typeof i!="string")return;let s=i.trim(),o=s.split(".").map(l=>{let[p,f]=l.split("Z");return{strTime:p,time:Date.parse(p+"Z"),uuid:f}}),a=o[0].uuid,c={...r,name:r?.name??"parent",run_type:r?.run_type??"chain",start_time:r?.start_time??Date.now(),id:o.at(-1)?.uuid,trace_id:a,dotted_order:s};if(n.baggage&&typeof n.baggage=="string"){let l=Jf.fromHeader(n.baggage);c.metadata=l.metadata,c.tags=l.tags,c.project_name=l.project_name,c.replicas=l.replicas}let u=new e(c);return u.distributedParentId=u.id,u}toHeaders(t){let r={"langsmith-trace":this.dotted_order,baggage:new Jf(this.extra?.metadata,this.tags,this.project_name,this.replicas).toHeader()};if(t)for(let[n,i]of Object.entries(r))t.set(n,i);return r}};Object.defineProperty(Tn,"sharedClient",{enumerable:!0,configurable:!0,writable:!0,value:null});function HO(e){return e!=null&&typeof e.createChild=="function"&&typeof e.postRun=="function"}function WO(e){return typeof e=="object"&&e!=null&&typeof e.name=="string"&&e.name==="langchain_tracer"}function KO(e){return Array.isArray(e)&&e.some(t=>WO(t))}function oF(e){return typeof e=="object"&&e!=null&&Array.isArray(e.handlers)}function aF(e){let t=e?.callbacks;return e!=null&&typeof t=="object"&&(KO(t?.handlers)||KO(t))}function cF(){let e=Fr("LANGSMITH_RUNS_ENDPOINTS");if(!e)return[];try{let t=JSON.parse(e);if(Array.isArray(t)){let r=[];for(let n of t){if(typeof n!="object"||n===null){console.warn(`Invalid item type in LANGSMITH_RUNS_ENDPOINTS: expected object, got ${typeof n}`);continue}if(typeof n.api_url!="string"){console.warn(`Invalid api_url type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof n.api_url}`);continue}if(typeof n.api_key!="string"){console.warn(`Invalid api_key type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof n.api_key}`);continue}r.push({apiUrl:n.api_url.replace(/\/$/,""),apiKey:n.api_key})}return r}else if(typeof t=="object"&&t!==null){lF(t);let r=[];for(let[n,i]of Object.entries(t)){let s=n.replace(/\/$/,"");if(typeof i=="string")r.push({apiUrl:s,apiKey:i});else{console.warn(`Invalid value type in LANGSMITH_RUNS_ENDPOINTS for URL ${n}: expected string, got ${typeof i}`);continue}}return r}else return console.warn(`Invalid LANGSMITH_RUNS_ENDPOINTS \u2013 must be valid JSON array of objects with api_url and api_key properties, or object mapping url->apiKey, got ${typeof t}`),[]}catch(t){if(MO(t))throw t;return console.warn("Invalid LANGSMITH_RUNS_ENDPOINTS \u2013 must be valid JSON array of objects with api_url and api_key properties, or object mapping url->apiKey"),[]}}function uF(e){return e?e.map(t=>Array.isArray(t)?{projectName:t[0],updates:t[1]}:t):cF()}function lF(e){if(Object.keys(e).length>0&&wt("ENDPOINT"))throw new Gf}var cv={};M(cv,{BaseTracer:()=>Zt,isBaseTracer:()=>zo});var pF=e=>{if(e)return e.events=e.events??[],e.child_runs=e.child_runs??[],e};function av(e,t){if(e)return new Tn({...e,start_time:e._serialized_start_time??e.start_time,parent_run:av(t),child_runs:e.child_runs.map(r=>av(r)).filter(r=>r!==void 0),extra:{...e.extra,runtime:Y_()},tracingEnabled:!1})}function ov(e,t){return e&&!Array.isArray(e)&&typeof e=="object"?e:{[t]:e}}function zo(e){return typeof e._addRunToRunMap=="function"}var Zt=class extends Fi{runMap=new Map;runTreeMap=new Map;usesRunTreeMap=!1;constructor(e){super(...arguments)}copy(){return this}getRunById(e){if(e!==void 0)return this.usesRunTreeMap?pF(this.runTreeMap.get(e)):this.runMap.get(e)}stringifyError(e){return e instanceof Error?e.message+(e?.stack?`
|
|
43
|
+
|
|
44
|
+
${e.stack}`:""):typeof e=="string"?e:`${e}`}_addChildRun(e,t){e.child_runs.push(t)}_addRunToRunMap(e){let{dottedOrder:t,microsecondPrecisionDatestring:r}=sv(new Date(e.start_time).getTime(),e.id,e.execution_order),n={...e},i=this.getRunById(n.parent_run_id);if(n.parent_run_id!==void 0?i?(this._addChildRun(i,n),i.child_execution_order=Math.max(i.child_execution_order,n.child_execution_order),n.trace_id=i.trace_id,i.dotted_order!==void 0&&(n.dotted_order=[i.dotted_order,t].join("."),n._serialized_start_time=r)):n.parent_run_id=void 0:(n.trace_id=n.id,n.dotted_order=t,n._serialized_start_time=r),this.usesRunTreeMap){let s=av(n,i);s!==void 0&&this.runTreeMap.set(n.id,s)}else this.runMap.set(n.id,n);return n}async _endTrace(e){let t=e.parent_run_id!==void 0&&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=e!==void 0&&this.getRunById(e);return t?t.child_execution_order+1:1}_createRunForLLMStart(e,t,r,n,i,s,o,a){let c=this._getExecutionOrder(n),u=Date.now(),l=o?{...i,metadata:o}:i,p={id:r,name:a??e.id[e.id.length-1],parent_run_id:n,start_time:u,serialized:e,events:[{name:"start",time:new Date(u).toISOString()}],inputs:{prompts:t},execution_order:c,child_runs:[],child_execution_order:c,run_type:"llm",extra:l??{},tags:s||[]};return this._addRunToRunMap(p)}async handleLLMStart(e,t,r,n,i,s,o,a){let c=this.getRunById(r)??this._createRunForLLMStart(e,t,r,n,i,s,o,a);return await this.onRunCreate?.(c),await this.onLLMStart?.(c),c}_createRunForChatModelStart(e,t,r,n,i,s,o,a){let c=this._getExecutionOrder(n),u=Date.now(),l=o?{...i,metadata:o}:i,p={id:r,name:a??e.id[e.id.length-1],parent_run_id:n,start_time:u,serialized:e,events:[{name:"start",time:new Date(u).toISOString()}],inputs:{messages:t},execution_order:c,child_runs:[],child_execution_order:c,run_type:"llm",extra:l??{},tags:s||[]};return this._addRunToRunMap(p)}async handleChatModelStart(e,t,r,n,i,s,o,a){let c=this.getRunById(r)??this._createRunForChatModelStart(e,t,r,n,i,s,o,a);return await this.onRunCreate?.(c),await this.onLLMStart?.(c),c}async handleLLMEnd(e,t,r,n,i){let s=this.getRunById(t);if(!s||s?.run_type!=="llm")throw new Error("No LLM run to end.");return s.end_time=Date.now(),s.outputs=e,s.events.push({name:"end",time:new Date(s.end_time).toISOString()}),s.extra={...s.extra,...i},await this.onLLMEnd?.(s),await this._endTrace(s),s}async handleLLMError(e,t,r,n,i){let s=this.getRunById(t);if(!s||s?.run_type!=="llm")throw new Error("No LLM run to end.");return s.end_time=Date.now(),s.error=this.stringifyError(e),s.events.push({name:"error",time:new Date(s.end_time).toISOString()}),s.extra={...s.extra,...i},await this.onLLMError?.(s),await this._endTrace(s),s}_createRunForChainStart(e,t,r,n,i,s,o,a,c){let u=this._getExecutionOrder(n),l=Date.now(),p={id:r,name:a??e.id[e.id.length-1],parent_run_id:n,start_time:l,serialized:e,events:[{name:"start",time:new Date(l).toISOString()}],inputs:t,execution_order:u,child_execution_order:u,run_type:o??"chain",child_runs:[],extra:s?{...c,metadata:s}:{...c},tags:i||[]};return this._addRunToRunMap(p)}async handleChainStart(e,t,r,n,i,s,o,a){let c=this.getRunById(r)??this._createRunForChainStart(e,t,r,n,i,s,o,a);return await this.onRunCreate?.(c),await this.onChainStart?.(c),c}async handleChainEnd(e,t,r,n,i){let s=this.getRunById(t);if(!s)throw new Error("No chain run to end.");return s.end_time=Date.now(),s.outputs=ov(e,"output"),s.events.push({name:"end",time:new Date(s.end_time).toISOString()}),i?.inputs!==void 0&&(s.inputs=ov(i.inputs,"input")),await this.onChainEnd?.(s),await this._endTrace(s),s}async handleChainError(e,t,r,n,i){let s=this.getRunById(t);if(!s)throw new Error("No chain run to end.");return s.end_time=Date.now(),s.error=this.stringifyError(e),s.events.push({name:"error",time:new Date(s.end_time).toISOString()}),i?.inputs!==void 0&&(s.inputs=ov(i.inputs,"input")),await this.onChainError?.(s),await this._endTrace(s),s}_createRunForToolStart(e,t,r,n,i,s,o){let a=this._getExecutionOrder(n),c=Date.now(),u={id:r,name:o??e.id[e.id.length-1],parent_run_id:n,start_time:c,serialized:e,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{input:t},execution_order:a,child_execution_order:a,run_type:"tool",child_runs:[],extra:s?{metadata:s}:{},tags:i||[]};return this._addRunToRunMap(u)}async handleToolStart(e,t,r,n,i,s,o){let a=this.getRunById(r)??this._createRunForToolStart(e,t,r,n,i,s,o);return await this.onRunCreate?.(a),await this.onToolStart?.(a),a}async handleToolEnd(e,t){let r=this.getRunById(t);if(!r||r?.run_type!=="tool")throw new 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 new 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);if(!r||r?.run_type!=="chain")return;let n=r;n.actions=n.actions||[],n.actions.push(e),n.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,n,i,s,o){let a=this._getExecutionOrder(n),c=Date.now(),u={id:r,name:o??e.id[e.id.length-1],parent_run_id:n,start_time:c,serialized:e,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{query:t},execution_order:a,child_execution_order:a,run_type:"retriever",child_runs:[],extra:s?{metadata:s}:{},tags:i||[]};return this._addRunToRunMap(u)}async handleRetrieverStart(e,t,r,n,i,s,o){let a=this.getRunById(r)??this._createRunForRetrieverStart(e,t,r,n,i,s,o);return await this.onRunCreate?.(a),await this.onRetrieverStart?.(a),a}async handleRetrieverEnd(e,t){let r=this.getRunById(t);if(!r||r?.run_type!=="retriever")throw new 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 new 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,n,i,s){let o=this.getRunById(r);if(!o||o?.run_type!=="llm")throw new Error('Invalid "runId" provided to "handleLLMNewToken" callback.');return o.events.push({name:"new_token",time:new Date().toISOString(),kwargs:{token:e,idx:t,chunk:s?.chunk}}),await this.onLLMNewToken?.(o,e,{chunk:s?.chunk}),o}};var uv=Ps(QO(),1),lv={};M(lv,{ConsoleCallbackHandler:()=>Xf});function fr(e,t){return`${e.open}${t}${e.close}`}function cn(e,t){try{return JSON.stringify(e,null,2)}catch{return t}}function e$(e){return typeof e=="string"?e.trim():e==null?e:cn(e,e.toString())}function Ms(e){if(!e.end_time)return"";let t=e.end_time-e.start_time;return t<1e3?`${t}ms`:`${(t/1e3).toFixed(2)}s`}var{color:$r}=uv.default,Xf=class extends Zt{name="console_callback_handler";persistRun(e){return Promise.resolve()}getParents(e){let t=[],r=e;for(;r.parent_run_id;){let n=this.runMap.get(r.parent_run_id);if(n)t.push(n),r=n;else break}return t}getBreadcrumbs(e){let r=[...this.getParents(e).reverse(),e].map((n,i,s)=>{let o=`${n.execution_order}:${n.run_type}:${n.name}`;return i===s.length-1?fr(uv.default.bold,o):o}).join(" > ");return fr($r.grey,r)}onChainStart(e){let t=this.getBreadcrumbs(e);console.log(`${fr($r.green,"[chain/start]")} [${t}] Entering Chain run with input: ${cn(e.inputs,"[inputs]")}`)}onChainEnd(e){let t=this.getBreadcrumbs(e);console.log(`${fr($r.cyan,"[chain/end]")} [${t}] [${Ms(e)}] Exiting Chain run with output: ${cn(e.outputs,"[outputs]")}`)}onChainError(e){let t=this.getBreadcrumbs(e);console.log(`${fr($r.red,"[chain/error]")} [${t}] [${Ms(e)}] Chain run errored with error: ${cn(e.error,"[error]")}`)}onLLMStart(e){let t=this.getBreadcrumbs(e),r="prompts"in e.inputs?{prompts:e.inputs.prompts.map(n=>n.trim())}:e.inputs;console.log(`${fr($r.green,"[llm/start]")} [${t}] Entering LLM run with input: ${cn(r,"[inputs]")}`)}onLLMEnd(e){let t=this.getBreadcrumbs(e);console.log(`${fr($r.cyan,"[llm/end]")} [${t}] [${Ms(e)}] Exiting LLM run with output: ${cn(e.outputs,"[response]")}`)}onLLMError(e){let t=this.getBreadcrumbs(e);console.log(`${fr($r.red,"[llm/error]")} [${t}] [${Ms(e)}] LLM run errored with error: ${cn(e.error,"[error]")}`)}onToolStart(e){let t=this.getBreadcrumbs(e);console.log(`${fr($r.green,"[tool/start]")} [${t}] Entering Tool run with input: "${e$(e.inputs.input)}"`)}onToolEnd(e){let t=this.getBreadcrumbs(e);console.log(`${fr($r.cyan,"[tool/end]")} [${t}] [${Ms(e)}] Exiting Tool run with output: "${e$(e.outputs?.output)}"`)}onToolError(e){let t=this.getBreadcrumbs(e);console.log(`${fr($r.red,"[tool/error]")} [${t}] [${Ms(e)}] Tool run errored with error: ${cn(e.error,"[error]")}`)}onRetrieverStart(e){let t=this.getBreadcrumbs(e);console.log(`${fr($r.green,"[retriever/start]")} [${t}] Entering Retriever run with input: ${cn(e.inputs,"[inputs]")}`)}onRetrieverEnd(e){let t=this.getBreadcrumbs(e);console.log(`${fr($r.cyan,"[retriever/end]")} [${t}] [${Ms(e)}] Exiting Retriever run with output: ${cn(e.outputs,"[outputs]")}`)}onRetrieverError(e){let t=this.getBreadcrumbs(e);console.log(`${fr($r.red,"[retriever/error]")} [${t}] [${Ms(e)}] Retriever run errored with error: ${cn(e.error,"[error]")}`)}onAgentAction(e){let t=e,r=this.getBreadcrumbs(e);console.log(`${fr($r.blue,"[agent/action]")} [${r}] Agent selected action: ${cn(t.actions[t.actions.length-1],"[action]")}`)}};function Yf(e,t){return st(e,t)??{}}function t$(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}function fF(e,t){let r={...t$(e,t)};return(e?.cache_read!==void 0||t?.cache_read!==void 0)&&(r.cache_read=(e?.cache_read??0)+(t?.cache_read??0)),(e?.cache_creation!==void 0||t?.cache_creation!==void 0)&&(r.cache_creation=(e?.cache_creation??0)+(t?.cache_creation??0)),r}function mF(e,t){let r={...t$(e,t)};return(e?.reasoning!==void 0||t?.reasoning!==void 0)&&(r.reasoning=(e?.reasoning??0)+(t?.reasoning??0)),r}function hc(e,t){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:fF(e?.input_token_details,t?.input_token_details),output_token_details:mF(e?.output_token_details,t?.output_token_details)}}function pv(e){switch(e){case"csv":return"text/csv";case"doc":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";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":return"image/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 hF(e){if(ue(e.document)&&ue(e.document.source)){let t=ue(e.document)&&z(e.document.format)?e.document.format:"",r=pv(t);if(ue(e.document.source)){if(ue(e.document.source.s3Location)&&z(e.document.source.s3Location.uri))return{type:"file",mimeType:r,fileId:e.document.source.s3Location.uri};if(mf(e.document.source.bytes))return{type:"file",mimeType:r,data:e.document.source.bytes};if(z(e.document.source.text))return{type:"file",mimeType:r,data:Buffer.from(e.document.source.text).toString("base64")};if(qt(e.document.source.content)){let n=e.document.source.content.reduce((i,s)=>ue(s)&&z(s.text)?i+s.text:i,"");return{type:"file",mimeType:r,data:n}}}}return{type:"non_standard",value:e}}function gF(e){if(re(e,"image")&&ue(e.image)){let t=ue(e.image)&&z(e.image.format)?e.image.format:"",r=pv(t);if(ue(e.image.source)){if(ue(e.image.source.s3Location)&&z(e.image.source.s3Location.uri))return{type:"image",mimeType:r,fileId:e.image.source.s3Location.uri};if(mf(e.image.source.bytes))return{type:"image",mimeType:r,data:e.image.source.bytes}}}return{type:"non_standard",value:e}}function _F(e){if(re(e,"video")&&ue(e.video)){let t=ue(e.video)&&z(e.video.format)?e.video.format:"",r=pv(t);if(ue(e.video.source)){if(ue(e.video.source.s3Location)&&z(e.video.source.s3Location.uri))return{type:"video",mimeType:r,fileId:e.video.source.s3Location.uri};if(mf(e.video.source.bytes))return{type:"video",mimeType:r,data:e.video.source.bytes}}}return{type:"non_standard",value:e}}function r$(e){function*t(){let r=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content;for(let n of r){if(re(n,"cache_point")){yield{type:"non_standard",value:n};continue}else if(re(n,"citations_content")&&ue(n.citationsContent)){let i=qt(n.citationsContent.content)?n.citationsContent.content.reduce((o,a)=>ue(a)&&z(a.text)?o+a.text:o,""):"",s=qt(n.citationsContent.citations)?n.citationsContent.citations.reduce((o,a)=>{if(ue(a)){let c=qt(a.sourceContent)?a.sourceContent.reduce((l,p)=>ue(p)&&z(p.text)?l+p.text:l,""):"",u=Li(()=>{if(ue(a.location)){let l=a.location.documentChar||a.location.documentPage||a.location.documentChunk;if(ue(l))return{source:Ur(l.documentIndex)?l.documentIndex.toString():void 0,startIndex:Ur(l.start)?l.start:void 0,endIndex:Ur(l.end)?l.end:void 0}}return{}});o.push({type:"citation",citedText:c,...u})}return o},[]):[];yield{type:"text",text:i,annotations:s};continue}else if(re(n,"document")&&ue(n.document)){yield hF(n);continue}else if(re(n,"guard_content")){yield{type:"non_standard",value:n};continue}else if(re(n,"image")&&ue(n.image)){yield gF(n);continue}else if(re(n,"reasoning_content")&&z(n.reasoningText)){yield{type:"reasoning",reasoning:n.reasoningText};continue}else if(re(n,"text")&&z(n.text)){yield{type:"text",text:n.text};continue}else if(re(n,"tool_result")){yield{type:"non_standard",value:n};continue}else{if(re(n,"tool_call"))continue;if(re(n,"video")&&ue(n.video)){yield _F(n);continue}}yield{type:"non_standard",value:n}}}return Array.from(t())}var n$={translateContent:r$,translateContentChunk:r$};function i$(e){let t=[],r=e.additional_kwargs?.reasoning_content;if(z(r)&&r.length>0&&t.push({type:"reasoning",reasoning:r}),typeof e.content=="string")e.content.length>0&&t.push({type:"text",text:e.content});else for(let n of e.content)typeof n=="object"&&"type"in n&&n.type==="text"&&"text"in n&&z(n.text)&&t.push({type:"text",text:n.text});for(let n of e.tool_calls??[])t.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return t}var s$={translateContent:i$,translateContentChunk:i$};function o$(e){function*t(){let r=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content;for(let n of r){if(re(n,"text")&&z(n.text)){yield{type:"text",text:n.text};continue}else if(re(n,"thinking")&&z(n.thinking)){yield{type:"reasoning",reasoning:n.thinking,...n.signature?{signature:n.signature}:{}};continue}else if(re(n,"inlineData")&&ue(n.inlineData)&&z(n.inlineData.mimeType)&&z(n.inlineData.data)){yield{type:"file",mimeType:n.inlineData.mimeType,data:n.inlineData.data};continue}else if(re(n,"functionCall")&&ue(n.functionCall)&&z(n.functionCall.name)&&ue(n.functionCall.args)){yield{type:"tool_call",id:e.id,name:n.functionCall.name,args:n.functionCall.args};continue}else if(re(n,"functionResponse")){yield{type:"non_standard",value:n};continue}else if(re(n,"fileData")&&ue(n.fileData)&&z(n.fileData.mimeType)&&z(n.fileData.fileUri)){yield{type:"file",mimeType:n.fileData.mimeType,fileId:n.fileData.fileUri};continue}else if(re(n,"executableCode")){yield{type:"non_standard",value:n};continue}else if(re(n,"codeExecutionResult")){yield{type:"non_standard",value:n};continue}yield{type:"non_standard",value:n}}}return Array.from(t())}var a$={translateContent:o$,translateContentChunk:o$};function c$(e){function*t(){let r=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content;for(let n of r){if(re(n,"reasoning")&&z(n.reasoning)){let i=Li(()=>{let s=r.indexOf(n);if(qt(e.additional_kwargs?.signatures)&&s>=0)return e.additional_kwargs.signatures.at(s)});z(i)?yield{type:"reasoning",reasoning:n.reasoning,signature:i}:yield{type:"reasoning",reasoning:n.reasoning};continue}else if(re(n,"thinking")&&z(n.thinking)){yield{type:"reasoning",reasoning:n.thinking,...n.signature?{signature:n.signature}:{}};continue}else if(re(n,"text")&&z(n.text)){yield{type:"text",text:n.text};continue}else if(re(n,"image_url")){if(z(n.image_url))if(n.image_url.startsWith("data:")){let i=/^data:([^;]+);base64,(.+)$/,s=n.image_url.match(i);s?yield{type:"image",data:s[2],mimeType:s[1]}:yield{type:"image",url:n.image_url}}else yield{type:"image",url:n.image_url};continue}else if(re(n,"media")&&z(n.mimeType)&&z(n.data)){yield{type:"file",mimeType:n.mimeType,data:n.data};continue}yield{type:"non_standard",value:n}}}return Array.from(t())}var u$={translateContent:c$,translateContentChunk:c$};function l$(e){let t=[],r=e.additional_kwargs?.reasoning;if(z(r)&&r.length>0&&t.push({type:"reasoning",reasoning:r}),typeof e.content=="string"){let n=e.content,i=n.match(/<think>([\s\S]*?)<\/think>/);if(i){let s=i[1].trim();s.length>0&&t.push({type:"reasoning",reasoning:s}),n=n.replace(/<think>[\s\S]*?<\/think>/,"").trim()}n.length>0&&t.push({type:"text",text:n})}else for(let n of e.content)if(typeof n=="object"&&"type"in n&&n.type==="text"&&"text"in n&&z(n.text)){let i=n.text,s=i.match(/<think>([\s\S]*?)<\/think>/);if(s){let o=s[1].trim();o.length>0&&t.push({type:"reasoning",reasoning:o}),i=i.replace(/<think>[\s\S]*?<\/think>/,"").trim()}i.length>0&&t.push({type:"text",text:i})}for(let n of e.tool_calls??[])t.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return t}var p$={translateContent:l$,translateContentChunk:l$};function d$(e){let t=[],r=e.additional_kwargs?.reasoning_content;if(z(r)&&r.length>0&&t.push({type:"reasoning",reasoning:r}),typeof e.content=="string")e.content.length>0&&t.push({type:"text",text:e.content});else for(let n of e.content)typeof n=="object"&&"type"in n&&n.type==="text"&&"text"in n&&z(n.text)&&t.push({type:"text",text:n.text});for(let n of e.tool_calls??[])t.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return t}var f$={translateContent:d$,translateContentChunk:d$};function m$(e){let t=[];if(ue(e.additional_kwargs?.reasoning)){let n=e.additional_kwargs.reasoning;if(qt(n.summary)){let i=n.summary.reduce((s,o)=>ue(o)&&z(o.text)?`${s}${o.text}`:s,"");i.length>0&&t.push({type:"reasoning",reasoning:i})}}let r=e.additional_kwargs?.reasoning_content;if(z(r)&&r.length>0&&t.push({type:"reasoning",reasoning:r}),typeof e.content=="string")e.content.length>0&&t.push({type:"text",text:e.content});else for(let n of e.content)typeof n=="object"&&"type"in n&&n.type==="text"&&"text"in n&&z(n.text)&&t.push({type:"text",text:n.text});for(let n of e.tool_calls??[])t.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return t}var h$={translateContent:m$,translateContentChunk:m$};globalThis.lc_block_translators_registry??=new Map([["anthropic",Bk],["bedrock-converse",n$],["deepseek",s$],["google-genai",a$],["google-vertexai",u$],["groq",p$],["ollama",f$],["openai",qk],["xai",h$]]);function dv(e){return globalThis.lc_block_translators_registry.get(e)}function js(e,t){return e.lc_error_code=t,e.message=`${e.message}
|
|
45
|
+
|
|
46
|
+
Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${t}/
|
|
47
|
+
`,e}function Ds(e){return!!(e&&typeof e=="object"&&"type"in e&&e.type==="tool_call")}function g$(e){return!!(e&&typeof e=="object"&&"toolCall"in e&&e.toolCall!=null&&typeof e.toolCall=="object"&&"id"in e.toolCall&&typeof e.toolCall.id=="string")}var gc=class extends Error{output;constructor(e,t){super(e),this.output=t}};function Rl(e,t=ai){e=e.trim();let r=e.indexOf("```");if(r===-1)return t(e);let n=e.substring(r+3);n.startsWith(`json
|
|
48
|
+
`)?n=n.substring(5):n.startsWith("json")?n=n.substring(4):n.startsWith(`
|
|
49
|
+
`)&&(n=n.substring(1));let i=n.indexOf("```"),s=n;return i!==-1&&(s=n.substring(0,i)),t(s.trim())}function yF(e){try{return JSON.parse(e)}catch{}let t=e.trim();if(t.length===0)throw new Error("Unexpected end of JSON input");let r=0;function n(){for(;r<t.length&&/\s/.test(t[r]);)r+=1}function i(){if(t[r]!=='"')throw new Error(`Expected '"' at position ${r}, got '${t[r]}'`);r+=1;let l="",p=!1;for(;r<t.length;){let f=t[r];if(p){if(f==="n")l+=`
|
|
50
|
+
`;else if(f==="t")l+=" ";else if(f==="r")l+="\r";else if(f==="\\")l+="\\";else if(f==='"')l+='"';else if(f==="b")l+="\b";else if(f==="f")l+="\f";else if(f==="/")l+="/";else if(f==="u"){let d=t.substring(r+1,r+5);if(/^[0-9A-Fa-f]{0,4}$/.test(d))d.length===4?l+=String.fromCharCode(Number.parseInt(d,16)):l+=`u${d}`,r+=d.length;else throw new Error(`Invalid unicode escape sequence '\\u${d}' at position ${r}`)}else throw new Error(`Invalid escape sequence '\\${f}' at position ${r}`);p=!1}else if(f==="\\")p=!0;else{if(f==='"')return r+=1,l;l+=f}r+=1}return p&&(l+="\\"),l}function s(){let l=r,p="";if(t[r]==="-"&&(p+="-",r+=1),r<t.length&&t[r]==="0"&&(p+="0",r+=1,t[r]>="0"&&t[r]<="9"))throw new Error(`Invalid number at position ${l}`);if(r<t.length&&t[r]>="1"&&t[r]<="9")for(;r<t.length&&t[r]>="0"&&t[r]<="9";)p+=t[r],r+=1;if(r<t.length&&t[r]===".")for(p+=".",r+=1;r<t.length&&t[r]>="0"&&t[r]<="9";)p+=t[r],r+=1;if(r<t.length&&(t[r]==="e"||t[r]==="E"))for(p+=t[r],r+=1,r<t.length&&(t[r]==="+"||t[r]==="-")&&(p+=t[r],r+=1);r<t.length&&t[r]>="0"&&t[r]<="9";)p+=t[r],r+=1;if(p==="-")return-0;let f=Number.parseFloat(p);if(Number.isNaN(f))throw r=l,new Error(`Invalid number '${p}' at position ${l}`);return f}function o(){if(n(),r>=t.length)throw new Error(`Unexpected end of input at position ${r}`);let l=t[r];if(l==="{")return c();if(l==="[")return a();if(l==='"')return i();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(l==="-"||l>="0"&&l<="9")return s();throw new Error(`Unexpected character '${l}' at position ${r}`)}function a(){if(t[r]!=="[")throw new Error(`Expected '[' at position ${r}, got '${t[r]}'`);let l=[];if(r+=1,n(),r>=t.length)return l;if(t[r]==="]")return r+=1,l;for(;r<t.length;){if(n(),r>=t.length||(l.push(o()),n(),r>=t.length))return l;if(t[r]==="]")return r+=1,l;if(t[r]===","){r+=1;continue}throw new Error(`Expected ',' or ']' at position ${r}, got '${t[r]}'`)}return l}function c(){if(t[r]!=="{")throw new Error(`Expected '{' at position ${r}, got '${t[r]}'`);let l={};if(r+=1,n(),r>=t.length)return l;if(t[r]==="}")return r+=1,l;for(;r<t.length;){if(n(),r>=t.length)return l;let p=i();if(n(),r>=t.length)return l;if(t[r]!==":")throw new Error(`Expected ':' at position ${r}, got '${t[r]}'`);if(r+=1,n(),r>=t.length||(l[p]=o(),n(),r>=t.length))return l;if(t[r]==="}")return r+=1,l;if(t[r]===","){r+=1;continue}throw new Error(`Expected ',' or '}' at position ${r}, got '${t[r]}'`)}return l}let u=o();if(n(),r<t.length)throw new Error(`Unexpected character '${t[r]}' at position ${r}`);return u}function ai(e){try{return typeof e>"u"?null:yF(e)}catch{return null}}var mr=class _$ extends bt{static lc_name(){return"ChatMessage"}type="generic";role;static _chatMessageClass(){return _$}constructor(t,r){(typeof t=="string"||Array.isArray(t))&&(t={content:t,role:r}),super(t),this.role=t.role}static isInstance(t){return super.isInstance(t)&&t.type==="generic"}get _printableFields(){return{...super._printableFields,role:this.role}}},Zi=class extends ur{static lc_name(){return"ChatMessageChunk"}type="generic";role;constructor(e,t){(typeof e=="string"||Array.isArray(e))&&(e={content:e,role:t}),super(e),this.role=e.role}concat(e){let t=this.constructor;return new t({content:Ht(this.content,e.content),additional_kwargs:st(this.additional_kwargs,e.additional_kwargs),response_metadata:st(this.response_metadata,e.response_metadata),role:this.role,id:this.id??e.id})}static isInstance(e){return super.isInstance(e)&&e.type==="generic"}get _printableFields(){return{...super._printableFields,role:this.role}}};function y$(e){return e._getType()==="generic"}function v$(e){return e._getType()==="generic"}var Lo=class extends bt{static lc_name(){return"FunctionMessage"}type="function";name;constructor(e){super(e),this.name=e.name}},Gi=class extends ur{static lc_name(){return"FunctionMessageChunk"}type="function";concat(e){let t=this.constructor;return new t({content:Ht(this.content,e.content),additional_kwargs:st(this.additional_kwargs,e.additional_kwargs),response_metadata:st(this.response_metadata,e.response_metadata),name:this.name??"",id:this.id??e.id})}};function b$(e){return e._getType()==="function"}function w$(e){return e._getType()==="function"}var at=class extends bt{static lc_name(){return"HumanMessage"}type="human";constructor(e){super(e)}static isInstance(e){return super.isInstance(e)&&e.type==="human"}},Ki=class extends ur{static lc_name(){return"HumanMessageChunk"}type="human";constructor(e){super(e)}concat(e){let t=this.constructor;return new t({content:Ht(this.content,e.content),additional_kwargs:st(this.additional_kwargs,e.additional_kwargs),response_metadata:st(this.response_metadata,e.response_metadata),id:this.id??e.id})}static isInstance(e){return super.isInstance(e)&&e.type==="human"}};function x$(e){return e.getType()==="human"}function I$(e){return e.getType()==="human"}var On=class extends bt{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)&&e.type==="remove"}};var Br=class Qf extends bt{static lc_name(){return"SystemMessage"}type="system";constructor(t){super(t)}concat(t){if(typeof t=="string")return new Qf({...this,content:Ht(this.content,t)});if(Qf.isInstance(t))return new Qf({...this,additional_kwargs:{...this.additional_kwargs,...t.additional_kwargs},response_metadata:{...this.response_metadata,...t.response_metadata},content:Ht(this.content,t.content)});throw new Error("Unexpected chunk type for system message")}static isInstance(t){return super.isInstance(t)&&t.type==="system"}},un=class extends ur{static lc_name(){return"SystemMessageChunk"}type="system";constructor(e){super(e)}concat(e){let t=this.constructor;return new t({content:Ht(this.content,e.content),additional_kwargs:st(this.additional_kwargs,e.additional_kwargs),response_metadata:st(this.response_metadata,e.response_metadata),id:this.id??e.id})}static isInstance(e){return super.isInstance(e)&&e.type==="system"}};function S$(e){return e._getType()==="system"}function E$(e){return e._getType()==="system"}var em=e=>e();function vF(e){return Ds(e)?e:typeof e.id=="string"&&e.type==="function"&&typeof e.function=="object"&&e.function!==null&&"arguments"in e.function&&typeof e.function.arguments=="string"&&"name"in e.function&&typeof e.function.name=="string"?{id:e.id,args:JSON.parse(e.function.arguments),name:e.function.name,type:"tool_call"}:e}function bF(e){return typeof e=="object"&&e!=null&&e.lc===1&&Array.isArray(e.id)&&e.kwargs!=null&&typeof e.kwargs=="object"}function fv(e){let t,r;if(bF(e)){let n=e.id.at(-1);n==="HumanMessage"||n==="HumanMessageChunk"?t="user":n==="AIMessage"||n==="AIMessageChunk"?t="assistant":n==="SystemMessage"||n==="SystemMessageChunk"?t="system":n==="FunctionMessage"||n==="FunctionMessageChunk"?t="function":n==="ToolMessage"||n==="ToolMessageChunk"?t="tool":t="unknown",r=e.kwargs}else{let{type:n,...i}=e;t=n,r=i}if(t==="human"||t==="user")return new at(r);if(t==="ai"||t==="assistant"){let{tool_calls:n,...i}=r;if(!Array.isArray(n))return new Oe(r);let s=n.map(vF);return new Oe({...i,tool_calls:s})}else{if(t==="system")return new Br(r);if(t==="developer")return new Br({...r,additional_kwargs:{...r.additional_kwargs,__openai_role__:"developer"}});if(t==="tool"&&"tool_call_id"in r)return new Wt({...r,content:r.content,tool_call_id:r.tool_call_id,name:r.name});if(t==="remove"&&"id"in r&&typeof r.id=="string")return new On({...r,id:r.id});throw js(new Error(`Unable to coerce message from array: only human, AI, system, developer, or tool message coercion is currently supported.
|
|
51
|
+
|
|
52
|
+
Received: ${JSON.stringify(e,null,2)}`),"MESSAGE_COERCION_FAILURE")}}function Qt(e){if(typeof e=="string")return new at(e);if(ot(e))return e;if(Array.isArray(e)){let[t,r]=e;return fv({type:t,content:r})}else if(vf(e)){let{role:t,...r}=e;return fv({...r,type:t})}else return fv(e)}function _c(e,t="Human",r="AI"){let n=[];for(let i of e){let s;if(i.type==="human")s=t;else if(i.type==="ai")s=r;else if(i.type==="system")s="System";else if(i.type==="tool")s="Tool";else if(i.type==="generic")s=i.role;else throw new Error(`Got unsupported message type: ${i.type}`);let o=i.name?`${i.name}, `:"",a=i.text,c=`${s}: ${o}${a}`;if(i.type==="ai"){let u=i;u.tool_calls&&u.tool_calls.length>0?c+=JSON.stringify(u.tool_calls):u.additional_kwargs&&"function_call"in u.additional_kwargs&&(c+=JSON.stringify(u.additional_kwargs.function_call))}n.push(c)}return n.join(`
|
|
53
|
+
`)}function wF(e){if(e.data!==void 0)return e;{let t=e;return{type:t.type,data:{content:t.text,role:t.role,name:void 0,tool_call_id:void 0}}}}function Ml(e){let t=wF(e);switch(t.type){case"human":return new at(t.data);case"ai":return new Oe(t.data);case"system":return new Br(t.data);case"function":if(t.data.name===void 0)throw new Error("Name must be defined for function messages");return new Lo(t.data);case"tool":if(t.data.tool_call_id===void 0)throw new Error("Tool call ID must be defined for tool messages");return new Wt(t.data);case"generic":if(t.data.role===void 0)throw new Error("Role must be defined for chat messages");return new mr(t.data);default:throw new Error(`Got unexpected type: ${t.type}`)}}function k$(e){return e.map(Ml)}function A$(e){return e.map(t=>t.toDict())}function Uo(e){let t=e._getType();if(t==="human")return new Ki({...e});if(t==="ai"){let r={...e};return"tool_calls"in r&&(r={...r,tool_call_chunks:r.tool_calls?.map(n=>({...n,type:"tool_call_chunk",index:void 0,args:JSON.stringify(n.args)}))}),new nt({...r})}else{if(t==="system")return new un({...e});if(t==="function")return new Gi({...e});if(mr.isInstance(e))return new Zi({...e});throw new Error("Unknown message type.")}}function tm(e){let t=e.reduce((i,s)=>{let o=i.findIndex(([a])=>"id"in s&&s.id&&"index"in s&&s.index!==void 0?s.id===a.id&&s.index===a.index:"id"in s&&s.id?s.id===a.id:"index"in s&&s.index!==void 0?s.index===a.index:!1);return o!==-1?i[o].push(s):i.push([s]),i},[]),r=[],n=[];for(let i of t){let s=null,o=i[0]?.name??"",a=i.map(l=>l.args||"").join("").trim(),c=a.length?a:"{}",u=i[0]?.id;try{if(s=ai(c),!u||s===null||typeof s!="object"||Array.isArray(s))throw new Error("Malformed tool call chunk args.");r.push({name:o,args:s,id:u,type:"tool_call"})}catch{n.push({name:o,args:c,id:u,error:"Malformed args.",type:"invalid_tool_call"})}}return{tool_call_chunks:e,tool_calls:r,invalid_tool_calls:n}}var Oe=class extends bt{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"}}constructor(e){let t;if(typeof e=="string"||Array.isArray(e))t={content:e,tool_calls:[],invalid_tool_calls:[],additional_kwargs:{}};else{t=e;let r=t.additional_kwargs?.tool_calls,n=t.tool_calls;r!=null&&r.length>0&&(n===void 0||n.length===0)&&console.warn(["New LangChain packages are available that more efficiently handle",`tool calling.
|
|
54
|
+
|
|
55
|
+
Please upgrade your packages to versions that set`,"message tool calls. e.g., `pnpm install @langchain/anthropic`,","pnpm install @langchain/openai`, etc."].join(" "));try{if(r!=null&&n===void 0){let[i,s]=yl(r);t.tool_calls=i??[],t.invalid_tool_calls=s??[]}else t.tool_calls=t.tool_calls??[],t.invalid_tool_calls=t.invalid_tool_calls??[]}catch{t.tool_calls=[],t.invalid_tool_calls=[]}if(t.response_metadata!==void 0&&"output_version"in t.response_metadata&&t.response_metadata.output_version==="v1"&&(t.contentBlocks=t.content,t.content=void 0),t.contentBlocks!==void 0){t.tool_calls&&t.contentBlocks.push(...t.tool_calls.map(s=>({type:"tool_call",id:s.id,name:s.name,args:s.args})));let i=t.contentBlocks.filter(s=>s.type==="tool_call").filter(s=>!t.tool_calls?.some(o=>o.id===s.id&&o.name===s.name));i.length>0&&(t.tool_calls=i.map(s=>({type:"tool_call",id:s.id,name:s.name,args:s.args})))}}super(t),typeof t!="string"&&(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&&this.response_metadata.output_version==="v1")return this.content;if(this.response_metadata&&"model_provider"in this.response_metadata&&typeof this.response_metadata.model_provider=="string"){let t=dv(this.response_metadata.model_provider);if(t)return t.translateContent(this)}let e=super.contentBlocks;if(this.tool_calls){let t=this.tool_calls.filter(r=>!e.some(n=>n.id===r.id&&n.name===r.name));e.push(...t.map(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,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}static isInstance(e){return super.isInstance(e)&&e.type==="ai"}};function ci(e){return e._getType()==="ai"}function jl(e){return e._getType()==="ai"}var nt=class extends ur{type="ai";tool_calls=[];invalid_tool_calls=[];tool_call_chunks=[];usage_metadata;constructor(e){let t;if(typeof e=="string"||Array.isArray(e))t={content:e,tool_calls:[],invalid_tool_calls:[],tool_call_chunks:[]};else if(e.tool_call_chunks===void 0||e.tool_call_chunks.length===0)t={...e,tool_calls:e.tool_calls??[],invalid_tool_calls:[],tool_call_chunks:[],usage_metadata:e.usage_metadata!==void 0?e.usage_metadata:void 0};else{let r=tm(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:e.usage_metadata!==void 0?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"}}static lc_name(){return"AIMessageChunk"}get contentBlocks(){if(this.response_metadata&&"output_version"in this.response_metadata&&this.response_metadata.output_version==="v1")return this.content;if(this.response_metadata&&"model_provider"in this.response_metadata&&typeof this.response_metadata.model_provider=="string"){let t=dv(this.response_metadata.model_provider);if(t)return t.translateContent(this)}let e=super.contentBlocks;if(this.tool_calls&&typeof this.content!="string"){let t=this.content.filter(r=>r.type==="tool_call").map(r=>r.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 t={content:Ht(this.content,e.content),additional_kwargs:st(this.additional_kwargs,e.additional_kwargs),response_metadata:Yf(this.response_metadata,e.response_metadata),tool_call_chunks:[],id:this.id??e.id};if(this.tool_call_chunks!==void 0||e.tool_call_chunks!==void 0){let n=Mo(this.tool_call_chunks,e.tool_call_chunks);n!==void 0&&n.length>0&&(t.tool_call_chunks=n)}(this.usage_metadata!==void 0||e.usage_metadata!==void 0)&&(t.usage_metadata=hc(this.usage_metadata,e.usage_metadata));let r=this.constructor;return new r(t)}static isInstance(e){return super.isInstance(e)&&e.type==="ai"}};var mv,rm=()=>{if(mv===void 0){let e=Pe("LANGCHAIN_CALLBACKS_BACKGROUND")==="false"?{blockOnRootRunFinalization:!0}:{};mv=new Bi(e)}return mv};var gv=class{getStore(){}run(t,r){return r()}},hv=Symbol.for("ls:tracing_async_local_storage"),xF=new gv,_v=class{getInstance(){return globalThis[hv]??xF}initializeGlobalInstance(t){globalThis[hv]===void 0&&(globalThis[hv]=t)}},IF=new _v;function T$(e=!1){let t=IF.getInstance().getStore();if(!e&&t===void 0)throw new Error(`Could not get the current run tree.
|
|
56
|
+
|
|
57
|
+
Please make sure you are calling this method within a traceable function and that tracing is enabled.`);return t}var OX=Symbol.for("langsmith:traceable:root");function nm(e){return typeof e=="function"&&"langsmith:traceable"in e}var yv={};M(yv,{LangChainTracer:()=>Dl});function SF(e){let t;for(let r of e)for(let n of r)Oe.isInstance(n.message)&&n.message.usage_metadata!==void 0&&(t=hc(t,n.message.usage_metadata));return t}var Dl=class O$ extends Zt{name="langchain_tracer";projectName;exampleId;client;replicas;usesRunTreeMap=!0;constructor(t={}){super(t);let{exampleId:r,projectName:n,client:i,replicas:s}=t;this.projectName=n??bl(),this.replicas=s,this.exampleId=r,this.client=i??rm();let o=O$.getTraceableRunTree();o&&this.updateFromRunTree(o)}async persistRun(t){}async onRunCreate(t){t.extra?.lc_defers_inputs||await this.getRunTreeWithTracingConfig(t.id)?.postRun()}async onRunUpdate(t){let r=this.getRunTreeWithTracingConfig(t.id);t.extra?.lc_defers_inputs?await r?.postRun():await r?.patchRun()}onLLMEnd(t){let r=t.outputs;if(r?.generations){let n=SF(r.generations);if(n!==void 0){t.extra=t.extra??{};let i=t.extra.metadata??{};i.usage_metadata=n,t.extra.metadata=i}}}getRun(t){return this.runTreeMap.get(t)}updateFromRunTree(t){this.runTreeMap.set(t.id,t);let r=t,n=new Set;for(;r.parent_run&&!(n.has(r.id)||(n.add(r.id),!r.parent_run));)r=r.parent_run;n.clear();let i=[r];for(;i.length>0;){let s=i.shift();!s||n.has(s.id)||(n.add(s.id),this.runTreeMap.set(s.id,s),s.child_runs&&i.push(...s.child_runs))}this.client=t.client??this.client,this.replicas=t.replicas??this.replicas,this.projectName=t.project_name??this.projectName,this.exampleId=t.reference_example_id??this.exampleId}getRunTreeWithTracingConfig(t){let r=this.runTreeMap.get(t);if(r)return new Tn({...r,client:this.client,project_name:this.projectName,replicas:this.replicas,reference_example_id:this.exampleId,tracingEnabled:!0})}static getTraceableRunTree(){try{return T$(!0)}catch{return}}};var $$=Symbol.for("ls:tracing_async_local_storage"),zs=Symbol.for("lc:context_variables"),C$=e=>{globalThis[$$]=e},Ls=()=>globalThis[$$];var im=Ps(Cf(),1),Fo;function EF(){let e="default"in im.default?im.default.default:im.default;return new e({autoStart:!0,concurrency:1})}function kF(){return typeof Fo>"u"&&(Fo=EF()),Fo}async function ht(e,t){if(t===!0){let r=Ls();r!==void 0?await r.run(void 0,async()=>e()):await e()}else Fo=kF(),Fo.add(async()=>{let r=Ls();r!==void 0?await r.run(void 0,async()=>e()):await e()})}async function P$(){let e=rm();await Promise.allSettled([typeof Fo<"u"?Fo.onIdle():Promise.resolve(),e.awaitPendingTraceBatches()])}var vv={};M(vv,{awaitAllCallbacks:()=>P$,consumeCallback:()=>ht});var N$=e=>e!==void 0?e:!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find(r=>Pe(r)==="true");function bv(e){let t=Ls();return t===void 0?void 0:t.getStore()?.[zs]?.[e]}var AF=Symbol("lc:configure_hooks"),R$=()=>bv(AF)||[];var xv={};M(xv,{BaseCallbackManager:()=>M$,BaseRunManager:()=>Ll,CallbackManager:()=>xt,CallbackManagerForChainRun:()=>D$,CallbackManagerForLLMRun:()=>wv,CallbackManagerForRetrieverRun:()=>j$,CallbackManagerForToolRun:()=>z$,ensureHandler:()=>yc,parseCallbackConfigArg:()=>Bo});function Bo(e){return e?Array.isArray(e)||"name"in e?{callbacks:e}:e:{}}var M$=class{setHandler(e){return this.setHandlers([e])}},Ll=class{constructor(e,t,r,n,i,s,o,a){this.runId=e,this.handlers=t,this.inheritableHandlers=r,this.tags=n,this.inheritableTags=i,this.metadata=s,this.inheritableMetadata=o,this._parentRunId=a}get parentRunId(){return this._parentRunId}async handleText(e){await Promise.all(this.handlers.map(t=>ht(async()=>{try{await t.handleText?.(e,this.runId,this._parentRunId,this.tags)}catch(r){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleText: ${r}`),t.raiseError)throw r}},t.awaitHandlers)))}async handleCustomEvent(e,t,r,n,i){await Promise.all(this.handlers.map(s=>ht(async()=>{try{await s.handleCustomEvent?.(e,t,this.runId,this.tags,this.metadata)}catch(o){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleCustomEvent: ${o}`),s.raiseError)throw o}},s.awaitHandlers)))}},j$=class extends Ll{getChild(e){let t=new xt(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=>ht(async()=>{if(!t.ignoreRetriever)try{await t.handleRetrieverEnd?.(e,this.runId,this._parentRunId,this.tags)}catch(r){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleRetriever`),t.raiseError)throw r}},t.awaitHandlers)))}async handleRetrieverError(e){await Promise.all(this.handlers.map(t=>ht(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)))}},wv=class extends Ll{async handleLLMNewToken(e,t,r,n,i,s){await Promise.all(this.handlers.map(o=>ht(async()=>{if(!o.ignoreLLM)try{await o.handleLLMNewToken?.(e,t??{prompt:0,completion:0},this.runId,this._parentRunId,this.tags,s)}catch(a){if((o.raiseError?console.error:console.warn)(`Error in handler ${o.constructor.name}, handleLLMNewToken: ${a}`),o.raiseError)throw a}},o.awaitHandlers)))}async handleLLMError(e,t,r,n,i){await Promise.all(this.handlers.map(s=>ht(async()=>{if(!s.ignoreLLM)try{await s.handleLLMError?.(e,this.runId,this._parentRunId,this.tags,i)}catch(o){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleLLMError: ${o}`),s.raiseError)throw o}},s.awaitHandlers)))}async handleLLMEnd(e,t,r,n,i){await Promise.all(this.handlers.map(s=>ht(async()=>{if(!s.ignoreLLM)try{await s.handleLLMEnd?.(e,this.runId,this._parentRunId,this.tags,i)}catch(o){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleLLMEnd: ${o}`),s.raiseError)throw o}},s.awaitHandlers)))}},D$=class extends Ll{getChild(e){let t=new xt(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,n,i){await Promise.all(this.handlers.map(s=>ht(async()=>{if(!s.ignoreChain)try{await s.handleChainError?.(e,this.runId,this._parentRunId,this.tags,i)}catch(o){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleChainError: ${o}`),s.raiseError)throw o}},s.awaitHandlers)))}async handleChainEnd(e,t,r,n,i){await Promise.all(this.handlers.map(s=>ht(async()=>{if(!s.ignoreChain)try{await s.handleChainEnd?.(e,this.runId,this._parentRunId,this.tags,i)}catch(o){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleChainEnd: ${o}`),s.raiseError)throw o}},s.awaitHandlers)))}async handleAgentAction(e){await Promise.all(this.handlers.map(t=>ht(async()=>{if(!t.ignoreAgent)try{await t.handleAgentAction?.(e,this.runId,this._parentRunId,this.tags)}catch(r){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleAgentAction: ${r}`),t.raiseError)throw r}},t.awaitHandlers)))}async handleAgentEnd(e){await Promise.all(this.handlers.map(t=>ht(async()=>{if(!t.ignoreAgent)try{await t.handleAgentEnd?.(e,this.runId,this._parentRunId,this.tags)}catch(r){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleAgentEnd: ${r}`),t.raiseError)throw r}},t.awaitHandlers)))}},z$=class extends Ll{getChild(e){let t=new xt(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=>ht(async()=>{if(!t.ignoreAgent)try{await t.handleToolError?.(e,this.runId,this._parentRunId,this.tags)}catch(r){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleToolError: ${r}`),t.raiseError)throw r}},t.awaitHandlers)))}async handleToolEnd(e){await Promise.all(this.handlers.map(t=>ht(async()=>{if(!t.ignoreAgent)try{await t.handleToolEnd?.(e,this.runId,this._parentRunId,this.tags)}catch(r){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleToolEnd: ${r}`),t.raiseError)throw r}},t.awaitHandlers)))}},xt=class zl extends M${handlers=[];inheritableHandlers=[];tags=[];inheritableTags=[];metadata={};inheritableMetadata={};name="callback_manager";_parentRunId;constructor(t,r){super(),this.handlers=r?.handlers??this.handlers,this.inheritableHandlers=r?.inheritableHandlers??this.inheritableHandlers,this.tags=r?.tags??this.tags,this.inheritableTags=r?.inheritableTags??this.inheritableTags,this.metadata=r?.metadata??this.metadata,this.inheritableMetadata=r?.inheritableMetadata??this.inheritableMetadata,this._parentRunId=t}getParentRunId(){return this._parentRunId}async handleLLMStart(t,r,n=void 0,i=void 0,s=void 0,o=void 0,a=void 0,c=void 0){return Promise.all(r.map(async(u,l)=>{let p=l===0&&n?n:sn();return await Promise.all(this.handlers.map(f=>{if(!f.ignoreLLM)return zo(f)&&f._createRunForLLMStart(t,[u],p,this._parentRunId,s,this.tags,this.metadata,c),ht(async()=>{try{await f.handleLLMStart?.(t,[u],p,this._parentRunId,s,this.tags,this.metadata,c)}catch(d){if((f.raiseError?console.error:console.warn)(`Error in handler ${f.constructor.name}, handleLLMStart: ${d}`),f.raiseError)throw d}},f.awaitHandlers)})),new wv(p,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChatModelStart(t,r,n=void 0,i=void 0,s=void 0,o=void 0,a=void 0,c=void 0){return Promise.all(r.map(async(u,l)=>{let p=l===0&&n?n:sn();return await Promise.all(this.handlers.map(f=>{if(!f.ignoreLLM)return zo(f)&&f._createRunForChatModelStart(t,[u],p,this._parentRunId,s,this.tags,this.metadata,c),ht(async()=>{try{if(f.handleChatModelStart)await f.handleChatModelStart?.(t,[u],p,this._parentRunId,s,this.tags,this.metadata,c);else if(f.handleLLMStart){let d=_c(u);await f.handleLLMStart?.(t,[d],p,this._parentRunId,s,this.tags,this.metadata,c)}}catch(d){if((f.raiseError?console.error:console.warn)(`Error in handler ${f.constructor.name}, handleLLMStart: ${d}`),f.raiseError)throw d}},f.awaitHandlers)})),new wv(p,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChainStart(t,r,n=sn(),i=void 0,s=void 0,o=void 0,a=void 0,c=void 0,u=void 0){return await Promise.all(this.handlers.map(l=>{if(!l.ignoreChain)return zo(l)&&l._createRunForChainStart(t,r,n,this._parentRunId,this.tags,this.metadata,i,a,u),ht(async()=>{try{await l.handleChainStart?.(t,r,n,this._parentRunId,this.tags,this.metadata,i,a,u)}catch(p){if((l.raiseError?console.error:console.warn)(`Error in handler ${l.constructor.name}, handleChainStart: ${p}`),l.raiseError)throw p}},l.awaitHandlers)})),new D$(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleToolStart(t,r,n=sn(),i=void 0,s=void 0,o=void 0,a=void 0){return await Promise.all(this.handlers.map(c=>{if(!c.ignoreAgent)return zo(c)&&c._createRunForToolStart(t,r,n,this._parentRunId,this.tags,this.metadata,a),ht(async()=>{try{await c.handleToolStart?.(t,r,n,this._parentRunId,this.tags,this.metadata,a)}catch(u){if((c.raiseError?console.error:console.warn)(`Error in handler ${c.constructor.name}, handleToolStart: ${u}`),c.raiseError)throw u}},c.awaitHandlers)})),new z$(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleRetrieverStart(t,r,n=sn(),i=void 0,s=void 0,o=void 0,a=void 0){return await Promise.all(this.handlers.map(c=>{if(!c.ignoreRetriever)return zo(c)&&c._createRunForRetrieverStart(t,r,n,this._parentRunId,this.tags,this.metadata,a),ht(async()=>{try{await c.handleRetrieverStart?.(t,r,n,this._parentRunId,this.tags,this.metadata,a)}catch(u){if((c.raiseError?console.error:console.warn)(`Error in handler ${c.constructor.name}, handleRetrieverStart: ${u}`),c.raiseError)throw u}},c.awaitHandlers)})),new j$(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleCustomEvent(t,r,n,i,s){await Promise.all(this.handlers.map(o=>ht(async()=>{if(!o.ignoreCustomEvent)try{await o.handleCustomEvent?.(t,r,n,this.tags,this.metadata)}catch(a){if((o.raiseError?console.error:console.warn)(`Error in handler ${o.constructor.name}, handleCustomEvent: ${a}`),o.raiseError)throw a}},o.awaitHandlers)))}addHandler(t,r=!0){this.handlers.push(t),r&&this.inheritableHandlers.push(t)}removeHandler(t){this.handlers=this.handlers.filter(r=>r!==t),this.inheritableHandlers=this.inheritableHandlers.filter(r=>r!==t)}setHandlers(t,r=!0){this.handlers=[],this.inheritableHandlers=[];for(let n of t)this.addHandler(n,r)}addTags(t,r=!0){this.removeTags(t),this.tags.push(...t),r&&this.inheritableTags.push(...t)}removeTags(t){this.tags=this.tags.filter(r=>!t.includes(r)),this.inheritableTags=this.inheritableTags.filter(r=>!t.includes(r))}addMetadata(t,r=!0){this.metadata={...this.metadata,...t},r&&(this.inheritableMetadata={...this.inheritableMetadata,...t})}removeMetadata(t){for(let r of Object.keys(t))delete this.metadata[r],delete this.inheritableMetadata[r]}copy(t=[],r=!0){let n=new zl(this._parentRunId);for(let i of this.handlers){let s=this.inheritableHandlers.includes(i);n.addHandler(i,s)}for(let i of this.tags){let s=this.inheritableTags.includes(i);n.addTags([i],s)}for(let i of Object.keys(this.metadata)){let s=Object.keys(this.inheritableMetadata).includes(i);n.addMetadata({[i]:this.metadata[i]},s)}for(let i of t)n.handlers.filter(s=>s.name==="console_callback_handler").some(s=>s.name===i.name)||n.addHandler(i,r);return n}static fromHandlers(t){class r extends Fi{name=sn();constructor(){super(),Object.assign(this,t)}}let n=new this;return n.addHandler(new r),n}static configure(t,r,n,i,s,o,a){return this._configureSync(t,r,n,i,s,o,a)}static _configureSync(t,r,n,i,s,o,a){let c;(t||r)&&(Array.isArray(t)||!t?(c=new zl,c.setHandlers(t?.map(yc)??[],!0)):c=t,c=c.copy(Array.isArray(r)?r.map(yc):r?.handlers,!1));let u=Pe("LANGCHAIN_VERBOSE")==="true"||a?.verbose,l=Dl.getTraceableRunTree()?.tracingEnabled??N$(),p=l||(Pe("LANGCHAIN_TRACING")??!1);if(u||p){if(c||(c=new zl),u&&!c.handlers.some(f=>f.name===Xf.prototype.name)){let f=new Xf;c.addHandler(f,!0)}if(p&&!c.handlers.some(f=>f.name==="langchain_tracer")&&l){let f=new Dl;c.addHandler(f,!0)}if(l){let f=Dl.getTraceableRunTree();f&&c._parentRunId===void 0&&(c._parentRunId=f.id,c.handlers.find(m=>m.name==="langchain_tracer")?.updateFromRunTree(f))}}for(let{contextVar:f,inheritable:d=!0,handlerClass:m,envVar:h}of R$()){let b=h&&Pe(h)==="true"&&m,_,y=f!==void 0?bv(f):void 0;y&&sy(y)?_=y:b&&(_=new m({})),_!==void 0&&(c||(c=new zl),c.handlers.some(x=>x.name===_.name)||c.addHandler(_,d))}return(n||i)&&c&&(c.addTags(n??[]),c.addTags(i??[],!1)),(s||o)&&c&&(c.addMetadata(s??{}),c.addMetadata(o??{},!1)),c}};function yc(e){return"name"in e?e:Fi.fromMethods(e)}var Iv=class{getStore(){}run(e,t){return t()}enterWith(e){}},TF=new Iv,L$=Symbol.for("lc:child_config"),OF=class{getInstance(){return Ls()??TF}getRunnableConfig(){return this.getInstance().getStore()?.extra?.[L$]}runWithConfig(e,t,r){let n=xt._configureSync(e?.callbacks,void 0,e?.tags,void 0,e?.metadata),i=this.getInstance(),s=i.getStore(),o=n?.getParentRunId(),a=n?.handlers?.find(u=>u?.name==="langchain_tracer"),c;return a&&o?c=a.getRunTreeWithTracingConfig(o):r||(c=new Tn({name:"<runnable_lambda>",tracingEnabled:!1})),c&&(c.extra={...c.extra,[L$]:e}),s!==void 0&&s[zs]!==void 0&&(c===void 0&&(c={}),c[zs]=s[zs]),i.run(c,t)}initializeGlobalInstance(e){Ls()===void 0&&C$(e)}},Ze=new OF;var Sv={};M(Sv,{AsyncLocalStorageProviderSingleton:()=>Ze,MockAsyncLocalStorage:()=>Iv,_CONTEXT_VARIABLES_KEY:()=>zs});var sm=25;async function Et(e){return xt._configureSync(e?.callbacks,void 0,e?.tags,void 0,e?.metadata)}function Dt(...e){let t={};for(let r of e.filter(n=>!!n))for(let n of Object.keys(r))if(n==="metadata")t[n]={...t[n],...r[n]};else if(n==="tags"){let i=t[n]??[];t[n]=[...new Set(i.concat(r[n]??[]))]}else if(n==="configurable")t[n]={...t[n],...r[n]};else if(n==="timeout")t.timeout===void 0?t.timeout=r.timeout:r.timeout!==void 0&&(t.timeout=Math.min(t.timeout,r.timeout));else if(n==="signal")t.signal===void 0?t.signal=r.signal:r.signal!==void 0&&("any"in AbortSignal?t.signal=AbortSignal.any([t.signal,r.signal]):t.signal=r.signal);else if(n==="callbacks"){let i=t.callbacks,s=r.callbacks;if(Array.isArray(s))if(!i)t.callbacks=s;else if(Array.isArray(i))t.callbacks=i.concat(s);else{let o=i.copy();for(let a of s)o.addHandler(yc(a),!0);t.callbacks=o}else if(s)if(!i)t.callbacks=s;else if(Array.isArray(i)){let o=s.copy();for(let a of i)o.addHandler(yc(a),!0);t.callbacks=o}else t.callbacks=new xt(s._parentRunId,{handlers:i.handlers.concat(s.handlers),inheritableHandlers:i.inheritableHandlers.concat(s.inheritableHandlers),tags:Array.from(new Set(i.tags.concat(s.tags))),inheritableTags:Array.from(new Set(i.inheritableTags.concat(s.inheritableTags))),metadata:{...i.metadata,...s.metadata}})}else{let i=n;t[i]=r[i]??t[i]}return t}var $F=new Set(["string","number","boolean"]);function $e(e){let t=Ze.getRunnableConfig(),r={tags:[],metadata:{},recursionLimit:25,runId:void 0};if(t){let{runId:n,runName:i,...s}=t;r=Object.entries(s).reduce((o,[a,c])=>(c!==void 0&&(o[a]=c),o),r)}if(e&&(r=Object.entries(e).reduce((n,[i,s])=>(s!==void 0&&(n[i]=s),n),r)),r?.configurable)for(let n of Object.keys(r.configurable))$F.has(typeof r.configurable[n])&&!r.metadata?.[n]&&(r.metadata||(r.metadata={}),r.metadata[n]=r.configurable[n]);if(r.timeout!==void 0){if(r.timeout<=0)throw new Error("Timeout must be a positive number");let n=r.timeout,i=AbortSignal.timeout(n);r.metadata||(r.metadata={}),r.metadata.timeoutMs===void 0&&(r.metadata.timeoutMs=n),r.signal!==void 0?"any"in AbortSignal&&(r.signal=AbortSignal.any([r.signal,i])):r.signal=i,delete r.timeout}return r}function Ne(e={},{callbacks:t,maxConcurrency:r,recursionLimit:n,runName:i,configurable:s,runId:o}={}){let a=$e(e);return t!==void 0&&(delete a.runName,a.callbacks=t),n!==void 0&&(a.recursionLimit=n),r!==void 0&&(a.maxConcurrency=r),i!==void 0&&(a.runName=i),s!==void 0&&(a.configurable={...a.configurable,...s}),o!==void 0&&delete a.runId,a}function hr(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 ln(e,t){if(t===void 0)return e;let r;return Promise.race([e.catch(n=>{if(!t?.aborted)throw n}),new Promise((n,i)=>{r=()=>{i(Us(t))},t.addEventListener("abort",r),t.aborted&&i(Us(t))})]).finally(()=>t.removeEventListener("abort",r))}function Us(e){return e?.reason instanceof Error?e.reason:typeof e?.reason=="string"?new Error(e.reason):new Error("Aborted")}var kv={};M(kv,{AsyncGeneratorWithSetup:()=>Fs,IterableReadableStream:()=>kt,atee:()=>om,concat:()=>Vr,pipeGeneratorWithSetup:()=>Av});var kt=class Ev extends ReadableStream{reader;ensureReader(){this.reader||(this.reader=this.getReader())}async next(){this.ensureReader();try{let t=await this.reader.read();return t.done?(this.reader.releaseLock(),{done:!0,value:void 0}):{done:!1,value:t.value}}catch(t){throw this.reader.releaseLock(),t}}async return(){if(this.ensureReader(),this.locked){let t=this.reader.cancel();this.reader.releaseLock(),await t}return{done:!0,value:void 0}}async throw(t){if(this.ensureReader(),this.locked){let r=this.reader.cancel();this.reader.releaseLock(),await r}throw t}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}static fromReadableStream(t){let r=t.getReader();return new Ev({start(n){return i();function i(){return r.read().then(({done:s,value:o})=>{if(s){n.close();return}return n.enqueue(o),i()})}},cancel(){r.releaseLock()}})}static fromAsyncGenerator(t){return new Ev({async pull(r){let{value:n,done:i}=await t.next();i&&r.close(),r.enqueue(n)},async cancel(r){await t.return(r)}})}};function om(e,t=2){let r=Array.from({length:t},()=>[]);return r.map(async function*(i){for(;;)if(i.length===0){let s=await e.next();for(let o of r)o.push(s)}else{if(i[0].done)return;yield i.shift().value}})}function Vr(e,t){if(Array.isArray(e)&&Array.isArray(t))return e.concat(t);if(typeof e=="string"&&typeof t=="string")return e+t;if(typeof e=="number"&&typeof t=="number")return e+t;if("concat"in e&&typeof e.concat=="function")return e.concat(t);if(typeof e=="object"&&typeof t=="object"){let r={...e};for(let[n,i]of Object.entries(t))n in r&&!Array.isArray(r[n])?r[n]=Vr(r[n],i):r[n]=i;return r}else throw new Error(`Cannot concat ${typeof e} and ${typeof t}`)}var Fs=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)=>{Ze.runWithConfig(hr(e.config),async()=>{this.firstResult=e.generator.next(),e.startSetup?this.firstResult.then(e.startSetup).then(t,r):this.firstResult.then(n=>t(void 0),r)},!0)})}async next(...e){return this.signal?.throwIfAborted(),this.firstResultUsed?Ze.runWithConfig(hr(this.config),this.signal?async()=>ln(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 Av(e,t,r,n,...i){let s=new Fs({generator:t,startSetup:r,signal:n}),o=await s.setup;return{output:e(s,o,...i),setup:o}}var CF=Object.prototype.hasOwnProperty;function cm(e,t){return CF.call(e,t)}function um(e){if(Array.isArray(e)){let r=new Array(e.length);for(let n=0;n<r.length;n++)r[n]=""+n;return r}if(Object.keys)return Object.keys(e);let t=[];for(let r in e)cm(e,r)&&t.push(r);return t}function gr(e){switch(typeof e){case"object":return JSON.parse(JSON.stringify(e));case"undefined":return null;default:return e}}function lm(e){let t=0,r=e.length,n;for(;t<r;){if(n=e.charCodeAt(t),n>=48&&n<=57){t++;continue}return!1}return!0}function qi(e){return e.indexOf("/")===-1&&e.indexOf("~")===-1?e:e.replace(/~/g,"~0").replace(/\//g,"~1")}function pm(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function am(e){if(e===void 0)return!0;if(e){if(Array.isArray(e)){for(let r=0,n=e.length;r<n;r++)if(am(e[r]))return!0}else if(typeof e=="object"){let r=um(e),n=r.length;for(var t=0;t<n;t++)if(am(e[r[t]]))return!0}}return!1}function U$(e,t){let r=[e];for(let n in t){let i=typeof t[n]=="object"?JSON.stringify(t[n],null,2):t[n];typeof i<"u"&&r.push(`${n}: ${i}`)}return r.join(`
|
|
58
|
+
`)}var dm=class extends Error{constructor(e,t,r,n,i){super(U$(e,{name:t,index:r,operation:n,tree:i})),this.name=t,this.index=r,this.operation=n,this.tree=i,Object.setPrototypeOf(this,new.target.prototype),this.message=U$(e,{name:t,index:r,operation:n,tree:i})}};var Ov={};M(Ov,{JsonPatchError:()=>gt,_areEquals:()=>Ul,applyOperation:()=>Vo,applyPatch:()=>Bs,applyReducer:()=>RF,deepClone:()=>PF,getValueByPointer:()=>fm,validate:()=>F$,validator:()=>mm});var gt=dm,PF=gr;function Tv(e){return Object.getOwnPropertyNames(Object.prototype).includes(e)}var vc={add:function(e,t,r){if(Tv(t))throw new TypeError("JSON-Patch: modifying `__proto__`, `constructor`, or `prototype` prop is banned for security reasons");return e[t]=this.value,{newDocument:r}},remove:function(e,t,r){if(Tv(t))throw new TypeError("JSON-Patch: modifying `__proto__`, `constructor`, or `prototype` prop is banned for security reasons");var n=e[t];return delete e[t],{newDocument:r,removed:n}},replace:function(e,t,r){if(Tv(t))throw new TypeError("JSON-Patch: modifying `__proto__`, `constructor`, or `prototype` prop is banned for security reasons");var n=e[t];return e[t]=this.value,{newDocument:r,removed:n}},move:function(e,t,r){let n=fm(r,this.path);n&&(n=gr(n));let i=Vo(r,{op:"remove",path:this.from}).removed;return Vo(r,{op:"add",path:this.path,value:i}),{newDocument:r,removed:n}},copy:function(e,t,r){let n=fm(r,this.from);return Vo(r,{op:"add",path:this.path,value:gr(n)}),{newDocument:r}},test:function(e,t,r){return{newDocument:r,test:Ul(e[t],this.value)}},_get:function(e,t,r){return this.value=e[t],{newDocument:r}}},NF={add:function(e,t,r){return lm(t)?e.splice(t,0,this.value):e[t]=this.value,{newDocument:r,index:t}},remove:function(e,t,r){var n=e.splice(t,1);return{newDocument:r,removed:n[0]}},replace:function(e,t,r){var n=e[t];return e[t]=this.value,{newDocument:r,removed:n}},move:vc.move,copy:vc.copy,test:vc.test,_get:vc._get};function fm(e,t){if(t=="")return e;var r={op:"_get",path:t};return Vo(e,r),r.value}function Vo(e,t,r=!1,n=!0,i=!0,s=0){if(r&&(typeof r=="function"?r(t,0,e,t.path):mm(t,0)),t.path===""){let o={newDocument:e};if(t.op==="add")return o.newDocument=t.value,o;if(t.op==="replace")return o.newDocument=t.value,o.removed=e,o;if(t.op==="move"||t.op==="copy")return o.newDocument=fm(e,t.from),t.op==="move"&&(o.removed=e),o;if(t.op==="test"){if(o.test=Ul(e,t.value),o.test===!1)throw new gt("Test operation failed","TEST_OPERATION_FAILED",s,t,e);return o.newDocument=e,o}else{if(t.op==="remove")return o.removed=e,o.newDocument=null,o;if(t.op==="_get")return t.value=e,o;if(r)throw new gt("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",s,t,e);return o}}else{n||(e=gr(e));let a=(t.path||"").split("/"),c=e,u=1,l=a.length,p,f,d;for(typeof r=="function"?d=r:d=mm;;){if(f=a[u],f&&f.indexOf("~")!=-1&&(f=pm(f)),i&&(f=="__proto__"||f=="prototype"&&u>0&&a[u-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(r&&p===void 0&&(c[f]===void 0?p=a.slice(0,u).join("/"):u==l-1&&(p=t.path),p!==void 0&&d(t,0,e,p)),u++,Array.isArray(c)){if(f==="-")f=c.length;else{if(r&&!lm(f))throw new gt("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",s,t,e);lm(f)&&(f=~~f)}if(u>=l){if(r&&t.op==="add"&&f>c.length)throw new gt("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",s,t,e);let m=NF[t.op].call(t,c,f,e);if(m.test===!1)throw new gt("Test operation failed","TEST_OPERATION_FAILED",s,t,e);return m}}else if(u>=l){let m=vc[t.op].call(t,c,f,e);if(m.test===!1)throw new gt("Test operation failed","TEST_OPERATION_FAILED",s,t,e);return m}if(c=c[f],r&&u<l&&(!c||typeof c!="object"))throw new gt("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",s,t,e)}}}function Bs(e,t,r,n=!0,i=!0){if(r&&!Array.isArray(t))throw new gt("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");n||(e=gr(e));let s=new Array(t.length);for(let o=0,a=t.length;o<a;o++)s[o]=Vo(e,t[o],r,!0,i,o),e=s[o].newDocument;return s.newDocument=e,s}function RF(e,t,r){let n=Vo(e,t);if(n.test===!1)throw new gt("Test operation failed","TEST_OPERATION_FAILED",r,t,e);return n.newDocument}function mm(e,t,r,n){if(typeof e!="object"||e===null||Array.isArray(e))throw new gt("Operation is not an object","OPERATION_NOT_AN_OBJECT",t,e,r);if(vc[e.op]){if(typeof e.path!="string")throw new gt("Operation `path` property is not a string","OPERATION_PATH_INVALID",t,e,r);if(e.path.indexOf("/")!==0&&e.path.length>0)throw new gt('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",t,e,r);if((e.op==="move"||e.op==="copy")&&typeof e.from!="string")throw new gt("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",t,e,r);if((e.op==="add"||e.op==="replace"||e.op==="test")&&e.value===void 0)throw new gt("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",t,e,r);if((e.op==="add"||e.op==="replace"||e.op==="test")&&am(e.value))throw new gt("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",t,e,r);if(r){if(e.op=="add"){var i=e.path.split("/").length,s=n.split("/").length;if(i!==s+1&&i!==s)throw new gt("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",t,e,r)}else if(e.op==="replace"||e.op==="remove"||e.op==="_get"){if(e.path!==n)throw new gt("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",t,e,r)}else if(e.op==="move"||e.op==="copy"){var o={op:"_get",path:e.from,value:void 0},a=F$([o],r);if(a&&a.name==="OPERATION_PATH_UNRESOLVABLE")throw new gt("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",t,e,r)}}}else throw new gt("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",t,e,r)}function F$(e,t,r){try{if(!Array.isArray(e))throw new gt("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(t)Bs(gr(t),gr(e),r||!0);else{r=r||mm;for(var n=0;n<e.length;n++)r(e[n],n,t,void 0)}}catch(i){if(i instanceof gt)return i;throw i}}function Ul(e,t){if(e===t)return!0;if(e&&t&&typeof e=="object"&&typeof t=="object"){var r=Array.isArray(e),n=Array.isArray(t),i,s,o;if(r&&n){if(s=e.length,s!=t.length)return!1;for(i=s;i--!==0;)if(!Ul(e[i],t[i]))return!1;return!0}if(r!=n)return!1;var a=Object.keys(e);if(s=a.length,s!==Object.keys(t).length)return!1;for(i=s;i--!==0;)if(!t.hasOwnProperty(a[i]))return!1;for(i=s;i--!==0;)if(o=a[i],!Ul(e[o],t[o]))return!1;return!0}return e!==e&&t!==t}function B$(e,t,r,n,i){if(t!==e){typeof t.toJSON=="function"&&(t=t.toJSON());for(var s=um(t),o=um(e),a=!1,c=!1,u=o.length-1;u>=0;u--){var l=o[u],p=e[l];if(cm(t,l)&&!(t[l]===void 0&&p!==void 0&&Array.isArray(t)===!1)){var f=t[l];typeof p=="object"&&p!=null&&typeof f=="object"&&f!=null&&Array.isArray(p)===Array.isArray(f)?B$(p,f,r,n+"/"+qi(l),i):p!==f&&(a=!0,i&&r.push({op:"test",path:n+"/"+qi(l),value:gr(p)}),r.push({op:"replace",path:n+"/"+qi(l),value:gr(f)}))}else Array.isArray(e)===Array.isArray(t)?(i&&r.push({op:"test",path:n+"/"+qi(l),value:gr(p)}),r.push({op:"remove",path:n+"/"+qi(l)}),c=!0):(i&&r.push({op:"test",path:n,value:e}),r.push({op:"replace",path:n,value:t}),a=!0)}if(!(!c&&s.length==o.length))for(var u=0;u<s.length;u++){var l=s[u];!cm(e,l)&&t[l]!==void 0&&r.push({op:"add",path:n+"/"+qi(l),value:gr(t[l])})}}}function Vs(e,t,r=!1){var n=[];return B$(e,t,n,"",r),n}var oQ={...Ov,JsonPatchError:dm,deepClone:gr,escapePathComponent:qi,unescapePathComponent:pm};var Cv={};M(Cv,{LogStreamCallbackHandler:()=>gm,RunLog:()=>hm,RunLogPatch:()=>ui,isLogStreamHandler:()=>Pv});var ui=class{ops;constructor(e){this.ops=e.ops??[]}concat(e){let t=this.ops.concat(e.ops),r=Bs({},t);return new hm({ops:t,state:r[r.length-1].newDocument})}},hm=class $v extends ui{state;constructor(t){super(t),this.state=t.state}concat(t){let r=this.ops.concat(t.ops),n=Bs(this.state,t.ops);return new $v({ops:r,state:n[n.length-1].newDocument})}static fromRunLogPatch(t){let r=Bs({},t.ops);return new $v({ops:t.ops,state:r[r.length-1].newDocument})}},Pv=e=>e.name==="log_stream_tracer";async function V$(e,t){if(t==="original")throw new Error("Do not assign inputs with original schema drop the key for now. When inputs are added to streamLog they should be added with standardized schema for streaming events.");let{inputs:r}=e;if(["retriever","llm","prompt"].includes(e.run_type))return r;if(!(Object.keys(r).length===1&&r?.input===""))return r.input}async function Z$(e,t){let{outputs:r}=e;return t==="original"||["retriever","llm","prompt"].includes(e.run_type)?r:r!==void 0&&Object.keys(r).length===1&&r?.output!==void 0?r.output:r}function MF(e){return e!==void 0&&e.message!==void 0}var gm=class extends Zt{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=kt.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=this.includeNames===void 0&&this.includeTags===void 0&&this.includeTypes===void 0;return this.includeNames!==void 0&&(r=r||this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(r=r||this.includeTypes.includes(e.run_type)),this.includeTags!==void 0&&(r=r||t.find(n=>this.includeTags?.includes(n))!==void 0),this.excludeNames!==void 0&&(r=r&&!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(r=r&&!this.excludeTypes.includes(e.run_type)),this.excludeTags!==void 0&&(r=r&&t.every(n=>!this.excludeTags?.includes(n))),r}async*tapOutputIterable(e,t){for await(let r of t){if(e!==this.rootId){let n=this.keyMapByRunId[e];n&&await this.writer.write(new ui({ops:[{op:"add",path:`/logs/${n}/streamed_output/-`,value:r}]}))}yield r}}async onRunCreate(e){if(this.rootId===void 0&&(this.rootId=e.id,await this.writer.write(new ui({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;this.counterMapByRunName[e.name]===void 0&&(this.counterMapByRunName[e.name]=0),this.counterMapByRunName[e.name]+=1;let t=this.counterMapByRunName[e.name];this.keyMapByRunId[e.id]=t===1?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};this._schemaFormat==="streaming_events"&&(r.inputs=await V$(e,this._schemaFormat)),await this.writer.write(new ui({ops:[{op:"add",path:`/logs/${this.keyMapByRunId[e.id]}`,value:r}]}))}async onRunUpdate(e){try{let t=this.keyMapByRunId[e.id];if(t===void 0)return;let r=[];this._schemaFormat==="streaming_events"&&r.push({op:"replace",path:`/logs/${t}/inputs`,value:await V$(e,this._schemaFormat)}),r.push({op:"add",path:`/logs/${t}/final_output`,value:await Z$(e,this._schemaFormat)}),e.end_time!==void 0&&r.push({op:"add",path:`/logs/${t}/end_time`,value:new Date(e.end_time).toISOString()});let n=new ui({ops:r});await this.writer.write(n)}finally{if(e.id===this.rootId){let t=new ui({ops:[{op:"replace",path:"/final_output",value:await Z$(e,this._schemaFormat)}]});await this.writer.write(t),this.autoClose&&await this.writer.close()}}}async onLLMNewToken(e,t,r){let n=this.keyMapByRunId[e.id];if(n===void 0)return;let i=e.inputs.messages!==void 0,s;i?MF(r?.chunk)?s=r?.chunk:s=new nt({id:`run-${e.id}`,content:t}):s=t;let o=new ui({ops:[{op:"add",path:`/logs/${n}/streamed_output_str/-`,value:t},{op:"add",path:`/logs/${n}/streamed_output/-`,value:s}]});await this.writer.write(o)}};var Nv={};M(Nv,{ChatGenerationChunk:()=>Zr,GenerationChunk:()=>li,RUN_KEY:()=>Zo});var Zo="__run",li=class G${text;generationInfo;constructor(t){this.text=t.text,this.generationInfo=t.generationInfo}concat(t){return new G$({text:this.text+t.text,generationInfo:{...this.generationInfo,...t.generationInfo}})}},Zr=class K$ extends li{message;constructor(t){super(t),this.message=t.message}concat(t){return new K$({text:this.text+t.text,generationInfo:{...this.generationInfo,...t.generationInfo},message:this.message.concat(t.message)})}};var jF=Object.prototype.toString,DF=e=>jF.call(e)==="[object Error]",zF=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 q$(e){if(!(e&&DF(e)&&e.name==="TypeError"&&typeof e.message=="string"))return!1;let{message:r,stack:n}=e;return r==="Load failed"?n===void 0||"__sentry_captured__"in e:r.startsWith("error sending request for url")?!0:zF.has(r)}function LF(e){if(typeof e=="number"){if(e<0)throw new TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(e))throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(e!==void 0)throw new TypeError("Expected `retries` to be a number or Infinity.")}function _m(e,t,{min:r=0,allowInfinity:n=!1}={}){if(t!==void 0){if(typeof t!="number"||Number.isNaN(t))throw new TypeError(`Expected \`${e}\` to be a number${n?" or Infinity":""}.`);if(!n&&!Number.isFinite(t))throw new TypeError(`Expected \`${e}\` to be a finite number.`);if(t<r)throw new TypeError(`Expected \`${e}\` to be \u2265 ${r}.`)}}var UF=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}};function FF(e,t){let r=Math.max(1,e+1),n=t.randomize?Math.random()+1:1,i=Math.round(n*t.minTimeout*t.factor**(r-1));return i=Math.min(i,t.maxTimeout),i}function H$(e,t){return Number.isFinite(t)?t-(performance.now()-e):t}async function BF({error:e,attemptNumber:t,retriesConsumed:r,startTime:n,options:i}){let s=e instanceof Error?e:new TypeError(`Non-error was thrown: "${e}". You should only throw errors.`);if(s instanceof UF)throw s.originalError;let o=Number.isFinite(i.retries)?Math.max(0,i.retries-r):i.retries,a=i.maxRetryTime??Number.POSITIVE_INFINITY,c=Object.freeze({error:s,attemptNumber:t,retriesLeft:o,retriesConsumed:r});if(await i.onFailedAttempt(c),H$(n,a)<=0)throw s;let u=await i.shouldConsumeRetry(c),l=H$(n,a);if(l<=0||o<=0)throw s;if(s instanceof TypeError&&!q$(s)){if(u)throw s;return i.signal?.throwIfAborted(),!1}if(!await i.shouldRetry(c))throw s;if(!u)return i.signal?.throwIfAborted(),!1;let p=FF(r,i),f=Math.min(p,l);return f>0&&await new Promise((d,m)=>{let h=()=>{clearTimeout(b),i.signal?.removeEventListener("abort",h),m(i.signal.reason)},b=setTimeout(()=>{i.signal?.removeEventListener("abort",h),d()},f);i.unref&&b.unref?.(),i.signal?.addEventListener("abort",h,{once:!0})}),i.signal?.throwIfAborted(),!0}async function Fl(e,t={}){if(t={...t},LF(t.retries),Object.hasOwn(t,"forever"))throw new 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??=Number.POSITIVE_INFINITY,t.maxRetryTime??=Number.POSITIVE_INFINITY,t.randomize??=!1,t.onFailedAttempt??=()=>{},t.shouldRetry??=()=>!0,t.shouldConsumeRetry??=()=>!0,_m("factor",t.factor,{min:0,allowInfinity:!1}),_m("minTimeout",t.minTimeout,{min:0,allowInfinity:!1}),_m("maxTimeout",t.maxTimeout,{min:0,allowInfinity:!0}),_m("maxRetryTime",t.maxRetryTime,{min:0,allowInfinity:!0}),t.factor>0||(t.factor=1),t.signal?.throwIfAborted();let r=0,n=0,i=performance.now();for(;!Number.isFinite(t.retries)||n<=t.retries;){r++;try{t.signal?.throwIfAborted();let s=await e(r);return t.signal?.throwIfAborted(),s}catch(s){await BF({error:s,attemptNumber:r,retriesConsumed:n,startTime:i,options:t})&&n++}}throw new Error("Retry attempts exhausted without throwing an error.")}var ym=Ps(Cf(),1),Rv={};M(Rv,{AsyncCaller:()=>Hi});var VF=[400,401,402,403,404,405,406,407,409],ZF=e=>{if(typeof e!="object"||e===null)return;if("message"in e&&typeof e.message=="string"&&(e.message.startsWith("Cancel")||e.message.startsWith("AbortError"))||"name"in e&&typeof e.name=="string"&&e.name==="AbortError"||"code"in e&&typeof e.code=="string"&&e.code==="ECONNABORTED")throw e;let t="response"in e&&typeof e.response=="object"&&e.response!==null&&"status"in e.response&&typeof e.response.status=="number"?e.response.status:void 0,r="status"in e&&typeof e.status=="number"?e.status:void 0,n=t??r;if(n&&VF.includes(+n))throw e;if(("error"in e&&typeof e.error=="object"&&e.error!==null&&"code"in e.error&&typeof e.error.code=="string"?e.error.code:void 0)==="insufficient_quota"){let s=new Error("message"in e&&typeof e.message=="string"?e.message:"Insufficient quota");throw s.name="InsufficientQuotaError",s}},Hi=class{maxConcurrency;maxRetries;onFailedAttempt;queue;constructor(e){this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,this.onFailedAttempt=e.onFailedAttempt??ZF;let t="default"in ym.default?ym.default.default:ym.default;this.queue=new t({concurrency:this.maxConcurrency})}async call(e,...t){return this.queue.add(()=>Fl(()=>e(...t).catch(r=>{throw r instanceof Error?r:new Error(r)}),{onFailedAttempt:({error:r})=>this.onFailedAttempt?.(r),retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(e,t,...r){if(e.signal){let n;return Promise.race([this.call(t,...r),new Promise((i,s)=>{n=()=>{s(Us(e.signal))},e.signal?.addEventListener("abort",n)})]).finally(()=>{e.signal&&n&&e.signal.removeEventListener("abort",n)})}return this.call(t,...r)}fetch(...e){return this.call(()=>fetch(...e).then(t=>t.ok?t:Promise.reject(t)))}};var Qi={};Cs(Qi,{$ZodAny:()=>Iw,$ZodArray:()=>rp,$ZodAsyncError:()=>pi,$ZodBase64:()=>fw,$ZodBase64URL:()=>mw,$ZodBigInt:()=>$m,$ZodBigIntFormat:()=>vw,$ZodBoolean:()=>ep,$ZodCIDRv4:()=>lw,$ZodCIDRv6:()=>pw,$ZodCUID:()=>Qb,$ZodCUID2:()=>ew,$ZodCatch:()=>Uw,$ZodCheck:()=>pt,$ZodCheckBigIntFormat:()=>Ob,$ZodCheckEndsWith:()=>Fb,$ZodCheckGreaterThan:()=>km,$ZodCheckIncludes:()=>Lb,$ZodCheckLengthEquals:()=>Mb,$ZodCheckLessThan:()=>Em,$ZodCheckLowerCase:()=>Db,$ZodCheckMaxLength:()=>Nb,$ZodCheckMaxSize:()=>$b,$ZodCheckMimeType:()=>Vb,$ZodCheckMinLength:()=>Rb,$ZodCheckMinSize:()=>Cb,$ZodCheckMultipleOf:()=>Ab,$ZodCheckNumberFormat:()=>Tb,$ZodCheckOverwrite:()=>Zb,$ZodCheckProperty:()=>Bb,$ZodCheckRegex:()=>jb,$ZodCheckSizeEquals:()=>Pb,$ZodCheckStartsWith:()=>Ub,$ZodCheckStringFormat:()=>Ic,$ZodCheckUpperCase:()=>zb,$ZodCustom:()=>Kw,$ZodCustomStringFormat:()=>_w,$ZodDate:()=>Ew,$ZodDefault:()=>jw,$ZodDiscriminatedUnion:()=>Aw,$ZodE164:()=>hw,$ZodEmail:()=>Wb,$ZodEmoji:()=>Xb,$ZodEnum:()=>Pw,$ZodError:()=>Jl,$ZodFile:()=>Rw,$ZodFunction:()=>th,$ZodGUID:()=>qb,$ZodIPv4:()=>cw,$ZodIPv6:()=>uw,$ZodISODate:()=>sw,$ZodISODateTime:()=>iw,$ZodISODuration:()=>aw,$ZodISOTime:()=>ow,$ZodIntersection:()=>Tw,$ZodJWT:()=>gw,$ZodKSUID:()=>nw,$ZodLazy:()=>Gw,$ZodLiteral:()=>Nw,$ZodMap:()=>$w,$ZodNaN:()=>Fw,$ZodNanoID:()=>Yb,$ZodNever:()=>tp,$ZodNonOptional:()=>zw,$ZodNull:()=>xw,$ZodNullable:()=>Mw,$ZodNumber:()=>Om,$ZodNumberFormat:()=>yw,$ZodObject:()=>kw,$ZodOptional:()=>Sc,$ZodPipe:()=>ip,$ZodPrefault:()=>Dw,$ZodPromise:()=>Zw,$ZodReadonly:()=>Bw,$ZodRealError:()=>xc,$ZodRecord:()=>Ow,$ZodRegistry:()=>Ec,$ZodSet:()=>Cw,$ZodString:()=>Jo,$ZodStringFormat:()=>We,$ZodSuccess:()=>Lw,$ZodSymbol:()=>bw,$ZodTemplateLiteral:()=>Vw,$ZodTransform:()=>np,$ZodTuple:()=>Xo,$ZodType:()=>_e,$ZodULID:()=>tw,$ZodURL:()=>Jb,$ZodUUID:()=>Hb,$ZodUndefined:()=>ww,$ZodUnion:()=>Cm,$ZodUnknown:()=>Gs,$ZodVoid:()=>Sw,$ZodXID:()=>rw,$brand:()=>jv,$constructor:()=>S,$input:()=>Hw,$output:()=>qw,Doc:()=>Ql,JSONSchema:()=>nP,JSONSchemaGenerator:()=>wp,NEVER:()=>Mv,TimePrecision:()=>Xw,_any:()=>yx,_array:()=>bp,_base64:()=>Xm,_base64url:()=>Ym,_bigint:()=>px,_boolean:()=>ux,_catch:()=>xB,_cidrv4:()=>Wm,_cidrv6:()=>Jm,_coercedBigint:()=>dx,_coercedBoolean:()=>lx,_coercedDate:()=>wx,_coercedNumber:()=>nx,_coercedString:()=>Jw,_cuid:()=>Bm,_cuid2:()=>Vm,_custom:()=>$x,_date:()=>bx,_default:()=>vB,_discriminatedUnion:()=>cB,_e164:()=>Qm,_email:()=>Rm,_emoji:()=>Um,_endsWith:()=>mp,_enum:()=>fB,_file:()=>Ox,_float32:()=>sx,_float64:()=>ox,_gt:()=>Xi,_gte:()=>Pr,_guid:()=>op,_includes:()=>dp,_int:()=>ix,_int32:()=>ax,_int64:()=>fx,_intersection:()=>uB,_ipv4:()=>qm,_ipv6:()=>Hm,_isoDate:()=>Qw,_isoDateTime:()=>Yw,_isoDuration:()=>tx,_isoTime:()=>ex,_jwt:()=>eh,_ksuid:()=>Km,_lazy:()=>kB,_length:()=>Tc,_literal:()=>hB,_lowercase:()=>lp,_lt:()=>Ji,_lte:()=>pn,_map:()=>pB,_max:()=>pn,_maxLength:()=>Ac,_maxSize:()=>kc,_mime:()=>hp,_min:()=>Pr,_minLength:()=>qs,_minSize:()=>Qo,_multipleOf:()=>Yo,_nan:()=>xx,_nanoid:()=>Fm,_nativeEnum:()=>mB,_negative:()=>Sx,_never:()=>ap,_nonnegative:()=>kx,_nonoptional:()=>bB,_nonpositive:()=>Ex,_normalize:()=>gp,_null:()=>_x,_nullable:()=>yB,_number:()=>rx,_optional:()=>_B,_overwrite:()=>Yi,_parse:()=>bm,_parseAsync:()=>wm,_pipe:()=>IB,_positive:()=>Ix,_promise:()=>AB,_property:()=>Ax,_readonly:()=>SB,_record:()=>lB,_refine:()=>Cx,_regex:()=>up,_safeParse:()=>xm,_safeParseAsync:()=>Im,_set:()=>dB,_size:()=>cp,_startsWith:()=>fp,_string:()=>Ww,_stringFormat:()=>Nx,_stringbool:()=>Px,_success:()=>wB,_symbol:()=>hx,_templateLiteral:()=>EB,_toLowerCase:()=>yp,_toUpperCase:()=>vp,_transform:()=>gB,_trim:()=>_p,_tuple:()=>Tx,_uint32:()=>cx,_uint64:()=>mx,_ulid:()=>Zm,_undefined:()=>gx,_union:()=>aB,_unknown:()=>Ks,_uppercase:()=>pp,_url:()=>Lm,_uuid:()=>Mm,_uuidv4:()=>jm,_uuidv6:()=>Dm,_uuidv7:()=>zm,_void:()=>vx,_xid:()=>Gm,clone:()=>lt,config:()=>At,flattenError:()=>Xl,formatError:()=>Yl,function:()=>Rx,globalConfig:()=>Bl,globalRegistry:()=>ct,isValidBase64:()=>dw,isValidBase64URL:()=>mC,isValidJWT:()=>hC,locales:()=>sp,parse:()=>di,parseAsync:()=>qo,prettifyError:()=>Wv,regexes:()=>Wo,registry:()=>Nm,safeParse:()=>Jv,safeParseAsync:()=>Xv,toDotPath:()=>J$,toJSONSchema:()=>Hs,treeifyError:()=>Hv,util:()=>G,version:()=>Gb});var Mv=Object.freeze({status:"aborted"});function S(e,t,r){function n(a,c){var u;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(u=a._zod).traits??(u.traits=new Set),a._zod.traits.add(e),t(a,c);for(let l in o.prototype)l in a||Object.defineProperty(a,l,{value:o.prototype[l].bind(a)});a._zod.constr=o,a._zod.def=c}let i=r?.Parent??Object;class s extends i{}Object.defineProperty(s,"name",{value:e});function o(a){var c;let u=r?.Parent?new s:this;n(u,a),(c=u._zod).deferred??(c.deferred=[]);for(let l of u._zod.deferred)l();return u}return Object.defineProperty(o,"init",{value:n}),Object.defineProperty(o,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(e)}),Object.defineProperty(o,"name",{value:e}),o}var jv=Symbol("zod_brand"),pi=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Bl={};function At(e){return e&&Object.assign(Bl,e),Bl}var G={};Cs(G,{BIGINT_FORMAT_RANGES:()=>Kv,Class:()=>zv,NUMBER_FORMAT_RANGES:()=>Gv,aborted:()=>Ko,allowsEval:()=>Bv,assert:()=>WF,assertEqual:()=>GF,assertIs:()=>qF,assertNever:()=>HF,assertNotEqual:()=>KF,assignProp:()=>Fv,cached:()=>Gl,captureStackTrace:()=>vm,cleanEnum:()=>c6,cleanRegex:()=>Kl,clone:()=>lt,createTransparentProxy:()=>t6,defineLazy:()=>Fe,esc:()=>Go,escapeRegex:()=>Wi,extend:()=>i6,finalizeIssue:()=>Gr,floatSafeRemainder:()=>Uv,getElementAtPath:()=>JF,getEnumValues:()=>Zl,getLengthableOrigin:()=>Wl,getParsedType:()=>e6,getSizableOrigin:()=>Hl,isObject:()=>bc,isPlainObject:()=>wc,issue:()=>qv,joinValues:()=>C,jsonStringifyReplacer:()=>Lv,merge:()=>s6,normalizeParams:()=>B,nullish:()=>Zs,numKeys:()=>QF,omit:()=>n6,optionalKeys:()=>Zv,partial:()=>o6,pick:()=>r6,prefixIssues:()=>Cr,primitiveTypes:()=>Vv,promiseAllObject:()=>XF,propertyKeyTypes:()=>ql,randomString:()=>YF,required:()=>a6,stringifyPrimitive:()=>K,unwrapMessage:()=>Vl});function GF(e){return e}function KF(e){return e}function qF(e){}function HF(e){throw new Error}function WF(e){}function Zl(e){let t=Object.values(e).filter(n=>typeof n=="number");return Object.entries(e).filter(([n,i])=>t.indexOf(+n)===-1).map(([n,i])=>i)}function C(e,t="|"){return e.map(r=>K(r)).join(t)}function Lv(e,t){return typeof t=="bigint"?t.toString():t}function Gl(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Zs(e){return e==null}function Kl(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function Uv(e,t){let r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,i=r>n?r:n,s=Number.parseInt(e.toFixed(i).replace(".","")),o=Number.parseInt(t.toFixed(i).replace(".",""));return s%o/10**i}function Fe(e,t,r){Object.defineProperty(e,t,{get(){{let i=r();return e[t]=i,i}throw new Error("cached value already set")},set(i){Object.defineProperty(e,t,{value:i})},configurable:!0})}function Fv(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function JF(e,t){return t?t.reduce((r,n)=>r?.[n],e):e}function XF(e){let t=Object.keys(e),r=t.map(n=>e[n]);return Promise.all(r).then(n=>{let i={};for(let s=0;s<t.length;s++)i[t[s]]=n[s];return i})}function YF(e=10){let t="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<e;n++)r+=t[Math.floor(Math.random()*t.length)];return r}function Go(e){return JSON.stringify(e)}var vm=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function bc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Bv=Gl(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});function wc(e){if(bc(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;let r=t.prototype;return!(bc(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function QF(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}var e6=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":return Array.isArray(e)?"array":e===null?"null":e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?"promise":typeof Map<"u"&&e instanceof Map?"map":typeof Set<"u"&&e instanceof Set?"set":typeof Date<"u"&&e instanceof Date?"date":typeof File<"u"&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},ql=new Set(["string","number","symbol"]),Vv=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Wi(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function lt(e,t,r){let n=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(n._zod.parent=e),n}function B(e){let t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function t6(e){let t;return new Proxy({},{get(r,n,i){return t??(t=e()),Reflect.get(t,n,i)},set(r,n,i,s){return t??(t=e()),Reflect.set(t,n,i,s)},has(r,n){return t??(t=e()),Reflect.has(t,n)},deleteProperty(r,n){return t??(t=e()),Reflect.deleteProperty(t,n)},ownKeys(r){return t??(t=e()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(r,n){return t??(t=e()),Reflect.getOwnPropertyDescriptor(t,n)},defineProperty(r,n,i){return t??(t=e()),Reflect.defineProperty(t,n,i)}})}function K(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function Zv(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var Gv={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},Kv={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function r6(e,t){let r={},n=e._zod.def;for(let i in t){if(!(i in n.shape))throw new Error(`Unrecognized key: "${i}"`);t[i]&&(r[i]=n.shape[i])}return lt(e,{...e._zod.def,shape:r,checks:[]})}function n6(e,t){let r={...e._zod.def.shape},n=e._zod.def;for(let i in t){if(!(i in n.shape))throw new Error(`Unrecognized key: "${i}"`);t[i]&&delete r[i]}return lt(e,{...e._zod.def,shape:r,checks:[]})}function i6(e,t){if(!wc(t))throw new Error("Invalid input to extend: expected a plain object");let r={...e._zod.def,get shape(){let n={...e._zod.def.shape,...t};return Fv(this,"shape",n),n},checks:[]};return lt(e,r)}function s6(e,t){return lt(e,{...e._zod.def,get shape(){let r={...e._zod.def.shape,...t._zod.def.shape};return Fv(this,"shape",r),r},catchall:t._zod.def.catchall,checks:[]})}function o6(e,t,r){let n=t._zod.def.shape,i={...n};if(r)for(let s in r){if(!(s in n))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(i[s]=e?new e({type:"optional",innerType:n[s]}):n[s])}else for(let s in n)i[s]=e?new e({type:"optional",innerType:n[s]}):n[s];return lt(t,{...t._zod.def,shape:i,checks:[]})}function a6(e,t,r){let n=t._zod.def.shape,i={...n};if(r)for(let s in r){if(!(s in i))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(i[s]=new e({type:"nonoptional",innerType:n[s]}))}else for(let s in n)i[s]=new e({type:"nonoptional",innerType:n[s]});return lt(t,{...t._zod.def,shape:i,checks:[]})}function Ko(e,t=0){for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function Cr(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function Vl(e){return typeof e=="string"?e:e?.message}function Gr(e,t,r){let n={...e,path:e.path??[]};if(!e.message){let i=Vl(e.inst?._zod.def?.error?.(e))??Vl(t?.error?.(e))??Vl(r.customError?.(e))??Vl(r.localeError?.(e))??"Invalid input";n.message=i}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function Hl(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function Wl(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function qv(...e){let[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}function c6(e){return Object.entries(e).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}var zv=class{constructor(...t){}};var W$=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),Object.defineProperty(e,"message",{get(){return JSON.stringify(t,Lv,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Jl=S("$ZodError",W$),xc=S("$ZodError",W$,{Parent:Error});function Xl(e,t=r=>r.message){let r={},n=[];for(let i of e.issues)i.path.length>0?(r[i.path[0]]=r[i.path[0]]||[],r[i.path[0]].push(t(i))):n.push(t(i));return{formErrors:n,fieldErrors:r}}function Yl(e,t){let r=t||function(s){return s.message},n={_errors:[]},i=s=>{for(let o of s.issues)if(o.code==="invalid_union"&&o.errors.length)o.errors.map(a=>i({issues:a}));else if(o.code==="invalid_key")i({issues:o.issues});else if(o.code==="invalid_element")i({issues:o.issues});else if(o.path.length===0)n._errors.push(r(o));else{let a=n,c=0;for(;c<o.path.length;){let u=o.path[c];c===o.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(o))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return i(e),n}function Hv(e,t){let r=t||function(s){return s.message},n={errors:[]},i=(s,o=[])=>{var a,c;for(let u of s.issues)if(u.code==="invalid_union"&&u.errors.length)u.errors.map(l=>i({issues:l},u.path));else if(u.code==="invalid_key")i({issues:u.issues},u.path);else if(u.code==="invalid_element")i({issues:u.issues},u.path);else{let l=[...o,...u.path];if(l.length===0){n.errors.push(r(u));continue}let p=n,f=0;for(;f<l.length;){let d=l[f],m=f===l.length-1;typeof d=="string"?(p.properties??(p.properties={}),(a=p.properties)[d]??(a[d]={errors:[]}),p=p.properties[d]):(p.items??(p.items=[]),(c=p.items)[d]??(c[d]={errors:[]}),p=p.items[d]),m&&p.errors.push(r(u)),f++}}};return i(e),n}function J$(e){let t=[];for(let r of e)typeof r=="number"?t.push(`[${r}]`):typeof r=="symbol"?t.push(`[${JSON.stringify(String(r))}]`):/[^\w$]/.test(r)?t.push(`[${JSON.stringify(r)}]`):(t.length&&t.push("."),t.push(r));return t.join("")}function Wv(e){let t=[],r=[...e.issues].sort((n,i)=>n.path.length-i.path.length);for(let n of r)t.push(`\u2716 ${n.message}`),n.path?.length&&t.push(` \u2192 at ${J$(n.path)}`);return t.join(`
|
|
59
|
+
`)}var bm=e=>(t,r,n,i)=>{let s=n?Object.assign(n,{async:!1}):{async:!1},o=t._zod.run({value:r,issues:[]},s);if(o instanceof Promise)throw new pi;if(o.issues.length){let a=new(i?.Err??e)(o.issues.map(c=>Gr(c,s,At())));throw vm(a,i?.callee),a}return o.value},di=bm(xc),wm=e=>async(t,r,n,i)=>{let s=n?Object.assign(n,{async:!0}):{async:!0},o=t._zod.run({value:r,issues:[]},s);if(o instanceof Promise&&(o=await o),o.issues.length){let a=new(i?.Err??e)(o.issues.map(c=>Gr(c,s,At())));throw vm(a,i?.callee),a}return o.value},qo=wm(xc),xm=e=>(t,r,n)=>{let i=n?{...n,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise)throw new pi;return s.issues.length?{success:!1,error:new(e??Jl)(s.issues.map(o=>Gr(o,i,At())))}:{success:!0,data:s.value}},Jv=xm(xc),Im=e=>async(t,r,n)=>{let i=n?Object.assign(n,{async:!0}):{async:!0},s=t._zod.run({value:r,issues:[]},i);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new e(s.issues.map(o=>Gr(o,i,At())))}:{success:!0,data:s.value}},Xv=Im(xc);var Wo={};Cs(Wo,{_emoji:()=>X$,base64:()=>db,base64url:()=>Sm,bigint:()=>vb,boolean:()=>xb,browserEmail:()=>_6,cidrv4:()=>lb,cidrv6:()=>pb,cuid:()=>Yv,cuid2:()=>Qv,date:()=>hb,datetime:()=>_b,domain:()=>y6,duration:()=>ib,e164:()=>mb,email:()=>ob,emoji:()=>ab,extendedDuration:()=>l6,guid:()=>sb,hostname:()=>fb,html5Email:()=>m6,integer:()=>bb,ipv4:()=>cb,ipv6:()=>ub,ksuid:()=>rb,lowercase:()=>Eb,nanoid:()=>nb,null:()=>Ib,number:()=>wb,rfc5322Email:()=>h6,string:()=>yb,time:()=>gb,ulid:()=>eb,undefined:()=>Sb,unicodeEmail:()=>g6,uppercase:()=>kb,uuid:()=>Ho,uuid4:()=>p6,uuid6:()=>d6,uuid7:()=>f6,xid:()=>tb});var Yv=/^[cC][^\s-]{8,}$/,Qv=/^[0-9a-z]+$/,eb=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,tb=/^[0-9a-vA-V]{20}$/,rb=/^[A-Za-z0-9]{27}$/,nb=/^[a-zA-Z0-9_-]{21}$/,ib=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,l6=/^[-+]?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)?)??$/,sb=/^([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})$/,Ho=e=>e?new 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)$/,p6=Ho(4),d6=Ho(6),f6=Ho(7),ob=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,m6=/^[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])?)*$/,h6=/^(([^<>()\[\]\\.,;:\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,}))$/,g6=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,_6=/^[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])?)*$/,X$="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function ab(){return new RegExp(X$,"u")}var cb=/^(?:(?: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])$/,ub=/^(([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})$/,lb=/^((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])$/,pb=/^(([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])$/,db=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Sm=/^[A-Za-z0-9_-]*$/,fb=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,y6=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,mb=/^\+(?:[0-9]){6,14}[0-9]$/,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])))",hb=new RegExp(`^${Y$}$`);function Q$(e){let t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function gb(e){return new RegExp(`^${Q$(e)}$`)}function _b(e){let t=Q$({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-]\\d{2}:\\d{2})");let n=`${t}(?:${r.join("|")})`;return new RegExp(`^${Y$}T(?:${n})$`)}var yb=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},vb=/^\d+n?$/,bb=/^\d+$/,wb=/^-?\d+(?:\.\d+)?/i,xb=/true|false/i,Ib=/null/i;var Sb=/undefined/i;var Eb=/^[^A-Z]*$/,kb=/^[^a-z]*$/;var pt=S("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),tC={number:"number",bigint:"bigint",object:"date"},Em=S("$ZodCheckLessThan",(e,t)=>{pt.init(e,t);let r=tC[typeof t.value];e._zod.onattach.push(n=>{let i=n._zod.bag,s=(t.inclusive?i.maximum:i.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<s&&(t.inclusive?i.maximum=t.value:i.exclusiveMaximum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value<=t.value:n.value<t.value)||n.issues.push({origin:r,code:"too_big",maximum:t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),km=S("$ZodCheckGreaterThan",(e,t)=>{pt.init(e,t);let r=tC[typeof t.value];e._zod.onattach.push(n=>{let i=n._zod.bag,s=(t.inclusive?i.minimum:i.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>s&&(t.inclusive?i.minimum=t.value:i.exclusiveMinimum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value>=t.value:n.value>t.value)||n.issues.push({origin:r,code:"too_small",minimum:t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Ab=S("$ZodCheckMultipleOf",(e,t)=>{pt.init(e,t),e._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%t.value===BigInt(0):Uv(r.value,t.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),Tb=S("$ZodCheckNumberFormat",(e,t)=>{pt.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),n=r?"int":"number",[i,s]=Gv[t.format];e._zod.onattach.push(o=>{let a=o._zod.bag;a.format=t.format,a.minimum=i,a.maximum=s,r&&(a.pattern=bb)}),e._zod.check=o=>{let a=o.value;if(r){if(!Number.isInteger(a)){o.issues.push({expected:n,format:t.format,code:"invalid_type",input:a,inst:e});return}if(!Number.isSafeInteger(a)){a>0?o.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,continue:!t.abort}):o.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,continue:!t.abort});return}}a<i&&o.issues.push({origin:"number",input:a,code:"too_small",minimum:i,inclusive:!0,inst:e,continue:!t.abort}),a>s&&o.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inst:e})}}),Ob=S("$ZodCheckBigIntFormat",(e,t)=>{pt.init(e,t);let[r,n]=Kv[t.format];e._zod.onattach.push(i=>{let s=i._zod.bag;s.format=t.format,s.minimum=r,s.maximum=n}),e._zod.check=i=>{let s=i.value;s<r&&i.issues.push({origin:"bigint",input:s,code:"too_small",minimum:r,inclusive:!0,inst:e,continue:!t.abort}),s>n&&i.issues.push({origin:"bigint",input:s,code:"too_big",maximum:n,inst:e})}}),$b=S("$ZodCheckMaxSize",(e,t)=>{var r;pt.init(e,t),(r=e._zod.def).when??(r.when=n=>{let i=n.value;return!Zs(i)&&i.size!==void 0}),e._zod.onattach.push(n=>{let i=n._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<i&&(n._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let i=n.value;i.size<=t.maximum||n.issues.push({origin:Hl(i),code:"too_big",maximum:t.maximum,input:i,inst:e,continue:!t.abort})}}),Cb=S("$ZodCheckMinSize",(e,t)=>{var r;pt.init(e,t),(r=e._zod.def).when??(r.when=n=>{let i=n.value;return!Zs(i)&&i.size!==void 0}),e._zod.onattach.push(n=>{let i=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>i&&(n._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let i=n.value;i.size>=t.minimum||n.issues.push({origin:Hl(i),code:"too_small",minimum:t.minimum,input:i,inst:e,continue:!t.abort})}}),Pb=S("$ZodCheckSizeEquals",(e,t)=>{var r;pt.init(e,t),(r=e._zod.def).when??(r.when=n=>{let i=n.value;return!Zs(i)&&i.size!==void 0}),e._zod.onattach.push(n=>{let i=n._zod.bag;i.minimum=t.size,i.maximum=t.size,i.size=t.size}),e._zod.check=n=>{let i=n.value,s=i.size;if(s===t.size)return;let o=s>t.size;n.issues.push({origin:Hl(i),...o?{code:"too_big",maximum:t.size}:{code:"too_small",minimum:t.size},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Nb=S("$ZodCheckMaxLength",(e,t)=>{var r;pt.init(e,t),(r=e._zod.def).when??(r.when=n=>{let i=n.value;return!Zs(i)&&i.length!==void 0}),e._zod.onattach.push(n=>{let i=n._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<i&&(n._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let i=n.value;if(i.length<=t.maximum)return;let o=Wl(i);n.issues.push({origin:o,code:"too_big",maximum:t.maximum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),Rb=S("$ZodCheckMinLength",(e,t)=>{var r;pt.init(e,t),(r=e._zod.def).when??(r.when=n=>{let i=n.value;return!Zs(i)&&i.length!==void 0}),e._zod.onattach.push(n=>{let i=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>i&&(n._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let i=n.value;if(i.length>=t.minimum)return;let o=Wl(i);n.issues.push({origin:o,code:"too_small",minimum:t.minimum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),Mb=S("$ZodCheckLengthEquals",(e,t)=>{var r;pt.init(e,t),(r=e._zod.def).when??(r.when=n=>{let i=n.value;return!Zs(i)&&i.length!==void 0}),e._zod.onattach.push(n=>{let i=n._zod.bag;i.minimum=t.length,i.maximum=t.length,i.length=t.length}),e._zod.check=n=>{let i=n.value,s=i.length;if(s===t.length)return;let o=Wl(i),a=s>t.length;n.issues.push({origin:o,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Ic=S("$ZodCheckStringFormat",(e,t)=>{var r,n;pt.init(e,t),e._zod.onattach.push(i=>{let s=i._zod.bag;s.format=t.format,t.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=i=>{t.pattern.lastIndex=0,!t.pattern.test(i.value)&&i.issues.push({origin:"string",code:"invalid_format",format:t.format,input:i.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(n=e._zod).check??(n.check=()=>{})}),jb=S("$ZodCheckRegex",(e,t)=>{Ic.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})}}),Db=S("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Eb),Ic.init(e,t)}),zb=S("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=kb),Ic.init(e,t)}),Lb=S("$ZodCheckIncludes",(e,t)=>{pt.init(e,t);let r=Wi(t.includes),n=new RegExp(typeof t.position=="number"?`^.{${t.position}}${r}`:r);t.pattern=n,e._zod.onattach.push(i=>{let s=i._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),e._zod.check=i=>{i.value.includes(t.includes,t.position)||i.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:i.value,inst:e,continue:!t.abort})}}),Ub=S("$ZodCheckStartsWith",(e,t)=>{pt.init(e,t);let r=new RegExp(`^${Wi(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{let i=n._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(r)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),Fb=S("$ZodCheckEndsWith",(e,t)=>{pt.init(e,t);let r=new RegExp(`.*${Wi(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{let i=n._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(r)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}});function eC(e,t,r){e.issues.length&&t.issues.push(...Cr(r,e.issues))}var Bb=S("$ZodCheckProperty",(e,t)=>{pt.init(e,t),e._zod.check=r=>{let n=t.schema._zod.run({value:r.value[t.property],issues:[]},{});if(n instanceof Promise)return n.then(i=>eC(i,r,t.property));eC(n,r,t.property)}}),Vb=S("$ZodCheckMimeType",(e,t)=>{pt.init(e,t);let r=new Set(t.mime);e._zod.onattach.push(n=>{n._zod.bag.mime=t.mime}),e._zod.check=n=>{r.has(n.value.type)||n.issues.push({code:"invalid_value",values:t.mime,input:n.value.type,inst:e})}}),Zb=S("$ZodCheckOverwrite",(e,t)=>{pt.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});var Ql=class{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}let n=t.split(`
|
|
60
|
+
`).filter(o=>o),i=Math.min(...n.map(o=>o.length-o.trimStart().length)),s=n.map(o=>o.slice(i)).map(o=>" ".repeat(this.indent*2)+o);for(let o of s)this.content.push(o)}compile(){let t=Function,r=this?.args,i=[...(this?.content??[""]).map(s=>` ${s}`)];return new t(...r,i.join(`
|
|
61
|
+
`))}};var Gb={major:4,minor:0,patch:0};var _e=S("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Gb;let n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(let i of n)for(let s of i._zod.onattach)s(e);if(n.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let i=(s,o,a)=>{let c=Ko(s),u;for(let l of o){if(l._zod.def.when){if(!l._zod.def.when(s))continue}else if(c)continue;let p=s.issues.length,f=l._zod.check(s);if(f instanceof Promise&&a?.async===!1)throw new pi;if(u||f instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await f,s.issues.length!==p&&(c||(c=Ko(s,p)))});else{if(s.issues.length===p)continue;c||(c=Ko(s,p))}}return u?u.then(()=>s):s};e._zod.run=(s,o)=>{let a=e._zod.parse(s,o);if(a instanceof Promise){if(o.async===!1)throw new pi;return a.then(c=>i(c,n,o))}return i(a,n,o)}}e["~standard"]={validate:i=>{try{let s=Jv(e,i);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return Xv(e,i).then(o=>o.success?{value:o.data}:{issues:o.error?.issues})}},vendor:"zod",version:1}}),Jo=S("$ZodString",(e,t)=>{_e.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??yb(e._zod.bag),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),We=S("$ZodStringFormat",(e,t)=>{Ic.init(e,t),Jo.init(e,t)}),qb=S("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=sb),We.init(e,t)}),Hb=S("$ZodUUID",(e,t)=>{if(t.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(n===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=Ho(n))}else t.pattern??(t.pattern=Ho());We.init(e,t)}),Wb=S("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=ob),We.init(e,t)}),Jb=S("$ZodURL",(e,t)=>{We.init(e,t),e._zod.check=r=>{try{let n=r.value,i=new URL(n),s=i.href;t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:fb.source,input:r.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(":")?i.protocol.slice(0,-1):i.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})),!n.endsWith("/")&&s.endsWith("/")?r.value=s.slice(0,-1):r.value=s;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),Xb=S("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=ab()),We.init(e,t)}),Yb=S("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=nb),We.init(e,t)}),Qb=S("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Yv),We.init(e,t)}),ew=S("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Qv),We.init(e,t)}),tw=S("$ZodULID",(e,t)=>{t.pattern??(t.pattern=eb),We.init(e,t)}),rw=S("$ZodXID",(e,t)=>{t.pattern??(t.pattern=tb),We.init(e,t)}),nw=S("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=rb),We.init(e,t)}),iw=S("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=_b(t)),We.init(e,t)}),sw=S("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=hb),We.init(e,t)}),ow=S("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=gb(t)),We.init(e,t)}),aw=S("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=ib),We.init(e,t)}),cw=S("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=cb),We.init(e,t),e._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),uw=S("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=ub),We.init(e,t),e._zod.onattach.push(r=>{let n=r._zod.bag;n.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})}}}),lw=S("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=lb),We.init(e,t)}),pw=S("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=pb),We.init(e,t),e._zod.check=r=>{let[n,i]=r.value.split("/");try{if(!i)throw new Error;let s=Number(i);if(`${s}`!==i)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function dw(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var fw=S("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=db),We.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),e._zod.check=r=>{dw(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function mC(e){if(!Sm.test(e))return!1;let t=e.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return dw(r)}var mw=S("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Sm),We.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),e._zod.check=r=>{mC(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),hw=S("$ZodE164",(e,t)=>{t.pattern??(t.pattern=mb),We.init(e,t)});function hC(e,t=null){try{let r=e.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let i=JSON.parse(atob(n));return!("typ"in i&&i?.typ!=="JWT"||!i.alg||t&&(!("alg"in i)||i.alg!==t))}catch{return!1}}var gw=S("$ZodJWT",(e,t)=>{We.init(e,t),e._zod.check=r=>{hC(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),_w=S("$ZodCustomStringFormat",(e,t)=>{We.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})}}),Om=S("$ZodNumber",(e,t)=>{_e.init(e,t),e._zod.pattern=e._zod.bag.pattern??wb,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch{}let i=r.value;if(typeof i=="number"&&!Number.isNaN(i)&&Number.isFinite(i))return r;let s=typeof i=="number"?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:i,inst:e,...s?{received:s}:{}}),r}}),yw=S("$ZodNumber",(e,t)=>{Tb.init(e,t),Om.init(e,t)}),ep=S("$ZodBoolean",(e,t)=>{_e.init(e,t),e._zod.pattern=xb,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=!!r.value}catch{}let i=r.value;return typeof i=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:e}),r}}),$m=S("$ZodBigInt",(e,t)=>{_e.init(e,t),e._zod.pattern=vb,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=BigInt(r.value)}catch{}return typeof r.value=="bigint"||r.issues.push({expected:"bigint",code:"invalid_type",input:r.value,inst:e}),r}}),vw=S("$ZodBigInt",(e,t)=>{Ob.init(e,t),$m.init(e,t)}),bw=S("$ZodSymbol",(e,t)=>{_e.init(e,t),e._zod.parse=(r,n)=>{let i=r.value;return typeof i=="symbol"||r.issues.push({expected:"symbol",code:"invalid_type",input:i,inst:e}),r}}),ww=S("$ZodUndefined",(e,t)=>{_e.init(e,t),e._zod.pattern=Sb,e._zod.values=new Set([void 0]),e._zod.optin="optional",e._zod.optout="optional",e._zod.parse=(r,n)=>{let i=r.value;return typeof i>"u"||r.issues.push({expected:"undefined",code:"invalid_type",input:i,inst:e}),r}}),xw=S("$ZodNull",(e,t)=>{_e.init(e,t),e._zod.pattern=Ib,e._zod.values=new Set([null]),e._zod.parse=(r,n)=>{let i=r.value;return i===null||r.issues.push({expected:"null",code:"invalid_type",input:i,inst:e}),r}}),Iw=S("$ZodAny",(e,t)=>{_e.init(e,t),e._zod.parse=r=>r}),Gs=S("$ZodUnknown",(e,t)=>{_e.init(e,t),e._zod.parse=r=>r}),tp=S("$ZodNever",(e,t)=>{_e.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)}),Sw=S("$ZodVoid",(e,t)=>{_e.init(e,t),e._zod.parse=(r,n)=>{let i=r.value;return typeof i>"u"||r.issues.push({expected:"void",code:"invalid_type",input:i,inst:e}),r}}),Ew=S("$ZodDate",(e,t)=>{_e.init(e,t),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=new Date(r.value)}catch{}let i=r.value,s=i instanceof Date;return s&&!Number.isNaN(i.getTime())||r.issues.push({expected:"date",code:"invalid_type",input:i,...s?{received:"Invalid Date"}:{},inst:e}),r}});function nC(e,t,r){e.issues.length&&t.issues.push(...Cr(r,e.issues)),t.value[r]=e.value}var rp=S("$ZodArray",(e,t)=>{_e.init(e,t),e._zod.parse=(r,n)=>{let i=r.value;if(!Array.isArray(i))return r.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),r;r.value=Array(i.length);let s=[];for(let o=0;o<i.length;o++){let a=i[o],c=t.element._zod.run({value:a,issues:[]},n);c instanceof Promise?s.push(c.then(u=>nC(u,r,o))):nC(c,r,o)}return s.length?Promise.all(s).then(()=>r):r}});function Am(e,t,r){e.issues.length&&t.issues.push(...Cr(r,e.issues)),t.value[r]=e.value}function iC(e,t,r,n){e.issues.length?n[r]===void 0?r in n?t.value[r]=void 0:t.value[r]=e.value:t.issues.push(...Cr(r,e.issues)):e.value===void 0?r in n&&(t.value[r]=void 0):t.value[r]=e.value}var kw=S("$ZodObject",(e,t)=>{_e.init(e,t);let r=Gl(()=>{let p=Object.keys(t.shape);for(let d of p)if(!(t.shape[d]instanceof _e))throw new Error(`Invalid element at key "${d}": expected a Zod schema`);let f=Zv(t.shape);return{shape:t.shape,keys:p,keySet:new Set(p),numKeys:p.length,optionalKeys:new Set(f)}});Fe(e._zod,"propValues",()=>{let p=t.shape,f={};for(let d in p){let m=p[d]._zod;if(m.values){f[d]??(f[d]=new Set);for(let h of m.values)f[d].add(h)}}return f});let n=p=>{let f=new Ql(["shape","payload","ctx"]),d=r.value,m=y=>{let x=Go(y);return`shape[${x}]._zod.run({ value: input[${x}], issues: [] }, ctx)`};f.write("const input = payload.value;");let h=Object.create(null),b=0;for(let y of d.keys)h[y]=`key_${b++}`;f.write("const newResult = {}");for(let y of d.keys)if(d.optionalKeys.has(y)){let x=h[y];f.write(`const ${x} = ${m(y)};`);let I=Go(y);f.write(`
|
|
62
|
+
if (${x}.issues.length) {
|
|
63
|
+
if (input[${I}] === undefined) {
|
|
64
|
+
if (${I} in input) {
|
|
65
|
+
newResult[${I}] = undefined;
|
|
66
|
+
}
|
|
67
|
+
} else {
|
|
68
|
+
payload.issues = payload.issues.concat(
|
|
69
|
+
${x}.issues.map((iss) => ({
|
|
70
|
+
...iss,
|
|
71
|
+
path: iss.path ? [${I}, ...iss.path] : [${I}],
|
|
72
|
+
}))
|
|
73
|
+
);
|
|
74
|
+
}
|
|
75
|
+
} else if (${x}.value === undefined) {
|
|
76
|
+
if (${I} in input) newResult[${I}] = undefined;
|
|
77
|
+
} else {
|
|
78
|
+
newResult[${I}] = ${x}.value;
|
|
79
|
+
}
|
|
80
|
+
`)}else{let x=h[y];f.write(`const ${x} = ${m(y)};`),f.write(`
|
|
81
|
+
if (${x}.issues.length) payload.issues = payload.issues.concat(${x}.issues.map(iss => ({
|
|
82
|
+
...iss,
|
|
83
|
+
path: iss.path ? [${Go(y)}, ...iss.path] : [${Go(y)}]
|
|
84
|
+
})));`),f.write(`newResult[${Go(y)}] = ${x}.value`)}f.write("payload.value = newResult;"),f.write("return payload;");let _=f.compile();return(y,x)=>_(p,y,x)},i,s=bc,o=!Bl.jitless,c=o&&Bv.value,u=t.catchall,l;e._zod.parse=(p,f)=>{l??(l=r.value);let d=p.value;if(!s(d))return p.issues.push({expected:"object",code:"invalid_type",input:d,inst:e}),p;let m=[];if(o&&c&&f?.async===!1&&f.jitless!==!0)i||(i=n(t.shape)),p=i(p,f);else{p.value={};let x=l.shape;for(let I of l.keys){let A=x[I],j=A._zod.run({value:d[I],issues:[]},f),O=A._zod.optin==="optional"&&A._zod.optout==="optional";j instanceof Promise?m.push(j.then(w=>O?iC(w,p,I,d):Am(w,p,I))):O?iC(j,p,I,d):Am(j,p,I)}}if(!u)return m.length?Promise.all(m).then(()=>p):p;let h=[],b=l.keySet,_=u._zod,y=_.def.type;for(let x of Object.keys(d)){if(b.has(x))continue;if(y==="never"){h.push(x);continue}let I=_.run({value:d[x],issues:[]},f);I instanceof Promise?m.push(I.then(A=>Am(A,p,x))):Am(I,p,x)}return h.length&&p.issues.push({code:"unrecognized_keys",keys:h,input:d,inst:e}),m.length?Promise.all(m).then(()=>p):p}});function sC(e,t,r,n){for(let i of e)if(i.issues.length===0)return t.value=i.value,t;return t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(i=>i.issues.map(s=>Gr(s,n,At())))}),t}var Cm=S("$ZodUnion",(e,t)=>{_e.init(e,t),Fe(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),Fe(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),Fe(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),Fe(e._zod,"pattern",()=>{if(t.options.every(r=>r._zod.pattern)){let r=t.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>Kl(n.source)).join("|")})$`)}}),e._zod.parse=(r,n)=>{let i=!1,s=[];for(let o of t.options){let a=o._zod.run({value:r.value,issues:[]},n);if(a instanceof Promise)s.push(a),i=!0;else{if(a.issues.length===0)return a;s.push(a)}}return i?Promise.all(s).then(o=>sC(o,r,e,n)):sC(s,r,e,n)}}),Aw=S("$ZodDiscriminatedUnion",(e,t)=>{Cm.init(e,t);let r=e._zod.parse;Fe(e._zod,"propValues",()=>{let i={};for(let s of t.options){let o=s._zod.propValues;if(!o||Object.keys(o).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(let[a,c]of Object.entries(o)){i[a]||(i[a]=new Set);for(let u of c)i[a].add(u)}}return i});let n=Gl(()=>{let i=t.options,s=new Map;for(let o of i){let a=o._zod.propValues[t.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(o)}"`);for(let c of a){if(s.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);s.set(c,o)}}return s});e._zod.parse=(i,s)=>{let o=i.value;if(!bc(o))return i.issues.push({code:"invalid_type",expected:"object",input:o,inst:e}),i;let a=n.value.get(o?.[t.discriminator]);return a?a._zod.run(i,s):t.unionFallback?r(i,s):(i.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:o,path:[t.discriminator],inst:e}),i)}}),Tw=S("$ZodIntersection",(e,t)=>{_e.init(e,t),e._zod.parse=(r,n)=>{let i=r.value,s=t.left._zod.run({value:i,issues:[]},n),o=t.right._zod.run({value:i,issues:[]},n);return s instanceof Promise||o instanceof Promise?Promise.all([s,o]).then(([c,u])=>oC(r,c,u)):oC(r,s,o)}});function Kb(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(wc(e)&&wc(t)){let r=Object.keys(t),n=Object.keys(e).filter(s=>r.indexOf(s)!==-1),i={...e,...t};for(let s of n){let o=Kb(e[s],t[s]);if(!o.valid)return{valid:!1,mergeErrorPath:[s,...o.mergeErrorPath]};i[s]=o.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<e.length;n++){let i=e[n],s=t[n],o=Kb(i,s);if(!o.valid)return{valid:!1,mergeErrorPath:[n,...o.mergeErrorPath]};r.push(o.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function oC(e,t,r){if(t.issues.length&&e.issues.push(...t.issues),r.issues.length&&e.issues.push(...r.issues),Ko(e))return e;let n=Kb(t.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return e.value=n.data,e}var Xo=S("$ZodTuple",(e,t)=>{_e.init(e,t);let r=t.items,n=r.length-[...r].reverse().findIndex(i=>i._zod.optin!=="optional");e._zod.parse=(i,s)=>{let o=i.value;if(!Array.isArray(o))return i.issues.push({input:o,inst:e,expected:"tuple",code:"invalid_type"}),i;i.value=[];let a=[];if(!t.rest){let u=o.length>r.length,l=o.length<n-1;if(u||l)return i.issues.push({input:o,inst:e,origin:"array",...u?{code:"too_big",maximum:r.length}:{code:"too_small",minimum:r.length}}),i}let c=-1;for(let u of r){if(c++,c>=o.length&&c>=n)continue;let l=u._zod.run({value:o[c],issues:[]},s);l instanceof Promise?a.push(l.then(p=>Tm(p,i,c))):Tm(l,i,c)}if(t.rest){let u=o.slice(r.length);for(let l of u){c++;let p=t.rest._zod.run({value:l,issues:[]},s);p instanceof Promise?a.push(p.then(f=>Tm(f,i,c))):Tm(p,i,c)}}return a.length?Promise.all(a).then(()=>i):i}});function Tm(e,t,r){e.issues.length&&t.issues.push(...Cr(r,e.issues)),t.value[r]=e.value}var Ow=S("$ZodRecord",(e,t)=>{_e.init(e,t),e._zod.parse=(r,n)=>{let i=r.value;if(!wc(i))return r.issues.push({expected:"record",code:"invalid_type",input:i,inst:e}),r;let s=[];if(t.keyType._zod.values){let o=t.keyType._zod.values;r.value={};for(let c of o)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){let u=t.valueType._zod.run({value:i[c],issues:[]},n);u instanceof Promise?s.push(u.then(l=>{l.issues.length&&r.issues.push(...Cr(c,l.issues)),r.value[c]=l.value})):(u.issues.length&&r.issues.push(...Cr(c,u.issues)),r.value[c]=u.value)}let a;for(let c in i)o.has(c)||(a=a??[],a.push(c));a&&a.length>0&&r.issues.push({code:"unrecognized_keys",input:i,inst:e,keys:a})}else{r.value={};for(let o of Reflect.ownKeys(i)){if(o==="__proto__")continue;let a=t.keyType._zod.run({value:o,issues:[]},n);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:a.issues.map(u=>Gr(u,n,At())),input:o,path:[o],inst:e}),r.value[a.value]=a.value;continue}let c=t.valueType._zod.run({value:i[o],issues:[]},n);c instanceof Promise?s.push(c.then(u=>{u.issues.length&&r.issues.push(...Cr(o,u.issues)),r.value[a.value]=u.value})):(c.issues.length&&r.issues.push(...Cr(o,c.issues)),r.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}}),$w=S("$ZodMap",(e,t)=>{_e.init(e,t),e._zod.parse=(r,n)=>{let i=r.value;if(!(i instanceof Map))return r.issues.push({expected:"map",code:"invalid_type",input:i,inst:e}),r;let s=[];r.value=new Map;for(let[o,a]of i){let c=t.keyType._zod.run({value:o,issues:[]},n),u=t.valueType._zod.run({value:a,issues:[]},n);c instanceof Promise||u instanceof Promise?s.push(Promise.all([c,u]).then(([l,p])=>{aC(l,p,r,o,i,e,n)})):aC(c,u,r,o,i,e,n)}return s.length?Promise.all(s).then(()=>r):r}});function aC(e,t,r,n,i,s,o){e.issues.length&&(ql.has(typeof n)?r.issues.push(...Cr(n,e.issues)):r.issues.push({origin:"map",code:"invalid_key",input:i,inst:s,issues:e.issues.map(a=>Gr(a,o,At()))})),t.issues.length&&(ql.has(typeof n)?r.issues.push(...Cr(n,t.issues)):r.issues.push({origin:"map",code:"invalid_element",input:i,inst:s,key:n,issues:t.issues.map(a=>Gr(a,o,At()))})),r.value.set(e.value,t.value)}var Cw=S("$ZodSet",(e,t)=>{_e.init(e,t),e._zod.parse=(r,n)=>{let i=r.value;if(!(i instanceof Set))return r.issues.push({input:i,inst:e,expected:"set",code:"invalid_type"}),r;let s=[];r.value=new Set;for(let o of i){let a=t.valueType._zod.run({value:o,issues:[]},n);a instanceof Promise?s.push(a.then(c=>cC(c,r))):cC(a,r)}return s.length?Promise.all(s).then(()=>r):r}});function cC(e,t){e.issues.length&&t.issues.push(...e.issues),t.value.add(e.value)}var Pw=S("$ZodEnum",(e,t)=>{_e.init(e,t);let r=Zl(t.entries);e._zod.values=new Set(r),e._zod.pattern=new RegExp(`^(${r.filter(n=>ql.has(typeof n)).map(n=>typeof n=="string"?Wi(n):n.toString()).join("|")})$`),e._zod.parse=(n,i)=>{let s=n.value;return e._zod.values.has(s)||n.issues.push({code:"invalid_value",values:r,input:s,inst:e}),n}}),Nw=S("$ZodLiteral",(e,t)=>{_e.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map(r=>typeof r=="string"?Wi(r):r?r.toString():String(r)).join("|")})$`),e._zod.parse=(r,n)=>{let i=r.value;return e._zod.values.has(i)||r.issues.push({code:"invalid_value",values:t.values,input:i,inst:e}),r}}),Rw=S("$ZodFile",(e,t)=>{_e.init(e,t),e._zod.parse=(r,n)=>{let i=r.value;return i instanceof File||r.issues.push({expected:"file",code:"invalid_type",input:i,inst:e}),r}}),np=S("$ZodTransform",(e,t)=>{_e.init(e,t),e._zod.parse=(r,n)=>{let i=t.transform(r.value,r);if(n.async)return(i instanceof Promise?i:Promise.resolve(i)).then(o=>(r.value=o,r));if(i instanceof Promise)throw new pi;return r.value=i,r}}),Sc=S("$ZodOptional",(e,t)=>{_e.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Fe(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Fe(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${Kl(r.source)})?$`):void 0}),e._zod.parse=(r,n)=>t.innerType._zod.optin==="optional"?t.innerType._zod.run(r,n):r.value===void 0?r:t.innerType._zod.run(r,n)}),Mw=S("$ZodNullable",(e,t)=>{_e.init(e,t),Fe(e._zod,"optin",()=>t.innerType._zod.optin),Fe(e._zod,"optout",()=>t.innerType._zod.optout),Fe(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${Kl(r.source)}|null)$`):void 0}),Fe(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(r,n)=>r.value===null?r:t.innerType._zod.run(r,n)}),jw=S("$ZodDefault",(e,t)=>{_e.init(e,t),e._zod.optin="optional",Fe(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=t.defaultValue,r;let i=t.innerType._zod.run(r,n);return i instanceof Promise?i.then(s=>uC(s,t)):uC(i,t)}});function uC(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var Dw=S("$ZodPrefault",(e,t)=>{_e.init(e,t),e._zod.optin="optional",Fe(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>(r.value===void 0&&(r.value=t.defaultValue),t.innerType._zod.run(r,n))}),zw=S("$ZodNonOptional",(e,t)=>{_e.init(e,t),Fe(e._zod,"values",()=>{let r=t.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),e._zod.parse=(r,n)=>{let i=t.innerType._zod.run(r,n);return i instanceof Promise?i.then(s=>lC(s,e)):lC(i,e)}});function lC(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}var Lw=S("$ZodSuccess",(e,t)=>{_e.init(e,t),e._zod.parse=(r,n)=>{let i=t.innerType._zod.run(r,n);return i instanceof Promise?i.then(s=>(r.value=s.issues.length===0,r)):(r.value=i.issues.length===0,r)}}),Uw=S("$ZodCatch",(e,t)=>{_e.init(e,t),e._zod.optin="optional",Fe(e._zod,"optout",()=>t.innerType._zod.optout),Fe(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{let i=t.innerType._zod.run(r,n);return i instanceof Promise?i.then(s=>(r.value=s.value,s.issues.length&&(r.value=t.catchValue({...r,error:{issues:s.issues.map(o=>Gr(o,n,At()))},input:r.value}),r.issues=[]),r)):(r.value=i.value,i.issues.length&&(r.value=t.catchValue({...r,error:{issues:i.issues.map(s=>Gr(s,n,At()))},input:r.value}),r.issues=[]),r)}}),Fw=S("$ZodNaN",(e,t)=>{_e.init(e,t),e._zod.parse=(r,n)=>((typeof r.value!="number"||!Number.isNaN(r.value))&&r.issues.push({input:r.value,inst:e,expected:"nan",code:"invalid_type"}),r)}),ip=S("$ZodPipe",(e,t)=>{_e.init(e,t),Fe(e._zod,"values",()=>t.in._zod.values),Fe(e._zod,"optin",()=>t.in._zod.optin),Fe(e._zod,"optout",()=>t.out._zod.optout),e._zod.parse=(r,n)=>{let i=t.in._zod.run(r,n);return i instanceof Promise?i.then(s=>pC(s,t,n)):pC(i,t,n)}});function pC(e,t,r){return Ko(e)?e:t.out._zod.run({value:e.value,issues:e.issues},r)}var Bw=S("$ZodReadonly",(e,t)=>{_e.init(e,t),Fe(e._zod,"propValues",()=>t.innerType._zod.propValues),Fe(e._zod,"values",()=>t.innerType._zod.values),Fe(e._zod,"optin",()=>t.innerType._zod.optin),Fe(e._zod,"optout",()=>t.innerType._zod.optout),e._zod.parse=(r,n)=>{let i=t.innerType._zod.run(r,n);return i instanceof Promise?i.then(dC):dC(i)}});function dC(e){return e.value=Object.freeze(e.value),e}var Vw=S("$ZodTemplateLiteral",(e,t)=>{_e.init(e,t);let r=[];for(let n of t.parts)if(n instanceof _e){if(!n._zod.pattern)throw new Error(`Invalid template literal part, no pattern found: ${[...n._zod.traits].shift()}`);let i=n._zod.pattern instanceof RegExp?n._zod.pattern.source:n._zod.pattern;if(!i)throw new Error(`Invalid template literal part: ${n._zod.traits}`);let s=i.startsWith("^")?1:0,o=i.endsWith("$")?i.length-1:i.length;r.push(i.slice(s,o))}else if(n===null||Vv.has(typeof n))r.push(Wi(`${n}`));else throw new Error(`Invalid template literal part: ${n}`);e._zod.pattern=new RegExp(`^${r.join("")}$`),e._zod.parse=(n,i)=>typeof n.value!="string"?(n.issues.push({input:n.value,inst:e,expected:"template_literal",code:"invalid_type"}),n):(e._zod.pattern.lastIndex=0,e._zod.pattern.test(n.value)||n.issues.push({input:n.value,inst:e,code:"invalid_format",format:"template_literal",pattern:e._zod.pattern.source}),n)}),Zw=S("$ZodPromise",(e,t)=>{_e.init(e,t),e._zod.parse=(r,n)=>Promise.resolve(r.value).then(i=>t.innerType._zod.run({value:i,issues:[]},n))}),Gw=S("$ZodLazy",(e,t)=>{_e.init(e,t),Fe(e._zod,"innerType",()=>t.getter()),Fe(e._zod,"pattern",()=>e._zod.innerType._zod.pattern),Fe(e._zod,"propValues",()=>e._zod.innerType._zod.propValues),Fe(e._zod,"optin",()=>e._zod.innerType._zod.optin),Fe(e._zod,"optout",()=>e._zod.innerType._zod.optout),e._zod.parse=(r,n)=>e._zod.innerType._zod.run(r,n)}),Kw=S("$ZodCustom",(e,t)=>{pt.init(e,t),_e.init(e,t),e._zod.parse=(r,n)=>r,e._zod.check=r=>{let n=r.value,i=t.fn(n);if(i instanceof Promise)return i.then(s=>fC(s,r,n,e));fC(i,r,n,e)}});function fC(e,t,r,n){if(!e){let i={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(i.params=n._zod.def.params),t.issues.push(qv(i))}}var sp={};Cs(sp,{ar:()=>_C,az:()=>yC,be:()=>bC,ca:()=>wC,cs:()=>xC,de:()=>IC,en:()=>Pm,eo:()=>SC,es:()=>EC,fa:()=>kC,fi:()=>AC,fr:()=>TC,frCA:()=>OC,he:()=>$C,hu:()=>CC,id:()=>PC,it:()=>NC,ja:()=>RC,kh:()=>MC,ko:()=>jC,mk:()=>DC,ms:()=>zC,nl:()=>LC,no:()=>UC,ota:()=>FC,pl:()=>VC,ps:()=>BC,pt:()=>ZC,ru:()=>KC,sl:()=>qC,sv:()=>HC,ta:()=>WC,th:()=>JC,tr:()=>XC,ua:()=>YC,ur:()=>QC,vi:()=>eP,zhCN:()=>tP,zhTW:()=>rP});var v6=()=>{let e={string:{unit:"\u062D\u0631\u0641",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"},file:{unit:"\u0628\u0627\u064A\u062A",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"},array:{unit:"\u0639\u0646\u0635\u0631",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"},set:{unit:"\u0639\u0646\u0635\u0631",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"}};function t(i){return e[i]??null}let r=i=>{let s=typeof i;switch(s){case"number":return Number.isNaN(i)?"NaN":"number";case"object":{if(Array.isArray(i))return"array";if(i===null)return"null";if(Object.getPrototypeOf(i)!==Object.prototype&&i.constructor)return i.constructor.name}}return s},n={regex:"\u0645\u062F\u062E\u0644",email:"\u0628\u0631\u064A\u062F \u0625\u0644\u0643\u062A\u0631\u0648\u0646\u064A",url:"\u0631\u0627\u0628\u0637",emoji:"\u0625\u064A\u0645\u0648\u062C\u064A",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u062A\u0627\u0631\u064A\u062E \u0648\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO",date:"\u062A\u0627\u0631\u064A\u062E \u0628\u0645\u0639\u064A\u0627\u0631 ISO",time:"\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO",duration:"\u0645\u062F\u0629 \u0628\u0645\u0639\u064A\u0627\u0631 ISO",ipv4:"\u0639\u0646\u0648\u0627\u0646 IPv4",ipv6:"\u0639\u0646\u0648\u0627\u0646 IPv6",cidrv4:"\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv4",cidrv6:"\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv6",base64:"\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64-encoded",base64url:"\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64url-encoded",json_string:"\u0646\u064E\u0635 \u0639\u0644\u0649 \u0647\u064A\u0626\u0629 JSON",e164:"\u0631\u0642\u0645 \u0647\u0627\u062A\u0641 \u0628\u0645\u0639\u064A\u0627\u0631 E.164",jwt:"JWT",template_literal:"\u0645\u062F\u062E\u0644"};return i=>{switch(i.code){case"invalid_type":return`\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${i.expected}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${r(i.input)}`;case"invalid_value":return i.values.length===1?`\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${K(i.values[0])}`:`\u0627\u062E\u062A\u064A\u0627\u0631 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062A\u0648\u0642\u0639 \u0627\u0646\u062A\u0642\u0627\u0621 \u0623\u062D\u062F \u0647\u0630\u0647 \u0627\u0644\u062E\u064A\u0627\u0631\u0627\u062A: ${C(i.values,"|")}`;case"too_big":{let s=i.inclusive?"<=":"<",o=t(i.origin);return o?` \u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${i.origin??"\u0627\u0644\u0642\u064A\u0645\u0629"} ${s} ${i.maximum.toString()} ${o.unit??"\u0639\u0646\u0635\u0631"}`:`\u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${i.origin??"\u0627\u0644\u0642\u064A\u0645\u0629"} ${s} ${i.maximum.toString()}`}case"too_small":{let s=i.inclusive?">=":">",o=t(i.origin);return o?`\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${i.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${s} ${i.minimum.toString()} ${o.unit}`:`\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${i.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${s} ${i.minimum.toString()}`}case"invalid_format":{let s=i;return s.format==="starts_with"?`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0628\u062F\u0623 \u0628\u0640 "${i.prefix}"`:s.format==="ends_with"?`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0646\u062A\u0647\u064A \u0628\u0640 "${s.suffix}"`:s.format==="includes"?`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u062A\u0636\u0645\u0651\u064E\u0646 "${s.includes}"`:s.format==="regex"?`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0637\u0627\u0628\u0642 \u0627\u0644\u0646\u0645\u0637 ${s.pattern}`:`${n[s.format]??i.format} \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644`}case"not_multiple_of":return`\u0631\u0642\u0645 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0643\u0648\u0646 \u0645\u0646 \u0645\u0636\u0627\u0639\u0641\u0627\u062A ${i.divisor}`;case"unrecognized_keys":return`\u0645\u0639\u0631\u0641${i.keys.length>1?"\u0627\u062A":""} \u063A\u0631\u064A\u0628${i.keys.length>1?"\u0629":""}: ${C(i.keys,"\u060C ")}`;case"invalid_key":return`\u0645\u0639\u0631\u0641 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${i.origin}`;case"invalid_union":return"\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644";case"invalid_element":return`\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${i.origin}`;default:return"\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644"}}};function _C(){return{localeError:v6()}}var b6=()=>{let e={string:{unit:"simvol",verb:"olmal\u0131d\u0131r"},file:{unit:"bayt",verb:"olmal\u0131d\u0131r"},array:{unit:"element",verb:"olmal\u0131d\u0131r"},set:{unit:"element",verb:"olmal\u0131d\u0131r"}};function t(i){return e[i]??null}let r=i=>{let s=typeof i;switch(s){case"number":return Number.isNaN(i)?"NaN":"number";case"object":{if(Array.isArray(i))return"array";if(i===null)return"null";if(Object.getPrototypeOf(i)!==Object.prototype&&i.constructor)return i.constructor.name}}return s},n={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return i=>{switch(i.code){case"invalid_type":return`Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${i.expected}, daxil olan ${r(i.input)}`;case"invalid_value":return i.values.length===1?`Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${K(i.values[0])}`:`Yanl\u0131\u015F se\xE7im: a\u015Fa\u011F\u0131dak\u0131lardan biri olmal\u0131d\u0131r: ${C(i.values,"|")}`;case"too_big":{let s=i.inclusive?"<=":"<",o=t(i.origin);return o?`\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${i.origin??"d\u0259y\u0259r"} ${s}${i.maximum.toString()} ${o.unit??"element"}`:`\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${i.origin??"d\u0259y\u0259r"} ${s}${i.maximum.toString()}`}case"too_small":{let s=i.inclusive?">=":">",o=t(i.origin);return o?`\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${i.origin} ${s}${i.minimum.toString()} ${o.unit}`:`\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${i.origin} ${s}${i.minimum.toString()}`}case"invalid_format":{let s=i;return s.format==="starts_with"?`Yanl\u0131\u015F m\u0259tn: "${s.prefix}" il\u0259 ba\u015Flamal\u0131d\u0131r`:s.format==="ends_with"?`Yanl\u0131\u015F m\u0259tn: "${s.suffix}" il\u0259 bitm\u0259lidir`:s.format==="includes"?`Yanl\u0131\u015F m\u0259tn: "${s.includes}" daxil olmal\u0131d\u0131r`:s.format==="regex"?`Yanl\u0131\u015F m\u0259tn: ${s.pattern} \u015Fablonuna uy\u011Fun olmal\u0131d\u0131r`:`Yanl\u0131\u015F ${n[s.format]??i.format}`}case"not_multiple_of":return`Yanl\u0131\u015F \u0259d\u0259d: ${i.divisor} il\u0259 b\xF6l\xFCn\u0259 bil\u0259n olmal\u0131d\u0131r`;case"unrecognized_keys":return`Tan\u0131nmayan a\xE7ar${i.keys.length>1?"lar":""}: ${C(i.keys,", ")}`;case"invalid_key":return`${i.origin} daxilind\u0259 yanl\u0131\u015F a\xE7ar`;case"invalid_union":return"Yanl\u0131\u015F d\u0259y\u0259r";case"invalid_element":return`${i.origin} daxilind\u0259 yanl\u0131\u015F d\u0259y\u0259r`;default:return"Yanl\u0131\u015F d\u0259y\u0259r"}}};function yC(){return{localeError:b6()}}function vC(e,t,r,n){let i=Math.abs(e),s=i%10,o=i%100;return o>=11&&o<=19?n:s===1?t:s>=2&&s<=4?r:n}var w6=()=>{let e={string:{unit:{one:"\u0441\u0456\u043C\u0432\u0430\u043B",few:"\u0441\u0456\u043C\u0432\u0430\u043B\u044B",many:"\u0441\u0456\u043C\u0432\u0430\u043B\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"},array:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"},set:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"},file:{unit:{one:"\u0431\u0430\u0439\u0442",few:"\u0431\u0430\u0439\u0442\u044B",many:"\u0431\u0430\u0439\u0442\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"}};function t(i){return e[i]??null}let r=i=>{let s=typeof i;switch(s){case"number":return Number.isNaN(i)?"NaN":"\u043B\u0456\u043A";case"object":{if(Array.isArray(i))return"\u043C\u0430\u0441\u0456\u045E";if(i===null)return"null";if(Object.getPrototypeOf(i)!==Object.prototype&&i.constructor)return i.constructor.name}}return s},n={regex:"\u0443\u0432\u043E\u0434",email:"email \u0430\u0434\u0440\u0430\u0441",url:"URL",emoji:"\u044D\u043C\u043E\u0434\u0437\u0456",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0434\u0430\u0442\u0430 \u0456 \u0447\u0430\u0441",date:"ISO \u0434\u0430\u0442\u0430",time:"ISO \u0447\u0430\u0441",duration:"ISO \u043F\u0440\u0430\u0446\u044F\u0433\u043B\u0430\u0441\u0446\u044C",ipv4:"IPv4 \u0430\u0434\u0440\u0430\u0441",ipv6:"IPv6 \u0430\u0434\u0440\u0430\u0441",cidrv4:"IPv4 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D",cidrv6:"IPv6 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D",base64:"\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64",base64url:"\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64url",json_string:"JSON \u0440\u0430\u0434\u043E\u043A",e164:"\u043D\u0443\u043C\u0430\u0440 E.164",jwt:"JWT",template_literal:"\u0443\u0432\u043E\u0434"};return i=>{switch(i.code){case"invalid_type":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F ${i.expected}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${r(i.input)}`;case"invalid_value":return i.values.length===1?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F ${K(i.values[0])}`:`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0432\u0430\u0440\u044B\u044F\u043D\u0442: \u0447\u0430\u043A\u0430\u045E\u0441\u044F \u0430\u0434\u0437\u0456\u043D \u0437 ${C(i.values,"|")}`;case"too_big":{let s=i.inclusive?"<=":"<",o=t(i.origin);if(o){let a=Number(i.maximum),c=vC(a,o.unit.one,o.unit.few,o.unit.many);return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${i.origin??"\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${o.verb} ${s}${i.maximum.toString()} ${c}`}return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${i.origin??"\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${s}${i.maximum.toString()}`}case"too_small":{let s=i.inclusive?">=":">",o=t(i.origin);if(o){let a=Number(i.minimum),c=vC(a,o.unit.one,o.unit.few,o.unit.many);return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${i.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${o.verb} ${s}${i.minimum.toString()} ${c}`}return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${i.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${s}${i.minimum.toString()}`}case"invalid_format":{let s=i;return s.format==="starts_with"?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u043F\u0430\u0447\u044B\u043D\u0430\u0446\u0446\u0430 \u0437 "${s.prefix}"`:s.format==="ends_with"?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u0430\u043A\u0430\u043D\u0447\u0432\u0430\u0446\u0446\u0430 \u043D\u0430 "${s.suffix}"`:s.format==="includes"?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u043C\u044F\u0448\u0447\u0430\u0446\u044C "${s.includes}"`:s.format==="regex"?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0430\u0434\u043F\u0430\u0432\u044F\u0434\u0430\u0446\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${s.pattern}`:`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B ${n[s.format]??i.format}`}case"not_multiple_of":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043B\u0456\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0431\u044B\u0446\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${i.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u0430\u0441\u043F\u0430\u0437\u043D\u0430\u043D\u044B ${i.keys.length>1?"\u043A\u043B\u044E\u0447\u044B":"\u043A\u043B\u044E\u0447"}: ${C(i.keys,", ")}`;case"invalid_key":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043A\u043B\u044E\u0447 \u0443 ${i.origin}`;case"invalid_union":return"\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434";case"invalid_element":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u0430\u0435 \u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435 \u045E ${i.origin}`;default:return"\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434"}}};function bC(){return{localeError:w6()}}var x6=()=>{let e={string:{unit:"car\xE0cters",verb:"contenir"},file:{unit:"bytes",verb:"contenir"},array:{unit:"elements",verb:"contenir"},set:{unit:"elements",verb:"contenir"}};function t(i){return e[i]??null}let r=i=>{let s=typeof i;switch(s){case"number":return Number.isNaN(i)?"NaN":"number";case"object":{if(Array.isArray(i))return"array";if(i===null)return"null";if(Object.getPrototypeOf(i)!==Object.prototype&&i.constructor)return i.constructor.name}}return s},n={regex:"entrada",email:"adre\xE7a electr\xF2nica",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i hora ISO",date:"data ISO",time:"hora ISO",duration:"durada ISO",ipv4:"adre\xE7a IPv4",ipv6:"adre\xE7a IPv6",cidrv4:"rang IPv4",cidrv6:"rang IPv6",base64:"cadena codificada en base64",base64url:"cadena codificada en base64url",json_string:"cadena JSON",e164:"n\xFAmero E.164",jwt:"JWT",template_literal:"entrada"};return i=>{switch(i.code){case"invalid_type":return`Tipus inv\xE0lid: s'esperava ${i.expected}, s'ha rebut ${r(i.input)}`;case"invalid_value":return i.values.length===1?`Valor inv\xE0lid: s'esperava ${K(i.values[0])}`:`Opci\xF3 inv\xE0lida: s'esperava una de ${C(i.values," o ")}`;case"too_big":{let s=i.inclusive?"com a m\xE0xim":"menys de",o=t(i.origin);return o?`Massa gran: s'esperava que ${i.origin??"el valor"} contingu\xE9s ${s} ${i.maximum.toString()} ${o.unit??"elements"}`:`Massa gran: s'esperava que ${i.origin??"el valor"} fos ${s} ${i.maximum.toString()}`}case"too_small":{let s=i.inclusive?"com a m\xEDnim":"m\xE9s de",o=t(i.origin);return o?`Massa petit: s'esperava que ${i.origin} contingu\xE9s ${s} ${i.minimum.toString()} ${o.unit}`:`Massa petit: s'esperava que ${i.origin} fos ${s} ${i.minimum.toString()}`}case"invalid_format":{let s=i;return s.format==="starts_with"?`Format inv\xE0lid: ha de comen\xE7ar amb "${s.prefix}"`:s.format==="ends_with"?`Format inv\xE0lid: ha d'acabar amb "${s.suffix}"`:s.format==="includes"?`Format inv\xE0lid: ha d'incloure "${s.includes}"`:s.format==="regex"?`Format inv\xE0lid: ha de coincidir amb el patr\xF3 ${s.pattern}`:`Format inv\xE0lid per a ${n[s.format]??i.format}`}case"not_multiple_of":return`N\xFAmero inv\xE0lid: ha de ser m\xFAltiple de ${i.divisor}`;case"unrecognized_keys":return`Clau${i.keys.length>1?"s":""} no reconeguda${i.keys.length>1?"s":""}: ${C(i.keys,", ")}`;case"invalid_key":return`Clau inv\xE0lida a ${i.origin}`;case"invalid_union":return"Entrada inv\xE0lida";case"invalid_element":return`Element inv\xE0lid a ${i.origin}`;default:return"Entrada inv\xE0lida"}}};function wC(){return{localeError:x6()}}var I6=()=>{let e={string:{unit:"znak\u016F",verb:"m\xEDt"},file:{unit:"bajt\u016F",verb:"m\xEDt"},array:{unit:"prvk\u016F",verb:"m\xEDt"},set:{unit:"prvk\u016F",verb:"m\xEDt"}};function t(i){return e[i]??null}let r=i=>{let s=typeof i;switch(s){case"number":return Number.isNaN(i)?"NaN":"\u010D\xEDslo";case"string":return"\u0159et\u011Bzec";case"boolean":return"boolean";case"bigint":return"bigint";case"function":return"funkce";case"symbol":return"symbol";case"undefined":return"undefined";case"object":{if(Array.isArray(i))return"pole";if(i===null)return"null";if(Object.getPrototypeOf(i)!==Object.prototype&&i.constructor)return i.constructor.name}}return s},n={regex:"regul\xE1rn\xED v\xFDraz",email:"e-mailov\xE1 adresa",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"datum a \u010Das ve form\xE1tu ISO",date:"datum ve form\xE1tu ISO",time:"\u010Das ve form\xE1tu ISO",duration:"doba trv\xE1n\xED ISO",ipv4:"IPv4 adresa",ipv6:"IPv6 adresa",cidrv4:"rozsah IPv4",cidrv6:"rozsah IPv6",base64:"\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64",base64url:"\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64url",json_string:"\u0159et\u011Bzec ve form\xE1tu JSON",e164:"\u010D\xEDslo E.164",jwt:"JWT",template_literal:"vstup"};return i=>{switch(i.code){case"invalid_type":return`Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${i.expected}, obdr\u017Eeno ${r(i.input)}`;case"invalid_value":return i.values.length===1?`Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${K(i.values[0])}`:`Neplatn\xE1 mo\u017Enost: o\u010Dek\xE1v\xE1na jedna z hodnot ${C(i.values,"|")}`;case"too_big":{let s=i.inclusive?"<=":"<",o=t(i.origin);return o?`Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${i.origin??"hodnota"} mus\xED m\xEDt ${s}${i.maximum.toString()} ${o.unit??"prvk\u016F"}`:`Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${i.origin??"hodnota"} mus\xED b\xFDt ${s}${i.maximum.toString()}`}case"too_small":{let s=i.inclusive?">=":">",o=t(i.origin);return o?`Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${i.origin??"hodnota"} mus\xED m\xEDt ${s}${i.minimum.toString()} ${o.unit??"prvk\u016F"}`:`Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${i.origin??"hodnota"} mus\xED b\xFDt ${s}${i.minimum.toString()}`}case"invalid_format":{let s=i;return s.format==="starts_with"?`Neplatn\xFD \u0159et\u011Bzec: mus\xED za\u010D\xEDnat na "${s.prefix}"`:s.format==="ends_with"?`Neplatn\xFD \u0159et\u011Bzec: mus\xED kon\u010Dit na "${s.suffix}"`:s.format==="includes"?`Neplatn\xFD \u0159et\u011Bzec: mus\xED obsahovat "${s.includes}"`:s.format==="regex"?`Neplatn\xFD \u0159et\u011Bzec: mus\xED odpov\xEDdat vzoru ${s.pattern}`:`Neplatn\xFD form\xE1t ${n[s.format]??i.format}`}case"not_multiple_of":return`Neplatn\xE9 \u010D\xEDslo: mus\xED b\xFDt n\xE1sobkem ${i.divisor}`;case"unrecognized_keys":return`Nezn\xE1m\xE9 kl\xED\u010De: ${C(i.keys,", ")}`;case"invalid_key":return`Neplatn\xFD kl\xED\u010D v ${i.origin}`;case"invalid_union":return"Neplatn\xFD vstup";case"invalid_element":return`Neplatn\xE1 hodnota v ${i.origin}`;default:return"Neplatn\xFD vstup"}}};function xC(){return{localeError:I6()}}var S6=()=>{let e={string:{unit:"Zeichen",verb:"zu haben"},file:{unit:"Bytes",verb:"zu haben"},array:{unit:"Elemente",verb:"zu haben"},set:{unit:"Elemente",verb:"zu haben"}};function t(i){return e[i]??null}let r=i=>{let s=typeof i;switch(s){case"number":return Number.isNaN(i)?"NaN":"Zahl";case"object":{if(Array.isArray(i))return"Array";if(i===null)return"null";if(Object.getPrototypeOf(i)!==Object.prototype&&i.constructor)return i.constructor.name}}return s},n={regex:"Eingabe",email:"E-Mail-Adresse",url:"URL",emoji:"Emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-Datum und -Uhrzeit",date:"ISO-Datum",time:"ISO-Uhrzeit",duration:"ISO-Dauer",ipv4:"IPv4-Adresse",ipv6:"IPv6-Adresse",cidrv4:"IPv4-Bereich",cidrv6:"IPv6-Bereich",base64:"Base64-codierter String",base64url:"Base64-URL-codierter String",json_string:"JSON-String",e164:"E.164-Nummer",jwt:"JWT",template_literal:"Eingabe"};return i=>{switch(i.code){case"invalid_type":return`Ung\xFCltige Eingabe: erwartet ${i.expected}, erhalten ${r(i.input)}`;case"invalid_value":return i.values.length===1?`Ung\xFCltige Eingabe: erwartet ${K(i.values[0])}`:`Ung\xFCltige Option: erwartet eine von ${C(i.values,"|")}`;case"too_big":{let s=i.inclusive?"<=":"<",o=t(i.origin);return o?`Zu gro\xDF: erwartet, dass ${i.origin??"Wert"} ${s}${i.maximum.toString()} ${o.unit??"Elemente"} hat`:`Zu gro\xDF: erwartet, dass ${i.origin??"Wert"} ${s}${i.maximum.toString()} ist`}case"too_small":{let s=i.inclusive?">=":">",o=t(i.origin);return o?`Zu klein: erwartet, dass ${i.origin} ${s}${i.minimum.toString()} ${o.unit} hat`:`Zu klein: erwartet, dass ${i.origin} ${s}${i.minimum.toString()} ist`}case"invalid_format":{let s=i;return s.format==="starts_with"?`Ung\xFCltiger String: muss mit "${s.prefix}" beginnen`:s.format==="ends_with"?`Ung\xFCltiger String: muss mit "${s.suffix}" enden`:s.format==="includes"?`Ung\xFCltiger String: muss "${s.includes}" enthalten`:s.format==="regex"?`Ung\xFCltiger String: muss dem Muster ${s.pattern} entsprechen`:`Ung\xFCltig: ${n[s.format]??i.format}`}case"not_multiple_of":return`Ung\xFCltige Zahl: muss ein Vielfaches von ${i.divisor} sein`;case"unrecognized_keys":return`${i.keys.length>1?"Unbekannte Schl\xFCssel":"Unbekannter Schl\xFCssel"}: ${C(i.keys,", ")}`;case"invalid_key":return`Ung\xFCltiger Schl\xFCssel in ${i.origin}`;case"invalid_union":return"Ung\xFCltige Eingabe";case"invalid_element":return`Ung\xFCltiger Wert in ${i.origin}`;default:return"Ung\xFCltige Eingabe"}}};function IC(){return{localeError:S6()}}var E6=e=>{let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":{if(Array.isArray(e))return"array";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return t},k6=()=>{let e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function t(n){return e[n]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return n=>{switch(n.code){case"invalid_type":return`Invalid input: expected ${n.expected}, received ${E6(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${K(n.values[0])}`:`Invalid option: expected one of ${C(n.values,"|")}`;case"too_big":{let i=n.inclusive?"<=":"<",s=t(n.origin);return s?`Too big: expected ${n.origin??"value"} to have ${i}${n.maximum.toString()} ${s.unit??"elements"}`:`Too big: expected ${n.origin??"value"} to be ${i}${n.maximum.toString()}`}case"too_small":{let i=n.inclusive?">=":">",s=t(n.origin);return s?`Too small: expected ${n.origin} to have ${i}${n.minimum.toString()} ${s.unit}`:`Too small: expected ${n.origin} to be ${i}${n.minimum.toString()}`}case"invalid_format":{let i=n;return i.format==="starts_with"?`Invalid string: must start with "${i.prefix}"`:i.format==="ends_with"?`Invalid string: must end with "${i.suffix}"`:i.format==="includes"?`Invalid string: must include "${i.includes}"`:i.format==="regex"?`Invalid string: must match pattern ${i.pattern}`:`Invalid ${r[i.format]??n.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${n.divisor}`;case"unrecognized_keys":return`Unrecognized key${n.keys.length>1?"s":""}: ${C(n.keys,", ")}`;case"invalid_key":return`Invalid key in ${n.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${n.origin}`;default:return"Invalid input"}}};function Pm(){return{localeError:k6()}}var A6=e=>{let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"nombro";case"object":{if(Array.isArray(e))return"tabelo";if(e===null)return"senvalora";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return t},T6=()=>{let e={string:{unit:"karaktrojn",verb:"havi"},file:{unit:"bajtojn",verb:"havi"},array:{unit:"elementojn",verb:"havi"},set:{unit:"elementojn",verb:"havi"}};function t(n){return e[n]??null}let r={regex:"enigo",email:"retadreso",url:"URL",emoji:"emo\u011Dio",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datotempo",date:"ISO-dato",time:"ISO-tempo",duration:"ISO-da\u016Dro",ipv4:"IPv4-adreso",ipv6:"IPv6-adreso",cidrv4:"IPv4-rango",cidrv6:"IPv6-rango",base64:"64-ume kodita karaktraro",base64url:"URL-64-ume kodita karaktraro",json_string:"JSON-karaktraro",e164:"E.164-nombro",jwt:"JWT",template_literal:"enigo"};return n=>{switch(n.code){case"invalid_type":return`Nevalida enigo: atendi\u011Dis ${n.expected}, ricevi\u011Dis ${A6(n.input)}`;case"invalid_value":return n.values.length===1?`Nevalida enigo: atendi\u011Dis ${K(n.values[0])}`:`Nevalida opcio: atendi\u011Dis unu el ${C(n.values,"|")}`;case"too_big":{let i=n.inclusive?"<=":"<",s=t(n.origin);return s?`Tro granda: atendi\u011Dis ke ${n.origin??"valoro"} havu ${i}${n.maximum.toString()} ${s.unit??"elementojn"}`:`Tro granda: atendi\u011Dis ke ${n.origin??"valoro"} havu ${i}${n.maximum.toString()}`}case"too_small":{let i=n.inclusive?">=":">",s=t(n.origin);return s?`Tro malgranda: atendi\u011Dis ke ${n.origin} havu ${i}${n.minimum.toString()} ${s.unit}`:`Tro malgranda: atendi\u011Dis ke ${n.origin} estu ${i}${n.minimum.toString()}`}case"invalid_format":{let i=n;return i.format==="starts_with"?`Nevalida karaktraro: devas komenci\u011Di per "${i.prefix}"`:i.format==="ends_with"?`Nevalida karaktraro: devas fini\u011Di per "${i.suffix}"`:i.format==="includes"?`Nevalida karaktraro: devas inkluzivi "${i.includes}"`:i.format==="regex"?`Nevalida karaktraro: devas kongrui kun la modelo ${i.pattern}`:`Nevalida ${r[i.format]??n.format}`}case"not_multiple_of":return`Nevalida nombro: devas esti oblo de ${n.divisor}`;case"unrecognized_keys":return`Nekonata${n.keys.length>1?"j":""} \u015Dlosilo${n.keys.length>1?"j":""}: ${C(n.keys,", ")}`;case"invalid_key":return`Nevalida \u015Dlosilo en ${n.origin}`;case"invalid_union":return"Nevalida enigo";case"invalid_element":return`Nevalida valoro en ${n.origin}`;default:return"Nevalida enigo"}}};function SC(){return{localeError:T6()}}var O6=()=>{let e={string:{unit:"caracteres",verb:"tener"},file:{unit:"bytes",verb:"tener"},array:{unit:"elementos",verb:"tener"},set:{unit:"elementos",verb:"tener"}};function t(i){return e[i]??null}let r=i=>{let s=typeof i;switch(s){case"number":return Number.isNaN(i)?"NaN":"n\xFAmero";case"object":{if(Array.isArray(i))return"arreglo";if(i===null)return"nulo";if(Object.getPrototypeOf(i)!==Object.prototype)return i.constructor.name}}return s},n={regex:"entrada",email:"direcci\xF3n de correo electr\xF3nico",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"fecha y hora ISO",date:"fecha ISO",time:"hora ISO",duration:"duraci\xF3n ISO",ipv4:"direcci\xF3n IPv4",ipv6:"direcci\xF3n IPv6",cidrv4:"rango IPv4",cidrv6:"rango IPv6",base64:"cadena codificada en base64",base64url:"URL codificada en base64",json_string:"cadena JSON",e164:"n\xFAmero E.164",jwt:"JWT",template_literal:"entrada"};return i=>{switch(i.code){case"invalid_type":return`Entrada inv\xE1lida: se esperaba ${i.expected}, recibido ${r(i.input)}`;case"invalid_value":return i.values.length===1?`Entrada inv\xE1lida: se esperaba ${K(i.values[0])}`:`Opci\xF3n inv\xE1lida: se esperaba una de ${C(i.values,"|")}`;case"too_big":{let s=i.inclusive?"<=":"<",o=t(i.origin);return o?`Demasiado grande: se esperaba que ${i.origin??"valor"} tuviera ${s}${i.maximum.toString()} ${o.unit??"elementos"}`:`Demasiado grande: se esperaba que ${i.origin??"valor"} fuera ${s}${i.maximum.toString()}`}case"too_small":{let s=i.inclusive?">=":">",o=t(i.origin);return o?`Demasiado peque\xF1o: se esperaba que ${i.origin} tuviera ${s}${i.minimum.toString()} ${o.unit}`:`Demasiado peque\xF1o: se esperaba que ${i.origin} fuera ${s}${i.minimum.toString()}`}case"invalid_format":{let s=i;return s.format==="starts_with"?`Cadena inv\xE1lida: debe comenzar con "${s.prefix}"`:s.format==="ends_with"?`Cadena inv\xE1lida: debe terminar en "${s.suffix}"`:s.format==="includes"?`Cadena inv\xE1lida: debe incluir "${s.includes}"`:s.format==="regex"?`Cadena inv\xE1lida: debe coincidir con el patr\xF3n ${s.pattern}`:`Inv\xE1lido ${n[s.format]??i.format}`}case"not_multiple_of":return`N\xFAmero inv\xE1lido: debe ser m\xFAltiplo de ${i.divisor}`;case"unrecognized_keys":return`Llave${i.keys.length>1?"s":""} desconocida${i.keys.length>1?"s":""}: ${C(i.keys,", ")}`;case"invalid_key":return`Llave inv\xE1lida en ${i.origin}`;case"invalid_union":return"Entrada inv\xE1lida";case"invalid_element":return`Valor inv\xE1lido en ${i.origin}`;default:return"Entrada inv\xE1lida"}}};function EC(){return{localeError:O6()}}var $6=()=>{let e={string:{unit:"\u06A9\u0627\u0631\u0627\u06A9\u062A\u0631",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"},file:{unit:"\u0628\u0627\u06CC\u062A",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"},array:{unit:"\u0622\u06CC\u062A\u0645",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"},set:{unit:"\u0622\u06CC\u062A\u0645",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"}};function t(i){return e[i]??null}let r=i=>{let s=typeof i;switch(s){case"number":return Number.isNaN(i)?"NaN":"\u0639\u062F\u062F";case"object":{if(Array.isArray(i))return"\u0622\u0631\u0627\u06CC\u0647";if(i===null)return"null";if(Object.getPrototypeOf(i)!==Object.prototype&&i.constructor)return i.constructor.name}}return s},n={regex:"\u0648\u0631\u0648\u062F\u06CC",email:"\u0622\u062F\u0631\u0633 \u0627\u06CC\u0645\u06CC\u0644",url:"URL",emoji:"\u0627\u06CC\u0645\u0648\u062C\u06CC",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u062A\u0627\u0631\u06CC\u062E \u0648 \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",date:"\u062A\u0627\u0631\u06CC\u062E \u0627\u06CC\u0632\u0648",time:"\u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",duration:"\u0645\u062F\u062A \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",ipv4:"IPv4 \u0622\u062F\u0631\u0633",ipv6:"IPv6 \u0622\u062F\u0631\u0633",cidrv4:"IPv4 \u062F\u0627\u0645\u0646\u0647",cidrv6:"IPv6 \u062F\u0627\u0645\u0646\u0647",base64:"base64-encoded \u0631\u0634\u062A\u0647",base64url:"base64url-encoded \u0631\u0634\u062A\u0647",json_string:"JSON \u0631\u0634\u062A\u0647",e164:"E.164 \u0639\u062F\u062F",jwt:"JWT",template_literal:"\u0648\u0631\u0648\u062F\u06CC"};return i=>{switch(i.code){case"invalid_type":return`\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${i.expected} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${r(i.input)} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`;case"invalid_value":return i.values.length===1?`\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${K(i.values[0])} \u0645\u06CC\u200C\u0628\u0648\u062F`:`\u06AF\u0632\u06CC\u0646\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A \u06CC\u06A9\u06CC \u0627\u0632 ${C(i.values,"|")} \u0645\u06CC\u200C\u0628\u0648\u062F`;case"too_big":{let s=i.inclusive?"<=":"<",o=t(i.origin);return o?`\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${i.origin??"\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${s}${i.maximum.toString()} ${o.unit??"\u0639\u0646\u0635\u0631"} \u0628\u0627\u0634\u062F`:`\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${i.origin??"\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${s}${i.maximum.toString()} \u0628\u0627\u0634\u062F`}case"too_small":{let s=i.inclusive?">=":">",o=t(i.origin);return o?`\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${i.origin} \u0628\u0627\u06CC\u062F ${s}${i.minimum.toString()} ${o.unit} \u0628\u0627\u0634\u062F`:`\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${i.origin} \u0628\u0627\u06CC\u062F ${s}${i.minimum.toString()} \u0628\u0627\u0634\u062F`}case"invalid_format":{let s=i;return s.format==="starts_with"?`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${s.prefix}" \u0634\u0631\u0648\u0639 \u0634\u0648\u062F`:s.format==="ends_with"?`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${s.suffix}" \u062A\u0645\u0627\u0645 \u0634\u0648\u062F`:s.format==="includes"?`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0634\u0627\u0645\u0644 "${s.includes}" \u0628\u0627\u0634\u062F`:s.format==="regex"?`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 \u0627\u0644\u06AF\u0648\u06CC ${s.pattern} \u0645\u0637\u0627\u0628\u0642\u062A \u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F`:`${n[s.format]??i.format} \u0646\u0627\u0645\u0639\u062A\u0628\u0631`}case"not_multiple_of":return`\u0639\u062F\u062F \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0645\u0636\u0631\u0628 ${i.divisor} \u0628\u0627\u0634\u062F`;case"unrecognized_keys":return`\u06A9\u0644\u06CC\u062F${i.keys.length>1?"\u0647\u0627\u06CC":""} \u0646\u0627\u0634\u0646\u0627\u0633: ${C(i.keys,", ")}`;case"invalid_key":return`\u06A9\u0644\u06CC\u062F \u0646\u0627\u0634\u0646\u0627\u0633 \u062F\u0631 ${i.origin}`;case"invalid_union":return"\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631";case"invalid_element":return`\u0645\u0642\u062F\u0627\u0631 \u0646\u0627\u0645\u0639\u062A\u0628\u0631 \u062F\u0631 ${i.origin}`;default:return"\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631"}}};function kC(){return{localeError:$6()}}var C6=()=>{let e={string:{unit:"merkki\xE4",subject:"merkkijonon"},file:{unit:"tavua",subject:"tiedoston"},array:{unit:"alkiota",subject:"listan"},set:{unit:"alkiota",subject:"joukon"},number:{unit:"",subject:"luvun"},bigint:{unit:"",subject:"suuren kokonaisluvun"},int:{unit:"",subject:"kokonaisluvun"},date:{unit:"",subject:"p\xE4iv\xE4m\xE4\xE4r\xE4n"}};function t(i){return e[i]??null}let r=i=>{let s=typeof i;switch(s){case"number":return Number.isNaN(i)?"NaN":"number";case"object":{if(Array.isArray(i))return"array";if(i===null)return"null";if(Object.getPrototypeOf(i)!==Object.prototype&&i.constructor)return i.constructor.name}}return s},n={regex:"s\xE4\xE4nn\xF6llinen lauseke",email:"s\xE4hk\xF6postiosoite",url:"URL-osoite",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-aikaleima",date:"ISO-p\xE4iv\xE4m\xE4\xE4r\xE4",time:"ISO-aika",duration:"ISO-kesto",ipv4:"IPv4-osoite",ipv6:"IPv6-osoite",cidrv4:"IPv4-alue",cidrv6:"IPv6-alue",base64:"base64-koodattu merkkijono",base64url:"base64url-koodattu merkkijono",json_string:"JSON-merkkijono",e164:"E.164-luku",jwt:"JWT",template_literal:"templaattimerkkijono"};return i=>{switch(i.code){case"invalid_type":return`Virheellinen tyyppi: odotettiin ${i.expected}, oli ${r(i.input)}`;case"invalid_value":return i.values.length===1?`Virheellinen sy\xF6te: t\xE4ytyy olla ${K(i.values[0])}`:`Virheellinen valinta: t\xE4ytyy olla yksi seuraavista: ${C(i.values,"|")}`;case"too_big":{let s=i.inclusive?"<=":"<",o=t(i.origin);return o?`Liian suuri: ${o.subject} t\xE4ytyy olla ${s}${i.maximum.toString()} ${o.unit}`.trim():`Liian suuri: arvon t\xE4ytyy olla ${s}${i.maximum.toString()}`}case"too_small":{let s=i.inclusive?">=":">",o=t(i.origin);return o?`Liian pieni: ${o.subject} t\xE4ytyy olla ${s}${i.minimum.toString()} ${o.unit}`.trim():`Liian pieni: arvon t\xE4ytyy olla ${s}${i.minimum.toString()}`}case"invalid_format":{let s=i;return s.format==="starts_with"?`Virheellinen sy\xF6te: t\xE4ytyy alkaa "${s.prefix}"`:s.format==="ends_with"?`Virheellinen sy\xF6te: t\xE4ytyy loppua "${s.suffix}"`:s.format==="includes"?`Virheellinen sy\xF6te: t\xE4ytyy sis\xE4lt\xE4\xE4 "${s.includes}"`:s.format==="regex"?`Virheellinen sy\xF6te: t\xE4ytyy vastata s\xE4\xE4nn\xF6llist\xE4 lauseketta ${s.pattern}`:`Virheellinen ${n[s.format]??i.format}`}case"not_multiple_of":return`Virheellinen luku: t\xE4ytyy olla luvun ${i.divisor} monikerta`;case"unrecognized_keys":return`${i.keys.length>1?"Tuntemattomat avaimet":"Tuntematon avain"}: ${C(i.keys,", ")}`;case"invalid_key":return"Virheellinen avain tietueessa";case"invalid_union":return"Virheellinen unioni";case"invalid_element":return"Virheellinen arvo joukossa";default:return"Virheellinen sy\xF6te"}}};function AC(){return{localeError:C6()}}var P6=()=>{let e={string:{unit:"caract\xE8res",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"\xE9l\xE9ments",verb:"avoir"},set:{unit:"\xE9l\xE9ments",verb:"avoir"}};function t(i){return e[i]??null}let r=i=>{let s=typeof i;switch(s){case"number":return Number.isNaN(i)?"NaN":"nombre";case"object":{if(Array.isArray(i))return"tableau";if(i===null)return"null";if(Object.getPrototypeOf(i)!==Object.prototype&&i.constructor)return i.constructor.name}}return s},n={regex:"entr\xE9e",email:"adresse e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date et heure ISO",date:"date ISO",time:"heure ISO",duration:"dur\xE9e ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"cha\xEEne encod\xE9e en base64",base64url:"cha\xEEne encod\xE9e en base64url",json_string:"cha\xEEne JSON",e164:"num\xE9ro E.164",jwt:"JWT",template_literal:"entr\xE9e"};return i=>{switch(i.code){case"invalid_type":return`Entr\xE9e invalide : ${i.expected} attendu, ${r(i.input)} re\xE7u`;case"invalid_value":return i.values.length===1?`Entr\xE9e invalide : ${K(i.values[0])} attendu`:`Option invalide : une valeur parmi ${C(i.values,"|")} attendue`;case"too_big":{let s=i.inclusive?"<=":"<",o=t(i.origin);return o?`Trop grand : ${i.origin??"valeur"} doit ${o.verb} ${s}${i.maximum.toString()} ${o.unit??"\xE9l\xE9ment(s)"}`:`Trop grand : ${i.origin??"valeur"} doit \xEAtre ${s}${i.maximum.toString()}`}case"too_small":{let s=i.inclusive?">=":">",o=t(i.origin);return o?`Trop petit : ${i.origin} doit ${o.verb} ${s}${i.minimum.toString()} ${o.unit}`:`Trop petit : ${i.origin} doit \xEAtre ${s}${i.minimum.toString()}`}case"invalid_format":{let s=i;return s.format==="starts_with"?`Cha\xEEne invalide : doit commencer par "${s.prefix}"`:s.format==="ends_with"?`Cha\xEEne invalide : doit se terminer par "${s.suffix}"`:s.format==="includes"?`Cha\xEEne invalide : doit inclure "${s.includes}"`:s.format==="regex"?`Cha\xEEne invalide : doit correspondre au mod\xE8le ${s.pattern}`:`${n[s.format]??i.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit \xEAtre un multiple de ${i.divisor}`;case"unrecognized_keys":return`Cl\xE9${i.keys.length>1?"s":""} non reconnue${i.keys.length>1?"s":""} : ${C(i.keys,", ")}`;case"invalid_key":return`Cl\xE9 invalide dans ${i.origin}`;case"invalid_union":return"Entr\xE9e invalide";case"invalid_element":return`Valeur invalide dans ${i.origin}`;default:return"Entr\xE9e invalide"}}};function TC(){return{localeError:P6()}}var N6=()=>{let e={string:{unit:"caract\xE8res",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"\xE9l\xE9ments",verb:"avoir"},set:{unit:"\xE9l\xE9ments",verb:"avoir"}};function t(i){return e[i]??null}let r=i=>{let s=typeof i;switch(s){case"number":return Number.isNaN(i)?"NaN":"number";case"object":{if(Array.isArray(i))return"array";if(i===null)return"null";if(Object.getPrototypeOf(i)!==Object.prototype&&i.constructor)return i.constructor.name}}return s},n={regex:"entr\xE9e",email:"adresse courriel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date-heure ISO",date:"date ISO",time:"heure ISO",duration:"dur\xE9e ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"cha\xEEne encod\xE9e en base64",base64url:"cha\xEEne encod\xE9e en base64url",json_string:"cha\xEEne JSON",e164:"num\xE9ro E.164",jwt:"JWT",template_literal:"entr\xE9e"};return i=>{switch(i.code){case"invalid_type":return`Entr\xE9e invalide : attendu ${i.expected}, re\xE7u ${r(i.input)}`;case"invalid_value":return i.values.length===1?`Entr\xE9e invalide : attendu ${K(i.values[0])}`:`Option invalide : attendu l'une des valeurs suivantes ${C(i.values,"|")}`;case"too_big":{let s=i.inclusive?"\u2264":"<",o=t(i.origin);return o?`Trop grand : attendu que ${i.origin??"la valeur"} ait ${s}${i.maximum.toString()} ${o.unit}`:`Trop grand : attendu que ${i.origin??"la valeur"} soit ${s}${i.maximum.toString()}`}case"too_small":{let s=i.inclusive?"\u2265":">",o=t(i.origin);return o?`Trop petit : attendu que ${i.origin} ait ${s}${i.minimum.toString()} ${o.unit}`:`Trop petit : attendu que ${i.origin} soit ${s}${i.minimum.toString()}`}case"invalid_format":{let s=i;return s.format==="starts_with"?`Cha\xEEne invalide : doit commencer par "${s.prefix}"`:s.format==="ends_with"?`Cha\xEEne invalide : doit se terminer par "${s.suffix}"`:s.format==="includes"?`Cha\xEEne invalide : doit inclure "${s.includes}"`:s.format==="regex"?`Cha\xEEne invalide : doit correspondre au motif ${s.pattern}`:`${n[s.format]??i.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit \xEAtre un multiple de ${i.divisor}`;case"unrecognized_keys":return`Cl\xE9${i.keys.length>1?"s":""} non reconnue${i.keys.length>1?"s":""} : ${C(i.keys,", ")}`;case"invalid_key":return`Cl\xE9 invalide dans ${i.origin}`;case"invalid_union":return"Entr\xE9e invalide";case"invalid_element":return`Valeur invalide dans ${i.origin}`;default:return"Entr\xE9e invalide"}}};function OC(){return{localeError:N6()}}var R6=()=>{let e={string:{unit:"\u05D0\u05D5\u05EA\u05D9\u05D5\u05EA",verb:"\u05DC\u05DB\u05DC\u05D5\u05DC"},file:{unit:"\u05D1\u05D9\u05D9\u05D8\u05D9\u05DD",verb:"\u05DC\u05DB\u05DC\u05D5\u05DC"},array:{unit:"\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD",verb:"\u05DC\u05DB\u05DC\u05D5\u05DC"},set:{unit:"\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD",verb:"\u05DC\u05DB\u05DC\u05D5\u05DC"}};function t(i){return e[i]??null}let r=i=>{let s=typeof i;switch(s){case"number":return Number.isNaN(i)?"NaN":"number";case"object":{if(Array.isArray(i))return"array";if(i===null)return"null";if(Object.getPrototypeOf(i)!==Object.prototype&&i.constructor)return i.constructor.name}}return s},n={regex:"\u05E7\u05DC\u05D8",email:"\u05DB\u05EA\u05D5\u05D1\u05EA \u05D0\u05D9\u05DE\u05D9\u05D9\u05DC",url:"\u05DB\u05EA\u05D5\u05D1\u05EA \u05E8\u05E9\u05EA",emoji:"\u05D0\u05D9\u05DE\u05D5\u05D2'\u05D9",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u05EA\u05D0\u05E8\u05D9\u05DA \u05D5\u05D6\u05DE\u05DF ISO",date:"\u05EA\u05D0\u05E8\u05D9\u05DA ISO",time:"\u05D6\u05DE\u05DF ISO",duration:"\u05DE\u05E9\u05DA \u05D6\u05DE\u05DF ISO",ipv4:"\u05DB\u05EA\u05D5\u05D1\u05EA IPv4",ipv6:"\u05DB\u05EA\u05D5\u05D1\u05EA IPv6",cidrv4:"\u05D8\u05D5\u05D5\u05D7 IPv4",cidrv6:"\u05D8\u05D5\u05D5\u05D7 IPv6",base64:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64",base64url:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64 \u05DC\u05DB\u05EA\u05D5\u05D1\u05D5\u05EA \u05E8\u05E9\u05EA",json_string:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA JSON",e164:"\u05DE\u05E1\u05E4\u05E8 E.164",jwt:"JWT",template_literal:"\u05E7\u05DC\u05D8"};return i=>{switch(i.code){case"invalid_type":return`\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA ${i.expected}, \u05D4\u05EA\u05E7\u05D1\u05DC ${r(i.input)}`;case"invalid_value":return i.values.length===1?`\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA ${K(i.values[0])}`:`\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05D0\u05D7\u05EA \u05DE\u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA ${C(i.values,"|")}`;case"too_big":{let s=i.inclusive?"<=":"<",o=t(i.origin);return o?`\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${i.origin??"value"} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${s}${i.maximum.toString()} ${o.unit??"elements"}`:`\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${i.origin??"value"} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${s}${i.maximum.toString()}`}case"too_small":{let s=i.inclusive?">=":">",o=t(i.origin);return o?`\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${i.origin} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${s}${i.minimum.toString()} ${o.unit}`:`\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${i.origin} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${s}${i.minimum.toString()}`}case"invalid_format":{let s=i;return s.format==="starts_with"?`\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05E0\u05D4: \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D7\u05D9\u05DC \u05D1"${s.prefix}"`:s.format==="ends_with"?`\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05E0\u05D4: \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05E1\u05EA\u05D9\u05D9\u05DD \u05D1 "${s.suffix}"`:s.format==="includes"?`\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05E0\u05D4: \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05DB\u05DC\u05D5\u05DC "${s.includes}"`:s.format==="regex"?`\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05E0\u05D4: \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D0\u05D9\u05DD \u05DC\u05EA\u05D1\u05E0\u05D9\u05EA ${s.pattern}`:`${n[s.format]??i.format} \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF`}case"not_multiple_of":return`\u05DE\u05E1\u05E4\u05E8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA \u05DE\u05DB\u05E4\u05DC\u05D4 \u05E9\u05DC ${i.divisor}`;case"unrecognized_keys":return`\u05DE\u05E4\u05EA\u05D7${i.keys.length>1?"\u05D5\u05EA":""} \u05DC\u05D0 \u05DE\u05D6\u05D5\u05D4${i.keys.length>1?"\u05D9\u05DD":"\u05D4"}: ${C(i.keys,", ")}`;case"invalid_key":return`\u05DE\u05E4\u05EA\u05D7 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1${i.origin}`;case"invalid_union":return"\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF";case"invalid_element":return`\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1${i.origin}`;default:return"\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF"}}};function $C(){return{localeError:R6()}}var M6=()=>{let e={string:{unit:"karakter",verb:"legyen"},file:{unit:"byte",verb:"legyen"},array:{unit:"elem",verb:"legyen"},set:{unit:"elem",verb:"legyen"}};function t(i){return e[i]??null}let r=i=>{let s=typeof i;switch(s){case"number":return Number.isNaN(i)?"NaN":"sz\xE1m";case"object":{if(Array.isArray(i))return"t\xF6mb";if(i===null)return"null";if(Object.getPrototypeOf(i)!==Object.prototype&&i.constructor)return i.constructor.name}}return s},n={regex:"bemenet",email:"email c\xEDm",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO id\u0151b\xE9lyeg",date:"ISO d\xE1tum",time:"ISO id\u0151",duration:"ISO id\u0151intervallum",ipv4:"IPv4 c\xEDm",ipv6:"IPv6 c\xEDm",cidrv4:"IPv4 tartom\xE1ny",cidrv6:"IPv6 tartom\xE1ny",base64:"base64-k\xF3dolt string",base64url:"base64url-k\xF3dolt string",json_string:"JSON string",e164:"E.164 sz\xE1m",jwt:"JWT",template_literal:"bemenet"};return i=>{switch(i.code){case"invalid_type":return`\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${i.expected}, a kapott \xE9rt\xE9k ${r(i.input)}`;case"invalid_value":return i.values.length===1?`\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${K(i.values[0])}`:`\xC9rv\xE9nytelen opci\xF3: valamelyik \xE9rt\xE9k v\xE1rt ${C(i.values,"|")}`;case"too_big":{let s=i.inclusive?"<=":"<",o=t(i.origin);return o?`T\xFAl nagy: ${i.origin??"\xE9rt\xE9k"} m\xE9rete t\xFAl nagy ${s}${i.maximum.toString()} ${o.unit??"elem"}`:`T\xFAl nagy: a bemeneti \xE9rt\xE9k ${i.origin??"\xE9rt\xE9k"} t\xFAl nagy: ${s}${i.maximum.toString()}`}case"too_small":{let s=i.inclusive?">=":">",o=t(i.origin);return o?`T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${i.origin} m\xE9rete t\xFAl kicsi ${s}${i.minimum.toString()} ${o.unit}`:`T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${i.origin} t\xFAl kicsi ${s}${i.minimum.toString()}`}case"invalid_format":{let s=i;return s.format==="starts_with"?`\xC9rv\xE9nytelen string: "${s.prefix}" \xE9rt\xE9kkel kell kezd\u0151dnie`:s.format==="ends_with"?`\xC9rv\xE9nytelen string: "${s.suffix}" \xE9rt\xE9kkel kell v\xE9gz\u0151dnie`:s.format==="includes"?`\xC9rv\xE9nytelen string: "${s.includes}" \xE9rt\xE9ket kell tartalmaznia`:s.format==="regex"?`\xC9rv\xE9nytelen string: ${s.pattern} mint\xE1nak kell megfelelnie`:`\xC9rv\xE9nytelen ${n[s.format]??i.format}`}case"not_multiple_of":return`\xC9rv\xE9nytelen sz\xE1m: ${i.divisor} t\xF6bbsz\xF6r\xF6s\xE9nek kell lennie`;case"unrecognized_keys":return`Ismeretlen kulcs${i.keys.length>1?"s":""}: ${C(i.keys,", ")}`;case"invalid_key":return`\xC9rv\xE9nytelen kulcs ${i.origin}`;case"invalid_union":return"\xC9rv\xE9nytelen bemenet";case"invalid_element":return`\xC9rv\xE9nytelen \xE9rt\xE9k: ${i.origin}`;default:return"\xC9rv\xE9nytelen bemenet"}}};function CC(){return{localeError:M6()}}var j6=()=>{let e={string:{unit:"karakter",verb:"memiliki"},file:{unit:"byte",verb:"memiliki"},array:{unit:"item",verb:"memiliki"},set:{unit:"item",verb:"memiliki"}};function t(i){return e[i]??null}let r=i=>{let s=typeof i;switch(s){case"number":return Number.isNaN(i)?"NaN":"number";case"object":{if(Array.isArray(i))return"array";if(i===null)return"null";if(Object.getPrototypeOf(i)!==Object.prototype&&i.constructor)return i.constructor.name}}return s},n={regex:"input",email:"alamat email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tanggal dan waktu format ISO",date:"tanggal format ISO",time:"jam format ISO",duration:"durasi format ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"rentang alamat IPv4",cidrv6:"rentang alamat IPv6",base64:"string dengan enkode base64",base64url:"string dengan enkode base64url",json_string:"string JSON",e164:"angka E.164",jwt:"JWT",template_literal:"input"};return i=>{switch(i.code){case"invalid_type":return`Input tidak valid: diharapkan ${i.expected}, diterima ${r(i.input)}`;case"invalid_value":return i.values.length===1?`Input tidak valid: diharapkan ${K(i.values[0])}`:`Pilihan tidak valid: diharapkan salah satu dari ${C(i.values,"|")}`;case"too_big":{let s=i.inclusive?"<=":"<",o=t(i.origin);return o?`Terlalu besar: diharapkan ${i.origin??"value"} memiliki ${s}${i.maximum.toString()} ${o.unit??"elemen"}`:`Terlalu besar: diharapkan ${i.origin??"value"} menjadi ${s}${i.maximum.toString()}`}case"too_small":{let s=i.inclusive?">=":">",o=t(i.origin);return o?`Terlalu kecil: diharapkan ${i.origin} memiliki ${s}${i.minimum.toString()} ${o.unit}`:`Terlalu kecil: diharapkan ${i.origin} menjadi ${s}${i.minimum.toString()}`}case"invalid_format":{let s=i;return s.format==="starts_with"?`String tidak valid: harus dimulai dengan "${s.prefix}"`:s.format==="ends_with"?`String tidak valid: harus berakhir dengan "${s.suffix}"`:s.format==="includes"?`String tidak valid: harus menyertakan "${s.includes}"`:s.format==="regex"?`String tidak valid: harus sesuai pola ${s.pattern}`:`${n[s.format]??i.format} tidak valid`}case"not_multiple_of":return`Angka tidak valid: harus kelipatan dari ${i.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali ${i.keys.length>1?"s":""}: ${C(i.keys,", ")}`;case"invalid_key":return`Kunci tidak valid di ${i.origin}`;case"invalid_union":return"Input tidak valid";case"invalid_element":return`Nilai tidak valid di ${i.origin}`;default:return"Input tidak valid"}}};function PC(){return{localeError:j6()}}var D6=()=>{let e={string:{unit:"caratteri",verb:"avere"},file:{unit:"byte",verb:"avere"},array:{unit:"elementi",verb:"avere"},set:{unit:"elementi",verb:"avere"}};function t(i){return e[i]??null}let r=i=>{let s=typeof i;switch(s){case"number":return Number.isNaN(i)?"NaN":"numero";case"object":{if(Array.isArray(i))return"vettore";if(i===null)return"null";if(Object.getPrototypeOf(i)!==Object.prototype&&i.constructor)return i.constructor.name}}return s},n={regex:"input",email:"indirizzo email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e ora ISO",date:"data ISO",time:"ora ISO",duration:"durata ISO",ipv4:"indirizzo IPv4",ipv6:"indirizzo IPv6",cidrv4:"intervallo IPv4",cidrv6:"intervallo IPv6",base64:"stringa codificata in base64",base64url:"URL codificata in base64",json_string:"stringa JSON",e164:"numero E.164",jwt:"JWT",template_literal:"input"};return i=>{switch(i.code){case"invalid_type":return`Input non valido: atteso ${i.expected}, ricevuto ${r(i.input)}`;case"invalid_value":return i.values.length===1?`Input non valido: atteso ${K(i.values[0])}`:`Opzione non valida: atteso uno tra ${C(i.values,"|")}`;case"too_big":{let s=i.inclusive?"<=":"<",o=t(i.origin);return o?`Troppo grande: ${i.origin??"valore"} deve avere ${s}${i.maximum.toString()} ${o.unit??"elementi"}`:`Troppo grande: ${i.origin??"valore"} deve essere ${s}${i.maximum.toString()}`}case"too_small":{let s=i.inclusive?">=":">",o=t(i.origin);return o?`Troppo piccolo: ${i.origin} deve avere ${s}${i.minimum.toString()} ${o.unit}`:`Troppo piccolo: ${i.origin} deve essere ${s}${i.minimum.toString()}`}case"invalid_format":{let s=i;return s.format==="starts_with"?`Stringa non valida: deve iniziare con "${s.prefix}"`:s.format==="ends_with"?`Stringa non valida: deve terminare con "${s.suffix}"`:s.format==="includes"?`Stringa non valida: deve includere "${s.includes}"`:s.format==="regex"?`Stringa non valida: deve corrispondere al pattern ${s.pattern}`:`Invalid ${n[s.format]??i.format}`}case"not_multiple_of":return`Numero non valido: deve essere un multiplo di ${i.divisor}`;case"unrecognized_keys":return`Chiav${i.keys.length>1?"i":"e"} non riconosciut${i.keys.length>1?"e":"a"}: ${C(i.keys,", ")}`;case"invalid_key":return`Chiave non valida in ${i.origin}`;case"invalid_union":return"Input non valido";case"invalid_element":return`Valore non valido in ${i.origin}`;default:return"Input non valido"}}};function NC(){return{localeError:D6()}}var z6=()=>{let e={string:{unit:"\u6587\u5B57",verb:"\u3067\u3042\u308B"},file:{unit:"\u30D0\u30A4\u30C8",verb:"\u3067\u3042\u308B"},array:{unit:"\u8981\u7D20",verb:"\u3067\u3042\u308B"},set:{unit:"\u8981\u7D20",verb:"\u3067\u3042\u308B"}};function t(i){return e[i]??null}let r=i=>{let s=typeof i;switch(s){case"number":return Number.isNaN(i)?"NaN":"\u6570\u5024";case"object":{if(Array.isArray(i))return"\u914D\u5217";if(i===null)return"null";if(Object.getPrototypeOf(i)!==Object.prototype&&i.constructor)return i.constructor.name}}return s},n={regex:"\u5165\u529B\u5024",email:"\u30E1\u30FC\u30EB\u30A2\u30C9\u30EC\u30B9",url:"URL",emoji:"\u7D75\u6587\u5B57",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO\u65E5\u6642",date:"ISO\u65E5\u4ED8",time:"ISO\u6642\u523B",duration:"ISO\u671F\u9593",ipv4:"IPv4\u30A2\u30C9\u30EC\u30B9",ipv6:"IPv6\u30A2\u30C9\u30EC\u30B9",cidrv4:"IPv4\u7BC4\u56F2",cidrv6:"IPv6\u7BC4\u56F2",base64:"base64\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217",base64url:"base64url\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217",json_string:"JSON\u6587\u5B57\u5217",e164:"E.164\u756A\u53F7",jwt:"JWT",template_literal:"\u5165\u529B\u5024"};return i=>{switch(i.code){case"invalid_type":return`\u7121\u52B9\u306A\u5165\u529B: ${i.expected}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${r(i.input)}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`;case"invalid_value":return i.values.length===1?`\u7121\u52B9\u306A\u5165\u529B: ${K(i.values[0])}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F`:`\u7121\u52B9\u306A\u9078\u629E: ${C(i.values,"\u3001")}\u306E\u3044\u305A\u308C\u304B\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;case"too_big":{let s=i.inclusive?"\u4EE5\u4E0B\u3067\u3042\u308B":"\u3088\u308A\u5C0F\u3055\u3044",o=t(i.origin);return o?`\u5927\u304D\u3059\u304E\u308B\u5024: ${i.origin??"\u5024"}\u306F${i.maximum.toString()}${o.unit??"\u8981\u7D20"}${s}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:`\u5927\u304D\u3059\u304E\u308B\u5024: ${i.origin??"\u5024"}\u306F${i.maximum.toString()}${s}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`}case"too_small":{let s=i.inclusive?"\u4EE5\u4E0A\u3067\u3042\u308B":"\u3088\u308A\u5927\u304D\u3044",o=t(i.origin);return o?`\u5C0F\u3055\u3059\u304E\u308B\u5024: ${i.origin}\u306F${i.minimum.toString()}${o.unit}${s}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:`\u5C0F\u3055\u3059\u304E\u308B\u5024: ${i.origin}\u306F${i.minimum.toString()}${s}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`}case"invalid_format":{let s=i;return s.format==="starts_with"?`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${s.prefix}"\u3067\u59CB\u307E\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:s.format==="ends_with"?`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${s.suffix}"\u3067\u7D42\u308F\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:s.format==="includes"?`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${s.includes}"\u3092\u542B\u3080\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:s.format==="regex"?`\u7121\u52B9\u306A\u6587\u5B57\u5217: \u30D1\u30BF\u30FC\u30F3${s.pattern}\u306B\u4E00\u81F4\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:`\u7121\u52B9\u306A${n[s.format]??i.format}`}case"not_multiple_of":return`\u7121\u52B9\u306A\u6570\u5024: ${i.divisor}\u306E\u500D\u6570\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;case"unrecognized_keys":return`\u8A8D\u8B58\u3055\u308C\u3066\u3044\u306A\u3044\u30AD\u30FC${i.keys.length>1?"\u7FA4":""}: ${C(i.keys,"\u3001")}`;case"invalid_key":return`${i.origin}\u5185\u306E\u7121\u52B9\u306A\u30AD\u30FC`;case"invalid_union":return"\u7121\u52B9\u306A\u5165\u529B";case"invalid_element":return`${i.origin}\u5185\u306E\u7121\u52B9\u306A\u5024`;default:return"\u7121\u52B9\u306A\u5165\u529B"}}};function RC(){return{localeError:z6()}}var L6=()=>{let e={string:{unit:"\u178F\u17BD\u17A2\u1780\u17D2\u179F\u179A",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"},file:{unit:"\u1794\u17C3",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"},array:{unit:"\u1792\u17B6\u178F\u17BB",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"},set:{unit:"\u1792\u17B6\u178F\u17BB",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"}};function t(i){return e[i]??null}let r=i=>{let s=typeof i;switch(s){case"number":return Number.isNaN(i)?"\u1798\u17B7\u1793\u1798\u17C2\u1793\u1787\u17B6\u179B\u17C1\u1781 (NaN)":"\u179B\u17C1\u1781";case"object":{if(Array.isArray(i))return"\u17A2\u17B6\u179A\u17C1 (Array)";if(i===null)return"\u1782\u17D2\u1798\u17B6\u1793\u178F\u1798\u17D2\u179B\u17C3 (null)";if(Object.getPrototypeOf(i)!==Object.prototype&&i.constructor)return i.constructor.name}}return s},n={regex:"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B",email:"\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793\u17A2\u17CA\u17B8\u1798\u17C2\u179B",url:"URL",emoji:"\u179F\u1789\u17D2\u1789\u17B6\u17A2\u17B6\u179A\u1798\u17D2\u1798\u178E\u17CD",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 \u1793\u17B7\u1784\u1798\u17C9\u17C4\u1784 ISO",date:"\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 ISO",time:"\u1798\u17C9\u17C4\u1784 ISO",duration:"\u179A\u1799\u17C8\u1796\u17C1\u179B ISO",ipv4:"\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4",ipv6:"\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6",cidrv4:"\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4",cidrv6:"\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6",base64:"\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64",base64url:"\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64url",json_string:"\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A JSON",e164:"\u179B\u17C1\u1781 E.164",jwt:"JWT",template_literal:"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B"};return i=>{switch(i.code){case"invalid_type":return`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${i.expected} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${r(i.input)}`;case"invalid_value":return i.values.length===1?`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${K(i.values[0])}`:`\u1787\u1798\u17D2\u179A\u17BE\u179F\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1787\u17B6\u1798\u17BD\u1799\u1780\u17D2\u1793\u17BB\u1784\u1785\u17C6\u178E\u17C4\u1798 ${C(i.values,"|")}`;case"too_big":{let s=i.inclusive?"<=":"<",o=t(i.origin);return o?`\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${i.origin??"\u178F\u1798\u17D2\u179B\u17C3"} ${s} ${i.maximum.toString()} ${o.unit??"\u1792\u17B6\u178F\u17BB"}`:`\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${i.origin??"\u178F\u1798\u17D2\u179B\u17C3"} ${s} ${i.maximum.toString()}`}case"too_small":{let s=i.inclusive?">=":">",o=t(i.origin);return o?`\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${i.origin} ${s} ${i.minimum.toString()} ${o.unit}`:`\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${i.origin} ${s} ${i.minimum.toString()}`}case"invalid_format":{let s=i;return s.format==="starts_with"?`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1785\u17B6\u1794\u17CB\u1795\u17D2\u178F\u17BE\u1798\u178A\u17C4\u1799 "${s.prefix}"`:s.format==="ends_with"?`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1794\u1789\u17D2\u1785\u1794\u17CB\u178A\u17C4\u1799 "${s.suffix}"`:s.format==="includes"?`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1798\u17B6\u1793 "${s.includes}"`:s.format==="regex"?`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1795\u17D2\u1782\u17BC\u1795\u17D2\u1782\u1784\u1793\u17B9\u1784\u1791\u1798\u17D2\u179A\u1784\u17CB\u178A\u17C2\u179B\u1794\u17B6\u1793\u1780\u17C6\u178E\u178F\u17CB ${s.pattern}`:`\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 ${n[s.format]??i.format}`}case"not_multiple_of":return`\u179B\u17C1\u1781\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1787\u17B6\u1796\u17A0\u17BB\u1782\u17BB\u178E\u1793\u17C3 ${i.divisor}`;case"unrecognized_keys":return`\u179A\u1780\u1783\u17BE\u1789\u179F\u17C4\u1798\u17B7\u1793\u179F\u17D2\u1782\u17B6\u179B\u17CB\u17D6 ${C(i.keys,", ")}`;case"invalid_key":return`\u179F\u17C4\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${i.origin}`;case"invalid_union":return"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C";case"invalid_element":return`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${i.origin}`;default:return"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C"}}};function MC(){return{localeError:L6()}}var U6=()=>{let e={string:{unit:"\uBB38\uC790",verb:"to have"},file:{unit:"\uBC14\uC774\uD2B8",verb:"to have"},array:{unit:"\uAC1C",verb:"to have"},set:{unit:"\uAC1C",verb:"to have"}};function t(i){return e[i]??null}let r=i=>{let s=typeof i;switch(s){case"number":return Number.isNaN(i)?"NaN":"number";case"object":{if(Array.isArray(i))return"array";if(i===null)return"null";if(Object.getPrototypeOf(i)!==Object.prototype&&i.constructor)return i.constructor.name}}return s},n={regex:"\uC785\uB825",email:"\uC774\uBA54\uC77C \uC8FC\uC18C",url:"URL",emoji:"\uC774\uBAA8\uC9C0",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \uB0A0\uC9DC\uC2DC\uAC04",date:"ISO \uB0A0\uC9DC",time:"ISO \uC2DC\uAC04",duration:"ISO \uAE30\uAC04",ipv4:"IPv4 \uC8FC\uC18C",ipv6:"IPv6 \uC8FC\uC18C",cidrv4:"IPv4 \uBC94\uC704",cidrv6:"IPv6 \uBC94\uC704",base64:"base64 \uC778\uCF54\uB529 \uBB38\uC790\uC5F4",base64url:"base64url \uC778\uCF54\uB529 \uBB38\uC790\uC5F4",json_string:"JSON \uBB38\uC790\uC5F4",e164:"E.164 \uBC88\uD638",jwt:"JWT",template_literal:"\uC785\uB825"};return i=>{switch(i.code){case"invalid_type":return`\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 ${i.expected}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${r(i.input)}\uC785\uB2C8\uB2E4`;case"invalid_value":return i.values.length===1?`\uC798\uBABB\uB41C \uC785\uB825: \uAC12\uC740 ${K(i.values[0])} \uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4`:`\uC798\uBABB\uB41C \uC635\uC158: ${C(i.values,"\uB610\uB294 ")} \uC911 \uD558\uB098\uC5EC\uC57C \uD569\uB2C8\uB2E4`;case"too_big":{let s=i.inclusive?"\uC774\uD558":"\uBBF8\uB9CC",o=s==="\uBBF8\uB9CC"?"\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4":"\uC5EC\uC57C \uD569\uB2C8\uB2E4",a=t(i.origin),c=a?.unit??"\uC694\uC18C";return a?`${i.origin??"\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${i.maximum.toString()}${c} ${s}${o}`:`${i.origin??"\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${i.maximum.toString()} ${s}${o}`}case"too_small":{let s=i.inclusive?"\uC774\uC0C1":"\uCD08\uACFC",o=s==="\uC774\uC0C1"?"\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4":"\uC5EC\uC57C \uD569\uB2C8\uB2E4",a=t(i.origin),c=a?.unit??"\uC694\uC18C";return a?`${i.origin??"\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${i.minimum.toString()}${c} ${s}${o}`:`${i.origin??"\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${i.minimum.toString()} ${s}${o}`}case"invalid_format":{let s=i;return s.format==="starts_with"?`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${s.prefix}"(\uC73C)\uB85C \uC2DC\uC791\uD574\uC57C \uD569\uB2C8\uB2E4`:s.format==="ends_with"?`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${s.suffix}"(\uC73C)\uB85C \uB05D\uB098\uC57C \uD569\uB2C8\uB2E4`:s.format==="includes"?`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${s.includes}"\uC744(\uB97C) \uD3EC\uD568\uD574\uC57C \uD569\uB2C8\uB2E4`:s.format==="regex"?`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: \uC815\uADDC\uC2DD ${s.pattern} \uD328\uD134\uACFC \uC77C\uCE58\uD574\uC57C \uD569\uB2C8\uB2E4`:`\uC798\uBABB\uB41C ${n[s.format]??i.format}`}case"not_multiple_of":return`\uC798\uBABB\uB41C \uC22B\uC790: ${i.divisor}\uC758 \uBC30\uC218\uC5EC\uC57C \uD569\uB2C8\uB2E4`;case"unrecognized_keys":return`\uC778\uC2DD\uD560 \uC218 \uC5C6\uB294 \uD0A4: ${C(i.keys,", ")}`;case"invalid_key":return`\uC798\uBABB\uB41C \uD0A4: ${i.origin}`;case"invalid_union":return"\uC798\uBABB\uB41C \uC785\uB825";case"invalid_element":return`\uC798\uBABB\uB41C \uAC12: ${i.origin}`;default:return"\uC798\uBABB\uB41C \uC785\uB825"}}};function jC(){return{localeError:U6()}}var F6=()=>{let e={string:{unit:"\u0437\u043D\u0430\u0446\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"},file:{unit:"\u0431\u0430\u0458\u0442\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"},array:{unit:"\u0441\u0442\u0430\u0432\u043A\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"},set:{unit:"\u0441\u0442\u0430\u0432\u043A\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"}};function t(i){return e[i]??null}let r=i=>{let s=typeof i;switch(s){case"number":return Number.isNaN(i)?"NaN":"\u0431\u0440\u043E\u0458";case"object":{if(Array.isArray(i))return"\u043D\u0438\u0437\u0430";if(i===null)return"null";if(Object.getPrototypeOf(i)!==Object.prototype&&i.constructor)return i.constructor.name}}return s},n={regex:"\u0432\u043D\u0435\u0441",email:"\u0430\u0434\u0440\u0435\u0441\u0430 \u043D\u0430 \u0435-\u043F\u043E\u0448\u0442\u0430",url:"URL",emoji:"\u0435\u043C\u043E\u045F\u0438",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0434\u0430\u0442\u0443\u043C \u0438 \u0432\u0440\u0435\u043C\u0435",date:"ISO \u0434\u0430\u0442\u0443\u043C",time:"ISO \u0432\u0440\u0435\u043C\u0435",duration:"ISO \u0432\u0440\u0435\u043C\u0435\u0442\u0440\u0430\u0435\u045A\u0435",ipv4:"IPv4 \u0430\u0434\u0440\u0435\u0441\u0430",ipv6:"IPv6 \u0430\u0434\u0440\u0435\u0441\u0430",cidrv4:"IPv4 \u043E\u043F\u0441\u0435\u0433",cidrv6:"IPv6 \u043E\u043F\u0441\u0435\u0433",base64:"base64-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430",base64url:"base64url-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430",json_string:"JSON \u043D\u0438\u0437\u0430",e164:"E.164 \u0431\u0440\u043E\u0458",jwt:"JWT",template_literal:"\u0432\u043D\u0435\u0441"};return i=>{switch(i.code){case"invalid_type":return`\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${i.expected}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${r(i.input)}`;case"invalid_value":return i.values.length===1?`Invalid input: expected ${K(i.values[0])}`:`\u0413\u0440\u0435\u0448\u0430\u043D\u0430 \u043E\u043F\u0446\u0438\u0458\u0430: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 \u0435\u0434\u043D\u0430 ${C(i.values,"|")}`;case"too_big":{let s=i.inclusive?"<=":"<",o=t(i.origin);return o?`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${i.origin??"\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0438\u043C\u0430 ${s}${i.maximum.toString()} ${o.unit??"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0438"}`:`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${i.origin??"\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0431\u0438\u0434\u0435 ${s}${i.maximum.toString()}`}case"too_small":{let s=i.inclusive?">=":">",o=t(i.origin);return o?`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${i.origin} \u0434\u0430 \u0438\u043C\u0430 ${s}${i.minimum.toString()} ${o.unit}`:`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${i.origin} \u0434\u0430 \u0431\u0438\u0434\u0435 ${s}${i.minimum.toString()}`}case"invalid_format":{let s=i;return s.format==="starts_with"?`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u043D\u0443\u0432\u0430 \u0441\u043E "${s.prefix}"`:s.format==="ends_with"?`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u0432\u0440\u0448\u0443\u0432\u0430 \u0441\u043E "${s.suffix}"`:s.format==="includes"?`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0432\u043A\u043B\u0443\u0447\u0443\u0432\u0430 "${s.includes}"`:s.format==="regex"?`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u043E\u0434\u0433\u043E\u0430\u0440\u0430 \u043D\u0430 \u043F\u0430\u0442\u0435\u0440\u043D\u043E\u0442 ${s.pattern}`:`Invalid ${n[s.format]??i.format}`}case"not_multiple_of":return`\u0413\u0440\u0435\u0448\u0435\u043D \u0431\u0440\u043E\u0458: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0431\u0438\u0434\u0435 \u0434\u0435\u043B\u0438\u0432 \u0441\u043E ${i.divisor}`;case"unrecognized_keys":return`${i.keys.length>1?"\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D\u0438 \u043A\u043B\u0443\u0447\u0435\u0432\u0438":"\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D \u043A\u043B\u0443\u0447"}: ${C(i.keys,", ")}`;case"invalid_key":return`\u0413\u0440\u0435\u0448\u0435\u043D \u043A\u043B\u0443\u0447 \u0432\u043E ${i.origin}`;case"invalid_union":return"\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441";case"invalid_element":return`\u0413\u0440\u0435\u0448\u043D\u0430 \u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442 \u0432\u043E ${i.origin}`;default:return"\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441"}}};function DC(){return{localeError:F6()}}var B6=()=>{let e={string:{unit:"aksara",verb:"mempunyai"},file:{unit:"bait",verb:"mempunyai"},array:{unit:"elemen",verb:"mempunyai"},set:{unit:"elemen",verb:"mempunyai"}};function t(i){return e[i]??null}let r=i=>{let s=typeof i;switch(s){case"number":return Number.isNaN(i)?"NaN":"nombor";case"object":{if(Array.isArray(i))return"array";if(i===null)return"null";if(Object.getPrototypeOf(i)!==Object.prototype&&i.constructor)return i.constructor.name}}return s},n={regex:"input",email:"alamat e-mel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tarikh masa ISO",date:"tarikh ISO",time:"masa ISO",duration:"tempoh ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"julat IPv4",cidrv6:"julat IPv6",base64:"string dikodkan base64",base64url:"string dikodkan base64url",json_string:"string JSON",e164:"nombor E.164",jwt:"JWT",template_literal:"input"};return i=>{switch(i.code){case"invalid_type":return`Input tidak sah: dijangka ${i.expected}, diterima ${r(i.input)}`;case"invalid_value":return i.values.length===1?`Input tidak sah: dijangka ${K(i.values[0])}`:`Pilihan tidak sah: dijangka salah satu daripada ${C(i.values,"|")}`;case"too_big":{let s=i.inclusive?"<=":"<",o=t(i.origin);return o?`Terlalu besar: dijangka ${i.origin??"nilai"} ${o.verb} ${s}${i.maximum.toString()} ${o.unit??"elemen"}`:`Terlalu besar: dijangka ${i.origin??"nilai"} adalah ${s}${i.maximum.toString()}`}case"too_small":{let s=i.inclusive?">=":">",o=t(i.origin);return o?`Terlalu kecil: dijangka ${i.origin} ${o.verb} ${s}${i.minimum.toString()} ${o.unit}`:`Terlalu kecil: dijangka ${i.origin} adalah ${s}${i.minimum.toString()}`}case"invalid_format":{let s=i;return s.format==="starts_with"?`String tidak sah: mesti bermula dengan "${s.prefix}"`:s.format==="ends_with"?`String tidak sah: mesti berakhir dengan "${s.suffix}"`:s.format==="includes"?`String tidak sah: mesti mengandungi "${s.includes}"`:s.format==="regex"?`String tidak sah: mesti sepadan dengan corak ${s.pattern}`:`${n[s.format]??i.format} tidak sah`}case"not_multiple_of":return`Nombor tidak sah: perlu gandaan ${i.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali: ${C(i.keys,", ")}`;case"invalid_key":return`Kunci tidak sah dalam ${i.origin}`;case"invalid_union":return"Input tidak sah";case"invalid_element":return`Nilai tidak sah dalam ${i.origin}`;default:return"Input tidak sah"}}};function zC(){return{localeError:B6()}}var V6=()=>{let e={string:{unit:"tekens"},file:{unit:"bytes"},array:{unit:"elementen"},set:{unit:"elementen"}};function t(i){return e[i]??null}let r=i=>{let s=typeof i;switch(s){case"number":return Number.isNaN(i)?"NaN":"getal";case"object":{if(Array.isArray(i))return"array";if(i===null)return"null";if(Object.getPrototypeOf(i)!==Object.prototype&&i.constructor)return i.constructor.name}}return s},n={regex:"invoer",email:"emailadres",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum en tijd",date:"ISO datum",time:"ISO tijd",duration:"ISO duur",ipv4:"IPv4-adres",ipv6:"IPv6-adres",cidrv4:"IPv4-bereik",cidrv6:"IPv6-bereik",base64:"base64-gecodeerde tekst",base64url:"base64 URL-gecodeerde tekst",json_string:"JSON string",e164:"E.164-nummer",jwt:"JWT",template_literal:"invoer"};return i=>{switch(i.code){case"invalid_type":return`Ongeldige invoer: verwacht ${i.expected}, ontving ${r(i.input)}`;case"invalid_value":return i.values.length===1?`Ongeldige invoer: verwacht ${K(i.values[0])}`:`Ongeldige optie: verwacht \xE9\xE9n van ${C(i.values,"|")}`;case"too_big":{let s=i.inclusive?"<=":"<",o=t(i.origin);return o?`Te lang: verwacht dat ${i.origin??"waarde"} ${s}${i.maximum.toString()} ${o.unit??"elementen"} bevat`:`Te lang: verwacht dat ${i.origin??"waarde"} ${s}${i.maximum.toString()} is`}case"too_small":{let s=i.inclusive?">=":">",o=t(i.origin);return o?`Te kort: verwacht dat ${i.origin} ${s}${i.minimum.toString()} ${o.unit} bevat`:`Te kort: verwacht dat ${i.origin} ${s}${i.minimum.toString()} is`}case"invalid_format":{let s=i;return s.format==="starts_with"?`Ongeldige tekst: moet met "${s.prefix}" beginnen`:s.format==="ends_with"?`Ongeldige tekst: moet op "${s.suffix}" eindigen`:s.format==="includes"?`Ongeldige tekst: moet "${s.includes}" bevatten`:s.format==="regex"?`Ongeldige tekst: moet overeenkomen met patroon ${s.pattern}`:`Ongeldig: ${n[s.format]??i.format}`}case"not_multiple_of":return`Ongeldig getal: moet een veelvoud van ${i.divisor} zijn`;case"unrecognized_keys":return`Onbekende key${i.keys.length>1?"s":""}: ${C(i.keys,", ")}`;case"invalid_key":return`Ongeldige key in ${i.origin}`;case"invalid_union":return"Ongeldige invoer";case"invalid_element":return`Ongeldige waarde in ${i.origin}`;default:return"Ongeldige invoer"}}};function LC(){return{localeError:V6()}}var Z6=()=>{let e={string:{unit:"tegn",verb:"\xE5 ha"},file:{unit:"bytes",verb:"\xE5 ha"},array:{unit:"elementer",verb:"\xE5 inneholde"},set:{unit:"elementer",verb:"\xE5 inneholde"}};function t(i){return e[i]??null}let r=i=>{let s=typeof i;switch(s){case"number":return Number.isNaN(i)?"NaN":"tall";case"object":{if(Array.isArray(i))return"liste";if(i===null)return"null";if(Object.getPrototypeOf(i)!==Object.prototype&&i.constructor)return i.constructor.name}}return s},n={regex:"input",email:"e-postadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkeslett",date:"ISO-dato",time:"ISO-klokkeslett",duration:"ISO-varighet",ipv4:"IPv4-omr\xE5de",ipv6:"IPv6-omr\xE5de",cidrv4:"IPv4-spekter",cidrv6:"IPv6-spekter",base64:"base64-enkodet streng",base64url:"base64url-enkodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"};return i=>{switch(i.code){case"invalid_type":return`Ugyldig input: forventet ${i.expected}, fikk ${r(i.input)}`;case"invalid_value":return i.values.length===1?`Ugyldig verdi: forventet ${K(i.values[0])}`:`Ugyldig valg: forventet en av ${C(i.values,"|")}`;case"too_big":{let s=i.inclusive?"<=":"<",o=t(i.origin);return o?`For stor(t): forventet ${i.origin??"value"} til \xE5 ha ${s}${i.maximum.toString()} ${o.unit??"elementer"}`:`For stor(t): forventet ${i.origin??"value"} til \xE5 ha ${s}${i.maximum.toString()}`}case"too_small":{let s=i.inclusive?">=":">",o=t(i.origin);return o?`For lite(n): forventet ${i.origin} til \xE5 ha ${s}${i.minimum.toString()} ${o.unit}`:`For lite(n): forventet ${i.origin} til \xE5 ha ${s}${i.minimum.toString()}`}case"invalid_format":{let s=i;return s.format==="starts_with"?`Ugyldig streng: m\xE5 starte med "${s.prefix}"`:s.format==="ends_with"?`Ugyldig streng: m\xE5 ende med "${s.suffix}"`:s.format==="includes"?`Ugyldig streng: m\xE5 inneholde "${s.includes}"`:s.format==="regex"?`Ugyldig streng: m\xE5 matche m\xF8nsteret ${s.pattern}`:`Ugyldig ${n[s.format]??i.format}`}case"not_multiple_of":return`Ugyldig tall: m\xE5 v\xE6re et multiplum av ${i.divisor}`;case"unrecognized_keys":return`${i.keys.length>1?"Ukjente n\xF8kler":"Ukjent n\xF8kkel"}: ${C(i.keys,", ")}`;case"invalid_key":return`Ugyldig n\xF8kkel i ${i.origin}`;case"invalid_union":return"Ugyldig input";case"invalid_element":return`Ugyldig verdi i ${i.origin}`;default:return"Ugyldig input"}}};function UC(){return{localeError:Z6()}}var G6=()=>{let e={string:{unit:"harf",verb:"olmal\u0131d\u0131r"},file:{unit:"bayt",verb:"olmal\u0131d\u0131r"},array:{unit:"unsur",verb:"olmal\u0131d\u0131r"},set:{unit:"unsur",verb:"olmal\u0131d\u0131r"}};function t(i){return e[i]??null}let r=i=>{let s=typeof i;switch(s){case"number":return Number.isNaN(i)?"NaN":"numara";case"object":{if(Array.isArray(i))return"saf";if(i===null)return"gayb";if(Object.getPrototypeOf(i)!==Object.prototype&&i.constructor)return i.constructor.name}}return s},n={regex:"giren",email:"epostag\xE2h",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO heng\xE2m\u0131",date:"ISO tarihi",time:"ISO zaman\u0131",duration:"ISO m\xFCddeti",ipv4:"IPv4 ni\u015F\xE2n\u0131",ipv6:"IPv6 ni\u015F\xE2n\u0131",cidrv4:"IPv4 menzili",cidrv6:"IPv6 menzili",base64:"base64-\u015Fifreli metin",base64url:"base64url-\u015Fifreli metin",json_string:"JSON metin",e164:"E.164 say\u0131s\u0131",jwt:"JWT",template_literal:"giren"};return i=>{switch(i.code){case"invalid_type":return`F\xE2sit giren: umulan ${i.expected}, al\u0131nan ${r(i.input)}`;case"invalid_value":return i.values.length===1?`F\xE2sit giren: umulan ${K(i.values[0])}`:`F\xE2sit tercih: m\xFBteberler ${C(i.values,"|")}`;case"too_big":{let s=i.inclusive?"<=":"<",o=t(i.origin);return o?`Fazla b\xFCy\xFCk: ${i.origin??"value"}, ${s}${i.maximum.toString()} ${o.unit??"elements"} sahip olmal\u0131yd\u0131.`:`Fazla b\xFCy\xFCk: ${i.origin??"value"}, ${s}${i.maximum.toString()} olmal\u0131yd\u0131.`}case"too_small":{let s=i.inclusive?">=":">",o=t(i.origin);return o?`Fazla k\xFC\xE7\xFCk: ${i.origin}, ${s}${i.minimum.toString()} ${o.unit} sahip olmal\u0131yd\u0131.`:`Fazla k\xFC\xE7\xFCk: ${i.origin}, ${s}${i.minimum.toString()} olmal\u0131yd\u0131.`}case"invalid_format":{let s=i;return s.format==="starts_with"?`F\xE2sit metin: "${s.prefix}" ile ba\u015Flamal\u0131.`:s.format==="ends_with"?`F\xE2sit metin: "${s.suffix}" ile bitmeli.`:s.format==="includes"?`F\xE2sit metin: "${s.includes}" ihtiv\xE2 etmeli.`:s.format==="regex"?`F\xE2sit metin: ${s.pattern} nak\u015F\u0131na uymal\u0131.`:`F\xE2sit ${n[s.format]??i.format}`}case"not_multiple_of":return`F\xE2sit say\u0131: ${i.divisor} kat\u0131 olmal\u0131yd\u0131.`;case"unrecognized_keys":return`Tan\u0131nmayan anahtar ${i.keys.length>1?"s":""}: ${C(i.keys,", ")}`;case"invalid_key":return`${i.origin} i\xE7in tan\u0131nmayan anahtar var.`;case"invalid_union":return"Giren tan\u0131namad\u0131.";case"invalid_element":return`${i.origin} i\xE7in tan\u0131nmayan k\u0131ymet var.`;default:return"K\u0131ymet tan\u0131namad\u0131."}}};function FC(){return{localeError:G6()}}var K6=()=>{let e={string:{unit:"\u062A\u0648\u06A9\u064A",verb:"\u0648\u0644\u0631\u064A"},file:{unit:"\u0628\u0627\u06CC\u067C\u0633",verb:"\u0648\u0644\u0631\u064A"},array:{unit:"\u062A\u0648\u06A9\u064A",verb:"\u0648\u0644\u0631\u064A"},set:{unit:"\u062A\u0648\u06A9\u064A",verb:"\u0648\u0644\u0631\u064A"}};function t(i){return e[i]??null}let r=i=>{let s=typeof i;switch(s){case"number":return Number.isNaN(i)?"NaN":"\u0639\u062F\u062F";case"object":{if(Array.isArray(i))return"\u0627\u0631\u06D0";if(i===null)return"null";if(Object.getPrototypeOf(i)!==Object.prototype&&i.constructor)return i.constructor.name}}return s},n={regex:"\u0648\u0631\u0648\u062F\u064A",email:"\u0628\u0631\u06CC\u069A\u0646\u0627\u0644\u06CC\u06A9",url:"\u06CC\u0648 \u0622\u0631 \u0627\u0644",emoji:"\u0627\u06CC\u0645\u0648\u062C\u064A",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u0646\u06CC\u067C\u0647 \u0627\u0648 \u0648\u062E\u062A",date:"\u0646\u06D0\u067C\u0647",time:"\u0648\u062E\u062A",duration:"\u0645\u0648\u062F\u0647",ipv4:"\u062F IPv4 \u067E\u062A\u0647",ipv6:"\u062F IPv6 \u067E\u062A\u0647",cidrv4:"\u062F IPv4 \u0633\u0627\u062D\u0647",cidrv6:"\u062F IPv6 \u0633\u0627\u062D\u0647",base64:"base64-encoded \u0645\u062A\u0646",base64url:"base64url-encoded \u0645\u062A\u0646",json_string:"JSON \u0645\u062A\u0646",e164:"\u062F E.164 \u0634\u0645\u06D0\u0631\u0647",jwt:"JWT",template_literal:"\u0648\u0631\u0648\u062F\u064A"};return i=>{switch(i.code){case"invalid_type":return`\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${i.expected} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${r(i.input)} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`;case"invalid_value":return i.values.length===1?`\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${K(i.values[0])} \u0648\u0627\u06CC`:`\u0646\u0627\u0633\u0645 \u0627\u0646\u062A\u062E\u0627\u0628: \u0628\u0627\u06CC\u062F \u06CC\u0648 \u0644\u0647 ${C(i.values,"|")} \u0685\u062E\u0647 \u0648\u0627\u06CC`;case"too_big":{let s=i.inclusive?"<=":"<",o=t(i.origin);return o?`\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${i.origin??"\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${s}${i.maximum.toString()} ${o.unit??"\u0639\u0646\u0635\u0631\u0648\u0646\u0647"} \u0648\u0644\u0631\u064A`:`\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${i.origin??"\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${s}${i.maximum.toString()} \u0648\u064A`}case"too_small":{let s=i.inclusive?">=":">",o=t(i.origin);return o?`\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${i.origin} \u0628\u0627\u06CC\u062F ${s}${i.minimum.toString()} ${o.unit} \u0648\u0644\u0631\u064A`:`\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${i.origin} \u0628\u0627\u06CC\u062F ${s}${i.minimum.toString()} \u0648\u064A`}case"invalid_format":{let s=i;return s.format==="starts_with"?`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${s.prefix}" \u0633\u0631\u0647 \u067E\u06CC\u0644 \u0634\u064A`:s.format==="ends_with"?`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${s.suffix}" \u0633\u0631\u0647 \u067E\u0627\u06CC \u062A\u0647 \u0648\u0631\u0633\u064A\u0696\u064A`:s.format==="includes"?`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F "${s.includes}" \u0648\u0644\u0631\u064A`:s.format==="regex"?`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F ${s.pattern} \u0633\u0631\u0647 \u0645\u0637\u0627\u0628\u0642\u062A \u0648\u0644\u0631\u064A`:`${n[s.format]??i.format} \u0646\u0627\u0633\u0645 \u062F\u06CC`}case"not_multiple_of":return`\u0646\u0627\u0633\u0645 \u0639\u062F\u062F: \u0628\u0627\u06CC\u062F \u062F ${i.divisor} \u0645\u0636\u0631\u0628 \u0648\u064A`;case"unrecognized_keys":return`\u0646\u0627\u0633\u0645 ${i.keys.length>1?"\u06A9\u0644\u06CC\u0689\u0648\u0646\u0647":"\u06A9\u0644\u06CC\u0689"}: ${C(i.keys,", ")}`;case"invalid_key":return`\u0646\u0627\u0633\u0645 \u06A9\u0644\u06CC\u0689 \u067E\u0647 ${i.origin} \u06A9\u06D0`;case"invalid_union":return"\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A";case"invalid_element":return`\u0646\u0627\u0633\u0645 \u0639\u0646\u0635\u0631 \u067E\u0647 ${i.origin} \u06A9\u06D0`;default:return"\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A"}}};function BC(){return{localeError:K6()}}var q6=()=>{let e={string:{unit:"znak\xF3w",verb:"mie\u0107"},file:{unit:"bajt\xF3w",verb:"mie\u0107"},array:{unit:"element\xF3w",verb:"mie\u0107"},set:{unit:"element\xF3w",verb:"mie\u0107"}};function t(i){return e[i]??null}let r=i=>{let s=typeof i;switch(s){case"number":return Number.isNaN(i)?"NaN":"liczba";case"object":{if(Array.isArray(i))return"tablica";if(i===null)return"null";if(Object.getPrototypeOf(i)!==Object.prototype&&i.constructor)return i.constructor.name}}return s},n={regex:"wyra\u017Cenie",email:"adres email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i godzina w formacie ISO",date:"data w formacie ISO",time:"godzina w formacie ISO",duration:"czas trwania ISO",ipv4:"adres IPv4",ipv6:"adres IPv6",cidrv4:"zakres IPv4",cidrv6:"zakres IPv6",base64:"ci\u0105g znak\xF3w zakodowany w formacie base64",base64url:"ci\u0105g znak\xF3w zakodowany w formacie base64url",json_string:"ci\u0105g znak\xF3w w formacie JSON",e164:"liczba E.164",jwt:"JWT",template_literal:"wej\u015Bcie"};return i=>{switch(i.code){case"invalid_type":return`Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${i.expected}, otrzymano ${r(i.input)}`;case"invalid_value":return i.values.length===1?`Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${K(i.values[0])}`:`Nieprawid\u0142owa opcja: oczekiwano jednej z warto\u015Bci ${C(i.values,"|")}`;case"too_big":{let s=i.inclusive?"<=":"<",o=t(i.origin);return o?`Za du\u017Ca warto\u015B\u0107: oczekiwano, \u017Ce ${i.origin??"warto\u015B\u0107"} b\u0119dzie mie\u0107 ${s}${i.maximum.toString()} ${o.unit??"element\xF3w"}`:`Zbyt du\u017C(y/a/e): oczekiwano, \u017Ce ${i.origin??"warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${s}${i.maximum.toString()}`}case"too_small":{let s=i.inclusive?">=":">",o=t(i.origin);return o?`Za ma\u0142a warto\u015B\u0107: oczekiwano, \u017Ce ${i.origin??"warto\u015B\u0107"} b\u0119dzie mie\u0107 ${s}${i.minimum.toString()} ${o.unit??"element\xF3w"}`:`Zbyt ma\u0142(y/a/e): oczekiwano, \u017Ce ${i.origin??"warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${s}${i.minimum.toString()}`}case"invalid_format":{let s=i;return s.format==="starts_with"?`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zaczyna\u0107 si\u0119 od "${s.prefix}"`:s.format==="ends_with"?`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi ko\u0144czy\u0107 si\u0119 na "${s.suffix}"`:s.format==="includes"?`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zawiera\u0107 "${s.includes}"`:s.format==="regex"?`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi odpowiada\u0107 wzorcowi ${s.pattern}`:`Nieprawid\u0142ow(y/a/e) ${n[s.format]??i.format}`}case"not_multiple_of":return`Nieprawid\u0142owa liczba: musi by\u0107 wielokrotno\u015Bci\u0105 ${i.divisor}`;case"unrecognized_keys":return`Nierozpoznane klucze${i.keys.length>1?"s":""}: ${C(i.keys,", ")}`;case"invalid_key":return`Nieprawid\u0142owy klucz w ${i.origin}`;case"invalid_union":return"Nieprawid\u0142owe dane wej\u015Bciowe";case"invalid_element":return`Nieprawid\u0142owa warto\u015B\u0107 w ${i.origin}`;default:return"Nieprawid\u0142owe dane wej\u015Bciowe"}}};function VC(){return{localeError:q6()}}var H6=()=>{let e={string:{unit:"caracteres",verb:"ter"},file:{unit:"bytes",verb:"ter"},array:{unit:"itens",verb:"ter"},set:{unit:"itens",verb:"ter"}};function t(i){return e[i]??null}let r=i=>{let s=typeof i;switch(s){case"number":return Number.isNaN(i)?"NaN":"n\xFAmero";case"object":{if(Array.isArray(i))return"array";if(i===null)return"nulo";if(Object.getPrototypeOf(i)!==Object.prototype&&i.constructor)return i.constructor.name}}return s},n={regex:"padr\xE3o",email:"endere\xE7o de e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e hora ISO",date:"data ISO",time:"hora ISO",duration:"dura\xE7\xE3o ISO",ipv4:"endere\xE7o IPv4",ipv6:"endere\xE7o IPv6",cidrv4:"faixa de IPv4",cidrv6:"faixa de IPv6",base64:"texto codificado em base64",base64url:"URL codificada em base64",json_string:"texto JSON",e164:"n\xFAmero E.164",jwt:"JWT",template_literal:"entrada"};return i=>{switch(i.code){case"invalid_type":return`Tipo inv\xE1lido: esperado ${i.expected}, recebido ${r(i.input)}`;case"invalid_value":return i.values.length===1?`Entrada inv\xE1lida: esperado ${K(i.values[0])}`:`Op\xE7\xE3o inv\xE1lida: esperada uma das ${C(i.values,"|")}`;case"too_big":{let s=i.inclusive?"<=":"<",o=t(i.origin);return o?`Muito grande: esperado que ${i.origin??"valor"} tivesse ${s}${i.maximum.toString()} ${o.unit??"elementos"}`:`Muito grande: esperado que ${i.origin??"valor"} fosse ${s}${i.maximum.toString()}`}case"too_small":{let s=i.inclusive?">=":">",o=t(i.origin);return o?`Muito pequeno: esperado que ${i.origin} tivesse ${s}${i.minimum.toString()} ${o.unit}`:`Muito pequeno: esperado que ${i.origin} fosse ${s}${i.minimum.toString()}`}case"invalid_format":{let s=i;return s.format==="starts_with"?`Texto inv\xE1lido: deve come\xE7ar com "${s.prefix}"`:s.format==="ends_with"?`Texto inv\xE1lido: deve terminar com "${s.suffix}"`:s.format==="includes"?`Texto inv\xE1lido: deve incluir "${s.includes}"`:s.format==="regex"?`Texto inv\xE1lido: deve corresponder ao padr\xE3o ${s.pattern}`:`${n[s.format]??i.format} inv\xE1lido`}case"not_multiple_of":return`N\xFAmero inv\xE1lido: deve ser m\xFAltiplo de ${i.divisor}`;case"unrecognized_keys":return`Chave${i.keys.length>1?"s":""} desconhecida${i.keys.length>1?"s":""}: ${C(i.keys,", ")}`;case"invalid_key":return`Chave inv\xE1lida em ${i.origin}`;case"invalid_union":return"Entrada inv\xE1lida";case"invalid_element":return`Valor inv\xE1lido em ${i.origin}`;default:return"Campo inv\xE1lido"}}};function ZC(){return{localeError:H6()}}function GC(e,t,r,n){let i=Math.abs(e),s=i%10,o=i%100;return o>=11&&o<=19?n:s===1?t:s>=2&&s<=4?r:n}var W6=()=>{let e={string:{unit:{one:"\u0441\u0438\u043C\u0432\u043E\u043B",few:"\u0441\u0438\u043C\u0432\u043E\u043B\u0430",many:"\u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432"},verb:"\u0438\u043C\u0435\u0442\u044C"},file:{unit:{one:"\u0431\u0430\u0439\u0442",few:"\u0431\u0430\u0439\u0442\u0430",many:"\u0431\u0430\u0439\u0442"},verb:"\u0438\u043C\u0435\u0442\u044C"},array:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432"},verb:"\u0438\u043C\u0435\u0442\u044C"},set:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432"},verb:"\u0438\u043C\u0435\u0442\u044C"}};function t(i){return e[i]??null}let r=i=>{let s=typeof i;switch(s){case"number":return Number.isNaN(i)?"NaN":"\u0447\u0438\u0441\u043B\u043E";case"object":{if(Array.isArray(i))return"\u043C\u0430\u0441\u0441\u0438\u0432";if(i===null)return"null";if(Object.getPrototypeOf(i)!==Object.prototype&&i.constructor)return i.constructor.name}}return s},n={regex:"\u0432\u0432\u043E\u0434",email:"email \u0430\u0434\u0440\u0435\u0441",url:"URL",emoji:"\u044D\u043C\u043E\u0434\u0437\u0438",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0434\u0430\u0442\u0430 \u0438 \u0432\u0440\u0435\u043C\u044F",date:"ISO \u0434\u0430\u0442\u0430",time:"ISO \u0432\u0440\u0435\u043C\u044F",duration:"ISO \u0434\u043B\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u044C",ipv4:"IPv4 \u0430\u0434\u0440\u0435\u0441",ipv6:"IPv6 \u0430\u0434\u0440\u0435\u0441",cidrv4:"IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",cidrv6:"IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",base64:"\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64",base64url:"\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64url",json_string:"JSON \u0441\u0442\u0440\u043E\u043A\u0430",e164:"\u043D\u043E\u043C\u0435\u0440 E.164",jwt:"JWT",template_literal:"\u0432\u0432\u043E\u0434"};return i=>{switch(i.code){case"invalid_type":return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${i.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${r(i.input)}`;case"invalid_value":return i.values.length===1?`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${K(i.values[0])}`:`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0430\u0440\u0438\u0430\u043D\u0442: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C \u043E\u0434\u043D\u043E \u0438\u0437 ${C(i.values,"|")}`;case"too_big":{let s=i.inclusive?"<=":"<",o=t(i.origin);if(o){let a=Number(i.maximum),c=GC(a,o.unit.one,o.unit.few,o.unit.many);return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${i.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${s}${i.maximum.toString()} ${c}`}return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${i.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 ${s}${i.maximum.toString()}`}case"too_small":{let s=i.inclusive?">=":">",o=t(i.origin);if(o){let a=Number(i.minimum),c=GC(a,o.unit.one,o.unit.few,o.unit.many);return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${i.origin} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${s}${i.minimum.toString()} ${c}`}return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${i.origin} \u0431\u0443\u0434\u0435\u0442 ${s}${i.minimum.toString()}`}case"invalid_format":{let s=i;return s.format==="starts_with"?`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u043D\u0430\u0447\u0438\u043D\u0430\u0442\u044C\u0441\u044F \u0441 "${s.prefix}"`:s.format==="ends_with"?`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0437\u0430\u043A\u0430\u043D\u0447\u0438\u0432\u0430\u0442\u044C\u0441\u044F \u043D\u0430 "${s.suffix}"`:s.format==="includes"?`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u0434\u0435\u0440\u0436\u0430\u0442\u044C "${s.includes}"`:s.format==="regex"?`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u043E\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u043E\u0432\u0430\u0442\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${s.pattern}`:`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 ${n[s.format]??i.format}`}case"not_multiple_of":return`\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0447\u0438\u0441\u043B\u043E: \u0434\u043E\u043B\u0436\u043D\u043E \u0431\u044B\u0442\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${i.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u0430\u0441\u043F\u043E\u0437\u043D\u0430\u043D\u043D${i.keys.length>1?"\u044B\u0435":"\u044B\u0439"} \u043A\u043B\u044E\u0447${i.keys.length>1?"\u0438":""}: ${C(i.keys,", ")}`;case"invalid_key":return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u043A\u043B\u044E\u0447 \u0432 ${i.origin}`;case"invalid_union":return"\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435";case"invalid_element":return`\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u0432 ${i.origin}`;default:return"\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435"}}};function KC(){return{localeError:W6()}}var J6=()=>{let e={string:{unit:"znakov",verb:"imeti"},file:{unit:"bajtov",verb:"imeti"},array:{unit:"elementov",verb:"imeti"},set:{unit:"elementov",verb:"imeti"}};function t(i){return e[i]??null}let r=i=>{let s=typeof i;switch(s){case"number":return Number.isNaN(i)?"NaN":"\u0161tevilo";case"object":{if(Array.isArray(i))return"tabela";if(i===null)return"null";if(Object.getPrototypeOf(i)!==Object.prototype&&i.constructor)return i.constructor.name}}return s},n={regex:"vnos",email:"e-po\u0161tni naslov",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum in \u010Das",date:"ISO datum",time:"ISO \u010Das",duration:"ISO trajanje",ipv4:"IPv4 naslov",ipv6:"IPv6 naslov",cidrv4:"obseg IPv4",cidrv6:"obseg IPv6",base64:"base64 kodiran niz",base64url:"base64url kodiran niz",json_string:"JSON niz",e164:"E.164 \u0161tevilka",jwt:"JWT",template_literal:"vnos"};return i=>{switch(i.code){case"invalid_type":return`Neveljaven vnos: pri\u010Dakovano ${i.expected}, prejeto ${r(i.input)}`;case"invalid_value":return i.values.length===1?`Neveljaven vnos: pri\u010Dakovano ${K(i.values[0])}`:`Neveljavna mo\u017Enost: pri\u010Dakovano eno izmed ${C(i.values,"|")}`;case"too_big":{let s=i.inclusive?"<=":"<",o=t(i.origin);return o?`Preveliko: pri\u010Dakovano, da bo ${i.origin??"vrednost"} imelo ${s}${i.maximum.toString()} ${o.unit??"elementov"}`:`Preveliko: pri\u010Dakovano, da bo ${i.origin??"vrednost"} ${s}${i.maximum.toString()}`}case"too_small":{let s=i.inclusive?">=":">",o=t(i.origin);return o?`Premajhno: pri\u010Dakovano, da bo ${i.origin} imelo ${s}${i.minimum.toString()} ${o.unit}`:`Premajhno: pri\u010Dakovano, da bo ${i.origin} ${s}${i.minimum.toString()}`}case"invalid_format":{let s=i;return s.format==="starts_with"?`Neveljaven niz: mora se za\u010Deti z "${s.prefix}"`:s.format==="ends_with"?`Neveljaven niz: mora se kon\u010Dati z "${s.suffix}"`:s.format==="includes"?`Neveljaven niz: mora vsebovati "${s.includes}"`:s.format==="regex"?`Neveljaven niz: mora ustrezati vzorcu ${s.pattern}`:`Neveljaven ${n[s.format]??i.format}`}case"not_multiple_of":return`Neveljavno \u0161tevilo: mora biti ve\u010Dkratnik ${i.divisor}`;case"unrecognized_keys":return`Neprepoznan${i.keys.length>1?"i klju\u010Di":" klju\u010D"}: ${C(i.keys,", ")}`;case"invalid_key":return`Neveljaven klju\u010D v ${i.origin}`;case"invalid_union":return"Neveljaven vnos";case"invalid_element":return`Neveljavna vrednost v ${i.origin}`;default:return"Neveljaven vnos"}}};function qC(){return{localeError:J6()}}var X6=()=>{let e={string:{unit:"tecken",verb:"att ha"},file:{unit:"bytes",verb:"att ha"},array:{unit:"objekt",verb:"att inneh\xE5lla"},set:{unit:"objekt",verb:"att inneh\xE5lla"}};function t(i){return e[i]??null}let r=i=>{let s=typeof i;switch(s){case"number":return Number.isNaN(i)?"NaN":"antal";case"object":{if(Array.isArray(i))return"lista";if(i===null)return"null";if(Object.getPrototypeOf(i)!==Object.prototype&&i.constructor)return i.constructor.name}}return s},n={regex:"regulj\xE4rt uttryck",email:"e-postadress",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datum och tid",date:"ISO-datum",time:"ISO-tid",duration:"ISO-varaktighet",ipv4:"IPv4-intervall",ipv6:"IPv6-intervall",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodad str\xE4ng",base64url:"base64url-kodad str\xE4ng",json_string:"JSON-str\xE4ng",e164:"E.164-nummer",jwt:"JWT",template_literal:"mall-literal"};return i=>{switch(i.code){case"invalid_type":return`Ogiltig inmatning: f\xF6rv\xE4ntat ${i.expected}, fick ${r(i.input)}`;case"invalid_value":return i.values.length===1?`Ogiltig inmatning: f\xF6rv\xE4ntat ${K(i.values[0])}`:`Ogiltigt val: f\xF6rv\xE4ntade en av ${C(i.values,"|")}`;case"too_big":{let s=i.inclusive?"<=":"<",o=t(i.origin);return o?`F\xF6r stor(t): f\xF6rv\xE4ntade ${i.origin??"v\xE4rdet"} att ha ${s}${i.maximum.toString()} ${o.unit??"element"}`:`F\xF6r stor(t): f\xF6rv\xE4ntat ${i.origin??"v\xE4rdet"} att ha ${s}${i.maximum.toString()}`}case"too_small":{let s=i.inclusive?">=":">",o=t(i.origin);return o?`F\xF6r lite(t): f\xF6rv\xE4ntade ${i.origin??"v\xE4rdet"} att ha ${s}${i.minimum.toString()} ${o.unit}`:`F\xF6r lite(t): f\xF6rv\xE4ntade ${i.origin??"v\xE4rdet"} att ha ${s}${i.minimum.toString()}`}case"invalid_format":{let s=i;return s.format==="starts_with"?`Ogiltig str\xE4ng: m\xE5ste b\xF6rja med "${s.prefix}"`:s.format==="ends_with"?`Ogiltig str\xE4ng: m\xE5ste sluta med "${s.suffix}"`:s.format==="includes"?`Ogiltig str\xE4ng: m\xE5ste inneh\xE5lla "${s.includes}"`:s.format==="regex"?`Ogiltig str\xE4ng: m\xE5ste matcha m\xF6nstret "${s.pattern}"`:`Ogiltig(t) ${n[s.format]??i.format}`}case"not_multiple_of":return`Ogiltigt tal: m\xE5ste vara en multipel av ${i.divisor}`;case"unrecognized_keys":return`${i.keys.length>1?"Ok\xE4nda nycklar":"Ok\xE4nd nyckel"}: ${C(i.keys,", ")}`;case"invalid_key":return`Ogiltig nyckel i ${i.origin??"v\xE4rdet"}`;case"invalid_union":return"Ogiltig input";case"invalid_element":return`Ogiltigt v\xE4rde i ${i.origin??"v\xE4rdet"}`;default:return"Ogiltig input"}}};function HC(){return{localeError:X6()}}var Y6=()=>{let e={string:{unit:"\u0B8E\u0BB4\u0BC1\u0BA4\u0BCD\u0BA4\u0BC1\u0B95\u0BCD\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"},file:{unit:"\u0BAA\u0BC8\u0B9F\u0BCD\u0B9F\u0BC1\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"},array:{unit:"\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"},set:{unit:"\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"}};function t(i){return e[i]??null}let r=i=>{let s=typeof i;switch(s){case"number":return Number.isNaN(i)?"\u0B8E\u0BA3\u0BCD \u0B85\u0BB2\u0BCD\u0BB2\u0BBE\u0BA4\u0BA4\u0BC1":"\u0B8E\u0BA3\u0BCD";case"object":{if(Array.isArray(i))return"\u0B85\u0BA3\u0BBF";if(i===null)return"\u0BB5\u0BC6\u0BB1\u0BC1\u0BAE\u0BC8";if(Object.getPrototypeOf(i)!==Object.prototype&&i.constructor)return i.constructor.name}}return s},n={regex:"\u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1",email:"\u0BAE\u0BBF\u0BA9\u0BCD\u0BA9\u0B9E\u0BCD\u0B9A\u0BB2\u0BCD \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0BA4\u0BC7\u0BA4\u0BBF \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD",date:"ISO \u0BA4\u0BC7\u0BA4\u0BBF",time:"ISO \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD",duration:"ISO \u0B95\u0BBE\u0BB2 \u0B85\u0BB3\u0BB5\u0BC1",ipv4:"IPv4 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",ipv6:"IPv6 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",cidrv4:"IPv4 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1",cidrv6:"IPv6 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1",base64:"base64-encoded \u0B9A\u0BB0\u0BAE\u0BCD",base64url:"base64url-encoded \u0B9A\u0BB0\u0BAE\u0BCD",json_string:"JSON \u0B9A\u0BB0\u0BAE\u0BCD",e164:"E.164 \u0B8E\u0BA3\u0BCD",jwt:"JWT",template_literal:"input"};return i=>{switch(i.code){case"invalid_type":return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${i.expected}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${r(i.input)}`;case"invalid_value":return i.values.length===1?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${K(i.values[0])}`:`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0BB0\u0BC1\u0BAA\u0BCD\u0BAA\u0BAE\u0BCD: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${C(i.values,"|")} \u0B87\u0BB2\u0BCD \u0B92\u0BA9\u0BCD\u0BB1\u0BC1`;case"too_big":{let s=i.inclusive?"<=":"<",o=t(i.origin);return o?`\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${i.origin??"\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${s}${i.maximum.toString()} ${o.unit??"\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD"} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:`\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${i.origin??"\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${s}${i.maximum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`}case"too_small":{let s=i.inclusive?">=":">",o=t(i.origin);return o?`\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${i.origin} ${s}${i.minimum.toString()} ${o.unit} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:`\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${i.origin} ${s}${i.minimum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`}case"invalid_format":{let s=i;return s.format==="starts_with"?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${s.prefix}" \u0B87\u0BB2\u0BCD \u0BA4\u0BCA\u0B9F\u0B99\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:s.format==="ends_with"?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${s.suffix}" \u0B87\u0BB2\u0BCD \u0BAE\u0BC1\u0B9F\u0BBF\u0BB5\u0B9F\u0BC8\u0BAF \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:s.format==="includes"?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${s.includes}" \u0B90 \u0B89\u0BB3\u0BCD\u0BB3\u0B9F\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:s.format==="regex"?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: ${s.pattern} \u0BAE\u0BC1\u0BB1\u0BC8\u0BAA\u0BBE\u0B9F\u0BCD\u0B9F\u0BC1\u0B9F\u0BA9\u0BCD \u0BAA\u0BCA\u0BB0\u0BC1\u0BA8\u0BCD\u0BA4 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 ${n[s.format]??i.format}`}case"not_multiple_of":return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B8E\u0BA3\u0BCD: ${i.divisor} \u0B87\u0BA9\u0BCD \u0BAA\u0BB2\u0BAE\u0BBE\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;case"unrecognized_keys":return`\u0B85\u0B9F\u0BC8\u0BAF\u0BBE\u0BB3\u0BAE\u0BCD \u0BA4\u0BC6\u0BB0\u0BBF\u0BAF\u0BBE\u0BA4 \u0BB5\u0BBF\u0B9A\u0BC8${i.keys.length>1?"\u0B95\u0BB3\u0BCD":""}: ${C(i.keys,", ")}`;case"invalid_key":return`${i.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0B9A\u0BC8`;case"invalid_union":return"\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1";case"invalid_element":return`${i.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1`;default:return"\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1"}}};function WC(){return{localeError:Y6()}}var Q6=()=>{let e={string:{unit:"\u0E15\u0E31\u0E27\u0E2D\u0E31\u0E01\u0E29\u0E23",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"},file:{unit:"\u0E44\u0E1A\u0E15\u0E4C",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"},array:{unit:"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"},set:{unit:"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"}};function t(i){return e[i]??null}let r=i=>{let s=typeof i;switch(s){case"number":return Number.isNaN(i)?"\u0E44\u0E21\u0E48\u0E43\u0E0A\u0E48\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02 (NaN)":"\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02";case"object":{if(Array.isArray(i))return"\u0E2D\u0E32\u0E23\u0E4C\u0E40\u0E23\u0E22\u0E4C (Array)";if(i===null)return"\u0E44\u0E21\u0E48\u0E21\u0E35\u0E04\u0E48\u0E32 (null)";if(Object.getPrototypeOf(i)!==Object.prototype&&i.constructor)return i.constructor.name}}return s},n={regex:"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19",email:"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48\u0E2D\u0E35\u0E40\u0E21\u0E25",url:"URL",emoji:"\u0E2D\u0E34\u0E42\u0E21\u0E08\u0E34",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",date:"\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E41\u0E1A\u0E1A ISO",time:"\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",duration:"\u0E0A\u0E48\u0E27\u0E07\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",ipv4:"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv4",ipv6:"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv6",cidrv4:"\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv4",cidrv6:"\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv6",base64:"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64",base64url:"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64 \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A URL",json_string:"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A JSON",e164:"\u0E40\u0E1A\u0E2D\u0E23\u0E4C\u0E42\u0E17\u0E23\u0E28\u0E31\u0E1E\u0E17\u0E4C\u0E23\u0E30\u0E2B\u0E27\u0E48\u0E32\u0E07\u0E1B\u0E23\u0E30\u0E40\u0E17\u0E28 (E.164)",jwt:"\u0E42\u0E17\u0E40\u0E04\u0E19 JWT",template_literal:"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19"};return i=>{switch(i.code){case"invalid_type":return`\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${i.expected} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${r(i.input)}`;case"invalid_value":return i.values.length===1?`\u0E04\u0E48\u0E32\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${K(i.values[0])}`:`\u0E15\u0E31\u0E27\u0E40\u0E25\u0E37\u0E2D\u0E01\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19\u0E2B\u0E19\u0E36\u0E48\u0E07\u0E43\u0E19 ${C(i.values,"|")}`;case"too_big":{let s=i.inclusive?"\u0E44\u0E21\u0E48\u0E40\u0E01\u0E34\u0E19":"\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32",o=t(i.origin);return o?`\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${i.origin??"\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${s} ${i.maximum.toString()} ${o.unit??"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23"}`:`\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${i.origin??"\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${s} ${i.maximum.toString()}`}case"too_small":{let s=i.inclusive?"\u0E2D\u0E22\u0E48\u0E32\u0E07\u0E19\u0E49\u0E2D\u0E22":"\u0E21\u0E32\u0E01\u0E01\u0E27\u0E48\u0E32",o=t(i.origin);return o?`\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${i.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${s} ${i.minimum.toString()} ${o.unit}`:`\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${i.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${s} ${i.minimum.toString()}`}case"invalid_format":{let s=i;return s.format==="starts_with"?`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E02\u0E36\u0E49\u0E19\u0E15\u0E49\u0E19\u0E14\u0E49\u0E27\u0E22 "${s.prefix}"`:s.format==="ends_with"?`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E25\u0E07\u0E17\u0E49\u0E32\u0E22\u0E14\u0E49\u0E27\u0E22 "${s.suffix}"`:s.format==="includes"?`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E21\u0E35 "${s.includes}" \u0E2D\u0E22\u0E39\u0E48\u0E43\u0E19\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21`:s.format==="regex"?`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14 ${s.pattern}`:`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: ${n[s.format]??i.format}`}case"not_multiple_of":return`\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E40\u0E1B\u0E47\u0E19\u0E08\u0E33\u0E19\u0E27\u0E19\u0E17\u0E35\u0E48\u0E2B\u0E32\u0E23\u0E14\u0E49\u0E27\u0E22 ${i.divisor} \u0E44\u0E14\u0E49\u0E25\u0E07\u0E15\u0E31\u0E27`;case"unrecognized_keys":return`\u0E1E\u0E1A\u0E04\u0E35\u0E22\u0E4C\u0E17\u0E35\u0E48\u0E44\u0E21\u0E48\u0E23\u0E39\u0E49\u0E08\u0E31\u0E01: ${C(i.keys,", ")}`;case"invalid_key":return`\u0E04\u0E35\u0E22\u0E4C\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${i.origin}`;case"invalid_union":return"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E44\u0E21\u0E48\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E22\u0E39\u0E40\u0E19\u0E35\u0E22\u0E19\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14\u0E44\u0E27\u0E49";case"invalid_element":return`\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${i.origin}`;default:return"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07"}}};function JC(){return{localeError:Q6()}}var eB=e=>{let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":{if(Array.isArray(e))return"array";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return t},tB=()=>{let e={string:{unit:"karakter",verb:"olmal\u0131"},file:{unit:"bayt",verb:"olmal\u0131"},array:{unit:"\xF6\u011Fe",verb:"olmal\u0131"},set:{unit:"\xF6\u011Fe",verb:"olmal\u0131"}};function t(n){return e[n]??null}let r={regex:"girdi",email:"e-posta adresi",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO tarih ve saat",date:"ISO tarih",time:"ISO saat",duration:"ISO s\xFCre",ipv4:"IPv4 adresi",ipv6:"IPv6 adresi",cidrv4:"IPv4 aral\u0131\u011F\u0131",cidrv6:"IPv6 aral\u0131\u011F\u0131",base64:"base64 ile \u015Fifrelenmi\u015F metin",base64url:"base64url ile \u015Fifrelenmi\u015F metin",json_string:"JSON dizesi",e164:"E.164 say\u0131s\u0131",jwt:"JWT",template_literal:"\u015Eablon dizesi"};return n=>{switch(n.code){case"invalid_type":return`Ge\xE7ersiz de\u011Fer: beklenen ${n.expected}, al\u0131nan ${eB(n.input)}`;case"invalid_value":return n.values.length===1?`Ge\xE7ersiz de\u011Fer: beklenen ${K(n.values[0])}`:`Ge\xE7ersiz se\xE7enek: a\u015Fa\u011F\u0131dakilerden biri olmal\u0131: ${C(n.values,"|")}`;case"too_big":{let i=n.inclusive?"<=":"<",s=t(n.origin);return s?`\xC7ok b\xFCy\xFCk: beklenen ${n.origin??"de\u011Fer"} ${i}${n.maximum.toString()} ${s.unit??"\xF6\u011Fe"}`:`\xC7ok b\xFCy\xFCk: beklenen ${n.origin??"de\u011Fer"} ${i}${n.maximum.toString()}`}case"too_small":{let i=n.inclusive?">=":">",s=t(n.origin);return s?`\xC7ok k\xFC\xE7\xFCk: beklenen ${n.origin} ${i}${n.minimum.toString()} ${s.unit}`:`\xC7ok k\xFC\xE7\xFCk: beklenen ${n.origin} ${i}${n.minimum.toString()}`}case"invalid_format":{let i=n;return i.format==="starts_with"?`Ge\xE7ersiz metin: "${i.prefix}" ile ba\u015Flamal\u0131`:i.format==="ends_with"?`Ge\xE7ersiz metin: "${i.suffix}" ile bitmeli`:i.format==="includes"?`Ge\xE7ersiz metin: "${i.includes}" i\xE7ermeli`:i.format==="regex"?`Ge\xE7ersiz metin: ${i.pattern} desenine uymal\u0131`:`Ge\xE7ersiz ${r[i.format]??n.format}`}case"not_multiple_of":return`Ge\xE7ersiz say\u0131: ${n.divisor} ile tam b\xF6l\xFCnebilmeli`;case"unrecognized_keys":return`Tan\u0131nmayan anahtar${n.keys.length>1?"lar":""}: ${C(n.keys,", ")}`;case"invalid_key":return`${n.origin} i\xE7inde ge\xE7ersiz anahtar`;case"invalid_union":return"Ge\xE7ersiz de\u011Fer";case"invalid_element":return`${n.origin} i\xE7inde ge\xE7ersiz de\u011Fer`;default:return"Ge\xE7ersiz de\u011Fer"}}};function XC(){return{localeError:tB()}}var rB=()=>{let e={string:{unit:"\u0441\u0438\u043C\u0432\u043E\u043B\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"},file:{unit:"\u0431\u0430\u0439\u0442\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"},array:{unit:"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"},set:{unit:"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"}};function t(i){return e[i]??null}let r=i=>{let s=typeof i;switch(s){case"number":return Number.isNaN(i)?"NaN":"\u0447\u0438\u0441\u043B\u043E";case"object":{if(Array.isArray(i))return"\u043C\u0430\u0441\u0438\u0432";if(i===null)return"null";if(Object.getPrototypeOf(i)!==Object.prototype&&i.constructor)return i.constructor.name}}return s},n={regex:"\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456",email:"\u0430\u0434\u0440\u0435\u0441\u0430 \u0435\u043B\u0435\u043A\u0442\u0440\u043E\u043D\u043D\u043E\u0457 \u043F\u043E\u0448\u0442\u0438",url:"URL",emoji:"\u0435\u043C\u043E\u0434\u0437\u0456",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u0434\u0430\u0442\u0430 \u0442\u0430 \u0447\u0430\u0441 ISO",date:"\u0434\u0430\u0442\u0430 ISO",time:"\u0447\u0430\u0441 ISO",duration:"\u0442\u0440\u0438\u0432\u0430\u043B\u0456\u0441\u0442\u044C ISO",ipv4:"\u0430\u0434\u0440\u0435\u0441\u0430 IPv4",ipv6:"\u0430\u0434\u0440\u0435\u0441\u0430 IPv6",cidrv4:"\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv4",cidrv6:"\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv6",base64:"\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64",base64url:"\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64url",json_string:"\u0440\u044F\u0434\u043E\u043A JSON",e164:"\u043D\u043E\u043C\u0435\u0440 E.164",jwt:"JWT",template_literal:"\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456"};return i=>{switch(i.code){case"invalid_type":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${i.expected}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${r(i.input)}`;case"invalid_value":return i.values.length===1?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${K(i.values[0])}`:`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0430 \u043E\u043F\u0446\u0456\u044F: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F \u043E\u0434\u043D\u0435 \u0437 ${C(i.values,"|")}`;case"too_big":{let s=i.inclusive?"<=":"<",o=t(i.origin);return o?`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${i.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} ${o.verb} ${s}${i.maximum.toString()} ${o.unit??"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432"}`:`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${i.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} \u0431\u0443\u0434\u0435 ${s}${i.maximum.toString()}`}case"too_small":{let s=i.inclusive?">=":">",o=t(i.origin);return o?`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${i.origin} ${o.verb} ${s}${i.minimum.toString()} ${o.unit}`:`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${i.origin} \u0431\u0443\u0434\u0435 ${s}${i.minimum.toString()}`}case"invalid_format":{let s=i;return s.format==="starts_with"?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043F\u043E\u0447\u0438\u043D\u0430\u0442\u0438\u0441\u044F \u0437 "${s.prefix}"`:s.format==="ends_with"?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0437\u0430\u043A\u0456\u043D\u0447\u0443\u0432\u0430\u0442\u0438\u0441\u044F \u043D\u0430 "${s.suffix}"`:s.format==="includes"?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043C\u0456\u0441\u0442\u0438\u0442\u0438 "${s.includes}"`:s.format==="regex"?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0432\u0456\u0434\u043F\u043E\u0432\u0456\u0434\u0430\u0442\u0438 \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${s.pattern}`:`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 ${n[s.format]??i.format}`}case"not_multiple_of":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0447\u0438\u0441\u043B\u043E: \u043F\u043E\u0432\u0438\u043D\u043D\u043E \u0431\u0443\u0442\u0438 \u043A\u0440\u0430\u0442\u043D\u0438\u043C ${i.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u043E\u0437\u043F\u0456\u0437\u043D\u0430\u043D\u0438\u0439 \u043A\u043B\u044E\u0447${i.keys.length>1?"\u0456":""}: ${C(i.keys,", ")}`;case"invalid_key":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u043A\u043B\u044E\u0447 \u0443 ${i.origin}`;case"invalid_union":return"\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456";case"invalid_element":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F \u0443 ${i.origin}`;default:return"\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456"}}};function YC(){return{localeError:rB()}}var nB=()=>{let e={string:{unit:"\u062D\u0631\u0648\u0641",verb:"\u06C1\u0648\u0646\u0627"},file:{unit:"\u0628\u0627\u0626\u0679\u0633",verb:"\u06C1\u0648\u0646\u0627"},array:{unit:"\u0622\u0626\u0679\u0645\u0632",verb:"\u06C1\u0648\u0646\u0627"},set:{unit:"\u0622\u0626\u0679\u0645\u0632",verb:"\u06C1\u0648\u0646\u0627"}};function t(i){return e[i]??null}let r=i=>{let s=typeof i;switch(s){case"number":return Number.isNaN(i)?"NaN":"\u0646\u0645\u0628\u0631";case"object":{if(Array.isArray(i))return"\u0622\u0631\u06D2";if(i===null)return"\u0646\u0644";if(Object.getPrototypeOf(i)!==Object.prototype&&i.constructor)return i.constructor.name}}return s},n={regex:"\u0627\u0646 \u067E\u0679",email:"\u0627\u06CC \u0645\u06CC\u0644 \u0627\u06CC\u0688\u0631\u06CC\u0633",url:"\u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644",emoji:"\u0627\u06CC\u0645\u0648\u062C\u06CC",uuid:"\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",uuidv4:"\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 4",uuidv6:"\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 6",nanoid:"\u0646\u06CC\u0646\u0648 \u0622\u0626\u06CC \u0688\u06CC",guid:"\u062C\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",cuid:"\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",cuid2:"\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC 2",ulid:"\u06CC\u0648 \u0627\u06CC\u0644 \u0622\u0626\u06CC \u0688\u06CC",xid:"\u0627\u06CC\u06A9\u0633 \u0622\u0626\u06CC \u0688\u06CC",ksuid:"\u06A9\u06D2 \u0627\u06CC\u0633 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",datetime:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0688\u06CC\u0679 \u0679\u0627\u0626\u0645",date:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u062A\u0627\u0631\u06CC\u062E",time:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0648\u0642\u062A",duration:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0645\u062F\u062A",ipv4:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0627\u06CC\u0688\u0631\u06CC\u0633",ipv6:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0627\u06CC\u0688\u0631\u06CC\u0633",cidrv4:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0631\u06CC\u0646\u062C",cidrv6:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0631\u06CC\u0646\u062C",base64:"\u0628\u06CC\u0633 64 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF",base64url:"\u0628\u06CC\u0633 64 \u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF",json_string:"\u062C\u06D2 \u0627\u06CC\u0633 \u0627\u0648 \u0627\u06CC\u0646 \u0633\u0679\u0631\u0646\u06AF",e164:"\u0627\u06CC 164 \u0646\u0645\u0628\u0631",jwt:"\u062C\u06D2 \u0688\u0628\u0644\u06CC\u0648 \u0679\u06CC",template_literal:"\u0627\u0646 \u067E\u0679"};return i=>{switch(i.code){case"invalid_type":return`\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${i.expected} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${r(i.input)} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`;case"invalid_value":return i.values.length===1?`\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${K(i.values[0])} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`:`\u063A\u0644\u0637 \u0622\u067E\u0634\u0646: ${C(i.values,"|")} \u0645\u06CC\u06BA \u0633\u06D2 \u0627\u06CC\u06A9 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;case"too_big":{let s=i.inclusive?"<=":"<",o=t(i.origin);return o?`\u0628\u06C1\u062A \u0628\u0691\u0627: ${i.origin??"\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u06D2 ${s}${i.maximum.toString()} ${o.unit??"\u0639\u0646\u0627\u0635\u0631"} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`:`\u0628\u06C1\u062A \u0628\u0691\u0627: ${i.origin??"\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u0627 ${s}${i.maximum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`}case"too_small":{let s=i.inclusive?">=":">",o=t(i.origin);return o?`\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${i.origin} \u06A9\u06D2 ${s}${i.minimum.toString()} ${o.unit} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`:`\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${i.origin} \u06A9\u0627 ${s}${i.minimum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`}case"invalid_format":{let s=i;return s.format==="starts_with"?`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${s.prefix}" \u0633\u06D2 \u0634\u0631\u0648\u0639 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`:s.format==="ends_with"?`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${s.suffix}" \u067E\u0631 \u062E\u062A\u0645 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`:s.format==="includes"?`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${s.includes}" \u0634\u0627\u0645\u0644 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`:s.format==="regex"?`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: \u067E\u06CC\u0679\u0631\u0646 ${s.pattern} \u0633\u06D2 \u0645\u06CC\u0686 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`:`\u063A\u0644\u0637 ${n[s.format]??i.format}`}case"not_multiple_of":return`\u063A\u0644\u0637 \u0646\u0645\u0628\u0631: ${i.divisor} \u06A9\u0627 \u0645\u0636\u0627\u0639\u0641 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;case"unrecognized_keys":return`\u063A\u06CC\u0631 \u062A\u0633\u0644\u06CC\u0645 \u0634\u062F\u06C1 \u06A9\u06CC${i.keys.length>1?"\u0632":""}: ${C(i.keys,"\u060C ")}`;case"invalid_key":return`${i.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u06A9\u06CC`;case"invalid_union":return"\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679";case"invalid_element":return`${i.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u0648\u06CC\u0644\u06CC\u0648`;default:return"\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679"}}};function QC(){return{localeError:nB()}}var iB=()=>{let e={string:{unit:"k\xFD t\u1EF1",verb:"c\xF3"},file:{unit:"byte",verb:"c\xF3"},array:{unit:"ph\u1EA7n t\u1EED",verb:"c\xF3"},set:{unit:"ph\u1EA7n t\u1EED",verb:"c\xF3"}};function t(i){return e[i]??null}let r=i=>{let s=typeof i;switch(s){case"number":return Number.isNaN(i)?"NaN":"s\u1ED1";case"object":{if(Array.isArray(i))return"m\u1EA3ng";if(i===null)return"null";if(Object.getPrototypeOf(i)!==Object.prototype&&i.constructor)return i.constructor.name}}return s},n={regex:"\u0111\u1EA7u v\xE0o",email:"\u0111\u1ECBa ch\u1EC9 email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ng\xE0y gi\u1EDD ISO",date:"ng\xE0y ISO",time:"gi\u1EDD ISO",duration:"kho\u1EA3ng th\u1EDDi gian ISO",ipv4:"\u0111\u1ECBa ch\u1EC9 IPv4",ipv6:"\u0111\u1ECBa ch\u1EC9 IPv6",cidrv4:"d\u1EA3i IPv4",cidrv6:"d\u1EA3i IPv6",base64:"chu\u1ED7i m\xE3 h\xF3a base64",base64url:"chu\u1ED7i m\xE3 h\xF3a base64url",json_string:"chu\u1ED7i JSON",e164:"s\u1ED1 E.164",jwt:"JWT",template_literal:"\u0111\u1EA7u v\xE0o"};return i=>{switch(i.code){case"invalid_type":return`\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${i.expected}, nh\u1EADn \u0111\u01B0\u1EE3c ${r(i.input)}`;case"invalid_value":return i.values.length===1?`\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${K(i.values[0])}`:`T\xF9y ch\u1ECDn kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i m\u1ED9t trong c\xE1c gi\xE1 tr\u1ECB ${C(i.values,"|")}`;case"too_big":{let s=i.inclusive?"<=":"<",o=t(i.origin);return o?`Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${i.origin??"gi\xE1 tr\u1ECB"} ${o.verb} ${s}${i.maximum.toString()} ${o.unit??"ph\u1EA7n t\u1EED"}`:`Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${i.origin??"gi\xE1 tr\u1ECB"} ${s}${i.maximum.toString()}`}case"too_small":{let s=i.inclusive?">=":">",o=t(i.origin);return o?`Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${i.origin} ${o.verb} ${s}${i.minimum.toString()} ${o.unit}`:`Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${i.origin} ${s}${i.minimum.toString()}`}case"invalid_format":{let s=i;return s.format==="starts_with"?`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i b\u1EAFt \u0111\u1EA7u b\u1EB1ng "${s.prefix}"`:s.format==="ends_with"?`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i k\u1EBFt th\xFAc b\u1EB1ng "${s.suffix}"`:s.format==="includes"?`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i bao g\u1ED3m "${s.includes}"`:s.format==="regex"?`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i kh\u1EDBp v\u1EDBi m\u1EABu ${s.pattern}`:`${n[s.format]??i.format} kh\xF4ng h\u1EE3p l\u1EC7`}case"not_multiple_of":return`S\u1ED1 kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i l\xE0 b\u1ED9i s\u1ED1 c\u1EE7a ${i.divisor}`;case"unrecognized_keys":return`Kh\xF3a kh\xF4ng \u0111\u01B0\u1EE3c nh\u1EADn d\u1EA1ng: ${C(i.keys,", ")}`;case"invalid_key":return`Kh\xF3a kh\xF4ng h\u1EE3p l\u1EC7 trong ${i.origin}`;case"invalid_union":return"\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7";case"invalid_element":return`Gi\xE1 tr\u1ECB kh\xF4ng h\u1EE3p l\u1EC7 trong ${i.origin}`;default:return"\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7"}}};function eP(){return{localeError:iB()}}var sB=()=>{let e={string:{unit:"\u5B57\u7B26",verb:"\u5305\u542B"},file:{unit:"\u5B57\u8282",verb:"\u5305\u542B"},array:{unit:"\u9879",verb:"\u5305\u542B"},set:{unit:"\u9879",verb:"\u5305\u542B"}};function t(i){return e[i]??null}let r=i=>{let s=typeof i;switch(s){case"number":return Number.isNaN(i)?"\u975E\u6570\u5B57(NaN)":"\u6570\u5B57";case"object":{if(Array.isArray(i))return"\u6570\u7EC4";if(i===null)return"\u7A7A\u503C(null)";if(Object.getPrototypeOf(i)!==Object.prototype&&i.constructor)return i.constructor.name}}return s},n={regex:"\u8F93\u5165",email:"\u7535\u5B50\u90AE\u4EF6",url:"URL",emoji:"\u8868\u60C5\u7B26\u53F7",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO\u65E5\u671F\u65F6\u95F4",date:"ISO\u65E5\u671F",time:"ISO\u65F6\u95F4",duration:"ISO\u65F6\u957F",ipv4:"IPv4\u5730\u5740",ipv6:"IPv6\u5730\u5740",cidrv4:"IPv4\u7F51\u6BB5",cidrv6:"IPv6\u7F51\u6BB5",base64:"base64\u7F16\u7801\u5B57\u7B26\u4E32",base64url:"base64url\u7F16\u7801\u5B57\u7B26\u4E32",json_string:"JSON\u5B57\u7B26\u4E32",e164:"E.164\u53F7\u7801",jwt:"JWT",template_literal:"\u8F93\u5165"};return i=>{switch(i.code){case"invalid_type":return`\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${i.expected}\uFF0C\u5B9E\u9645\u63A5\u6536 ${r(i.input)}`;case"invalid_value":return i.values.length===1?`\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${K(i.values[0])}`:`\u65E0\u6548\u9009\u9879\uFF1A\u671F\u671B\u4EE5\u4E0B\u4E4B\u4E00 ${C(i.values,"|")}`;case"too_big":{let s=i.inclusive?"<=":"<",o=t(i.origin);return o?`\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${i.origin??"\u503C"} ${s}${i.maximum.toString()} ${o.unit??"\u4E2A\u5143\u7D20"}`:`\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${i.origin??"\u503C"} ${s}${i.maximum.toString()}`}case"too_small":{let s=i.inclusive?">=":">",o=t(i.origin);return o?`\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${i.origin} ${s}${i.minimum.toString()} ${o.unit}`:`\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${i.origin} ${s}${i.minimum.toString()}`}case"invalid_format":{let s=i;return s.format==="starts_with"?`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${s.prefix}" \u5F00\u5934`:s.format==="ends_with"?`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${s.suffix}" \u7ED3\u5C3E`:s.format==="includes"?`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u5305\u542B "${s.includes}"`:s.format==="regex"?`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u6EE1\u8DB3\u6B63\u5219\u8868\u8FBE\u5F0F ${s.pattern}`:`\u65E0\u6548${n[s.format]??i.format}`}case"not_multiple_of":return`\u65E0\u6548\u6570\u5B57\uFF1A\u5FC5\u987B\u662F ${i.divisor} \u7684\u500D\u6570`;case"unrecognized_keys":return`\u51FA\u73B0\u672A\u77E5\u7684\u952E(key): ${C(i.keys,", ")}`;case"invalid_key":return`${i.origin} \u4E2D\u7684\u952E(key)\u65E0\u6548`;case"invalid_union":return"\u65E0\u6548\u8F93\u5165";case"invalid_element":return`${i.origin} \u4E2D\u5305\u542B\u65E0\u6548\u503C(value)`;default:return"\u65E0\u6548\u8F93\u5165"}}};function tP(){return{localeError:sB()}}var oB=()=>{let e={string:{unit:"\u5B57\u5143",verb:"\u64C1\u6709"},file:{unit:"\u4F4D\u5143\u7D44",verb:"\u64C1\u6709"},array:{unit:"\u9805\u76EE",verb:"\u64C1\u6709"},set:{unit:"\u9805\u76EE",verb:"\u64C1\u6709"}};function t(i){return e[i]??null}let r=i=>{let s=typeof i;switch(s){case"number":return Number.isNaN(i)?"NaN":"number";case"object":{if(Array.isArray(i))return"array";if(i===null)return"null";if(Object.getPrototypeOf(i)!==Object.prototype&&i.constructor)return i.constructor.name}}return s},n={regex:"\u8F38\u5165",email:"\u90F5\u4EF6\u5730\u5740",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u65E5\u671F\u6642\u9593",date:"ISO \u65E5\u671F",time:"ISO \u6642\u9593",duration:"ISO \u671F\u9593",ipv4:"IPv4 \u4F4D\u5740",ipv6:"IPv6 \u4F4D\u5740",cidrv4:"IPv4 \u7BC4\u570D",cidrv6:"IPv6 \u7BC4\u570D",base64:"base64 \u7DE8\u78BC\u5B57\u4E32",base64url:"base64url \u7DE8\u78BC\u5B57\u4E32",json_string:"JSON \u5B57\u4E32",e164:"E.164 \u6578\u503C",jwt:"JWT",template_literal:"\u8F38\u5165"};return i=>{switch(i.code){case"invalid_type":return`\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${i.expected}\uFF0C\u4F46\u6536\u5230 ${r(i.input)}`;case"invalid_value":return i.values.length===1?`\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${K(i.values[0])}`:`\u7121\u6548\u7684\u9078\u9805\uFF1A\u9810\u671F\u70BA\u4EE5\u4E0B\u5176\u4E2D\u4E4B\u4E00 ${C(i.values,"|")}`;case"too_big":{let s=i.inclusive?"<=":"<",o=t(i.origin);return o?`\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${i.origin??"\u503C"} \u61C9\u70BA ${s}${i.maximum.toString()} ${o.unit??"\u500B\u5143\u7D20"}`:`\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${i.origin??"\u503C"} \u61C9\u70BA ${s}${i.maximum.toString()}`}case"too_small":{let s=i.inclusive?">=":">",o=t(i.origin);return o?`\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${i.origin} \u61C9\u70BA ${s}${i.minimum.toString()} ${o.unit}`:`\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${i.origin} \u61C9\u70BA ${s}${i.minimum.toString()}`}case"invalid_format":{let s=i;return s.format==="starts_with"?`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${s.prefix}" \u958B\u982D`:s.format==="ends_with"?`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${s.suffix}" \u7D50\u5C3E`:s.format==="includes"?`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u5305\u542B "${s.includes}"`:s.format==="regex"?`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u7B26\u5408\u683C\u5F0F ${s.pattern}`:`\u7121\u6548\u7684 ${n[s.format]??i.format}`}case"not_multiple_of":return`\u7121\u6548\u7684\u6578\u5B57\uFF1A\u5FC5\u9808\u70BA ${i.divisor} \u7684\u500D\u6578`;case"unrecognized_keys":return`\u7121\u6CD5\u8B58\u5225\u7684\u9375\u503C${i.keys.length>1?"\u5011":""}\uFF1A${C(i.keys,"\u3001")}`;case"invalid_key":return`${i.origin} \u4E2D\u6709\u7121\u6548\u7684\u9375\u503C`;case"invalid_union":return"\u7121\u6548\u7684\u8F38\u5165\u503C";case"invalid_element":return`${i.origin} \u4E2D\u6709\u7121\u6548\u7684\u503C`;default:return"\u7121\u6548\u7684\u8F38\u5165\u503C"}}};function rP(){return{localeError:oB()}}var qw=Symbol("ZodOutput"),Hw=Symbol("ZodInput"),Ec=class{constructor(){this._map=new Map,this._idmap=new Map}add(t,...r){let n=r[0];if(this._map.set(t,n),n&&typeof n=="object"&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,t)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(t){let r=this._map.get(t);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(t),this}get(t){let r=t._zod.parent;if(r){let n={...this.get(r)??{}};return delete n.id,{...n,...this._map.get(t)}}return this._map.get(t)}has(t){return this._map.has(t)}};function Nm(){return new Ec}var ct=Nm();function Ww(e,t){return new e({type:"string",...B(t)})}function Jw(e,t){return new e({type:"string",coerce:!0,...B(t)})}function Rm(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...B(t)})}function op(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...B(t)})}function Mm(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...B(t)})}function jm(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...B(t)})}function Dm(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...B(t)})}function zm(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...B(t)})}function Lm(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...B(t)})}function Um(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...B(t)})}function Fm(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...B(t)})}function Bm(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...B(t)})}function Vm(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...B(t)})}function Zm(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...B(t)})}function Gm(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...B(t)})}function Km(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...B(t)})}function qm(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...B(t)})}function Hm(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...B(t)})}function Wm(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...B(t)})}function Jm(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...B(t)})}function Xm(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...B(t)})}function Ym(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...B(t)})}function Qm(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...B(t)})}function eh(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...B(t)})}var Xw={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6};function Yw(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...B(t)})}function Qw(e,t){return new e({type:"string",format:"date",check:"string_format",...B(t)})}function ex(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...B(t)})}function tx(e,t){return new e({type:"string",format:"duration",check:"string_format",...B(t)})}function rx(e,t){return new e({type:"number",checks:[],...B(t)})}function nx(e,t){return new e({type:"number",coerce:!0,checks:[],...B(t)})}function ix(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...B(t)})}function sx(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float32",...B(t)})}function ox(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float64",...B(t)})}function ax(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"int32",...B(t)})}function cx(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"uint32",...B(t)})}function ux(e,t){return new e({type:"boolean",...B(t)})}function lx(e,t){return new e({type:"boolean",coerce:!0,...B(t)})}function px(e,t){return new e({type:"bigint",...B(t)})}function dx(e,t){return new e({type:"bigint",coerce:!0,...B(t)})}function fx(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...B(t)})}function mx(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...B(t)})}function hx(e,t){return new e({type:"symbol",...B(t)})}function gx(e,t){return new e({type:"undefined",...B(t)})}function _x(e,t){return new e({type:"null",...B(t)})}function yx(e){return new e({type:"any"})}function Ks(e){return new e({type:"unknown"})}function ap(e,t){return new e({type:"never",...B(t)})}function vx(e,t){return new e({type:"void",...B(t)})}function bx(e,t){return new e({type:"date",...B(t)})}function wx(e,t){return new e({type:"date",coerce:!0,...B(t)})}function xx(e,t){return new e({type:"nan",...B(t)})}function Ji(e,t){return new Em({check:"less_than",...B(t),value:e,inclusive:!1})}function pn(e,t){return new Em({check:"less_than",...B(t),value:e,inclusive:!0})}function Xi(e,t){return new km({check:"greater_than",...B(t),value:e,inclusive:!1})}function Pr(e,t){return new km({check:"greater_than",...B(t),value:e,inclusive:!0})}function Ix(e){return Xi(0,e)}function Sx(e){return Ji(0,e)}function Ex(e){return pn(0,e)}function kx(e){return Pr(0,e)}function Yo(e,t){return new Ab({check:"multiple_of",...B(t),value:e})}function kc(e,t){return new $b({check:"max_size",...B(t),maximum:e})}function Qo(e,t){return new Cb({check:"min_size",...B(t),minimum:e})}function cp(e,t){return new Pb({check:"size_equals",...B(t),size:e})}function Ac(e,t){return new Nb({check:"max_length",...B(t),maximum:e})}function qs(e,t){return new Rb({check:"min_length",...B(t),minimum:e})}function Tc(e,t){return new Mb({check:"length_equals",...B(t),length:e})}function up(e,t){return new jb({check:"string_format",format:"regex",...B(t),pattern:e})}function lp(e){return new Db({check:"string_format",format:"lowercase",...B(e)})}function pp(e){return new zb({check:"string_format",format:"uppercase",...B(e)})}function dp(e,t){return new Lb({check:"string_format",format:"includes",...B(t),includes:e})}function fp(e,t){return new Ub({check:"string_format",format:"starts_with",...B(t),prefix:e})}function mp(e,t){return new Fb({check:"string_format",format:"ends_with",...B(t),suffix:e})}function Ax(e,t,r){return new Bb({check:"property",property:e,schema:t,...B(r)})}function hp(e,t){return new Vb({check:"mime_type",mime:e,...B(t)})}function Yi(e){return new Zb({check:"overwrite",tx:e})}function gp(e){return Yi(t=>t.normalize(e))}function _p(){return Yi(e=>e.trim())}function yp(){return Yi(e=>e.toLowerCase())}function vp(){return Yi(e=>e.toUpperCase())}function bp(e,t,r){return new e({type:"array",element:t,...B(r)})}function aB(e,t,r){return new e({type:"union",options:t,...B(r)})}function cB(e,t,r,n){return new e({type:"union",options:r,discriminator:t,...B(n)})}function uB(e,t,r){return new e({type:"intersection",left:t,right:r})}function Tx(e,t,r,n){let i=r instanceof _e,s=i?n:r,o=i?r:null;return new e({type:"tuple",items:t,rest:o,...B(s)})}function lB(e,t,r,n){return new e({type:"record",keyType:t,valueType:r,...B(n)})}function pB(e,t,r,n){return new e({type:"map",keyType:t,valueType:r,...B(n)})}function dB(e,t,r){return new e({type:"set",valueType:t,...B(r)})}function fB(e,t,r){let n=Array.isArray(t)?Object.fromEntries(t.map(i=>[i,i])):t;return new e({type:"enum",entries:n,...B(r)})}function mB(e,t,r){return new e({type:"enum",entries:t,...B(r)})}function hB(e,t,r){return new e({type:"literal",values:Array.isArray(t)?t:[t],...B(r)})}function Ox(e,t){return new e({type:"file",...B(t)})}function gB(e,t){return new e({type:"transform",transform:t})}function _B(e,t){return new e({type:"optional",innerType:t})}function yB(e,t){return new e({type:"nullable",innerType:t})}function vB(e,t,r){return new e({type:"default",innerType:t,get defaultValue(){return typeof r=="function"?r():r}})}function bB(e,t,r){return new e({type:"nonoptional",innerType:t,...B(r)})}function wB(e,t){return new e({type:"success",innerType:t})}function xB(e,t,r){return new e({type:"catch",innerType:t,catchValue:typeof r=="function"?r:()=>r})}function IB(e,t,r){return new e({type:"pipe",in:t,out:r})}function SB(e,t){return new e({type:"readonly",innerType:t})}function EB(e,t,r){return new e({type:"template_literal",parts:t,...B(r)})}function kB(e,t){return new e({type:"lazy",getter:t})}function AB(e,t){return new e({type:"promise",innerType:t})}function $x(e,t,r){let n=B(r);return n.abort??(n.abort=!0),new e({type:"custom",check:"custom",fn:t,...n})}function Cx(e,t,r){return new e({type:"custom",check:"custom",fn:t,...B(r)})}function Px(e,t){let r=B(t),n=r.truthy??["true","1","yes","on","y","enabled"],i=r.falsy??["false","0","no","off","n","disabled"];r.case!=="sensitive"&&(n=n.map(m=>typeof m=="string"?m.toLowerCase():m),i=i.map(m=>typeof m=="string"?m.toLowerCase():m));let s=new Set(n),o=new Set(i),a=e.Pipe??ip,c=e.Boolean??ep,u=e.String??Jo,l=e.Transform??np,p=new l({type:"transform",transform:(m,h)=>{let b=m;return r.case!=="sensitive"&&(b=b.toLowerCase()),s.has(b)?!0:o.has(b)?!1:(h.issues.push({code:"invalid_value",expected:"stringbool",values:[...s,...o],input:h.value,inst:p}),{})},error:r.error}),f=new a({type:"pipe",in:new u({type:"string",error:r.error}),out:p,error:r.error});return new a({type:"pipe",in:f,out:new c({type:"boolean",error:r.error}),error:r.error})}function Nx(e,t,r,n={}){let i=B(n),s={...B(n),check:"string_format",type:"string",format:t,fn:typeof r=="function"?r:a=>r.test(a),...i};return r instanceof RegExp&&(s.pattern=r),new e(s)}var th=class{constructor(t){this._def=t,this.def=t}implement(t){if(typeof t!="function")throw new Error("implement() must be called with a function");let r=((...n)=>{let i=this._def.input?di(this._def.input,n,void 0,{callee:r}):n;if(!Array.isArray(i))throw new Error("Invalid arguments schema: not an array or tuple schema.");let s=t(...i);return this._def.output?di(this._def.output,s,void 0,{callee:r}):s});return r}implementAsync(t){if(typeof t!="function")throw new Error("implement() must be called with a function");let r=(async(...n)=>{let i=this._def.input?await qo(this._def.input,n,void 0,{callee:r}):n;if(!Array.isArray(i))throw new Error("Invalid arguments schema: not an array or tuple schema.");let s=await t(...i);return this._def.output?qo(this._def.output,s,void 0,{callee:r}):s});return r}input(...t){let r=this.constructor;return Array.isArray(t[0])?new r({type:"function",input:new Xo({type:"tuple",items:t[0],rest:t[1]}),output:this._def.output}):new r({type:"function",input:t[0],output:this._def.output})}output(t){let r=this.constructor;return new r({type:"function",input:this._def.input,output:t})}};function Rx(e){return new th({type:"function",input:Array.isArray(e?.input)?Tx(Xo,e?.input):e?.input??bp(rp,Ks(Gs)),output:e?.output??Ks(Gs)})}var wp=class{constructor(t){this.counter=0,this.metadataRegistry=t?.metadata??ct,this.target=t?.target??"draft-2020-12",this.unrepresentable=t?.unrepresentable??"throw",this.override=t?.override??(()=>{}),this.io=t?.io??"output",this.seen=new Map}process(t,r={path:[],schemaPath:[]}){var n;let i=t._zod.def,s={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},o=this.seen.get(t);if(o)return o.count++,r.schemaPath.includes(t)&&(o.cycle=r.path),o.schema;let a={schema:{},count:1,cycle:void 0,path:r.path};this.seen.set(t,a);let c=t._zod.toJSONSchema?.();if(c)a.schema=c;else{let p={...r,schemaPath:[...r.schemaPath,t],path:r.path},f=t._zod.parent;if(f)a.ref=f,this.process(f,p),this.seen.get(f).isParent=!0;else{let d=a.schema;switch(i.type){case"string":{let m=d;m.type="string";let{minimum:h,maximum:b,format:_,patterns:y,contentEncoding:x}=t._zod.bag;if(typeof h=="number"&&(m.minLength=h),typeof b=="number"&&(m.maxLength=b),_&&(m.format=s[_]??_,m.format===""&&delete m.format),x&&(m.contentEncoding=x),y&&y.size>0){let I=[...y];I.length===1?m.pattern=I[0].source:I.length>1&&(a.schema.allOf=[...I.map(A=>({...this.target==="draft-7"?{type:"string"}:{},pattern:A.source}))])}break}case"number":{let m=d,{minimum:h,maximum:b,format:_,multipleOf:y,exclusiveMaximum:x,exclusiveMinimum:I}=t._zod.bag;typeof _=="string"&&_.includes("int")?m.type="integer":m.type="number",typeof I=="number"&&(m.exclusiveMinimum=I),typeof h=="number"&&(m.minimum=h,typeof I=="number"&&(I>=h?delete m.minimum:delete m.exclusiveMinimum)),typeof x=="number"&&(m.exclusiveMaximum=x),typeof b=="number"&&(m.maximum=b,typeof x=="number"&&(x<=b?delete m.maximum:delete m.exclusiveMaximum)),typeof y=="number"&&(m.multipleOf=y);break}case"boolean":{let m=d;m.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{d.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{d.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{let m=d,{minimum:h,maximum:b}=t._zod.bag;typeof h=="number"&&(m.minItems=h),typeof b=="number"&&(m.maxItems=b),m.type="array",m.items=this.process(i.element,{...p,path:[...p.path,"items"]});break}case"object":{let m=d;m.type="object",m.properties={};let h=i.shape;for(let y in h)m.properties[y]=this.process(h[y],{...p,path:[...p.path,"properties",y]});let b=new Set(Object.keys(h)),_=new Set([...b].filter(y=>{let x=i.shape[y]._zod;return this.io==="input"?x.optin===void 0:x.optout===void 0}));_.size>0&&(m.required=Array.from(_)),i.catchall?._zod.def.type==="never"?m.additionalProperties=!1:i.catchall?i.catchall&&(m.additionalProperties=this.process(i.catchall,{...p,path:[...p.path,"additionalProperties"]})):this.io==="output"&&(m.additionalProperties=!1);break}case"union":{let m=d;m.anyOf=i.options.map((h,b)=>this.process(h,{...p,path:[...p.path,"anyOf",b]}));break}case"intersection":{let m=d,h=this.process(i.left,{...p,path:[...p.path,"allOf",0]}),b=this.process(i.right,{...p,path:[...p.path,"allOf",1]}),_=x=>"allOf"in x&&Object.keys(x).length===1,y=[..._(h)?h.allOf:[h],..._(b)?b.allOf:[b]];m.allOf=y;break}case"tuple":{let m=d;m.type="array";let h=i.items.map((y,x)=>this.process(y,{...p,path:[...p.path,"prefixItems",x]}));if(this.target==="draft-2020-12"?m.prefixItems=h:m.items=h,i.rest){let y=this.process(i.rest,{...p,path:[...p.path,"items"]});this.target==="draft-2020-12"?m.items=y:m.additionalItems=y}i.rest&&(m.items=this.process(i.rest,{...p,path:[...p.path,"items"]}));let{minimum:b,maximum:_}=t._zod.bag;typeof b=="number"&&(m.minItems=b),typeof _=="number"&&(m.maxItems=_);break}case"record":{let m=d;m.type="object",m.propertyNames=this.process(i.keyType,{...p,path:[...p.path,"propertyNames"]}),m.additionalProperties=this.process(i.valueType,{...p,path:[...p.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{let m=d,h=Zl(i.entries);h.every(b=>typeof b=="number")&&(m.type="number"),h.every(b=>typeof b=="string")&&(m.type="string"),m.enum=h;break}case"literal":{let m=d,h=[];for(let b of i.values)if(b===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof b=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");h.push(Number(b))}else h.push(b);if(h.length!==0)if(h.length===1){let b=h[0];m.type=b===null?"null":typeof b,m.const=b}else h.every(b=>typeof b=="number")&&(m.type="number"),h.every(b=>typeof b=="string")&&(m.type="string"),h.every(b=>typeof b=="boolean")&&(m.type="string"),h.every(b=>b===null)&&(m.type="null"),m.enum=h;break}case"file":{let m=d,h={type:"string",format:"binary",contentEncoding:"binary"},{minimum:b,maximum:_,mime:y}=t._zod.bag;b!==void 0&&(h.minLength=b),_!==void 0&&(h.maxLength=_),y?y.length===1?(h.contentMediaType=y[0],Object.assign(m,h)):m.anyOf=y.map(x=>({...h,contentMediaType:x})):Object.assign(m,h);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let m=this.process(i.innerType,p);d.anyOf=[m,{type:"null"}];break}case"nonoptional":{this.process(i.innerType,p),a.ref=i.innerType;break}case"success":{let m=d;m.type="boolean";break}case"default":{this.process(i.innerType,p),a.ref=i.innerType,d.default=JSON.parse(JSON.stringify(i.defaultValue));break}case"prefault":{this.process(i.innerType,p),a.ref=i.innerType,this.io==="input"&&(d._prefault=JSON.parse(JSON.stringify(i.defaultValue)));break}case"catch":{this.process(i.innerType,p),a.ref=i.innerType;let m;try{m=i.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}d.default=m;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let m=d,h=t._zod.pattern;if(!h)throw new Error("Pattern not found in template literal");m.type="string",m.pattern=h.source;break}case"pipe":{let m=this.io==="input"?i.in._zod.def.type==="transform"?i.out:i.in:i.out;this.process(m,p),a.ref=m;break}case"readonly":{this.process(i.innerType,p),a.ref=i.innerType,d.readOnly=!0;break}case"promise":{this.process(i.innerType,p),a.ref=i.innerType;break}case"optional":{this.process(i.innerType,p),a.ref=i.innerType;break}case"lazy":{let m=t._zod.innerType;this.process(m,p),a.ref=m;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}default:}}}let u=this.metadataRegistry.get(t);return u&&Object.assign(a.schema,u),this.io==="input"&&Ct(t)&&(delete a.schema.examples,delete a.schema.default),this.io==="input"&&a.schema._prefault&&((n=a.schema).default??(n.default=a.schema._prefault)),delete a.schema._prefault,this.seen.get(t).schema}emit(t,r){let n={cycles:r?.cycles??"ref",reused:r?.reused??"inline",external:r?.external??void 0},i=this.seen.get(t);if(!i)throw new Error("Unprocessed schema. This is a bug in Zod.");let s=l=>{let p=this.target==="draft-2020-12"?"$defs":"definitions";if(n.external){let h=n.external.registry.get(l[0])?.id,b=n.external.uri??(y=>y);if(h)return{ref:b(h)};let _=l[1].defId??l[1].schema.id??`schema${this.counter++}`;return l[1].defId=_,{defId:_,ref:`${b("__shared")}#/${p}/${_}`}}if(l[1]===i)return{ref:"#"};let d=`#/${p}/`,m=l[1].schema.id??`__schema${this.counter++}`;return{defId:m,ref:d+m}},o=l=>{if(l[1].schema.$ref)return;let p=l[1],{ref:f,defId:d}=s(l);p.def={...p.schema},d&&(p.defId=d);let m=p.schema;for(let h in m)delete m[h];m.$ref=f};if(n.cycles==="throw")for(let l of this.seen.entries()){let p=l[1];if(p.cycle)throw new Error(`Cycle detected: #/${p.cycle?.join("/")}/<root>
|
|
85
|
+
|
|
86
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let l of this.seen.entries()){let p=l[1];if(t===l[0]){o(l);continue}if(n.external){let d=n.external.registry.get(l[0])?.id;if(t!==l[0]&&d){o(l);continue}}if(this.metadataRegistry.get(l[0])?.id){o(l);continue}if(p.cycle){o(l);continue}if(p.count>1&&n.reused==="ref"){o(l);continue}}let a=(l,p)=>{let f=this.seen.get(l),d=f.def??f.schema,m={...d};if(f.ref===null)return;let h=f.ref;if(f.ref=null,h){a(h,p);let b=this.seen.get(h).schema;b.$ref&&p.target==="draft-7"?(d.allOf=d.allOf??[],d.allOf.push(b)):(Object.assign(d,b),Object.assign(d,m))}f.isParent||this.override({zodSchema:l,jsonSchema:d,path:f.path??[]})};for(let l of[...this.seen.entries()].reverse())a(l[0],{target:this.target});let c={};if(this.target==="draft-2020-12"?c.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?c.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),n.external?.uri){let l=n.external.registry.get(t)?.id;if(!l)throw new Error("Schema is missing an `id` property");c.$id=n.external.uri(l)}Object.assign(c,i.def);let u=n.external?.defs??{};for(let l of this.seen.entries()){let p=l[1];p.def&&p.defId&&(u[p.defId]=p.def)}n.external||Object.keys(u).length>0&&(this.target==="draft-2020-12"?c.$defs=u:c.definitions=u);try{return JSON.parse(JSON.stringify(c))}catch{throw new Error("Error converting schema to JSON.")}}};function Hs(e,t){if(e instanceof Ec){let n=new wp(t),i={};for(let a of e._idmap.entries()){let[c,u]=a;n.process(u)}let s={},o={registry:e,uri:t?.uri,defs:i};for(let a of e._idmap.entries()){let[c,u]=a;s[c]=n.emit(u,{...t,external:o})}if(Object.keys(i).length>0){let a=n.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[a]:i}}return{schemas:s}}let r=new wp(t);return r.process(e),r.emit(e,t)}function Ct(e,t){let r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);let i=e._zod.def;switch(i.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return Ct(i.element,r);case"object":{for(let s in i.shape)if(Ct(i.shape[s],r))return!0;return!1}case"union":{for(let s of i.options)if(Ct(s,r))return!0;return!1}case"intersection":return Ct(i.left,r)||Ct(i.right,r);case"tuple":{for(let s of i.items)if(Ct(s,r))return!0;return!!(i.rest&&Ct(i.rest,r))}case"record":return Ct(i.keyType,r)||Ct(i.valueType,r);case"map":return Ct(i.keyType,r)||Ct(i.valueType,r);case"set":return Ct(i.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Ct(i.innerType,r);case"lazy":return Ct(i.getter(),r);case"default":return Ct(i.innerType,r);case"prefault":return Ct(i.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return Ct(i.in,r)||Ct(i.out,r);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${i.type}`)}var nP={};function Je(e){if(typeof e!="object"||e===null)return!1;let t=e;if(!("_zod"in t))return!1;let r=t._zod;return typeof r=="object"&&r!==null&&"def"in r}function it(e){if(typeof e!="object"||e===null)return!1;let t=e;if(!("_def"in t)||"_zod"in t)return!1;let r=t._def;return typeof r=="object"&&r!=null&&"typeName"in r}function iP(e){return Je(e)&&console.warn("[WARNING] Attempting to use Zod 4 schema in a context where Zod 3 schema is expected. This may cause unexpected behavior."),it(e)}function _r(e){return!e||typeof e!="object"||Array.isArray(e)?!1:!!(Je(e)||it(e))}function Mx(e){return typeof e=="object"&&e!==null&&"_def"in e&&typeof e._def=="object"&&e._def!==null&&"typeName"in e._def&&e._def.typeName==="ZodLiteral"}function jx(e){return Je(e)?typeof e=="object"&&e!==null&&"_zod"in e&&typeof e._zod=="object"&&e._zod!==null&&"def"in e._zod&&typeof e._zod.def=="object"&&e._zod.def!==null&&"type"in e._zod.def&&e._zod.def.type==="literal":!1}function sP(e){return!!(Mx(e)||jx(e))}async function nh(e,t){if(Je(e))try{return{success:!0,data:await qo(e,t)}}catch(r){return{success:!1,error:r}}if(it(e))return await e.safeParseAsync(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}async function Ws(e,t){if(Je(e))return await qo(e,t);if(it(e))return await e.parseAsync(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function oP(e,t){if(Je(e))try{return{success:!0,data:di(e,t)}}catch(r){return{success:!1,error:r}}if(it(e))return e.safeParse(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function $c(e,t){if(Je(e))return di(e,t);if(it(e))return e.parse(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function $n(e){if(Je(e))return ct.get(e)?.description;if(it(e)||"description"in e&&typeof e.description=="string")return e.description}function aP(e){if(!_r(e))return!1;if(it(e)){let t=e._def;if(t.typeName==="ZodObject"){let r=e;return!r.shape||Object.keys(r.shape).length===0}if(t.typeName==="ZodRecord")return!0}if(Je(e)){let t=e._zod.def;if(t.type==="object"){let r=e;return!r.shape||Object.keys(r.shape).length===0}if(t.type==="record")return!0}return typeof e=="object"&&e!==null&&!("shape"in e)}function Cc(e){return _r(e)?it(e)?e._def.typeName==="ZodString":Je(e)?e._zod.def.type==="string":!1:!1}function ih(e){return typeof e=="object"&&e!==null&&"_def"in e&&typeof e._def=="object"&&e._def!==null&&"typeName"in e._def&&e._def.typeName==="ZodObject"}function dn(e){return Je(e)?typeof e=="object"&&e!==null&&"_zod"in e&&typeof e._zod=="object"&&e._zod!==null&&"def"in e._zod&&typeof e._zod.def=="object"&&e._zod.def!==null&&"type"in e._zod.def&&e._zod.def.type==="object":!1}function xp(e){return Je(e)?typeof e=="object"&&e!==null&&"_zod"in e&&typeof e._zod=="object"&&e._zod!==null&&"def"in e._zod&&typeof e._zod.def=="object"&&e._zod.def!==null&&"type"in e._zod.def&&e._zod.def.type==="array":!1}function Dx(e){return Je(e)?typeof e=="object"&&e!==null&&"_zod"in e&&typeof e._zod=="object"&&e._zod!==null&&"def"in e._zod&&typeof e._zod.def=="object"&&e._zod.def!==null&&"type"in e._zod.def&&e._zod.def.type==="optional":!1}function zx(e){return Je(e)?typeof e=="object"&&e!==null&&"_zod"in e&&typeof e._zod=="object"&&e._zod!==null&&"def"in e._zod&&typeof e._zod.def=="object"&&e._zod.def!==null&&"type"in e._zod.def&&e._zod.def.type==="nullable":!1}function yr(e){return!!(ih(e)||dn(e))}function ta(e){if(it(e))return e.shape;if(Je(e))return e._zod.def.shape;throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function sh(e,t){if(it(e))return e.extend(t);if(Je(e))return G.extend(e,t);throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Pc(e){if(it(e))return e.partial();if(Je(e))return G.partial(Sc,e,void 0);throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Oc(e,t=!1){if(it(e))return e.strict();if(dn(e)){let r=e._zod.def.shape;if(t)for(let[s,o]of Object.entries(e._zod.def.shape)){if(dn(o)){let c=Oc(o,t);r[s]=c}else if(xp(o)){let c=o._zod.def.element;dn(c)&&(c=Oc(c,t)),r[s]=lt(o,{...o._zod.def,element:c})}else r[s]=o;let a=ct.get(o);a&&ct.add(r[s],a)}let n=lt(e,{...e._zod.def,shape:r,catchall:ap(tp)}),i=ct.get(e);return i&&ct.add(n,i),n}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function rh(e,t=!1){if(ih(e))return e.passthrough();if(dn(e)){let r=e._zod.def.shape;if(t)for(let[s,o]of Object.entries(e._zod.def.shape)){if(dn(o)){let c=rh(o,t);r[s]=c}else if(xp(o)){let c=o._zod.def.element;dn(c)&&(c=rh(c,t)),r[s]=lt(o,{...o._zod.def,element:c})}else r[s]=o;let a=ct.get(o);a&&ct.add(r[s],a)}let n=lt(e,{...e._zod.def,shape:r,catchall:Ks(Gs)}),i=ct.get(e);return i&&ct.add(n,i),n}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function oh(e){if(it(e))try{let t=e.parse(void 0);return()=>t}catch{return}if(Je(e))try{let t=di(e,void 0);return()=>t}catch{return}}function TB(e){return it(e)&&"typeName"in e._def&&e._def.typeName==="ZodEffects"}function OB(e){return Je(e)&&e._zod.def.type==="pipe"}function ea(e,t,r){let n=r.get(e);if(n!==void 0)return n;if(it(e))return TB(e)?ea(e._def.schema,t,r):e;if(Je(e)){let i=e;if(OB(e)&&(i=ea(e._zod.def.in,t,r)),t){if(dn(i)){let o={};for(let[a,c]of Object.entries(i._zod.def.shape))o[a]=ea(c,t,r);i=lt(i,{...i._zod.def,shape:o})}else if(xp(i)){let o=ea(i._zod.def.element,t,r);i=lt(i,{...i._zod.def,element:o})}else if(Dx(i)){let o=ea(i._zod.def.innerType,t,r);i=lt(i,{...i._zod.def,innerType:o})}else if(zx(i)){let o=ea(i._zod.def.innerType,t,r);i=lt(i,{...i._zod.def,innerType:o})}}let s=ct.get(e);return s&&ct.add(i,s),r.set(e,i),i}throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function ah(e,t=!1){return ea(e,t,new WeakMap)}function cP(e,t){if(it(e)){let r=ta(e),n={};for(let[i,s]of Object.entries(r))t(i,s)?n[i]=s.optional():n[i]=s;return e.extend(n)}if(Je(e)){let r=ta(e),n={...e._zod.def.shape};for(let[o,a]of Object.entries(r))t(o,a)&&(n[o]=new Sc({type:"optional",innerType:a}));let i=lt(e,{...e._zod.def,shape:n}),s=ct.get(e);return s&&ct.add(i,s),i}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function ch(e){return e instanceof Error&&(e.constructor.name==="ZodError"||e.constructor.name==="$ZodError")}var lP=Symbol("Let zodToJsonSchema decide on which parser to use"),uP={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"},pP=e=>typeof e=="string"?{...uP,name:e}:{...uP,...e};var dP=e=>{let t=pP(e),r=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([n,i])=>[i._def,{def:i._def,path:[...t.basePath,t.definitionPath,n],jsonSchema:void 0}]))}};var uh=(e,t)=>{let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];r++);return[(e.length-r).toString(),...t.slice(r)].join("/")};function ut(e){if(e.target!=="openAi")return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy==="relative"?uh(t,e.currentPath):t.join("/")}}function Lx(e,t,r,n){n?.errorMessages&&r&&(e.errorMessage={...e.errorMessage,[t]:r})}function Le(e,t,r,n,i){e[t]=r,Lx(e,t,n,i)}var Ge={};Cs(Ge,{BRAND:()=>tV,DIRTY:()=>ra,EMPTY_PATH:()=>NB,INVALID:()=>pe,NEVER:()=>LV,OK:()=>er,ParseStatus:()=>Gt,Schema:()=>Se,ZodAny:()=>Ys,ZodArray:()=>ns,ZodBigInt:()=>ia,ZodBoolean:()=>sa,ZodBranded:()=>Sp,ZodCatch:()=>ga,ZodDate:()=>oa,ZodDefault:()=>ha,ZodDiscriminatedUnion:()=>dh,ZodEffects:()=>hn,ZodEnum:()=>fa,ZodError:()=>Nr,ZodFirstPartyTypeKind:()=>T,ZodFunction:()=>mh,ZodIntersection:()=>la,ZodIssueCode:()=>D,ZodLazy:()=>pa,ZodLiteral:()=>da,ZodMap:()=>zc,ZodNaN:()=>Uc,ZodNativeEnum:()=>ma,ZodNever:()=>Cn,ZodNull:()=>ca,ZodNullable:()=>hi,ZodNumber:()=>na,ZodObject:()=>Rr,ZodOptional:()=>fn,ZodParsedType:()=>X,ZodPipeline:()=>Ep,ZodPromise:()=>Qs,ZodReadonly:()=>_a,ZodRecord:()=>fh,ZodSchema:()=>Se,ZodSet:()=>Lc,ZodString:()=>Xs,ZodSymbol:()=>jc,ZodTransformer:()=>hn,ZodTuple:()=>mi,ZodType:()=>Se,ZodUndefined:()=>aa,ZodUnion:()=>ua,ZodUnknown:()=>rs,ZodVoid:()=>Dc,addIssueToContext:()=>H,any:()=>lV,array:()=>mV,bigint:()=>sV,boolean:()=>IP,coerce:()=>zV,custom:()=>bP,date:()=>oV,datetimeRegex:()=>yP,defaultErrorMap:()=>es,discriminatedUnion:()=>yV,effect:()=>$V,enum:()=>AV,function:()=>SV,getErrorMap:()=>Nc,getParsedType:()=>fi,instanceof:()=>nV,intersection:()=>vV,isAborted:()=>lh,isAsync:()=>Rc,isDirty:()=>ph,isValid:()=>Js,late:()=>rV,lazy:()=>EV,literal:()=>kV,makeIssue:()=>Ip,map:()=>xV,nan:()=>iV,nativeEnum:()=>TV,never:()=>dV,null:()=>uV,nullable:()=>PV,number:()=>xP,object:()=>hV,objectUtil:()=>Ux,oboolean:()=>DV,onumber:()=>jV,optional:()=>CV,ostring:()=>MV,pipeline:()=>RV,preprocess:()=>NV,promise:()=>OV,quotelessJson:()=>$B,record:()=>wV,set:()=>IV,setErrorMap:()=>PB,strictObject:()=>gV,string:()=>wP,symbol:()=>aV,transformer:()=>$V,tuple:()=>bV,undefined:()=>cV,union:()=>_V,unknown:()=>pV,util:()=>ze,void:()=>fV});var ze;(function(e){e.assertEqual=i=>{};function t(i){}e.assertIs=t;function r(i){throw new Error}e.assertNever=r,e.arrayToEnum=i=>{let s={};for(let o of i)s[o]=o;return s},e.getValidEnumValues=i=>{let s=e.objectKeys(i).filter(a=>typeof i[i[a]]!="number"),o={};for(let a of s)o[a]=i[a];return e.objectValues(o)},e.objectValues=i=>e.objectKeys(i).map(function(s){return i[s]}),e.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let s=[];for(let o in i)Object.prototype.hasOwnProperty.call(i,o)&&s.push(o);return s},e.find=(i,s)=>{for(let o of i)if(s(o))return o},e.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function n(i,s=" | "){return i.map(o=>typeof o=="string"?`'${o}'`:o).join(s)}e.joinValues=n,e.jsonStringifyReplacer=(i,s)=>typeof s=="bigint"?s.toString():s})(ze||(ze={}));var Ux;(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(Ux||(Ux={}));var X=ze.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),fi=e=>{switch(typeof e){case"undefined":return X.undefined;case"string":return X.string;case"number":return Number.isNaN(e)?X.nan:X.number;case"boolean":return X.boolean;case"function":return X.function;case"bigint":return X.bigint;case"symbol":return X.symbol;case"object":return Array.isArray(e)?X.array:e===null?X.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?X.promise:typeof Map<"u"&&e instanceof Map?X.map:typeof Set<"u"&&e instanceof Set?X.set:typeof Date<"u"&&e instanceof Date?X.date:X.object;default:return X.unknown}};var D=ze.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"]),$B=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),Nr=class e extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=t}format(t){let r=t||function(s){return s.message},n={_errors:[]},i=s=>{for(let o of s.issues)if(o.code==="invalid_union")o.unionErrors.map(i);else if(o.code==="invalid_return_type")i(o.returnTypeError);else if(o.code==="invalid_arguments")i(o.argumentsError);else if(o.path.length===0)n._errors.push(r(o));else{let a=n,c=0;for(;c<o.path.length;){let u=o.path[c];c===o.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(o))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return i(this),n}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,ze.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=r=>r.message){let r={},n=[];for(let i of this.issues)if(i.path.length>0){let s=i.path[0];r[s]=r[s]||[],r[s].push(t(i))}else n.push(t(i));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};Nr.create=e=>new Nr(e);var CB=(e,t)=>{let r;switch(e.code){case D.invalid_type:e.received===X.undefined?r="Required":r=`Expected ${e.expected}, received ${e.received}`;break;case D.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,ze.jsonStringifyReplacer)}`;break;case D.unrecognized_keys:r=`Unrecognized key(s) in object: ${ze.joinValues(e.keys,", ")}`;break;case D.invalid_union:r="Invalid input";break;case D.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${ze.joinValues(e.options)}`;break;case D.invalid_enum_value:r=`Invalid enum value. Expected ${ze.joinValues(e.options)}, received '${e.received}'`;break;case D.invalid_arguments:r="Invalid function arguments";break;case D.invalid_return_type:r="Invalid function return type";break;case D.invalid_date:r="Invalid date";break;case D.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:ze.assertNever(e.validation):e.validation!=="regex"?r=`Invalid ${e.validation}`:r="Invalid";break;case D.too_small:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:r="Invalid input";break;case D.too_big:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?r=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:r="Invalid input";break;case D.custom:r="Invalid input";break;case D.invalid_intersection_types:r="Intersection results could not be merged";break;case D.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case D.not_finite:r="Number must be finite";break;default:r=t.defaultError,ze.assertNever(e)}return{message:r}},es=CB;var fP=es;function PB(e){fP=e}function Nc(){return fP}var Ip=e=>{let{data:t,path:r,errorMaps:n,issueData:i}=e,s=[...r,...i.path||[]],o={...i,path:s};if(i.message!==void 0)return{...i,path:s,message:i.message};let a="",c=n.filter(u=>!!u).slice().reverse();for(let u of c)a=u(o,{data:t,defaultError:a}).message;return{...i,path:s,message:a}},NB=[];function H(e,t){let r=Nc(),n=Ip({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===es?void 0:es].filter(i=>!!i)});e.common.issues.push(n)}var Gt=class e{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,r){let n=[];for(let i of r){if(i.status==="aborted")return pe;i.status==="dirty"&&t.dirty(),n.push(i.value)}return{status:t.value,value:n}}static async mergeObjectAsync(t,r){let n=[];for(let i of r){let s=await i.key,o=await i.value;n.push({key:s,value:o})}return e.mergeObjectSync(t,n)}static mergeObjectSync(t,r){let n={};for(let i of r){let{key:s,value:o}=i;if(s.status==="aborted"||o.status==="aborted")return pe;s.status==="dirty"&&t.dirty(),o.status==="dirty"&&t.dirty(),s.value!=="__proto__"&&(typeof o.value<"u"||i.alwaysSet)&&(n[s.value]=o.value)}return{status:t.value,value:n}}},pe=Object.freeze({status:"aborted"}),ra=e=>({status:"dirty",value:e}),er=e=>({status:"valid",value:e}),lh=e=>e.status==="aborted",ph=e=>e.status==="dirty",Js=e=>e.status==="valid",Rc=e=>typeof Promise<"u"&&e instanceof Promise;var ne;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(ne||(ne={}));var mn=class{constructor(t,r,n,i){this._cachedPath=[],this.parent=t,this.data=r,this._path=n,this._key=i}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}},mP=(e,t)=>{if(Js(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new Nr(e.common.issues);return this._error=r,this._error}}};function xe(e){if(!e)return{};let{errorMap:t,invalid_type_error:r,required_error:n,description:i}=e;if(t&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:(o,a)=>{let{message:c}=e;return o.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:o.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:i}}var Se=class{get description(){return this._def.description}_getType(t){return fi(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:fi(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new Gt,ctx:{common:t.parent.common,data:t.data,parsedType:fi(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let r=this._parse(t);if(Rc(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(t){let r=this._parse(t);return Promise.resolve(r)}parse(t,r){let n=this.safeParse(t,r);if(n.success)return n.data;throw n.error}safeParse(t,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:fi(t)},i=this._parseSync({data:t,path:n.path,parent:n});return mP(n,i)}"~validate"(t){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:fi(t)};if(!this["~standard"].async)try{let n=this._parseSync({data:t,path:[],parent:r});return Js(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:r}).then(n=>Js(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(t,r){let n=await this.safeParseAsync(t,r);if(n.success)return n.data;throw n.error}async safeParseAsync(t,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:fi(t)},i=this._parse({data:t,path:n.path,parent:n}),s=await(Rc(i)?i:Promise.resolve(i));return mP(n,s)}refine(t,r){let n=i=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(i):r;return this._refinement((i,s)=>{let o=t(i),a=()=>s.addIssue({code:D.custom,...n(i)});return typeof Promise<"u"&&o instanceof Promise?o.then(c=>c?!0:(a(),!1)):o?!0:(a(),!1)})}refinement(t,r){return this._refinement((n,i)=>t(n)?!0:(i.addIssue(typeof r=="function"?r(n,i):r),!1))}_refinement(t){return new hn({schema:this,typeName:T.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,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:r=>this["~validate"](r)}}optional(){return fn.create(this,this._def)}nullable(){return hi.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ns.create(this)}promise(){return Qs.create(this,this._def)}or(t){return ua.create([this,t],this._def)}and(t){return la.create(this,t,this._def)}transform(t){return new hn({...xe(this._def),schema:this,typeName:T.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let r=typeof t=="function"?t:()=>t;return new ha({...xe(this._def),innerType:this,defaultValue:r,typeName:T.ZodDefault})}brand(){return new Sp({typeName:T.ZodBranded,type:this,...xe(this._def)})}catch(t){let r=typeof t=="function"?t:()=>t;return new ga({...xe(this._def),innerType:this,catchValue:r,typeName:T.ZodCatch})}describe(t){let r=this.constructor;return new r({...this._def,description:t})}pipe(t){return Ep.create(this,t)}readonly(){return _a.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},RB=/^c[^\s-]{8,}$/i,MB=/^[0-9a-z]+$/,jB=/^[0-9A-HJKMNP-TV-Z]{26}$/i,DB=/^[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,zB=/^[a-z0-9_-]{21}$/i,LB=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,UB=/^[-+]?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)?)??$/,FB=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,BB="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Fx,VB=/^(?:(?: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])$/,ZB=/^(?:(?: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])$/,GB=/^(([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]))$/,KB=/^(([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])$/,qB=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,HB=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,gP="((\\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])))",WB=new RegExp(`^${gP}$`);function _P(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);let r=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${r}`}function JB(e){return new RegExp(`^${_P(e)}$`)}function yP(e){let t=`${gP}T${_P(e)}`,r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function XB(e,t){return!!((t==="v4"||!t)&&VB.test(e)||(t==="v6"||!t)&&GB.test(e))}function YB(e,t){if(!LB.test(e))return!1;try{let[r]=e.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),i=JSON.parse(atob(n));return!(typeof i!="object"||i===null||"typ"in i&&i?.typ!=="JWT"||!i.alg||t&&i.alg!==t)}catch{return!1}}function QB(e,t){return!!((t==="v4"||!t)&&ZB.test(e)||(t==="v6"||!t)&&KB.test(e))}var Xs=class e extends Se{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==X.string){let s=this._getOrReturnCtx(t);return H(s,{code:D.invalid_type,expected:X.string,received:s.parsedType}),pe}let n=new Gt,i;for(let s of this._def.checks)if(s.kind==="min")t.data.length<s.value&&(i=this._getOrReturnCtx(t,i),H(i,{code:D.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")t.data.length>s.value&&(i=this._getOrReturnCtx(t,i),H(i,{code:D.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){let o=t.data.length>s.value,a=t.data.length<s.value;(o||a)&&(i=this._getOrReturnCtx(t,i),o?H(i,{code:D.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&H(i,{code:D.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")FB.test(t.data)||(i=this._getOrReturnCtx(t,i),H(i,{validation:"email",code:D.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")Fx||(Fx=new RegExp(BB,"u")),Fx.test(t.data)||(i=this._getOrReturnCtx(t,i),H(i,{validation:"emoji",code:D.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")DB.test(t.data)||(i=this._getOrReturnCtx(t,i),H(i,{validation:"uuid",code:D.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")zB.test(t.data)||(i=this._getOrReturnCtx(t,i),H(i,{validation:"nanoid",code:D.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")RB.test(t.data)||(i=this._getOrReturnCtx(t,i),H(i,{validation:"cuid",code:D.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")MB.test(t.data)||(i=this._getOrReturnCtx(t,i),H(i,{validation:"cuid2",code:D.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")jB.test(t.data)||(i=this._getOrReturnCtx(t,i),H(i,{validation:"ulid",code:D.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(t.data)}catch{i=this._getOrReturnCtx(t,i),H(i,{validation:"url",code:D.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(t.data)||(i=this._getOrReturnCtx(t,i),H(i,{validation:"regex",code:D.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?t.data=t.data.trim():s.kind==="includes"?t.data.includes(s.value,s.position)||(i=this._getOrReturnCtx(t,i),H(i,{code:D.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.dirty()):s.kind==="toLowerCase"?t.data=t.data.toLowerCase():s.kind==="toUpperCase"?t.data=t.data.toUpperCase():s.kind==="startsWith"?t.data.startsWith(s.value)||(i=this._getOrReturnCtx(t,i),H(i,{code:D.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?t.data.endsWith(s.value)||(i=this._getOrReturnCtx(t,i),H(i,{code:D.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?yP(s).test(t.data)||(i=this._getOrReturnCtx(t,i),H(i,{code:D.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?WB.test(t.data)||(i=this._getOrReturnCtx(t,i),H(i,{code:D.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?JB(s).test(t.data)||(i=this._getOrReturnCtx(t,i),H(i,{code:D.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?UB.test(t.data)||(i=this._getOrReturnCtx(t,i),H(i,{validation:"duration",code:D.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?XB(t.data,s.version)||(i=this._getOrReturnCtx(t,i),H(i,{validation:"ip",code:D.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?YB(t.data,s.alg)||(i=this._getOrReturnCtx(t,i),H(i,{validation:"jwt",code:D.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?QB(t.data,s.version)||(i=this._getOrReturnCtx(t,i),H(i,{validation:"cidr",code:D.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?qB.test(t.data)||(i=this._getOrReturnCtx(t,i),H(i,{validation:"base64",code:D.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?HB.test(t.data)||(i=this._getOrReturnCtx(t,i),H(i,{validation:"base64url",code:D.invalid_string,message:s.message}),n.dirty()):ze.assertNever(s);return{status:n.value,value:t.data}}_regex(t,r,n){return this.refinement(i=>t.test(i),{validation:r,code:D.invalid_string,...ne.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...ne.errToObj(t)})}url(t){return this._addCheck({kind:"url",...ne.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...ne.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...ne.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...ne.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...ne.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...ne.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...ne.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...ne.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...ne.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...ne.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...ne.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...ne.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...ne.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...ne.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...ne.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...ne.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,...ne.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...ne.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...ne.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...ne.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...ne.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...ne.errToObj(r)})}nonempty(t){return this.min(1,ne.errToObj(t))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxLength(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}};Xs.create=e=>new Xs({checks:[],typeName:T.ZodString,coerce:e?.coerce??!1,...xe(e)});function eV(e,t){let r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,i=r>n?r:n,s=Number.parseInt(e.toFixed(i).replace(".","")),o=Number.parseInt(t.toFixed(i).replace(".",""));return s%o/10**i}var na=class e extends Se{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==X.number){let s=this._getOrReturnCtx(t);return H(s,{code:D.invalid_type,expected:X.number,received:s.parsedType}),pe}let n,i=new Gt;for(let s of this._def.checks)s.kind==="int"?ze.isInteger(t.data)||(n=this._getOrReturnCtx(t,n),H(n,{code:D.invalid_type,expected:"integer",received:"float",message:s.message}),i.dirty()):s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(n=this._getOrReturnCtx(t,n),H(n,{code:D.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(n=this._getOrReturnCtx(t,n),H(n,{code:D.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):s.kind==="multipleOf"?eV(t.data,s.value)!==0&&(n=this._getOrReturnCtx(t,n),H(n,{code:D.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):s.kind==="finite"?Number.isFinite(t.data)||(n=this._getOrReturnCtx(t,n),H(n,{code:D.not_finite,message:s.message}),i.dirty()):ze.assertNever(s);return{status:i.value,value:t.data}}gte(t,r){return this.setLimit("min",t,!0,ne.toString(r))}gt(t,r){return this.setLimit("min",t,!1,ne.toString(r))}lte(t,r){return this.setLimit("max",t,!0,ne.toString(r))}lt(t,r){return this.setLimit("max",t,!1,ne.toString(r))}setLimit(t,r,n,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:ne.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:ne.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:ne.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:ne.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:ne.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:ne.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:ne.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:ne.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:ne.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:ne.toString(t)})}get minValue(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&ze.isInteger(t.value))}get isFinite(){let t=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(t===null||n.value<t)&&(t=n.value)}return Number.isFinite(r)&&Number.isFinite(t)}};na.create=e=>new na({checks:[],typeName:T.ZodNumber,coerce:e?.coerce||!1,...xe(e)});var ia=class e extends Se{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==X.bigint)return this._getInvalidInput(t);let n,i=new Gt;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(n=this._getOrReturnCtx(t,n),H(n,{code:D.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(n=this._getOrReturnCtx(t,n),H(n,{code:D.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):s.kind==="multipleOf"?t.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(t,n),H(n,{code:D.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):ze.assertNever(s);return{status:i.value,value:t.data}}_getInvalidInput(t){let r=this._getOrReturnCtx(t);return H(r,{code:D.invalid_type,expected:X.bigint,received:r.parsedType}),pe}gte(t,r){return this.setLimit("min",t,!0,ne.toString(r))}gt(t,r){return this.setLimit("min",t,!1,ne.toString(r))}lte(t,r){return this.setLimit("max",t,!0,ne.toString(r))}lt(t,r){return this.setLimit("max",t,!1,ne.toString(r))}setLimit(t,r,n,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:ne.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:ne.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:ne.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:ne.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:ne.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:ne.toString(r)})}get minValue(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}};ia.create=e=>new ia({checks:[],typeName:T.ZodBigInt,coerce:e?.coerce??!1,...xe(e)});var sa=class extends Se{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==X.boolean){let n=this._getOrReturnCtx(t);return H(n,{code:D.invalid_type,expected:X.boolean,received:n.parsedType}),pe}return er(t.data)}};sa.create=e=>new sa({typeName:T.ZodBoolean,coerce:e?.coerce||!1,...xe(e)});var oa=class e extends Se{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==X.date){let s=this._getOrReturnCtx(t);return H(s,{code:D.invalid_type,expected:X.date,received:s.parsedType}),pe}if(Number.isNaN(t.data.getTime())){let s=this._getOrReturnCtx(t);return H(s,{code:D.invalid_date}),pe}let n=new Gt,i;for(let s of this._def.checks)s.kind==="min"?t.data.getTime()<s.value&&(i=this._getOrReturnCtx(t,i),H(i,{code:D.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?t.data.getTime()>s.value&&(i=this._getOrReturnCtx(t,i),H(i,{code:D.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):ze.assertNever(s);return{status:n.value,value:new Date(t.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(t,r){return this._addCheck({kind:"min",value:t.getTime(),message:ne.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:ne.toString(r)})}get minDate(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t!=null?new Date(t):null}};oa.create=e=>new oa({checks:[],coerce:e?.coerce||!1,typeName:T.ZodDate,...xe(e)});var jc=class extends Se{_parse(t){if(this._getType(t)!==X.symbol){let n=this._getOrReturnCtx(t);return H(n,{code:D.invalid_type,expected:X.symbol,received:n.parsedType}),pe}return er(t.data)}};jc.create=e=>new jc({typeName:T.ZodSymbol,...xe(e)});var aa=class extends Se{_parse(t){if(this._getType(t)!==X.undefined){let n=this._getOrReturnCtx(t);return H(n,{code:D.invalid_type,expected:X.undefined,received:n.parsedType}),pe}return er(t.data)}};aa.create=e=>new aa({typeName:T.ZodUndefined,...xe(e)});var ca=class extends Se{_parse(t){if(this._getType(t)!==X.null){let n=this._getOrReturnCtx(t);return H(n,{code:D.invalid_type,expected:X.null,received:n.parsedType}),pe}return er(t.data)}};ca.create=e=>new ca({typeName:T.ZodNull,...xe(e)});var Ys=class extends Se{constructor(){super(...arguments),this._any=!0}_parse(t){return er(t.data)}};Ys.create=e=>new Ys({typeName:T.ZodAny,...xe(e)});var rs=class extends Se{constructor(){super(...arguments),this._unknown=!0}_parse(t){return er(t.data)}};rs.create=e=>new rs({typeName:T.ZodUnknown,...xe(e)});var Cn=class extends Se{_parse(t){let r=this._getOrReturnCtx(t);return H(r,{code:D.invalid_type,expected:X.never,received:r.parsedType}),pe}};Cn.create=e=>new Cn({typeName:T.ZodNever,...xe(e)});var Dc=class extends Se{_parse(t){if(this._getType(t)!==X.undefined){let n=this._getOrReturnCtx(t);return H(n,{code:D.invalid_type,expected:X.void,received:n.parsedType}),pe}return er(t.data)}};Dc.create=e=>new Dc({typeName:T.ZodVoid,...xe(e)});var ns=class e extends Se{_parse(t){let{ctx:r,status:n}=this._processInputParams(t),i=this._def;if(r.parsedType!==X.array)return H(r,{code:D.invalid_type,expected:X.array,received:r.parsedType}),pe;if(i.exactLength!==null){let o=r.data.length>i.exactLength.value,a=r.data.length<i.exactLength.value;(o||a)&&(H(r,{code:o?D.too_big:D.too_small,minimum:a?i.exactLength.value:void 0,maximum:o?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),n.dirty())}if(i.minLength!==null&&r.data.length<i.minLength.value&&(H(r,{code:D.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),n.dirty()),i.maxLength!==null&&r.data.length>i.maxLength.value&&(H(r,{code:D.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((o,a)=>i.type._parseAsync(new mn(r,o,r.path,a)))).then(o=>Gt.mergeArray(n,o));let s=[...r.data].map((o,a)=>i.type._parseSync(new mn(r,o,r.path,a)));return Gt.mergeArray(n,s)}get element(){return this._def.type}min(t,r){return new e({...this._def,minLength:{value:t,message:ne.toString(r)}})}max(t,r){return new e({...this._def,maxLength:{value:t,message:ne.toString(r)}})}length(t,r){return new e({...this._def,exactLength:{value:t,message:ne.toString(r)}})}nonempty(t){return this.min(1,t)}};ns.create=(e,t)=>new ns({type:e,minLength:null,maxLength:null,exactLength:null,typeName:T.ZodArray,...xe(t)});function Mc(e){if(e instanceof Rr){let t={};for(let r in e.shape){let n=e.shape[r];t[r]=fn.create(Mc(n))}return new Rr({...e._def,shape:()=>t})}else return e instanceof ns?new ns({...e._def,type:Mc(e.element)}):e instanceof fn?fn.create(Mc(e.unwrap())):e instanceof hi?hi.create(Mc(e.unwrap())):e instanceof mi?mi.create(e.items.map(t=>Mc(t))):e}var Rr=class e extends Se{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),r=ze.objectKeys(t);return this._cached={shape:t,keys:r},this._cached}_parse(t){if(this._getType(t)!==X.object){let u=this._getOrReturnCtx(t);return H(u,{code:D.invalid_type,expected:X.object,received:u.parsedType}),pe}let{status:n,ctx:i}=this._processInputParams(t),{shape:s,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof Cn&&this._def.unknownKeys==="strip"))for(let u in i.data)o.includes(u)||a.push(u);let c=[];for(let u of o){let l=s[u],p=i.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new mn(i,p,i.path,u)),alwaysSet:u in i.data})}if(this._def.catchall instanceof Cn){let u=this._def.unknownKeys;if(u==="passthrough")for(let l of a)c.push({key:{status:"valid",value:l},value:{status:"valid",value:i.data[l]}});else if(u==="strict")a.length>0&&(H(i,{code:D.unrecognized_keys,keys:a}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let l of a){let p=i.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new mn(i,p,i.path,l)),alwaysSet:l in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let u=[];for(let l of c){let p=await l.key,f=await l.value;u.push({key:p,value:f,alwaysSet:l.alwaysSet})}return u}).then(u=>Gt.mergeObjectSync(n,u)):Gt.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(t){return ne.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(r,n)=>{let i=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:ne.errToObj(t).message??i}:{message:i}}}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:T.ZodObject})}setKey(t,r){return this.augment({[t]:r})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let r={};for(let n of ze.objectKeys(t))t[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new e({...this._def,shape:()=>r})}omit(t){let r={};for(let n of ze.objectKeys(this.shape))t[n]||(r[n]=this.shape[n]);return new e({...this._def,shape:()=>r})}deepPartial(){return Mc(this)}partial(t){let r={};for(let n of ze.objectKeys(this.shape)){let i=this.shape[n];t&&!t[n]?r[n]=i:r[n]=i.optional()}return new e({...this._def,shape:()=>r})}required(t){let r={};for(let n of ze.objectKeys(this.shape))if(t&&!t[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof fn;)s=s._def.innerType;r[n]=s}return new e({...this._def,shape:()=>r})}keyof(){return vP(ze.objectKeys(this.shape))}};Rr.create=(e,t)=>new Rr({shape:()=>e,unknownKeys:"strip",catchall:Cn.create(),typeName:T.ZodObject,...xe(t)});Rr.strictCreate=(e,t)=>new Rr({shape:()=>e,unknownKeys:"strict",catchall:Cn.create(),typeName:T.ZodObject,...xe(t)});Rr.lazycreate=(e,t)=>new Rr({shape:e,unknownKeys:"strip",catchall:Cn.create(),typeName:T.ZodObject,...xe(t)});var ua=class extends Se{_parse(t){let{ctx:r}=this._processInputParams(t),n=this._def.options;function i(s){for(let a of s)if(a.result.status==="valid")return a.result;for(let a of s)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let o=s.map(a=>new Nr(a.ctx.common.issues));return H(r,{code:D.invalid_union,unionErrors:o}),pe}if(r.common.async)return Promise.all(n.map(async s=>{let o={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:o}),ctx:o}})).then(i);{let s,o=[];for(let c of n){let u={...r,common:{...r.common,issues:[]},parent:null},l=c._parseSync({data:r.data,path:r.path,parent:u});if(l.status==="valid")return l;l.status==="dirty"&&!s&&(s={result:l,ctx:u}),u.common.issues.length&&o.push(u.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;let a=o.map(c=>new Nr(c));return H(r,{code:D.invalid_union,unionErrors:a}),pe}}get options(){return this._def.options}};ua.create=(e,t)=>new ua({options:e,typeName:T.ZodUnion,...xe(t)});var ts=e=>e instanceof pa?ts(e.schema):e instanceof hn?ts(e.innerType()):e instanceof da?[e.value]:e instanceof fa?e.options:e instanceof ma?ze.objectValues(e.enum):e instanceof ha?ts(e._def.innerType):e instanceof aa?[void 0]:e instanceof ca?[null]:e instanceof fn?[void 0,...ts(e.unwrap())]:e instanceof hi?[null,...ts(e.unwrap())]:e instanceof Sp||e instanceof _a?ts(e.unwrap()):e instanceof ga?ts(e._def.innerType):[],dh=class e extends Se{_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==X.object)return H(r,{code:D.invalid_type,expected:X.object,received:r.parsedType}),pe;let n=this.discriminator,i=r.data[n],s=this.optionsMap.get(i);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(H(r,{code:D.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),pe)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,r,n){let i=new Map;for(let s of r){let o=ts(s.shape[t]);if(!o.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let a of o){if(i.has(a))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(a)}`);i.set(a,s)}}return new e({typeName:T.ZodDiscriminatedUnion,discriminator:t,options:r,optionsMap:i,...xe(n)})}};function Bx(e,t){let r=fi(e),n=fi(t);if(e===t)return{valid:!0,data:e};if(r===X.object&&n===X.object){let i=ze.objectKeys(t),s=ze.objectKeys(e).filter(a=>i.indexOf(a)!==-1),o={...e,...t};for(let a of s){let c=Bx(e[a],t[a]);if(!c.valid)return{valid:!1};o[a]=c.data}return{valid:!0,data:o}}else if(r===X.array&&n===X.array){if(e.length!==t.length)return{valid:!1};let i=[];for(let s=0;s<e.length;s++){let o=e[s],a=t[s],c=Bx(o,a);if(!c.valid)return{valid:!1};i.push(c.data)}return{valid:!0,data:i}}else return r===X.date&&n===X.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var la=class extends Se{_parse(t){let{status:r,ctx:n}=this._processInputParams(t),i=(s,o)=>{if(lh(s)||lh(o))return pe;let a=Bx(s.value,o.value);return a.valid?((ph(s)||ph(o))&&r.dirty(),{status:r.value,value:a.data}):(H(n,{code:D.invalid_intersection_types}),pe)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,o])=>i(s,o)):i(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};la.create=(e,t,r)=>new la({left:e,right:t,typeName:T.ZodIntersection,...xe(r)});var mi=class e extends Se{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==X.array)return H(n,{code:D.invalid_type,expected:X.array,received:n.parsedType}),pe;if(n.data.length<this._def.items.length)return H(n,{code:D.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),pe;!this._def.rest&&n.data.length>this._def.items.length&&(H(n,{code:D.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let s=[...n.data].map((o,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new mn(n,o,n.path,a)):null}).filter(o=>!!o);return n.common.async?Promise.all(s).then(o=>Gt.mergeArray(r,o)):Gt.mergeArray(r,s)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};mi.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new mi({items:e,typeName:T.ZodTuple,rest:null,...xe(t)})};var fh=class e extends Se{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==X.object)return H(n,{code:D.invalid_type,expected:X.object,received:n.parsedType}),pe;let i=[],s=this._def.keyType,o=this._def.valueType;for(let a in n.data)i.push({key:s._parse(new mn(n,a,n.path,a)),value:o._parse(new mn(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?Gt.mergeObjectAsync(r,i):Gt.mergeObjectSync(r,i)}get element(){return this._def.valueType}static create(t,r,n){return r instanceof Se?new e({keyType:t,valueType:r,typeName:T.ZodRecord,...xe(n)}):new e({keyType:Xs.create(),valueType:t,typeName:T.ZodRecord,...xe(r)})}},zc=class extends Se{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==X.map)return H(n,{code:D.invalid_type,expected:X.map,received:n.parsedType}),pe;let i=this._def.keyType,s=this._def.valueType,o=[...n.data.entries()].map(([a,c],u)=>({key:i._parse(new mn(n,a,n.path,[u,"key"])),value:s._parse(new mn(n,c,n.path,[u,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of o){let u=await c.key,l=await c.value;if(u.status==="aborted"||l.status==="aborted")return pe;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of o){let u=c.key,l=c.value;if(u.status==="aborted"||l.status==="aborted")return pe;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}}}};zc.create=(e,t,r)=>new zc({valueType:t,keyType:e,typeName:T.ZodMap,...xe(r)});var Lc=class e extends Se{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==X.set)return H(n,{code:D.invalid_type,expected:X.set,received:n.parsedType}),pe;let i=this._def;i.minSize!==null&&n.data.size<i.minSize.value&&(H(n,{code:D.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),r.dirty()),i.maxSize!==null&&n.data.size>i.maxSize.value&&(H(n,{code:D.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),r.dirty());let s=this._def.valueType;function o(c){let u=new Set;for(let l of c){if(l.status==="aborted")return pe;l.status==="dirty"&&r.dirty(),u.add(l.value)}return{status:r.value,value:u}}let a=[...n.data.values()].map((c,u)=>s._parse(new mn(n,c,n.path,u)));return n.common.async?Promise.all(a).then(c=>o(c)):o(a)}min(t,r){return new e({...this._def,minSize:{value:t,message:ne.toString(r)}})}max(t,r){return new e({...this._def,maxSize:{value:t,message:ne.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}};Lc.create=(e,t)=>new Lc({valueType:e,minSize:null,maxSize:null,typeName:T.ZodSet,...xe(t)});var mh=class e extends Se{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==X.function)return H(r,{code:D.invalid_type,expected:X.function,received:r.parsedType}),pe;function n(a,c){return Ip({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Nc(),es].filter(u=>!!u),issueData:{code:D.invalid_arguments,argumentsError:c}})}function i(a,c){return Ip({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Nc(),es].filter(u=>!!u),issueData:{code:D.invalid_return_type,returnTypeError:c}})}let s={errorMap:r.common.contextualErrorMap},o=r.data;if(this._def.returns instanceof Qs){let a=this;return er(async function(...c){let u=new Nr([]),l=await a._def.args.parseAsync(c,s).catch(d=>{throw u.addIssue(n(c,d)),u}),p=await Reflect.apply(o,this,l);return await a._def.returns._def.type.parseAsync(p,s).catch(d=>{throw u.addIssue(i(p,d)),u})})}else{let a=this;return er(function(...c){let u=a._def.args.safeParse(c,s);if(!u.success)throw new Nr([n(c,u.error)]);let l=Reflect.apply(o,this,u.data),p=a._def.returns.safeParse(l,s);if(!p.success)throw new Nr([i(l,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:mi.create(t).rest(rs.create())})}returns(t){return new e({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,r,n){return new e({args:t||mi.create([]).rest(rs.create()),returns:r||rs.create(),typeName:T.ZodFunction,...xe(n)})}},pa=class extends Se{get schema(){return this._def.getter()}_parse(t){let{ctx:r}=this._processInputParams(t);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};pa.create=(e,t)=>new pa({getter:e,typeName:T.ZodLazy,...xe(t)});var da=class extends Se{_parse(t){if(t.data!==this._def.value){let r=this._getOrReturnCtx(t);return H(r,{received:r.data,code:D.invalid_literal,expected:this._def.value}),pe}return{status:"valid",value:t.data}}get value(){return this._def.value}};da.create=(e,t)=>new da({value:e,typeName:T.ZodLiteral,...xe(t)});function vP(e,t){return new fa({values:e,typeName:T.ZodEnum,...xe(t)})}var fa=class e extends Se{_parse(t){if(typeof t.data!="string"){let r=this._getOrReturnCtx(t),n=this._def.values;return H(r,{expected:ze.joinValues(n),received:r.parsedType,code:D.invalid_type}),pe}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){let r=this._getOrReturnCtx(t),n=this._def.values;return H(r,{received:r.data,code:D.invalid_enum_value,options:n}),pe}return er(t.data)}get options(){return this._def.values}get enum(){let t={};for(let r of this._def.values)t[r]=r;return t}get Values(){let t={};for(let r of this._def.values)t[r]=r;return t}get Enum(){let t={};for(let r of this._def.values)t[r]=r;return t}extract(t,r=this._def){return e.create(t,{...this._def,...r})}exclude(t,r=this._def){return e.create(this.options.filter(n=>!t.includes(n)),{...this._def,...r})}};fa.create=vP;var ma=class extends Se{_parse(t){let r=ze.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(t);if(n.parsedType!==X.string&&n.parsedType!==X.number){let i=ze.objectValues(r);return H(n,{expected:ze.joinValues(i),received:n.parsedType,code:D.invalid_type}),pe}if(this._cache||(this._cache=new Set(ze.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let i=ze.objectValues(r);return H(n,{received:n.data,code:D.invalid_enum_value,options:i}),pe}return er(t.data)}get enum(){return this._def.values}};ma.create=(e,t)=>new ma({values:e,typeName:T.ZodNativeEnum,...xe(t)});var Qs=class extends Se{unwrap(){return this._def.type}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==X.promise&&r.common.async===!1)return H(r,{code:D.invalid_type,expected:X.promise,received:r.parsedType}),pe;let n=r.parsedType===X.promise?r.data:Promise.resolve(r.data);return er(n.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Qs.create=(e,t)=>new Qs({type:e,typeName:T.ZodPromise,...xe(t)});var hn=class extends Se{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===T.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:r,ctx:n}=this._processInputParams(t),i=this._def.effect||null,s={addIssue:o=>{H(n,o),o.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),i.type==="preprocess"){let o=i.transform(n.data,s);if(n.common.async)return Promise.resolve(o).then(async a=>{if(r.value==="aborted")return pe;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?pe:c.status==="dirty"?ra(c.value):r.value==="dirty"?ra(c.value):c});{if(r.value==="aborted")return pe;let a=this._def.schema._parseSync({data:o,path:n.path,parent:n});return a.status==="aborted"?pe:a.status==="dirty"?ra(a.value):r.value==="dirty"?ra(a.value):a}}if(i.type==="refinement"){let o=a=>{let c=i.refinement(a,s);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?pe:(a.status==="dirty"&&r.dirty(),o(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?pe:(a.status==="dirty"&&r.dirty(),o(a.value).then(()=>({status:r.value,value:a.value}))))}if(i.type==="transform")if(n.common.async===!1){let o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Js(o))return pe;let a=i.transform(o.value,s);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>Js(o)?Promise.resolve(i.transform(o.value,s)).then(a=>({status:r.value,value:a})):pe);ze.assertNever(i)}};hn.create=(e,t,r)=>new hn({schema:e,typeName:T.ZodEffects,effect:t,...xe(r)});hn.createWithPreprocess=(e,t,r)=>new hn({schema:t,effect:{type:"preprocess",transform:e},typeName:T.ZodEffects,...xe(r)});var fn=class extends Se{_parse(t){return this._getType(t)===X.undefined?er(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};fn.create=(e,t)=>new fn({innerType:e,typeName:T.ZodOptional,...xe(t)});var hi=class extends Se{_parse(t){return this._getType(t)===X.null?er(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};hi.create=(e,t)=>new hi({innerType:e,typeName:T.ZodNullable,...xe(t)});var ha=class extends Se{_parse(t){let{ctx:r}=this._processInputParams(t),n=r.data;return r.parsedType===X.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};ha.create=(e,t)=>new ha({innerType:e,typeName:T.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...xe(t)});var ga=class extends Se{_parse(t){let{ctx:r}=this._processInputParams(t),n={...r,common:{...r.common,issues:[]}},i=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Rc(i)?i.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Nr(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Nr(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};ga.create=(e,t)=>new ga({innerType:e,typeName:T.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...xe(t)});var Uc=class extends Se{_parse(t){if(this._getType(t)!==X.nan){let n=this._getOrReturnCtx(t);return H(n,{code:D.invalid_type,expected:X.nan,received:n.parsedType}),pe}return{status:"valid",value:t.data}}};Uc.create=e=>new Uc({typeName:T.ZodNaN,...xe(e)});var tV=Symbol("zod_brand"),Sp=class extends Se{_parse(t){let{ctx:r}=this._processInputParams(t),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},Ep=class e extends Se{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?pe:s.status==="dirty"?(r.dirty(),ra(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{let i=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?pe:i.status==="dirty"?(r.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:n.path,parent:n})}}static create(t,r){return new e({in:t,out:r,typeName:T.ZodPipeline})}},_a=class extends Se{_parse(t){let r=this._def.innerType._parse(t),n=i=>(Js(i)&&(i.value=Object.freeze(i.value)),i);return Rc(r)?r.then(i=>n(i)):n(r)}unwrap(){return this._def.innerType}};_a.create=(e,t)=>new _a({innerType:e,typeName:T.ZodReadonly,...xe(t)});function hP(e,t){let r=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof r=="string"?{message:r}:r}function bP(e,t={},r){return e?Ys.create().superRefine((n,i)=>{let s=e(n);if(s instanceof Promise)return s.then(o=>{if(!o){let a=hP(t,n),c=a.fatal??r??!0;i.addIssue({code:"custom",...a,fatal:c})}});if(!s){let o=hP(t,n),a=o.fatal??r??!0;i.addIssue({code:"custom",...o,fatal:a})}}):Ys.create()}var rV={object:Rr.lazycreate},T;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(T||(T={}));var nV=(e,t={message:`Input not instance of ${e.name}`})=>bP(r=>r instanceof e,t),wP=Xs.create,xP=na.create,iV=Uc.create,sV=ia.create,IP=sa.create,oV=oa.create,aV=jc.create,cV=aa.create,uV=ca.create,lV=Ys.create,pV=rs.create,dV=Cn.create,fV=Dc.create,mV=ns.create,hV=Rr.create,gV=Rr.strictCreate,_V=ua.create,yV=dh.create,vV=la.create,bV=mi.create,wV=fh.create,xV=zc.create,IV=Lc.create,SV=mh.create,EV=pa.create,kV=da.create,AV=fa.create,TV=ma.create,OV=Qs.create,$V=hn.create,CV=fn.create,PV=hi.create,NV=hn.createWithPreprocess,RV=Ep.create,MV=()=>wP().optional(),jV=()=>xP().optional(),DV=()=>IP().optional(),zV={string:(e=>Xs.create({...e,coerce:!0})),number:(e=>na.create({...e,coerce:!0})),boolean:(e=>sa.create({...e,coerce:!0})),bigint:(e=>ia.create({...e,coerce:!0})),date:(e=>oa.create({...e,coerce:!0}))};var LV=pe;function SP(e,t){let r={type:"array"};return e.type?._def&&e.type?._def?.typeName!==T.ZodAny&&(r.items=fe(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&Le(r,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&Le(r,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(Le(r,"minItems",e.exactLength.value,e.exactLength.message,t),Le(r,"maxItems",e.exactLength.value,e.exactLength.message,t)),r}function EP(e,t){let r={type:"integer",format:"int64"};if(!e.checks)return r;for(let n of e.checks)switch(n.kind){case"min":t.target==="jsonSchema7"?n.inclusive?Le(r,"minimum",n.value,n.message,t):Le(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),Le(r,"minimum",n.value,n.message,t));break;case"max":t.target==="jsonSchema7"?n.inclusive?Le(r,"maximum",n.value,n.message,t):Le(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),Le(r,"maximum",n.value,n.message,t));break;case"multipleOf":Le(r,"multipleOf",n.value,n.message,t);break}return r}function kP(){return{type:"boolean"}}function hh(e,t){return fe(e.type._def,t)}var AP=(e,t)=>fe(e.innerType._def,t);function Vx(e,t,r){let n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map(i=>Vx(e,t,i))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return UV(e,t)}}var UV=(e,t)=>{let r={type:"integer",format:"unix-time"};if(t.target==="openApi3")return r;for(let n of e.checks)switch(n.kind){case"min":Le(r,"minimum",n.value,n.message,t);break;case"max":Le(r,"maximum",n.value,n.message,t);break}return r};function TP(e,t){return{...fe(e.innerType._def,t),default:e.defaultValue()}}function OP(e,t){return t.effectStrategy==="input"?fe(e.schema._def,t):ut(t)}function $P(e){return{type:"string",enum:Array.from(e.values)}}var FV=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function CP(e,t){let r=[fe(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),fe(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(s=>!!s),n=t.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,i=[];return r.forEach(s=>{if(FV(s))i.push(...s.allOf),s.unevaluatedProperties===void 0&&(n=void 0);else{let o=s;if("additionalProperties"in s&&s.additionalProperties===!1){let{additionalProperties:a,...c}=s;o=c}else n=void 0;i.push(o)}}),i.length?{allOf:i,...n}:void 0}function PP(e,t){let r=typeof e.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(e.value)?"array":"object"}:t.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[e.value]}:{type:r==="bigint"?"integer":r,const:e.value}}var Zx,Pn={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(Zx===void 0&&(Zx=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Zx),uuid:/^[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}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?: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])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([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])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function gh(e,t){let r={type:"string"};if(e.checks)for(let n of e.checks)switch(n.kind){case"min":Le(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,t);break;case"max":Le(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"email":switch(t.emailStrategy){case"format:email":Nn(r,"email",n.message,t);break;case"format:idn-email":Nn(r,"idn-email",n.message,t);break;case"pattern:zod":vr(r,Pn.email,n.message,t);break}break;case"url":Nn(r,"uri",n.message,t);break;case"uuid":Nn(r,"uuid",n.message,t);break;case"regex":vr(r,n.regex,n.message,t);break;case"cuid":vr(r,Pn.cuid,n.message,t);break;case"cuid2":vr(r,Pn.cuid2,n.message,t);break;case"startsWith":vr(r,RegExp(`^${Gx(n.value,t)}`),n.message,t);break;case"endsWith":vr(r,RegExp(`${Gx(n.value,t)}$`),n.message,t);break;case"datetime":Nn(r,"date-time",n.message,t);break;case"date":Nn(r,"date",n.message,t);break;case"time":Nn(r,"time",n.message,t);break;case"duration":Nn(r,"duration",n.message,t);break;case"length":Le(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,t),Le(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"includes":vr(r,RegExp(Gx(n.value,t)),n.message,t);break;case"ip":n.version!=="v6"&&Nn(r,"ipv4",n.message,t),n.version!=="v4"&&Nn(r,"ipv6",n.message,t);break;case"base64url":vr(r,Pn.base64url,n.message,t);break;case"jwt":vr(r,Pn.jwt,n.message,t);break;case"cidr":n.version!=="v6"&&vr(r,Pn.ipv4Cidr,n.message,t),n.version!=="v4"&&vr(r,Pn.ipv6Cidr,n.message,t);break;case"emoji":vr(r,Pn.emoji(),n.message,t);break;case"ulid":vr(r,Pn.ulid,n.message,t);break;case"base64":switch(t.base64Strategy){case"format:binary":Nn(r,"binary",n.message,t);break;case"contentEncoding:base64":Le(r,"contentEncoding","base64",n.message,t);break;case"pattern:zod":vr(r,Pn.base64,n.message,t);break}break;case"nanoid":vr(r,Pn.nanoid,n.message,t);break;case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function Gx(e,t){return t.patternStrategy==="escape"?VV(e):e}var BV=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function VV(e){let t="";for(let r=0;r<e.length;r++)BV.has(e[r])||(t+="\\"),t+=e[r];return t}function Nn(e,t,r,n){e.format||e.anyOf?.some(i=>i.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&n.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...r&&n.errorMessages&&{errorMessage:{format:r}}})):Le(e,"format",t,r,n)}function vr(e,t,r,n){e.pattern||e.allOf?.some(i=>i.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&n.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:NP(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):Le(e,"pattern",NP(t,n),r,n)}function NP(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")},n=r.i?e.source.toLowerCase():e.source,i="",s=!1,o=!1,a=!1;for(let c=0;c<n.length;c++){if(s){i+=n[c],s=!1;continue}if(r.i){if(o){if(n[c].match(/[a-z]/)){a?(i+=n[c],i+=`${n[c-2]}-${n[c]}`.toUpperCase(),a=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(i+=n[c],a=!0):i+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){i+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){i+=`(^|(?<=[\r
|
|
87
|
+
]))`;continue}else if(n[c]==="$"){i+=`($|(?=[\r
|
|
88
|
+
]))`;continue}}if(r.s&&n[c]==="."){i+=o?`${n[c]}\r
|
|
89
|
+
`:`[${n[c]}\r
|
|
90
|
+
]`;continue}i+=n[c],n[c]==="\\"?s=!0:o&&n[c]==="]"?o=!1:!o&&n[c]==="["&&(o=!0)}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return i}function _h(e,t){if(t.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),t.target==="openApi3"&&e.keyType?._def.typeName===T.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,i)=>({...n,[i]:fe(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",i]})??ut(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let r={type:"object",additionalProperties:fe(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if(t.target==="openApi3")return r;if(e.keyType?._def.typeName===T.ZodString&&e.keyType._def.checks?.length){let{type:n,...i}=gh(e.keyType._def,t);return{...r,propertyNames:i}}else{if(e.keyType?._def.typeName===T.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===T.ZodBranded&&e.keyType._def.type._def.typeName===T.ZodString&&e.keyType._def.type._def.checks?.length){let{type:n,...i}=hh(e.keyType._def,t);return{...r,propertyNames:i}}}return r}function RP(e,t){if(t.mapStrategy==="record")return _h(e,t);let r=fe(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||ut(t),n=fe(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||ut(t);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function MP(e){let t=e.values,n=Object.keys(e.values).filter(s=>typeof t[t[s]]!="number").map(s=>t[s]),i=Array.from(new Set(n.map(s=>typeof s)));return{type:i.length===1?i[0]==="string"?"string":"number":["string","number"],enum:n}}function jP(e){return e.target==="openAi"?void 0:{not:ut({...e,currentPath:[...e.currentPath,"not"]})}}function DP(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var kp={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function LP(e,t){if(t.target==="openApi3")return zP(e,t);let r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(n=>n._def.typeName in kp&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((i,s)=>{let o=kp[s._def.typeName];return o&&!i.includes(o)?[...i,o]:i},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((i,s)=>{let o=typeof s._def.value;switch(o){case"string":case"number":case"boolean":return[...i,o];case"bigint":return[...i,"integer"];case"object":return s._def.value===null?[...i,"null"]:i;case"symbol":case"undefined":case"function":default:return i}},[]);if(n.length===r.length){let i=n.filter((s,o,a)=>a.indexOf(s)===o);return{type:i.length>1?i:i[0],enum:r.reduce((s,o)=>s.includes(o._def.value)?s:[...s,o._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,i)=>[...n,...i._def.values.filter(s=>!n.includes(s))],[])};return zP(e,t)}var zP=(e,t)=>{let r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((n,i)=>fe(n._def,{...t,currentPath:[...t.currentPath,"anyOf",`${i}`]})).filter(n=>!!n&&(!t.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function UP(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target==="openApi3"?{type:kp[e.innerType._def.typeName],nullable:!0}:{type:[kp[e.innerType._def.typeName],"null"]};if(t.target==="openApi3"){let n=fe(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=fe(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function FP(e,t){let r={type:"number"};if(!e.checks)return r;for(let n of e.checks)switch(n.kind){case"int":r.type="integer",Lx(r,"type",n.message,t);break;case"min":t.target==="jsonSchema7"?n.inclusive?Le(r,"minimum",n.value,n.message,t):Le(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),Le(r,"minimum",n.value,n.message,t));break;case"max":t.target==="jsonSchema7"?n.inclusive?Le(r,"maximum",n.value,n.message,t):Le(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),Le(r,"maximum",n.value,n.message,t));break;case"multipleOf":Le(r,"multipleOf",n.value,n.message,t);break}return r}function BP(e,t){let r=t.target==="openAi",n={type:"object",properties:{}},i=[],s=e.shape();for(let a in s){let c=s[a];if(c===void 0||c._def===void 0)continue;let u=GV(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let l=fe(c._def,{...t,currentPath:[...t.currentPath,"properties",a],propertyPath:[...t.currentPath,"properties",a]});l!==void 0&&(n.properties[a]=l,u||i.push(a))}i.length&&(n.required=i);let o=ZV(e,t);return o!==void 0&&(n.additionalProperties=o),n}function ZV(e,t){if(e.catchall._def.typeName!=="ZodNever")return fe(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return t.removeAdditionalStrategy==="strict"?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function GV(e){try{return e.isOptional()}catch{return!0}}var VP=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return fe(e.innerType._def,t);let r=fe(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:ut(t)},r]}:ut(t)};var ZP=(e,t)=>{if(t.pipeStrategy==="input")return fe(e.in._def,t);if(t.pipeStrategy==="output")return fe(e.out._def,t);let r=fe(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),n=fe(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(i=>i!==void 0)}};function GP(e,t){return fe(e.type._def,t)}function KP(e,t){let n={type:"array",uniqueItems:!0,items:fe(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&Le(n,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&Le(n,"maxItems",e.maxSize.value,e.maxSize.message,t),n}function qP(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((r,n)=>fe(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:fe(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,n)=>fe(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function HP(e){return{not:ut(e)}}function WP(e){return ut(e)}var JP=(e,t)=>fe(e.innerType._def,t);var XP=(e,t,r)=>{switch(t){case T.ZodString:return gh(e,r);case T.ZodNumber:return FP(e,r);case T.ZodObject:return BP(e,r);case T.ZodBigInt:return EP(e,r);case T.ZodBoolean:return kP();case T.ZodDate:return Vx(e,r);case T.ZodUndefined:return HP(r);case T.ZodNull:return DP(r);case T.ZodArray:return SP(e,r);case T.ZodUnion:case T.ZodDiscriminatedUnion:return LP(e,r);case T.ZodIntersection:return CP(e,r);case T.ZodTuple:return qP(e,r);case T.ZodRecord:return _h(e,r);case T.ZodLiteral:return PP(e,r);case T.ZodEnum:return $P(e);case T.ZodNativeEnum:return MP(e);case T.ZodNullable:return UP(e,r);case T.ZodOptional:return VP(e,r);case T.ZodMap:return RP(e,r);case T.ZodSet:return KP(e,r);case T.ZodLazy:return()=>e.getter()._def;case T.ZodPromise:return GP(e,r);case T.ZodNaN:case T.ZodNever:return jP(r);case T.ZodEffects:return OP(e,r);case T.ZodAny:return ut(r);case T.ZodUnknown:return WP(r);case T.ZodDefault:return TP(e,r);case T.ZodBranded:return hh(e,r);case T.ZodReadonly:return JP(e,r);case T.ZodCatch:return AP(e,r);case T.ZodPipeline:return ZP(e,r);case T.ZodFunction:case T.ZodVoid:case T.ZodSymbol:return;default:return(n=>{})(t)}};function fe(e,t,r=!1){let n=t.seen.get(e);if(t.override){let a=t.override?.(e,t,n,r);if(a!==lP)return a}if(n&&!r){let a=KV(n,t);if(a!==void 0)return a}let i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);let s=XP(e,e.typeName,t),o=typeof s=="function"?fe(s(),t):s;if(o&&qV(e,t,o),t.postProcess){let a=t.postProcess(o,e,t);return i.jsonSchema=o,a}return i.jsonSchema=o,o}var KV=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:uh(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((r,n)=>t.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),ut(t)):t.$refStrategy==="seen"?ut(t):void 0}},qV=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r);var YP=(e,t)=>{let r=dP(t),n=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[u,l])=>({...c,[u]:fe(l._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??ut(r)}),{}):void 0,i=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,s=fe(e._def,i===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,i]},!1)??ut(r),o=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;o!==void 0&&(s.title=o),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let a=i===void 0?n?{...s,[r.definitionPath]:n}:s:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,i].join("/"),[r.definitionPath]:{...n,[i]:s}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a};function gi(e,t){let r=typeof e;if(r!==typeof t)return!1;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let n=e.length;if(n!==t.length)return!1;for(let i=0;i<n;i++)if(!gi(e[i],t[i]))return!1;return!0}if(r==="object"){if(!e||!t)return e===t;let n=Object.keys(e),i=Object.keys(t);if(n.length!==i.length)return!1;for(let o of n)if(!gi(e[o],t[o]))return!1;return!0}return e===t}function Kr(e){return encodeURI(HV(e))}function HV(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}var WV={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},JV={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},XV={id:!0,$id:!0,$ref:!0,$schema:!0,$anchor:!0,$vocabulary:!0,$comment:!0,default:!0,enum:!0,const:!0,required:!0,type:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0},YV=typeof self<"u"&&self.location&&self.location.origin!=="null"?new URL(self.location.origin+self.location.pathname+location.search):new URL("https://github.com/cfworker");function Rn(e,t=Object.create(null),r=YV,n=""){if(e&&typeof e=="object"&&!Array.isArray(e)){let s=e.$id||e.id;if(s){let o=new URL(s,r.href);o.hash.length>1?t[o.href]=e:(o.hash="",n===""?r=o:Rn(e,t,r))}}else if(e!==!0&&e!==!1)return t;let i=r.href+(n?"#"+n:"");if(t[i]!==void 0)throw new Error(`Duplicate schema URI "${i}".`);if(t[i]=e,e===!0||e===!1)return t;if(e.__absolute_uri__===void 0&&Object.defineProperty(e,"__absolute_uri__",{enumerable:!1,value:i}),e.$ref&&e.__absolute_ref__===void 0){let s=new URL(e.$ref,r.href);s.hash=s.hash,Object.defineProperty(e,"__absolute_ref__",{enumerable:!1,value:s.href})}if(e.$recursiveRef&&e.__absolute_recursive_ref__===void 0){let s=new URL(e.$recursiveRef,r.href);s.hash=s.hash,Object.defineProperty(e,"__absolute_recursive_ref__",{enumerable:!1,value:s.href})}if(e.$anchor){let s=new URL("#"+e.$anchor,r.href);t[s.href]=e}for(let s in e){if(XV[s])continue;let o=`${n}/${Kr(s)}`,a=e[s];if(Array.isArray(a)){if(WV[s]){let c=a.length;for(let u=0;u<c;u++)Rn(a[u],t,r,`${o}/${u}`)}}else if(JV[s])for(let c in a)Rn(a[c],t,r,`${o}/${Kr(c)}`);else Rn(a,t,r,o)}return t}var QV=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,eZ=[0,31,28,31,30,31,30,31,31,30,31,30,31],tZ=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,rZ=/^(?=.{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,nZ=/^(?:[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,iZ=/^(?:(?:[^\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,sZ=/^(?:(?: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,oZ=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,aZ=/^(?:\/(?:[^~/]|~0|~1)*)*$/,cZ=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,uZ=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,lZ=e=>{if(e[0]==='"')return!1;let[t,r,...n]=e.split("@");return!t||!r||n.length!==0||t.length>64||r.length>253||t[0]==="."||t.endsWith(".")||t.includes("..")||!/^[a-z0-9.-]+$/i.test(r)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t)?!1:r.split(".").every(i=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(i))},pZ=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,dZ=/^((([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,fZ=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));function _i(e){return e.test.bind(e)}var Kx={date:QP,time:eN.bind(void 0,!1),"date-time":gZ,duration:fZ,uri:vZ,"uri-reference":_i(nZ),"uri-template":_i(iZ),url:_i(sZ),email:lZ,hostname:_i(rZ),ipv4:_i(pZ),ipv6:_i(dZ),regex:wZ,uuid:_i(oZ),"json-pointer":_i(aZ),"json-pointer-uri-fragment":_i(cZ),"relative-json-pointer":_i(uZ)};function mZ(e){return e%4===0&&(e%100!==0||e%400===0)}function QP(e){let t=e.match(QV);if(!t)return!1;let r=+t[1],n=+t[2],i=+t[3];return n>=1&&n<=12&&i>=1&&i<=(n==2&&mZ(r)?29:eZ[n])}function eN(e,t){let r=t.match(tZ);if(!r)return!1;let n=+r[1],i=+r[2],s=+r[3],o=!!r[5];return(n<=23&&i<=59&&s<=59||n==23&&i==59&&s==60)&&(!e||o)}var hZ=/t|\s/i;function gZ(e){let t=e.split(hZ);return t.length==2&&QP(t[0])&&eN(!0,t[1])}var _Z=/\/|:/,yZ=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function vZ(e){return _Z.test(e)&&yZ.test(e)}var bZ=/[^\\]\\Z/;function wZ(e){if(bZ.test(e))return!1;try{return new RegExp(e,"u"),!0}catch{return!1}}var tN;(function(e){e[e.Flag=1]="Flag",e[e.Basic=2]="Basic",e[e.Detailed=4]="Detailed"})(tN||(tN={}));function rN(e){let t=0,r=e.length,n=0,i;for(;n<r;)t++,i=e.charCodeAt(n++),i>=55296&&i<=56319&&n<r&&(i=e.charCodeAt(n),(i&64512)==56320&&n++);return t}function Xe(e,t,r="2019-09",n=Rn(t),i=!0,s=null,o="#",a="#",c=Object.create(null)){if(t===!0)return{valid:!0,errors:[]};if(t===!1)return{valid:!1,errors:[{instanceLocation:o,keyword:"false",keywordLocation:o,error:"False boolean schema."}]};let u=typeof e,l;switch(u){case"boolean":case"number":case"string":l=u;break;case"object":e===null?l="null":Array.isArray(e)?l="array":l="object";break;default:throw new Error(`Instances of "${u}" type are not supported.`)}let{$ref:p,$recursiveRef:f,$recursiveAnchor:d,type:m,const:h,enum:b,required:_,not:y,anyOf:x,allOf:I,oneOf:A,if:j,then:O,else:w,format:F,properties:P,patternProperties:V,additionalProperties:Te,unevaluatedProperties:qe,minProperties:cr,maxProperties:Lr,propertyNames:Me,dependentRequired:To,dependentSchemas:Ni,dependencies:Oo,prefixItems:In,items:Ri,additionalItems:ll,unevaluatedItems:pl,contains:dl,minContains:Sn,maxContains:v,minItems:g,maxItems:R,uniqueItems:E,minimum:je,maximum:He,exclusiveMinimum:tt,exclusiveMaximum:St,multipleOf:Bt,minLength:En,maxLength:mt,pattern:tn,__absolute_ref__:ac,__absolute_recursive_ref__:Wd}=t,J=[];if(d===!0&&s===null&&(s=t),f==="#"){let me=s===null?n[Wd]:s,oe=`${a}/$recursiveRef`,ye=Xe(e,s===null?t:s,r,n,i,me,o,oe,c);ye.valid||J.push({instanceLocation:o,keyword:"$recursiveRef",keywordLocation:oe,error:"A subschema had errors."},...ye.errors)}if(p!==void 0){let oe=n[ac||p];if(oe===void 0){let W=`Unresolved $ref "${p}".`;throw ac&&ac!==p&&(W+=` Absolute URI "${ac}".`),W+=`
|
|
91
|
+
Known schemas:
|
|
92
|
+
- ${Object.keys(n).join(`
|
|
93
|
+
- `)}`,new Error(W)}let ye=`${a}/$ref`,ee=Xe(e,oe,r,n,i,s,o,ye,c);if(ee.valid||J.push({instanceLocation:o,keyword:"$ref",keywordLocation:ye,error:"A subschema had errors."},...ee.errors),r==="4"||r==="7")return{valid:J.length===0,errors:J}}if(Array.isArray(m)){let me=m.length,oe=!1;for(let ye=0;ye<me;ye++)if(l===m[ye]||m[ye]==="integer"&&l==="number"&&e%1===0&&e===e){oe=!0;break}oe||J.push({instanceLocation:o,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${l}" is invalid. Expected "${m.join('", "')}".`})}else m==="integer"?(l!=="number"||e%1||e!==e)&&J.push({instanceLocation:o,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${l}" is invalid. Expected "${m}".`}):m!==void 0&&l!==m&&J.push({instanceLocation:o,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${l}" is invalid. Expected "${m}".`});if(h!==void 0&&(l==="object"||l==="array"?gi(e,h)||J.push({instanceLocation:o,keyword:"const",keywordLocation:`${a}/const`,error:`Instance does not match ${JSON.stringify(h)}.`}):e!==h&&J.push({instanceLocation:o,keyword:"const",keywordLocation:`${a}/const`,error:`Instance does not match ${JSON.stringify(h)}.`})),b!==void 0&&(l==="object"||l==="array"?b.some(me=>gi(e,me))||J.push({instanceLocation:o,keyword:"enum",keywordLocation:`${a}/enum`,error:`Instance does not match any of ${JSON.stringify(b)}.`}):b.some(me=>e===me)||J.push({instanceLocation:o,keyword:"enum",keywordLocation:`${a}/enum`,error:`Instance does not match any of ${JSON.stringify(b)}.`})),y!==void 0){let me=`${a}/not`;Xe(e,y,r,n,i,s,o,me).valid&&J.push({instanceLocation:o,keyword:"not",keywordLocation:me,error:'Instance matched "not" schema.'})}let $o=[];if(x!==void 0){let me=`${a}/anyOf`,oe=J.length,ye=!1;for(let ee=0;ee<x.length;ee++){let W=x[ee],ge=Object.create(c),he=Xe(e,W,r,n,i,d===!0?s:null,o,`${me}/${ee}`,ge);J.push(...he.errors),ye=ye||he.valid,he.valid&&$o.push(ge)}ye?J.length=oe:J.splice(oe,0,{instanceLocation:o,keyword:"anyOf",keywordLocation:me,error:"Instance does not match any subschemas."})}if(I!==void 0){let me=`${a}/allOf`,oe=J.length,ye=!0;for(let ee=0;ee<I.length;ee++){let W=I[ee],ge=Object.create(c),he=Xe(e,W,r,n,i,d===!0?s:null,o,`${me}/${ee}`,ge);J.push(...he.errors),ye=ye&&he.valid,he.valid&&$o.push(ge)}ye?J.length=oe:J.splice(oe,0,{instanceLocation:o,keyword:"allOf",keywordLocation:me,error:"Instance does not match every subschema."})}if(A!==void 0){let me=`${a}/oneOf`,oe=J.length,ye=A.filter((ee,W)=>{let ge=Object.create(c),he=Xe(e,ee,r,n,i,d===!0?s:null,o,`${me}/${W}`,ge);return J.push(...he.errors),he.valid&&$o.push(ge),he.valid}).length;ye===1?J.length=oe:J.splice(oe,0,{instanceLocation:o,keyword:"oneOf",keywordLocation:me,error:`Instance does not match exactly one subschema (${ye} matches).`})}if((l==="object"||l==="array")&&Object.assign(c,...$o),j!==void 0){let me=`${a}/if`;if(Xe(e,j,r,n,i,s,o,me,c).valid){if(O!==void 0){let ye=Xe(e,O,r,n,i,s,o,`${a}/then`,c);ye.valid||J.push({instanceLocation:o,keyword:"if",keywordLocation:me,error:'Instance does not match "then" schema.'},...ye.errors)}}else if(w!==void 0){let ye=Xe(e,w,r,n,i,s,o,`${a}/else`,c);ye.valid||J.push({instanceLocation:o,keyword:"if",keywordLocation:me,error:'Instance does not match "else" schema.'},...ye.errors)}}if(l==="object"){if(_!==void 0)for(let ee of _)ee in e||J.push({instanceLocation:o,keyword:"required",keywordLocation:`${a}/required`,error:`Instance does not have required property "${ee}".`});let me=Object.keys(e);if(cr!==void 0&&me.length<cr&&J.push({instanceLocation:o,keyword:"minProperties",keywordLocation:`${a}/minProperties`,error:`Instance does not have at least ${cr} properties.`}),Lr!==void 0&&me.length>Lr&&J.push({instanceLocation:o,keyword:"maxProperties",keywordLocation:`${a}/maxProperties`,error:`Instance does not have at least ${Lr} properties.`}),Me!==void 0){let ee=`${a}/propertyNames`;for(let W in e){let ge=`${o}/${Kr(W)}`,he=Xe(W,Me,r,n,i,s,ge,ee);he.valid||J.push({instanceLocation:o,keyword:"propertyNames",keywordLocation:ee,error:`Property name "${W}" does not match schema.`},...he.errors)}}if(To!==void 0){let ee=`${a}/dependantRequired`;for(let W in To)if(W in e){let ge=To[W];for(let he of ge)he in e||J.push({instanceLocation:o,keyword:"dependentRequired",keywordLocation:ee,error:`Instance has "${W}" but does not have "${he}".`})}}if(Ni!==void 0)for(let ee in Ni){let W=`${a}/dependentSchemas`;if(ee in e){let ge=Xe(e,Ni[ee],r,n,i,s,o,`${W}/${Kr(ee)}`,c);ge.valid||J.push({instanceLocation:o,keyword:"dependentSchemas",keywordLocation:W,error:`Instance has "${ee}" but does not match dependant schema.`},...ge.errors)}}if(Oo!==void 0){let ee=`${a}/dependencies`;for(let W in Oo)if(W in e){let ge=Oo[W];if(Array.isArray(ge))for(let he of ge)he in e||J.push({instanceLocation:o,keyword:"dependencies",keywordLocation:ee,error:`Instance has "${W}" but does not have "${he}".`});else{let he=Xe(e,ge,r,n,i,s,o,`${ee}/${Kr(W)}`);he.valid||J.push({instanceLocation:o,keyword:"dependencies",keywordLocation:ee,error:`Instance has "${W}" but does not match dependant schema.`},...he.errors)}}}let oe=Object.create(null),ye=!1;if(P!==void 0){let ee=`${a}/properties`;for(let W in P){if(!(W in e))continue;let ge=`${o}/${Kr(W)}`,he=Xe(e[W],P[W],r,n,i,s,ge,`${ee}/${Kr(W)}`);if(he.valid)c[W]=oe[W]=!0;else if(ye=i,J.push({instanceLocation:o,keyword:"properties",keywordLocation:ee,error:`Property "${W}" does not match schema.`},...he.errors),ye)break}}if(!ye&&V!==void 0){let ee=`${a}/patternProperties`;for(let W in V){let ge=new RegExp(W,"u"),he=V[W];for(let kr in e){if(!ge.test(kr))continue;let sk=`${o}/${Kr(kr)}`,ok=Xe(e[kr],he,r,n,i,s,sk,`${ee}/${Kr(W)}`);ok.valid?c[kr]=oe[kr]=!0:(ye=i,J.push({instanceLocation:o,keyword:"patternProperties",keywordLocation:ee,error:`Property "${kr}" matches pattern "${W}" but does not match associated schema.`},...ok.errors))}}}if(!ye&&Te!==void 0){let ee=`${a}/additionalProperties`;for(let W in e){if(oe[W])continue;let ge=`${o}/${Kr(W)}`,he=Xe(e[W],Te,r,n,i,s,ge,ee);he.valid?c[W]=!0:(ye=i,J.push({instanceLocation:o,keyword:"additionalProperties",keywordLocation:ee,error:`Property "${W}" does not match additional properties schema.`},...he.errors))}}else if(!ye&&qe!==void 0){let ee=`${a}/unevaluatedProperties`;for(let W in e)if(!c[W]){let ge=`${o}/${Kr(W)}`,he=Xe(e[W],qe,r,n,i,s,ge,ee);he.valid?c[W]=!0:J.push({instanceLocation:o,keyword:"unevaluatedProperties",keywordLocation:ee,error:`Property "${W}" does not match unevaluated properties schema.`},...he.errors)}}}else if(l==="array"){R!==void 0&&e.length>R&&J.push({instanceLocation:o,keyword:"maxItems",keywordLocation:`${a}/maxItems`,error:`Array has too many items (${e.length} > ${R}).`}),g!==void 0&&e.length<g&&J.push({instanceLocation:o,keyword:"minItems",keywordLocation:`${a}/minItems`,error:`Array has too few items (${e.length} < ${g}).`});let me=e.length,oe=0,ye=!1;if(In!==void 0){let ee=`${a}/prefixItems`,W=Math.min(In.length,me);for(;oe<W;oe++){let ge=Xe(e[oe],In[oe],r,n,i,s,`${o}/${oe}`,`${ee}/${oe}`);if(c[oe]=!0,!ge.valid&&(ye=i,J.push({instanceLocation:o,keyword:"prefixItems",keywordLocation:ee,error:"Items did not match schema."},...ge.errors),ye))break}}if(Ri!==void 0){let ee=`${a}/items`;if(Array.isArray(Ri)){let W=Math.min(Ri.length,me);for(;oe<W;oe++){let ge=Xe(e[oe],Ri[oe],r,n,i,s,`${o}/${oe}`,`${ee}/${oe}`);if(c[oe]=!0,!ge.valid&&(ye=i,J.push({instanceLocation:o,keyword:"items",keywordLocation:ee,error:"Items did not match schema."},...ge.errors),ye))break}}else for(;oe<me;oe++){let W=Xe(e[oe],Ri,r,n,i,s,`${o}/${oe}`,ee);if(c[oe]=!0,!W.valid&&(ye=i,J.push({instanceLocation:o,keyword:"items",keywordLocation:ee,error:"Items did not match schema."},...W.errors),ye))break}if(!ye&&ll!==void 0){let W=`${a}/additionalItems`;for(;oe<me;oe++){let ge=Xe(e[oe],ll,r,n,i,s,`${o}/${oe}`,W);c[oe]=!0,ge.valid||(ye=i,J.push({instanceLocation:o,keyword:"additionalItems",keywordLocation:W,error:"Items did not match additional items schema."},...ge.errors))}}}if(dl!==void 0)if(me===0&&Sn===void 0)J.push({instanceLocation:o,keyword:"contains",keywordLocation:`${a}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(Sn!==void 0&&me<Sn)J.push({instanceLocation:o,keyword:"minContains",keywordLocation:`${a}/minContains`,error:`Array has less items (${me}) than minContains (${Sn}).`});else{let ee=`${a}/contains`,W=J.length,ge=0;for(let he=0;he<me;he++){let kr=Xe(e[he],dl,r,n,i,s,`${o}/${he}`,ee);kr.valid?(c[he]=!0,ge++):J.push(...kr.errors)}ge>=(Sn||0)&&(J.length=W),Sn===void 0&&v===void 0&&ge===0?J.splice(W,0,{instanceLocation:o,keyword:"contains",keywordLocation:ee,error:"Array does not contain item matching schema."}):Sn!==void 0&&ge<Sn?J.push({instanceLocation:o,keyword:"minContains",keywordLocation:`${a}/minContains`,error:`Array must contain at least ${Sn} items matching schema. Only ${ge} items were found.`}):v!==void 0&&ge>v&&J.push({instanceLocation:o,keyword:"maxContains",keywordLocation:`${a}/maxContains`,error:`Array may contain at most ${v} items matching schema. ${ge} items were found.`})}if(!ye&&pl!==void 0){let ee=`${a}/unevaluatedItems`;for(oe;oe<me;oe++){if(c[oe])continue;let W=Xe(e[oe],pl,r,n,i,s,`${o}/${oe}`,ee);c[oe]=!0,W.valid||J.push({instanceLocation:o,keyword:"unevaluatedItems",keywordLocation:ee,error:"Items did not match unevaluated items schema."},...W.errors)}}if(E)for(let ee=0;ee<me;ee++){let W=e[ee],ge=typeof W=="object"&&W!==null;for(let he=0;he<me;he++){if(ee===he)continue;let kr=e[he];(W===kr||ge&&(typeof kr=="object"&&kr!==null)&&gi(W,kr))&&(J.push({instanceLocation:o,keyword:"uniqueItems",keywordLocation:`${a}/uniqueItems`,error:`Duplicate items at indexes ${ee} and ${he}.`}),ee=Number.MAX_SAFE_INTEGER,he=Number.MAX_SAFE_INTEGER)}}}else if(l==="number"){if(r==="4"?(je!==void 0&&(tt===!0&&e<=je||e<je)&&J.push({instanceLocation:o,keyword:"minimum",keywordLocation:`${a}/minimum`,error:`${e} is less than ${tt?"or equal to ":""} ${je}.`}),He!==void 0&&(St===!0&&e>=He||e>He)&&J.push({instanceLocation:o,keyword:"maximum",keywordLocation:`${a}/maximum`,error:`${e} is greater than ${St?"or equal to ":""} ${He}.`})):(je!==void 0&&e<je&&J.push({instanceLocation:o,keyword:"minimum",keywordLocation:`${a}/minimum`,error:`${e} is less than ${je}.`}),He!==void 0&&e>He&&J.push({instanceLocation:o,keyword:"maximum",keywordLocation:`${a}/maximum`,error:`${e} is greater than ${He}.`}),tt!==void 0&&e<=tt&&J.push({instanceLocation:o,keyword:"exclusiveMinimum",keywordLocation:`${a}/exclusiveMinimum`,error:`${e} is less than ${tt}.`}),St!==void 0&&e>=St&&J.push({instanceLocation:o,keyword:"exclusiveMaximum",keywordLocation:`${a}/exclusiveMaximum`,error:`${e} is greater than or equal to ${St}.`})),Bt!==void 0){let me=e%Bt;Math.abs(0-me)>=11920929e-14&&Math.abs(Bt-me)>=11920929e-14&&J.push({instanceLocation:o,keyword:"multipleOf",keywordLocation:`${a}/multipleOf`,error:`${e} is not a multiple of ${Bt}.`})}}else if(l==="string"){let me=En===void 0&&mt===void 0?0:rN(e);En!==void 0&&me<En&&J.push({instanceLocation:o,keyword:"minLength",keywordLocation:`${a}/minLength`,error:`String is too short (${me} < ${En}).`}),mt!==void 0&&me>mt&&J.push({instanceLocation:o,keyword:"maxLength",keywordLocation:`${a}/maxLength`,error:`String is too long (${me} > ${mt}).`}),tn!==void 0&&!new RegExp(tn,"u").test(e)&&J.push({instanceLocation:o,keyword:"pattern",keywordLocation:`${a}/pattern`,error:"String does not match pattern."}),F!==void 0&&Kx[F]&&!Kx[F](e)&&J.push({instanceLocation:o,keyword:"format",keywordLocation:`${a}/format`,error:`String does not match format "${F}".`})}return{valid:J.length===0,errors:J}}var yh=class{schema;draft;shortCircuit;lookup;constructor(t,r="2019-09",n=!0){this.schema=t,this.draft=r,this.shortCircuit=n,this.lookup=Rn(t)}validate(t){return Xe(t,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(t,r){r&&(t={...t,$id:r}),Rn(t,this.lookup)}};var qx={};M(qx,{Validator:()=>yh,deepCompareStrict:()=>gi,toJsonSchema:()=>Ye,validatesOnlyStrings:()=>Fc});function Ye(e,t){if(Je(e)){let r=ah(e,!0);if(dn(r)){let n=Oc(r,!0);return Hs(n,t)}else return Hs(e,t)}return it(e)?YP(e):e}function Fc(e){if(!e||typeof e!="object"||Object.keys(e).length===0||Array.isArray(e))return!1;if("type"in e)return typeof e.type=="string"?e.type==="string":Array.isArray(e.type)?e.type.every(t=>t==="string"):!1;if("enum"in e)return Array.isArray(e.enum)&&e.enum.length>0&&e.enum.every(t=>typeof t=="string");if("const"in e)return typeof e.const=="string";if("allOf"in e&&Array.isArray(e.allOf))return e.allOf.some(t=>Fc(t));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(r=>Fc(r))}if("not"in e)return!1;if("$ref"in e&&typeof e.$ref=="string"){let t=e.$ref,r=Rn(e);return r[t]?Fc(r[t]):!1}return!1}function Ap(e){return e?e.lc_runnable:!1}var nN=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=this.includeNames===void 0&&this.includeTypes===void 0&&this.includeTags===void 0,n=e.tags??[];return this.includeNames!==void 0&&(r=r||this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(r=r||this.includeTypes.includes(t)),this.includeTags!==void 0&&(r=r||n.some(i=>this.includeTags?.includes(i))),this.excludeNames!==void 0&&(r=r&&!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(r=r&&!this.excludeTypes.includes(t)),this.excludeTags!==void 0&&(r=r&&n.every(i=>!this.excludeTags?.includes(i))),r}},iN=e=>btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");function Hx(e){return e.replace(/[^a-zA-Z-_0-9]/g,"_")}var xZ=["*","_","`"];function IZ(e){let t="";for(let[r,n]of Object.entries(e))t+=` classDef ${r} ${n};
|
|
94
|
+
`;return t}function sN(e,t,r){let{firstNode:n,lastNode:i,nodeColors:s,withStyles:o=!0,curveStyle:a="linear",wrapLabelNWords:c=9}=r??{},u=o?`%%{init: {'flowchart': {'curve': '${a}'}}}%%
|
|
95
|
+
graph TD;
|
|
96
|
+
`:`graph TD;
|
|
97
|
+
`;if(o){let m="default",h={[m]:"{0}({1})"};n!==void 0&&(h[n]="{0}([{1}]):::first"),i!==void 0&&(h[i]="{0}([{1}]):::last");for(let[b,_]of Object.entries(e)){let y=_.name.split(":").pop()??"",I=xZ.some(j=>y.startsWith(j)&&y.endsWith(j))?`<p>${y}</p>`:y;Object.keys(_.metadata??{}).length&&(I+=`<hr/><small><em>${Object.entries(_.metadata??{}).map(([j,O])=>`${j} = ${O}`).join(`
|
|
98
|
+
`)}</em></small>`);let A=(h[b]??h[m]).replace("{0}",Hx(b)).replace("{1}",I);u+=` ${A}
|
|
99
|
+
`}}let l={};for(let m of t){let h=m.source.split(":"),b=m.target.split(":"),_=h.filter((y,x)=>y===b[x]).join(":");l[_]||(l[_]=[]),l[_].push(m)}let p=new Set;function f(m){return[...m].sort((h,b)=>h.split(":").length-b.split(":").length)}function d(m,h){let b=m.length===1&&m[0].source===m[0].target;if(h&&!b){let y=h.split(":").pop();if(p.has(h))throw new Error(`Found duplicate subgraph '${y}' at '${h} -- 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(h),u+=` subgraph ${y}
|
|
100
|
+
`}let _=f(Object.keys(l).filter(y=>y.startsWith(`${h}:`)&&y!==h&&y.split(":").length===h.split(":").length+1));for(let y of _)d(l[y],y);for(let y of m){let{source:x,target:I,data:A,conditional:j}=y,O="";if(A!==void 0){let w=A,F=w.split(" ");F.length>c&&(w=Array.from({length:Math.ceil(F.length/c)},(P,V)=>F.slice(V*c,(V+1)*c).join(" ")).join(" <br> ")),O=j?` -. ${w} .-> `:` -- ${w} --> `}else O=j?" -.-> ":" --> ";u+=` ${Hx(x)}${O}${Hx(I)};
|
|
101
|
+
`}h&&!b&&(u+=` end
|
|
102
|
+
`)}d(l[""]??[],"");for(let m in l)!m.includes(":")&&m!==""&&d(l[m],m);return o&&(u+=IZ(s??{})),u}async function oN(e,t){let r=t?.backgroundColor??"white",n=t?.imageType??"png",i=iN(e);r!==void 0&&(/^#(?:[0-9a-fA-F]{3}){1,2}$/.test(r)||(r=`!${r}`));let s=`https://mermaid.ink/img/${i}?bgColor=${r}&type=${n}`,o=await fetch(s);if(!o.ok)throw new Error(["Failed to render the graph using the Mermaid.INK API.",`Status code: ${o.status}`,`Status text: ${o.statusText}`].join(`
|
|
103
|
+
`));return await o.blob()}var Wx={};M(Wx,{Graph:()=>ya});function SZ(e,t){if(e!==void 0&&!kn(e))return e;if(Ap(t))try{let r=t.getName();return r=r.startsWith("Runnable")?r.slice(8):r,r}catch{return t.getName()}else return t.name??"UnknownSchema"}function EZ(e){return Ap(e.data)?{type:"runnable",data:{id:e.data.lc_id,name:e.data.getName()}}:{type:"schema",data:{...Ye(e.data.schema),title:e.data.name}}}var ya=class uN{nodes={};edges=[];constructor(t){this.nodes=t?.nodes??this.nodes,this.edges=t?.edges??this.edges}toJSON(){let t={};return Object.values(this.nodes).forEach((r,n)=>{t[r.id]=kn(r.id)?n:r.id}),{nodes:Object.values(this.nodes).map(r=>({id:t[r.id],...EZ(r)})),edges:this.edges.map(r=>{let n={source:t[r.source],target:t[r.target]};return typeof r.data<"u"&&(n.data=r.data),typeof r.conditional<"u"&&(n.conditional=r.conditional),n})}}addNode(t,r,n){if(r!==void 0&&this.nodes[r]!==void 0)throw new Error(`Node with id ${r} already exists`);let i=r??Ar(),s={id:i,data:t,name:SZ(r,t),metadata:n};return this.nodes[i]=s,s}removeNode(t){delete this.nodes[t.id],this.edges=this.edges.filter(r=>r.source!==t.id&&r.target!==t.id)}addEdge(t,r,n,i){if(this.nodes[t.id]===void 0)throw new Error(`Source node ${t.id} not in graph`);if(this.nodes[r.id]===void 0)throw new Error(`Target node ${r.id} not in graph`);let s={source:t.id,target:r.id,data:n,conditional:i};return this.edges.push(s),s}firstNode(){return aN(this)}lastNode(){return cN(this)}extend(t,r=""){let n=r;Object.values(t.nodes).map(u=>u.id).every(kn)&&(n="");let s=u=>n?`${n}:${u}`:u;Object.entries(t.nodes).forEach(([u,l])=>{this.nodes[s(u)]={...l,id:s(u)}});let o=t.edges.map(u=>({...u,source:s(u.source),target:s(u.target)}));this.edges=[...this.edges,...o];let a=t.firstNode(),c=t.lastNode();return[a?{id:s(a.id),data:a.data}:void 0,c?{id:s(c.id),data:c.data}:void 0]}trimFirstNode(){let t=this.firstNode();t&&aN(this,[t.id])&&this.removeNode(t)}trimLastNode(){let t=this.lastNode();t&&cN(this,[t.id])&&this.removeNode(t)}reid(){let t=Object.fromEntries(Object.values(this.nodes).map(i=>[i.id,i.name])),r=new Map;Object.values(t).forEach(i=>{r.set(i,(r.get(i)||0)+1)});let n=i=>{let s=t[i];return kn(i)&&r.get(s)===1?s:i};return new uN({nodes:Object.fromEntries(Object.entries(this.nodes).map(([i,s])=>[n(i),{...s,id:n(i)}])),edges:this.edges.map(i=>({...i,source:n(i.source),target:n(i.target)}))})}drawMermaid(t){let{withStyles:r,curveStyle:n,nodeColors:i={default:"fill:#f2f0ff,line-height:1.2",first:"fill-opacity:0",last:"fill:#bfb6fc"},wrapLabelNWords:s}=t??{},o=this.reid(),a=o.firstNode(),c=o.lastNode();return sN(o.nodes,o.edges,{firstNode:a?.id,lastNode:c?.id,withStyles:r,curveStyle:n,nodeColors:i,wrapLabelNWords:s})}async drawMermaidPng(t){let r=this.drawMermaid(t);return oN(r,{backgroundColor:t?.backgroundColor})}};function aN(e,t=[]){let r=new Set(e.edges.filter(i=>!t.includes(i.source)).map(i=>i.target)),n=[];for(let i of Object.values(e.nodes))!t.includes(i.id)&&!r.has(i.id)&&n.push(i);return n.length===1?n[0]:void 0}function cN(e,t=[]){let r=new Set(e.edges.filter(i=>!t.includes(i.target)).map(i=>i.source)),n=[];for(let i of Object.values(e.nodes))!t.includes(i.id)&&!r.has(i.id)&&n.push(i);return n.length===1?n[0]:void 0}function vh({name:e,serialized:t}){return e!==void 0?e:t?.name!==void 0?t.name:t?.id!==void 0&&Array.isArray(t?.id)?t.id[t.id.length-1]:"Unnamed"}var lN=e=>e.name==="event_stream_tracer",pN=class extends Zt{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=kt.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){let t=e.tags??[],r=this.includeNames===void 0&&this.includeTags===void 0&&this.includeTypes===void 0;return this.includeNames!==void 0&&(r=r||this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(r=r||this.includeTypes.includes(e.runType)),this.includeTags!==void 0&&(r=r||t.find(n=>this.includeTags?.includes(n))!==void 0),this.excludeNames!==void 0&&(r=r&&!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(r=r&&!this.excludeTypes.includes(e.runType)),this.excludeTags!==void 0&&(r=r&&t.every(n=>!this.excludeTags?.includes(n))),r}async*tapOutputIterable(e,t){let r=await t.next();if(r.done)return;let n=this.runInfoMap.get(e);if(n===void 0){yield r.value;return}function i(o,a){return o==="llm"&&typeof a=="string"?new li({text:a}):a}let s=this.tappedPromises.get(e);if(s===void 0){let o;s=new Promise(a=>{o=a}),this.tappedPromises.set(e,s);try{let a={event:`on_${n.runType}_stream`,run_id:e,name:n.name,tags:n.tags,metadata:n.metadata,data:{}};await this.send({...a,data:{chunk:i(n.runType,r.value)}},n),yield r.value;for await(let c of t)n.runType!=="tool"&&n.runType!=="retriever"&&await this.send({...a,data:{chunk:i(n.runType,c)}},n),yield c}finally{o?.()}}else{yield r.value;for await(let o of t)yield o}}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);r!==void 0?r.then(()=>{this.send(e,t)}):await this.send(e,t)}async onLLMStart(e){let t=vh(e),r=e.inputs.messages!==void 0?"chat_model":"llm",n={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:r,inputs:e.inputs};this.runInfoMap.set(e.id,n);let i=`on_${r}_start`;await this.send({event:i,data:{input:e.inputs},name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},n)}async onLLMNewToken(e,t,r){let n=this.runInfoMap.get(e.id),i,s;if(n===void 0)throw new Error(`onLLMNewToken: Run ID ${e.id} not found in run map.`);if(this.runInfoMap.size!==1){if(n.runType==="chat_model")s="on_chat_model_stream",r?.chunk===void 0?i=new nt({content:t,id:`run-${e.id}`}):i=r.chunk.message;else if(n.runType==="llm")s="on_llm_stream",r?.chunk===void 0?i=new li({text:t}):i=r.chunk;else throw new Error(`Unexpected run type ${n.runType}`);await this.send({event:s,data:{chunk:i},run_id:e.id,name:n.name,tags:n.tags,metadata:n.metadata},n)}}async onLLMEnd(e){let t=this.runInfoMap.get(e.id);this.runInfoMap.delete(e.id);let r;if(t===void 0)throw new Error(`onLLMEnd: Run ID ${e.id} not found in run map.`);let n=e.outputs?.generations,i;if(t.runType==="chat_model"){for(let s of n??[]){if(i!==void 0)break;i=s[0]?.message}r="on_chat_model_end"}else if(t.runType==="llm")i={generations:n?.map(s=>s.map(o=>({text:o.text,generationInfo:o.generationInfo}))),llmOutput:e.outputs?.llmOutput??{}},r="on_llm_end";else throw new Error(`onLLMEnd: Unexpected run type: ${t.runType}`);await this.sendEndEvent({event:r,data:{output:i,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onChainStart(e){let t=vh(e),r=e.run_type??"chain",n={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:e.run_type},i={};e.inputs.input===""&&Object.keys(e.inputs).length===1?(i={},n.inputs={}):e.inputs.input!==void 0?(i.input=e.inputs.input,n.inputs=e.inputs.input):(i.input=e.inputs,n.inputs=e.inputs),this.runInfoMap.set(e.id,n),await this.send({event:`on_${r}_start`,data:i,name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},n)}async onChainEnd(e){let t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw new Error(`onChainEnd: Run ID ${e.id} not found in run map.`);let r=`on_${e.run_type}_end`,n=e.inputs??t.inputs??{},s={output:e.outputs?.output??e.outputs,input:n};n.input&&Object.keys(n).length===1&&(s.input=n.input,t.inputs=n.input),await this.sendEndEvent({event:r,data:s,run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata??{}},t)}async onToolStart(e){let t=vh(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),t===void 0)throw new Error(`onToolEnd: Run ID ${e.id} not found in run map.`);if(t.inputs===void 0)throw new 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),t===void 0)throw new Error(`onToolEnd: Run ID ${e.id} not found in run map.`);if(t.inputs===void 0)throw new 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=vh(e),n={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:"retriever",inputs:{query:e.inputs.query}};this.runInfoMap.set(e.id,n),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??{}},n)}async onRetrieverEnd(e){let t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw new 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 n=this.runInfoMap.get(r);if(n===void 0)throw new Error(`handleCustomEvent: Run ID ${r} not found in run map.`);await this.send({event:"on_custom_event",run_id:r,name:e,tags:n.tags,metadata:n.metadata,data:t},n)}async finish(){let e=[...this.tappedPromises.values()];Promise.all(e).finally(()=>{this.writer.close()})}};var Jx=class extends Zt{name="RootListenersTracer";rootId;config;argOnStart;argOnEnd;argOnError;constructor({config:e,onStart:t,onEnd:r,onError:n}){super({_awaitHandler:!0}),this.config=e,this.argOnStart=t,this.argOnEnd=r,this.argOnError=n}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))}};function dN(e){let t=new TextEncoder,r=new ReadableStream({async start(n){for await(let i of e)n.enqueue(t.encode(`event: data
|
|
104
|
+
data: ${JSON.stringify(i)}
|
|
105
|
+
|
|
106
|
+
`));n.enqueue(t.encode(`event: end
|
|
107
|
+
|
|
108
|
+
`)),n.close()}});return kt.fromReadableStream(r)}function Xx(e){return typeof e=="object"&&e!==null&&typeof e[Symbol.iterator]=="function"&&typeof e.next=="function"}var fN=e=>e!=null&&typeof e=="object"&&"next"in e&&typeof e.next=="function";function bh(e){return typeof e=="object"&&e!==null&&typeof e[Symbol.asyncIterator]=="function"}function*Yx(e,t){for(;;){let{value:r,done:n}=Ze.runWithConfig(hr(e),t.next.bind(t),!0);if(n)break;yield r}}async function*wh(e,t){let r=t[Symbol.asyncIterator]();for(;;){let{value:n,done:i}=await Ze.runWithConfig(hr(e),r.next.bind(t),!0);if(i)break;yield n}}function Tt(e,t){return e&&!Array.isArray(e)&&!(e instanceof Date)&&typeof e=="object"?e:{[t]:e}}var ce=class extends vt{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 Ih({bound:this,kwargs:{},config:{},maxAttemptNumber:e?.stopAfterAttempt,...e})}withConfig(e){return new gn({bound:this,config:e,kwargs:{}})}withFallbacks(e){let t=Array.isArray(e)?e:e.fallbacks;return new Qx({runnable:this,fallbacks:t})}_getOptionsList(e,t=0){if(Array.isArray(e)&&e.length!==t)throw new 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($e);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(([n])=>n!=="runId"));return Array.from({length:t},(n,i)=>$e(i===0?e:r))}return Array.from({length:t},()=>$e(e))}async batch(e,t,r){let n=this._getOptionsList(t??{},e.length),i=n[0]?.maxConcurrency??r?.maxConcurrency,s=new Hi({maxConcurrency:i,onFailedAttempt:a=>{throw a}}),o=e.map((a,c)=>s.call(async()=>{try{return await this.invoke(a,n[c])}catch(u){if(r?.returnExceptions)return u;throw u}}));return Promise.all(o)}async*_streamIterator(e,t){yield this.invoke(e,t)}async stream(e,t){let r=$e(t),n=new Fs({generator:this._streamIterator(e,r),config:r});return await n.setup,kt.fromAsyncGenerator(n)}_separateRunnableConfigFromCallOptions(e){let t;e===void 0?t=$e(e):t=$e({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 n=$e(r),s=await(await Et(n))?.handleChainStart(this.toJSON(),Tt(t,"input"),n.runId,n?.runType,void 0,void 0,n?.runName??this.getName());delete n.runId;let o;try{let a=e.call(this,t,n,s);o=await ln(a,r?.signal)}catch(a){throw await s?.handleChainError(a),a}return await s?.handleChainEnd(Tt(o,"output")),o}async _batchWithConfig(e,t,r,n){let i=this._getOptionsList(r??{},t.length),s=await Promise.all(i.map(Et)),o=await Promise.all(s.map(async(c,u)=>{let l=await c?.handleChainStart(this.toJSON(),Tt(t[u],"input"),i[u].runId,i[u].runType,void 0,void 0,i[u].runName??this.getName());return delete i[u].runId,l})),a;try{let c=e.call(this,t,i,o,n);a=await ln(c,i?.[0]?.signal)}catch(c){throw await Promise.all(o.map(u=>u?.handleChainError(c))),c}return await Promise.all(o.map(c=>c?.handleChainEnd(Tt(a,"output")))),a}_concatOutputChunks(e,t){return Vr(e,t)}async*_transformStreamWithConfig(e,t,r){let n,i=!0,s,o=!0,a=$e(r),c=await Et(a),u=this;async function*l(){for await(let f of e){if(i)if(n===void 0)n=f;else try{n=u._concatOutputChunks(n,f)}catch{n=void 0,i=!1}yield f}}let p;try{let f=await Av(t.bind(this),l(),async()=>c?.handleChainStart(this.toJSON(),{input:""},a.runId,a.runType,void 0,void 0,a.runName??this.getName(),void 0,{lc_defers_inputs:!0}),r?.signal,a);delete a.runId,p=f.setup;let d=p?.handlers.find(lN),m=f.output;d!==void 0&&p!==void 0&&(m=d.tapOutputIterable(p.runId,m));let h=p?.handlers.find(Pv);h!==void 0&&p!==void 0&&(m=h.tapOutputIterable(p.runId,m));for await(let b of m)if(yield b,o)if(s===void 0)s=b;else try{s=this._concatOutputChunks(s,b)}catch{s=void 0,o=!1}}catch(f){throw await p?.handleChainError(f,void 0,void 0,void 0,{inputs:Tt(n,"input")}),f}await p?.handleChainEnd(s??{},void 0,void 0,void 0,{inputs:Tt(n,"input")})}getGraph(e){let t=new ya,r=t.addNode({name:`${this.getName()}Input`,schema:Ge.any()}),n=t.addNode(this),i=t.addNode({name:`${this.getName()}Output`,schema:Ge.any()});return t.addEdge(r,n),t.addEdge(n,i),t}pipe(e){return new br({first:this,last:dt(e)})}pick(e){return this.pipe(new e0(e))}assign(e){return this.pipe(new Op(new eo({steps:e})))}async*transform(e,t){let r;for await(let n of e)r===void 0?r=n:r=this._concatOutputChunks(r,n);yield*this._streamIterator(r,$e(t))}async*streamLog(e,t,r){let n=new gm({...r,autoClose:!1,_schemaFormat:"original"}),i=$e(t);yield*this._streamLog(e,n,i)}async*_streamLog(e,t,r){let{callbacks:n}=r;if(n===void 0)r.callbacks=[t];else if(Array.isArray(n))r.callbacks=n.concat([t]);else{let a=n.copy();a.addHandler(t,!0),r.callbacks=a}let i=this.stream(e,r);async function s(){try{let a=await i;for await(let c of a){let u=new ui({ops:[{op:"add",path:"/streamed_output/-",value:c}]});await t.writer.write(u)}}finally{await t.writer.close()}}let o=s();try{for await(let a of t)yield a}finally{await o}}streamEvents(e,t,r){let n;if(t.version==="v1")n=this._streamEventsV1(e,t,r);else if(t.version==="v2")n=this._streamEventsV2(e,t,r);else throw new Error('Only versions "v1" and "v2" of the schema are currently supported.');return t.encoding==="text/event-stream"?dN(n):kt.fromAsyncGenerator(n)}async*_streamEventsV2(e,t,r){let n=new pN({...r,autoClose:!1}),i=$e(t),s=i.runId??Ar();i.runId=s;let o=i.callbacks;if(o===void 0)i.callbacks=[n];else if(Array.isArray(o))i.callbacks=o.concat(n);else{let d=o.copy();d.addHandler(n,!0),i.callbacks=d}let a=new AbortController,c=this;async function u(){let d,m=null;try{t?.signal?"any"in AbortSignal?d=AbortSignal.any([a.signal,t.signal]):(d=t.signal,m=()=>{a.abort()},t.signal.addEventListener("abort",m,{once:!0})):d=a.signal;let h=await c.stream(e,{...i,signal:d}),b=n.tapOutputIterable(s,h);for await(let _ of b)if(a.signal.aborted)break}finally{await n.finish(),d&&m&&d.removeEventListener("abort",m)}}let l=u(),p=!1,f;try{for await(let d of n){if(!p){d.data.input=e,p=!0,f=d.run_id,yield d;continue}d.run_id===f&&d.event.endsWith("_end")&&d.data?.input&&delete d.data.input,yield d}}finally{a.abort(),await l}}async*_streamEventsV1(e,t,r){let n,i=!1,s=$e(t),o=s.tags??[],a=s.metadata??{},c=s.runName??this.getName(),u=new gm({...r,autoClose:!1,_schemaFormat:"streaming_events"}),l=new nN({...r}),p=this._streamLog(e,u,s);for await(let d of p){if(n?n=n.concat(d):n=hm.fromRunLogPatch(d),n.state===void 0)throw new Error('Internal error: "streamEvents" state is missing. Please open a bug report.');if(!i){i=!0;let _={...n.state},y={run_id:_.id,event:`on_${_.type}_start`,name:c,tags:o,metadata:a,data:{input:e}};l.includeEvent(y,_.type)&&(yield y)}let m=d.ops.filter(_=>_.path.startsWith("/logs/")).map(_=>_.path.split("/")[2]),h=[...new Set(m)];for(let _ of h){let y,x={},I=n.state.logs[_];if(I.end_time===void 0?I.streamed_output.length>0?y="stream":y="start":y="end",y==="start")I.inputs!==void 0&&(x.input=I.inputs);else if(y==="end")I.inputs!==void 0&&(x.input=I.inputs),x.output=I.final_output;else if(y==="stream"){let A=I.streamed_output.length;if(A!==1)throw new Error(`Expected exactly one chunk of streamed output, got ${A} instead. Encountered in: "${I.name}"`);x={chunk:I.streamed_output[0]},I.streamed_output=[]}yield{event:`on_${I.type}_${y}`,name:I.name,run_id:I.id,tags:I.tags,metadata:I.metadata,data:x}}let{state:b}=n;if(b.streamed_output.length>0){let _=b.streamed_output.length;if(_!==1)throw new Error(`Expected exactly one chunk of streamed output, got ${_} instead. Encountered in: "${b.name}"`);let y={chunk:b.streamed_output[0]};b.streamed_output=[];let x={event:`on_${b.type}_stream`,run_id:b.id,tags:o,metadata:a,name:c,data:y};l.includeEvent(x,b.type)&&(yield x)}}let f=n?.state;if(f!==void 0){let d={event:`on_${f.type}_end`,name:c,run_id:f.id,tags:o,metadata:a,data:{output:f.final_output}};l.includeEvent(d,f.type)&&(yield d)}}static isRunnable(e){return Ap(e)}withListeners({onStart:e,onEnd:t,onError:r}){return new gn({bound:this,config:{},configFactories:[n=>({callbacks:[new Jx({config:n,onStart:e,onEnd:t,onError:r})]})]})}asTool(e){return TZ(this,e)}},gn=class mN extends ce{static lc_name(){return"RunnableBinding"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;bound;config;kwargs;configFactories;constructor(t){super(t),this.bound=t.bound,this.kwargs=t.kwargs,this.config=t.config,this.configFactories=t.configFactories}getName(t){return this.bound.getName(t)}async _mergeConfig(...t){let r=Dt(this.config,...t);return Dt(r,...this.configFactories?await Promise.all(this.configFactories.map(async n=>await n(r))):[])}withConfig(t){return new this.constructor({bound:this.bound,kwargs:this.kwargs,config:{...this.config,...t}})}withRetry(t){return new Ih({bound:this.bound,kwargs:this.kwargs,config:this.config,maxAttemptNumber:t?.stopAfterAttempt,...t})}async invoke(t,r){return this.bound.invoke(t,await this._mergeConfig(r,this.kwargs))}async batch(t,r,n){let i=Array.isArray(r)?await Promise.all(r.map(async s=>this._mergeConfig($e(s),this.kwargs))):await this._mergeConfig($e(r),this.kwargs);return this.bound.batch(t,i,n)}_concatOutputChunks(t,r){return this.bound._concatOutputChunks(t,r)}async*_streamIterator(t,r){yield*this.bound._streamIterator(t,await this._mergeConfig($e(r),this.kwargs))}async stream(t,r){return this.bound.stream(t,await this._mergeConfig($e(r),this.kwargs))}async*transform(t,r){yield*this.bound.transform(t,await this._mergeConfig($e(r),this.kwargs))}streamEvents(t,r,n){let i=this,s=async function*(){yield*i.bound.streamEvents(t,{...await i._mergeConfig($e(r),i.kwargs),version:r.version},n)};return kt.fromAsyncGenerator(s())}static isRunnableBinding(t){return t.bound&&ce.isRunnable(t.bound)}withListeners({onStart:t,onEnd:r,onError:n}){return new mN({bound:this.bound,kwargs:this.kwargs,config:this.config,configFactories:[i=>({callbacks:[new Jx({config:i,onStart:t,onEnd:r,onError:n})]})]})}},hN=class gN extends ce{static lc_name(){return"RunnableEach"}lc_serializable=!0;lc_namespace=["langchain_core","runnables"];bound;constructor(t){super(t),this.bound=t.bound}async invoke(t,r){return this._callWithConfig(this._invoke.bind(this),t,r)}async _invoke(t,r,n){return this.bound.batch(t,Ne(r,{callbacks:n?.getChild()}))}withListeners({onStart:t,onEnd:r,onError:n}){return new gN({bound:this.bound.withListeners({onStart:t,onEnd:r,onError:n})})}},Ih=class extends gn{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 n=e>1?`retry:attempt:${e}`:void 0;return Ne(t,{callbacks:r?.getChild(n)})}async _invoke(e,t,r){return Fl(n=>super.invoke(e,this._patchConfigForRetry(n,t,r)),{onFailedAttempt:({error:n})=>this.onFailedAttempt(n,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,n){let i={};try{await Fl(async s=>{let o=e.map((p,f)=>f).filter(p=>i[p.toString()]===void 0||i[p.toString()]instanceof Error),a=o.map(p=>e[p]),c=o.map(p=>this._patchConfigForRetry(s,t?.[p],r?.[p])),u=await super.batch(a,c,{...n,returnExceptions:!0}),l;for(let p=0;p<u.length;p+=1){let f=u[p],d=o[p];f instanceof Error&&l===void 0&&(l=f,l.input=a[p]),i[d.toString()]=f}if(l)throw l;return u},{onFailedAttempt:({error:s})=>this.onFailedAttempt(s,s.input),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}catch(s){if(n?.returnExceptions!==!0)throw s}return Object.keys(i).sort((s,o)=>parseInt(s,10)-parseInt(o,10)).map(s=>i[parseInt(s,10)])}async batch(e,t,r){return this._batchWithConfig(this._batch.bind(this),e,t,r)}},br=class Tp extends ce{static lc_name(){return"RunnableSequence"}first;middle=[];last;omitSequenceTags=!1;lc_serializable=!0;lc_namespace=["langchain_core","runnables"];constructor(t){super(t),this.first=t.first,this.middle=t.middle??this.middle,this.last=t.last,this.name=t.name,this.omitSequenceTags=t.omitSequenceTags??this.omitSequenceTags}get steps(){return[this.first,...this.middle,this.last]}async invoke(t,r){let n=$e(r),s=await(await Et(n))?.handleChainStart(this.toJSON(),Tt(t,"input"),n.runId,void 0,void 0,void 0,n?.runName);delete n.runId;let o=t,a;try{let c=[this.first,...this.middle];for(let u=0;u<c.length;u+=1){let p=c[u].invoke(o,Ne(n,{callbacks:s?.getChild(this.omitSequenceTags?void 0:`seq:step:${u+1}`)}));o=await ln(p,r?.signal)}if(r?.signal?.aborted)throw Us(r.signal);a=await this.last.invoke(o,Ne(n,{callbacks:s?.getChild(this.omitSequenceTags?void 0:`seq:step:${this.steps.length}`)}))}catch(c){throw await s?.handleChainError(c),c}return await s?.handleChainEnd(Tt(a,"output")),a}async batch(t,r,n){let i=this._getOptionsList(r??{},t.length),s=await Promise.all(i.map(Et)),o=await Promise.all(s.map(async(c,u)=>{let l=await c?.handleChainStart(this.toJSON(),Tt(t[u],"input"),i[u].runId,void 0,void 0,void 0,i[u].runName);return delete i[u].runId,l})),a=t;try{for(let c=0;c<this.steps.length;c+=1){let l=this.steps[c].batch(a,o.map((p,f)=>{let d=p?.getChild(this.omitSequenceTags?void 0:`seq:step:${c+1}`);return Ne(i[f],{callbacks:d})}),n);a=await ln(l,i[0]?.signal)}}catch(c){throw await Promise.all(o.map(u=>u?.handleChainError(c))),c}return await Promise.all(o.map(c=>c?.handleChainEnd(Tt(a,"output")))),a}_concatOutputChunks(t,r){return this.last._concatOutputChunks(t,r)}async*_streamIterator(t,r){let n=await Et(r),{runId:i,...s}=r??{},o=await n?.handleChainStart(this.toJSON(),Tt(t,"input"),i,void 0,void 0,void 0,s?.runName),a=[this.first,...this.middle,this.last],c=!0,u;async function*l(){yield t}try{let p=a[0].transform(l(),Ne(s,{callbacks:o?.getChild(this.omitSequenceTags?void 0:"seq:step:1")}));for(let f=1;f<a.length;f+=1)p=await a[f].transform(p,Ne(s,{callbacks:o?.getChild(this.omitSequenceTags?void 0:`seq:step:${f+1}`)}));for await(let f of p)if(r?.signal?.throwIfAborted(),yield f,c)if(u===void 0)u=f;else try{u=this._concatOutputChunks(u,f)}catch{u=void 0,c=!1}}catch(p){throw await o?.handleChainError(p),p}await o?.handleChainEnd(Tt(u,"output"))}getGraph(t){let r=new ya,n=null;return this.steps.forEach((i,s)=>{let o=i.getGraph(t);s!==0&&o.trimFirstNode(),s!==this.steps.length-1&&o.trimLastNode(),r.extend(o);let a=o.firstNode();if(!a)throw new Error(`Runnable ${i} has no first node`);n&&r.addEdge(n,a),n=o.lastNode()}),r}pipe(t){return Tp.isRunnableSequence(t)?new Tp({first:this.first,middle:this.middle.concat([this.last,t.first,...t.middle]),last:t.last,name:this.name??t.name}):new Tp({first:this.first,middle:[...this.middle,this.last],last:dt(t),name:this.name})}static isRunnableSequence(t){return Array.isArray(t.middle)&&ce.isRunnable(t)}static from([t,...r],n){let i={};return typeof n=="string"?i.name=n:n!==void 0&&(i=n),new Tp({...i,first:dt(t),middle:r.slice(0,-1).map(dt),last:dt(r[r.length-1])})}},eo=class _N extends ce{static lc_name(){return"RunnableMap"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;steps;getStepsKeys(){return Object.keys(this.steps)}constructor(t){super(t),this.steps={};for(let[r,n]of Object.entries(t.steps))this.steps[r]=dt(n)}static from(t){return new _N({steps:t})}async invoke(t,r){let n=$e(r),s=await(await Et(n))?.handleChainStart(this.toJSON(),{input:t},n.runId,void 0,void 0,void 0,n?.runName);delete n.runId;let o={};try{let a=Object.entries(this.steps).map(async([c,u])=>{o[c]=await u.invoke(t,Ne(n,{callbacks:s?.getChild(`map:key:${c}`)}))});await ln(Promise.all(a),r?.signal)}catch(a){throw await s?.handleChainError(a),a}return await s?.handleChainEnd(o),o}async*_transform(t,r,n){let i={...this.steps},s=om(t,Object.keys(i).length),o=new Map(Object.entries(i).map(([a,c],u)=>{let l=c.transform(s[u],Ne(n,{callbacks:r?.getChild(`map:key:${a}`)}));return[a,l.next().then(p=>({key:a,gen:l,result:p}))]}));for(;o.size;){let a=Promise.race(o.values()),{key:c,result:u,gen:l}=await ln(a,n?.signal);o.delete(c),u.done||(yield{[c]:u.value},o.set(c,l.next().then(p=>({key:c,gen:l,result:p}))))}}transform(t,r){return this._transformStreamWithConfig(t,this._transform.bind(this),r)}async stream(t,r){async function*n(){yield t}let i=$e(r),s=new Fs({generator:this.transform(n(),i),config:i});return await s.setup,kt.fromAsyncGenerator(s)}},kZ=class yN extends ce{lc_serializable=!1;lc_namespace=["langchain_core","runnables"];func;constructor(t){if(super(t),!nm(t.func))throw new Error("RunnableTraceable requires a function that is wrapped in traceable higher-order function");this.func=t.func}async invoke(t,r){let[n]=this._getOptionsList(r??{},1),i=await Et(n),s=this.func(Ne(n,{callbacks:i}),t);return ln(s,n?.signal)}async*_streamIterator(t,r){let[n]=this._getOptionsList(r??{},1),i=await this.invoke(t,r);if(bh(i)){for await(let s of i)n?.signal?.throwIfAborted(),yield s;return}if(fN(i)){for(;;){n?.signal?.throwIfAborted();let s=i.next();if(s.done)break;yield s.value}return}yield i}static from(t){return new yN({func:t})}};function AZ(e){if(nm(e))throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.")}var tr=class vN extends ce{static lc_name(){return"RunnableLambda"}lc_namespace=["langchain_core","runnables"];func;constructor(t){if(nm(t.func))return kZ.from(t.func);super(t),AZ(t.func),this.func=t.func}static from(t){return new vN({func:t})}async _invoke(t,r,n){return new Promise((i,s)=>{let o=Ne(r,{callbacks:n?.getChild(),recursionLimit:(r?.recursionLimit??sm)-1});Ze.runWithConfig(hr(o),async()=>{try{let a=await this.func(t,{...o});if(a&&ce.isRunnable(a)){if(r?.recursionLimit===0)throw new Error("Recursion limit reached.");a=await a.invoke(t,{...o,recursionLimit:(o.recursionLimit??sm)-1})}else if(bh(a)){let c;for await(let u of wh(o,a))if(r?.signal?.throwIfAborted(),c===void 0)c=u;else try{c=this._concatOutputChunks(c,u)}catch{c=u}a=c}else if(Xx(a)){let c;for(let u of Yx(o,a))if(r?.signal?.throwIfAborted(),c===void 0)c=u;else try{c=this._concatOutputChunks(c,u)}catch{c=u}a=c}i(a)}catch(a){s(a)}})})}async invoke(t,r){return this._callWithConfig(this._invoke.bind(this),t,r)}async*_transform(t,r,n){let i;for await(let a of t)if(i===void 0)i=a;else try{i=this._concatOutputChunks(i,a)}catch{i=a}let s=Ne(n,{callbacks:r?.getChild(),recursionLimit:(n?.recursionLimit??sm)-1}),o=await new Promise((a,c)=>{Ze.runWithConfig(hr(s),async()=>{try{let u=await this.func(i,{...s,config:s});a(u)}catch(u){c(u)}})});if(o&&ce.isRunnable(o)){if(n?.recursionLimit===0)throw new Error("Recursion limit reached.");let a=await o.stream(i,s);for await(let c of a)yield c}else if(bh(o))for await(let a of wh(s,o))n?.signal?.throwIfAborted(),yield a;else if(Xx(o))for(let a of Yx(s,o))n?.signal?.throwIfAborted(),yield a;else yield o}transform(t,r){return this._transformStreamWithConfig(t,this._transform.bind(this),r)}async stream(t,r){async function*n(){yield t}let i=$e(r),s=new Fs({generator:this.transform(n(),i),config:i});return await s.setup,kt.fromAsyncGenerator(s)}},bN=class extends eo{},Qx=class extends ce{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(){yield this.runnable;for(let e of this.fallbacks)yield e}async invoke(e,t){let r=$e(t),n=await Et(r),{runId:i,...s}=r,o=await n?.handleChainStart(this.toJSON(),Tt(e,"input"),i,void 0,void 0,void 0,s?.runName),a=Ne(s,{callbacks:o?.getChild()});return await Ze.runWithConfig(a,async()=>{let u;for(let l of this.runnables()){r?.signal?.throwIfAborted();try{let p=await l.invoke(e,a);return await o?.handleChainEnd(Tt(p,"output")),p}catch(p){u===void 0&&(u=p)}}throw u===void 0?new Error("No error stored at end of fallback."):(await o?.handleChainError(u),u)})}async*_streamIterator(e,t){let r=$e(t),n=await Et(r),{runId:i,...s}=r,o=await n?.handleChainStart(this.toJSON(),Tt(e,"input"),i,void 0,void 0,void 0,s?.runName),a,c;for(let l of this.runnables()){r?.signal?.throwIfAborted();let p=Ne(s,{callbacks:o?.getChild()});try{let f=await l.stream(e,p);c=wh(p,f);break}catch(f){a===void 0&&(a=f)}}if(c===void 0){let l=a??new Error("No error stored at end of fallback.");throw await o?.handleChainError(l),l}let u;try{for await(let l of c){yield l;try{u=u===void 0?u:this._concatOutputChunks(u,l)}catch{u=void 0}}}catch(l){throw await o?.handleChainError(l),l}await o?.handleChainEnd(Tt(u,"output"))}async batch(e,t,r){if(r?.returnExceptions)throw new Error("Not implemented.");let n=this._getOptionsList(t??{},e.length),i=await Promise.all(n.map(a=>Et(a))),s=await Promise.all(i.map(async(a,c)=>{let u=await a?.handleChainStart(this.toJSON(),Tt(e[c],"input"),n[c].runId,void 0,void 0,void 0,n[c].runName);return delete n[c].runId,u})),o;for(let a of this.runnables()){n[0].signal?.throwIfAborted();try{let c=await a.batch(e,s.map((u,l)=>Ne(n[l],{callbacks:u?.getChild()})),r);return await Promise.all(s.map((u,l)=>u?.handleChainEnd(Tt(c[l],"output")))),c}catch(c){o===void 0&&(o=c)}}throw o?(await Promise.all(s.map(a=>a?.handleChainError(o))),o):new Error("No error stored at end of fallbacks.")}};function dt(e){if(typeof e=="function")return new tr({func:e});if(ce.isRunnable(e))return e;if(!Array.isArray(e)&&typeof e=="object"){let t={};for(let[r,n]of Object.entries(e))t[r]=dt(n);return new eo({steps:t})}else throw new Error(`Expected a Runnable, function or object.
|
|
109
|
+
Instead got an unsupported type.`)}var Op=class extends ce{static lc_name(){return"RunnableAssign"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;mapper;constructor(e){e instanceof eo&&(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 n=this.mapper.getStepsKeys(),[i,s]=om(e),o=this.mapper.transform(s,Ne(r,{callbacks:t?.getChild()})),a=o.next();for await(let c of i){if(typeof c!="object"||Array.isArray(c))throw new Error(`RunnableAssign can only be used with objects as input, got ${typeof c}`);let u=Object.fromEntries(Object.entries(c).filter(([l])=>!n.includes(l)));Object.keys(u).length>0&&(yield u)}yield(await a).value;for await(let c of o)yield c}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*r(){yield e}let n=$e(t),i=new Fs({generator:this.transform(r(),n),config:n});return await i.setup,kt.fromAsyncGenerator(i)}},e0=class extends ce{static lc_name(){return"RunnablePick"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;keys;constructor(e){(typeof e=="string"||Array.isArray(e))&&(e={keys:e}),super(e),this.keys=e.keys}async _pick(e){if(typeof this.keys=="string")return e[this.keys];{let t=this.keys.map(r=>[r,e[r]]).filter(r=>r[1]!==void 0);return t.length===0?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 r=await this._pick(t);r!==void 0&&(yield r)}}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*r(){yield e}let n=$e(t),i=new Fs({generator:this.transform(r(),n),config:n});return await i.setup,kt.fromAsyncGenerator(i)}},xh=class extends gn{name;description;schema;constructor(e){let t=br.from([tr.from(async r=>{let n;if(Ds(r))try{n=await Ws(this.schema,r.args)}catch{throw new gc("Received tool input did not match expected schema",JSON.stringify(r.args))}else n=r;return n}).withConfig({runName:`${e.name}:parse_input`}),e.bound]).withConfig({runName:e.name});super({bound:t,config:e.config??{}}),this.name=e.name,this.description=e.description,this.schema=e.schema}static lc_name(){return"RunnableToolLike"}};function TZ(e,t){let r=t.name??e.getName(),n=t.description??$n(t.schema);return Cc(t.schema)?new xh({name:r,description:n,schema:Ge.object({input:Ge.string()}).transform(i=>i.input),bound:e}):new xh({name:r,description:n,schema:t.schema,bound:e})}var Sh=(e,t)=>{let r=[...new Set(t?.map(i=>{if(typeof i=="string")return i;let s=new i({});if(!("getType"in s)||typeof s.getType!="function")throw new Error("Invalid type provided.");return s.getType()}))],n=e.getType();return r.some(i=>i===n)};function EN(e,t){return Array.isArray(e)?wN(e,t):tr.from(r=>wN(r,e))}function wN(e,t={}){let{includeNames:r,excludeNames:n,includeTypes:i,excludeTypes:s,includeIds:o,excludeIds:a}=t,c=[];for(let u of e)if(!(n&&u.name&&n.includes(u.name))){{if(s&&Sh(u,s))continue;if(a&&u.id&&a.includes(u.id))continue}i||o||r?(r&&u.name&&r.some(l=>l===u.name)||i&&Sh(u,i)||o&&u.id&&o.some(l=>l===u.id))&&c.push(u):c.push(u)}return c}function kN(e){return Array.isArray(e)?xN(e):tr.from(xN)}function xN(e){if(!e.length)return[];let t=[];for(let r of e){let n=r,i=t.pop();if(!i)t.push(n);else if(n.getType()==="tool"||n.getType()!==i.getType())t.push(i,n);else{let s=Uo(i),o=Uo(n),a=s.concat(o);typeof s.content=="string"&&typeof o.content=="string"&&(a.content=`${s.content}
|
|
110
|
+
${o.content}`),t.push($Z(a))}}return t}function AN(e,t){if(Array.isArray(e)){let r=e;if(!t)throw new Error("Options parameter is required when providing messages.");return IN(r,t)}else{let r=e;return tr.from(n=>IN(n,r)).withConfig({runName:"trim_messages"})}}async function IN(e,t){let{maxTokens:r,tokenCounter:n,strategy:i="last",allowPartial:s=!1,endOn:o,startOn:a,includeSystem:c=!1,textSplitter:u}=t;if(a&&i==="first")throw new Error("`startOn` should only be specified if `strategy` is 'last'.");if(c&&i==="first")throw new Error("`includeSystem` should only be specified if `strategy` is 'last'.");let l;"getNumTokens"in n?l=async f=>(await Promise.all(f.map(m=>n.getNumTokens(m.content)))).reduce((m,h)=>m+h,0):l=async f=>n(f);let p=r0;if(u&&("splitText"in u?p=u.splitText:p=async f=>u(f)),i==="first")return TN(e,{maxTokens:r,tokenCounter:l,textSplitter:p,partialStrategy:s?"first":void 0,endOn:o});if(i==="last")return OZ(e,{maxTokens:r,tokenCounter:l,textSplitter:p,allowPartial:s,includeSystem:c,startOn:a,endOn:o});throw new Error(`Unrecognized strategy: '${i}'. Must be one of 'first' or 'last'.`)}async function TN(e,t){let{maxTokens:r,tokenCounter:n,textSplitter:i,partialStrategy:s,endOn:o}=t,a=[...e],c=0;for(let u=0;u<a.length;u+=1){let l=u>0?a.slice(0,-u):a;if(await n(l)<=r){c=a.length-u;break}}if(c<a.length&&s){let u=!1;if(Array.isArray(a[c].content)){let l=a[c];if(typeof l.content=="string")throw new Error("Expected content to be an array.");let p=l.content.length,f=s==="last"?[...l.content].reverse():l.content;for(let d=1;d<=p;d+=1){let m=s==="first"?f.slice(0,d):f.slice(-d),h=Object.fromEntries(Object.entries(l).filter(([y])=>y!=="type"&&!y.startsWith("lc_"))),b=t0(l.getType(),{...h,content:m}),_=[...a.slice(0,c),b];if(await n(_)<=r)a=_,c+=1,u=!0;else break}u&&s==="last"&&(l.content=[...f].reverse())}if(!u){let l=a[c],p;if(Array.isArray(l.content)&&l.content.some(f=>typeof f=="string"||f.type==="text")?p=l.content.find(d=>d.type==="text"&&d.text)?.text:typeof l.content=="string"&&(p=l.content),p){let f=await i(p),d=f.length;s==="last"&&f.reverse();for(let m=0;m<d-1;m+=1)if(f.pop(),l.content=f.join(""),await n([...a.slice(0,c),l])<=r){s==="last"&&(l.content=[...f].reverse().join("")),a=[...a.slice(0,c),l],c+=1;break}}}}if(o){let u=Array.isArray(o)?o:[o];for(;c>0&&!Sh(a[c-1],u);)c-=1}return a.slice(0,c)}async function OZ(e,t){let{allowPartial:r=!1,includeSystem:n=!1,endOn:i,startOn:s,...o}=t,a=e.map(l=>{let p=Object.fromEntries(Object.entries(l).filter(([f])=>f!=="type"&&!f.startsWith("lc_")));return t0(l.getType(),p,Ui(l))});if(i){let l=Array.isArray(i)?i:[i];for(;a.length>0&&!Sh(a[a.length-1],l);)a=a.slice(0,-1)}let c=n&&a[0]?.getType()==="system",u=c?a.slice(0,1).concat(a.slice(1).reverse()):a.reverse();return u=await TN(u,{...o,partialStrategy:r?"last":void 0,endOn:s}),c?[u[0],...u.slice(1).reverse()]:u.reverse()}var SN={human:{message:at,messageChunk:Ki},ai:{message:Oe,messageChunk:nt},system:{message:Br,messageChunk:un},developer:{message:Br,messageChunk:un},tool:{message:Wt,messageChunk:Rs},function:{message:Lo,messageChunk:Gi},generic:{message:mr,messageChunk:Zi},remove:{message:On,messageChunk:On}};function t0(e,t,r){let n,i;switch(e){case"human":r?n=new Ki(t):i=new at(t);break;case"ai":if(r){let s={...t};"tool_calls"in s&&(s={...s,tool_call_chunks:s.tool_calls?.map(o=>({...o,type:"tool_call_chunk",index:void 0,args:JSON.stringify(o.args)}))}),n=new nt(s)}else i=new Oe(t);break;case"system":r?n=new un(t):i=new Br(t);break;case"developer":r?n=new un({...t,additional_kwargs:{...t.additional_kwargs,__openai_role__:"developer"}}):i=new Br({...t,additional_kwargs:{...t.additional_kwargs,__openai_role__:"developer"}});break;case"tool":if("tool_call_id"in t)r?n=new Rs(t):i=new Wt(t);else throw new Error("Can not convert ToolMessage to ToolMessageChunk if 'tool_call_id' field is not defined.");break;case"function":if(r)n=new Gi(t);else{if(!t.name)throw new Error("FunctionMessage must have a 'name' field");i=new Lo(t)}break;case"generic":if("role"in t)r?n=new Zi(t):i=new mr(t);else throw new Error("Can not convert ChatMessage to ChatMessageChunk if 'role' field is not defined.");break;default:throw new Error(`Unrecognized message type ${e}`)}if(r&&n)return n;if(i)return i;throw new Error(`Unrecognized message type ${e}`)}function $Z(e){let t=e.getType(),r,n=Object.fromEntries(Object.entries(e).filter(([i])=>!["type","tool_call_chunks"].includes(i)&&!i.startsWith("lc_")));if(t in SN&&(r=t0(t,n)),!r)throw new Error(`Unrecognized message chunk class ${t}. Supported classes are ${Object.keys(SN)}`);return r}function r0(e){let t=e.split(`
|
|
111
|
+
`);return Promise.resolve([...t.slice(0,-1).map(r=>`${r}
|
|
112
|
+
`),t[t.length-1]])}var ON=["tool_call","tool_call_chunk","invalid_tool_call","server_tool_call","server_tool_call_chunk","server_tool_call_result"];var $N=["image","video","audio","text-plain","file"];var CN=["text","reasoning",...ON,...$N];var n0={};M(n0,{AIMessage:()=>Oe,AIMessageChunk:()=>nt,BaseMessage:()=>bt,BaseMessageChunk:()=>ur,ChatMessage:()=>mr,ChatMessageChunk:()=>Zi,DEFAULT_MERGE_IGNORE_KEYS:()=>ty,FunctionMessage:()=>Lo,FunctionMessageChunk:()=>Gi,HumanMessage:()=>at,HumanMessageChunk:()=>Ki,KNOWN_BLOCK_TYPES:()=>CN,RemoveMessage:()=>On,SystemMessage:()=>Br,SystemMessageChunk:()=>un,ToolMessage:()=>Wt,ToolMessageChunk:()=>Rs,_isMessageFieldWithRole:()=>vf,_mergeDicts:()=>st,_mergeLists:()=>Mo,_mergeObj:()=>yf,_mergeStatus:()=>_f,coerceMessageLikeToMessage:()=>Qt,collapseToolCallChunks:()=>tm,convertToChunk:()=>Uo,convertToOpenAIImageBlock:()=>ff,convertToProviderContentBlock:()=>dc,defaultTextSplitter:()=>r0,defaultToolCallParser:()=>yl,filterMessages:()=>EN,getBufferString:()=>_c,iife:()=>em,isAIMessage:()=>ci,isAIMessageChunk:()=>jl,isBase64ContentBlock:()=>pc,isBaseMessage:()=>ot,isBaseMessageChunk:()=>Ui,isChatMessage:()=>y$,isChatMessageChunk:()=>v$,isDataContentBlock:()=>Tr,isDirectToolOutput:()=>_l,isFunctionMessage:()=>b$,isFunctionMessageChunk:()=>w$,isHumanMessage:()=>x$,isHumanMessageChunk:()=>I$,isIDContentBlock:()=>df,isMessage:()=>gf,isOpenAIToolCallArray:()=>Wk,isPlainTextContentBlock:()=>zk,isSystemMessage:()=>S$,isSystemMessageChunk:()=>E$,isToolMessage:()=>jo,isToolMessageChunk:()=>ny,isURLContentBlock:()=>lc,mapChatMessagesToStoredMessages:()=>A$,mapStoredMessageToChatMessage:()=>Ml,mapStoredMessagesToChatMessages:()=>k$,mergeContent:()=>Ht,mergeMessageRuns:()=>kN,mergeResponseMetadata:()=>Yf,mergeUsageMetadata:()=>hc,parseBase64DataUrl:()=>Ns,parseMimeType:()=>gl,trimMessages:()=>AN});var i0={};M(i0,{BaseChatMessageHistory:()=>s0,BaseListChatMessageHistory:()=>Eh,InMemoryChatMessageHistory:()=>CZ});var s0=class extends vt{async addMessages(e){for(let t of e)await this.addMessage(t)}},Eh=class extends vt{addUserMessage(e){return this.addMessage(new at(e))}addAIMessage(e){return this.addMessage(new Oe(e))}async addMessages(e){for(let t of e)await this.addMessage(t)}clear(){throw new Error("Not implemented.")}},CZ=class extends Eh{lc_namespace=["langchain","stores","message","in_memory"];messages=[];constructor(e){super(...arguments),this.messages=e??[]}async getMessages(){return this.messages}async addMessage(e){this.messages.push(e)}async clear(){this.messages=[]}};var o0={};M(o0,{Embeddings:()=>Bc});var Bc=class{caller;constructor(e){this.caller=new Hi(e??{})}};var PN={};var a0={};M(a0,{BaseMemory:()=>PZ,getInputValue:()=>NZ,getOutputValue:()=>RZ,getPromptInputKey:()=>MZ});var PZ=class{},NN=(e,t)=>{if(t!==void 0)return e[t];let r=Object.keys(e);if(r.length===1)return e[r[0]]},NZ=(e,t)=>{let r=NN(e,t);if(!r){let n=Object.keys(e);throw new Error(`input values have ${n.length} keys, you must specify an input key or pass only 1 key as input`)}return r},RZ=(e,t)=>{let r=NN(e,t);if(!r&&r!==""){let n=Object.keys(e);throw new Error(`output values have ${n.length} keys, you must specify an output key or pass only 1 key as output`)}return r};function MZ(e,t){let r=Object.keys(e).filter(n=>!t.includes(n)&&n!=="stop");if(r.length!==1)throw new Error(`One input key expected, but got ${r.length}`);return r[0]}var c0={};M(c0,{BasePromptValue:()=>kh,ChatPromptValue:()=>Cp,ImagePromptValue:()=>u0,StringPromptValue:()=>$p});var kh=class extends vt{},$p=class extends kh{static lc_name(){return"StringPromptValue"}lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;value;constructor(e){super({value:e}),this.value=e}toString(){return this.value}toChatMessages(){return[new at(this.value)]}},Cp=class extends kh{lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;static lc_name(){return"ChatPromptValue"}messages;constructor(e){Array.isArray(e)&&(e={messages:e}),super(e),this.messages=e.messages}toString(){return _c(this.messages)}toChatMessages(){return this.messages}},u0=class extends kh{lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;static lc_name(){return"ImagePromptValue"}imageUrl;value;constructor(e){"imageUrl"in e||(e={imageUrl:e}),super(e),this.imageUrl=e.imageUrl}toString(){return this.imageUrl.url}toChatMessages(){return[new at({content:[{type:"image_url",image_url:{detail:this.imageUrl.detail,url:this.imageUrl.url}}]})]}};var l0={};M(l0,{BaseStore:()=>RN,InMemoryStore:()=>jZ});var RN=class extends vt{},jZ=class extends RN{lc_namespace=["langchain","storage"];store={};async mget(e){return e.map(t=>this.store[t])}async mset(e){for(let[t,r]of e)this.store[t]=r}async mdelete(e){for(let t of e)delete this.store[t]}async*yieldKeys(e){let t=Object.keys(this.store);for(let r of t)(e===void 0||r.startsWith(e))&&(yield r)}};var p0={};M(p0,{BaseRetriever:()=>Pp});var Pp=class extends ce{callbacks;tags;metadata;verbose;constructor(e){super(e),this.callbacks=e?.callbacks,this.tags=e?.tags??[],this.metadata=e?.metadata??{},this.verbose=e?.verbose??!1}_getRelevantDocuments(e,t){throw new Error("Not implemented!")}async invoke(e,t){let r=$e(Bo(t)),i=await(await xt.configure(r.callbacks,this.callbacks,r.tags,this.tags,r.metadata,this.metadata,{verbose:this.verbose}))?.handleRetrieverStart(this.toJSON(),e,r.runId,void 0,void 0,void 0,r.runName);try{let s=await this._getRelevantDocuments(e,i);return await i?.handleRetrieverEnd(s),s}catch(s){throw await i?.handleRetrieverError(s),s}}};var d0={};M(d0,{SaveableVectorStore:()=>DZ,VectorStore:()=>Th,VectorStoreRetriever:()=>Ah});var Ah=class extends Pp{static lc_name(){return"VectorStoreRetriever"}get lc_namespace(){return["langchain_core","vectorstores"]}vectorStore;k=4;searchType="similarity";searchKwargs;filter;_vectorstoreType(){return this.vectorStore._vectorstoreType()}constructor(e){super(e),this.vectorStore=e.vectorStore,this.k=e.k??this.k,this.searchType=e.searchType??this.searchType,this.filter=e.filter,e.searchType==="mmr"&&(this.searchKwargs=e.searchKwargs)}async _getRelevantDocuments(e,t){if(this.searchType==="mmr"){if(typeof this.vectorStore.maxMarginalRelevanceSearch!="function")throw new Error(`The vector store backing this retriever, ${this._vectorstoreType()} does not support max marginal relevance search.`);return this.vectorStore.maxMarginalRelevanceSearch(e,{k:this.k,filter:this.filter,...this.searchKwargs},t?.getChild("vectorstore"))}return this.vectorStore.similaritySearch(e,this.k,this.filter,t?.getChild("vectorstore"))}async addDocuments(e,t){return this.vectorStore.addDocuments(e,t)}},Th=class extends vt{lc_namespace=["langchain","vectorstores",this._vectorstoreType()];embeddings;constructor(e,t){super(t),this.embeddings=e}async delete(e){throw new Error("Not implemented.")}async similaritySearch(e,t=4,r=void 0,n=void 0){return(await this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(e),t,r)).map(s=>s[0])}async similaritySearchWithScore(e,t=4,r=void 0,n=void 0){return this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(e),t,r)}static fromTexts(e,t,r,n){throw new Error("the Langchain vectorstore implementation you are using forgot to override this, please report a bug")}static fromDocuments(e,t,r){throw new Error("the Langchain vectorstore implementation you are using forgot to override this, please report a bug")}asRetriever(e,t,r,n,i,s){if(typeof e=="number")return new Ah({vectorStore:this,k:e,filter:t,tags:[...n??[],this._vectorstoreType()],metadata:i,verbose:s,callbacks:r});{let o={vectorStore:this,k:e?.k,filter:e?.filter,tags:[...e?.tags??[],this._vectorstoreType()],metadata:e?.metadata,verbose:e?.verbose,callbacks:e?.callbacks,searchType:e?.searchType};return e?.searchType==="mmr"?new Ah({...o,searchKwargs:e.searchKwargs}):new Ah({...o})}}},DZ=class extends Th{static load(e,t){throw new Error("Not implemented")}};var te="0123456789abcdef".split(""),zZ=[-2147483648,8388608,32768,128],Mn=[24,16,8,0],Oh=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],zt=[];function jn(e,t){t?(zt[0]=zt[16]=zt[1]=zt[2]=zt[3]=zt[4]=zt[5]=zt[6]=zt[7]=zt[8]=zt[9]=zt[10]=zt[11]=zt[12]=zt[13]=zt[14]=zt[15]=0,this.blocks=zt):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],e?(this.h0=3238371032,this.h1=914150663,this.h2=812702999,this.h3=4144912697,this.h4=4290775857,this.h5=1750603025,this.h6=1694076839,this.h7=3204075428):(this.h0=1779033703,this.h1=3144134277,this.h2=1013904242,this.h3=2773480762,this.h4=1359893119,this.h5=2600822924,this.h6=528734635,this.h7=1541459225),this.block=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0,this.is224=e}jn.prototype.update=function(e){if(!this.finalized){var t,r=typeof e;if(r!=="string"){if(r==="object"){if(e===null)throw new Error(ERROR);if(ARRAY_BUFFER&&e.constructor===ArrayBuffer)e=new Uint8Array(e);else if(!Array.isArray(e)&&(!ARRAY_BUFFER||!ArrayBuffer.isView(e)))throw new Error(ERROR)}else throw new Error(ERROR);t=!0}for(var n,i=0,s,o=e.length,a=this.blocks;i<o;){if(this.hashed&&(this.hashed=!1,a[0]=this.block,this.block=a[16]=a[1]=a[2]=a[3]=a[4]=a[5]=a[6]=a[7]=a[8]=a[9]=a[10]=a[11]=a[12]=a[13]=a[14]=a[15]=0),t)for(s=this.start;i<o&&s<64;++i)a[s>>>2]|=e[i]<<Mn[s++&3];else for(s=this.start;i<o&&s<64;++i)n=e.charCodeAt(i),n<128?a[s>>>2]|=n<<Mn[s++&3]:n<2048?(a[s>>>2]|=(192|n>>>6)<<Mn[s++&3],a[s>>>2]|=(128|n&63)<<Mn[s++&3]):n<55296||n>=57344?(a[s>>>2]|=(224|n>>>12)<<Mn[s++&3],a[s>>>2]|=(128|n>>>6&63)<<Mn[s++&3],a[s>>>2]|=(128|n&63)<<Mn[s++&3]):(n=65536+((n&1023)<<10|e.charCodeAt(++i)&1023),a[s>>>2]|=(240|n>>>18)<<Mn[s++&3],a[s>>>2]|=(128|n>>>12&63)<<Mn[s++&3],a[s>>>2]|=(128|n>>>6&63)<<Mn[s++&3],a[s>>>2]|=(128|n&63)<<Mn[s++&3]);this.lastByteIndex=s,this.bytes+=s-this.start,s>=64?(this.block=a[16],this.start=s-64,this.hash(),this.hashed=!0):this.start=s}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this}};jn.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var e=this.blocks,t=this.lastByteIndex;e[16]=this.block,e[t>>>2]|=zZ[t&3],this.block=e[16],t>=56&&(this.hashed||this.hash(),e[0]=this.block,e[16]=e[1]=e[2]=e[3]=e[4]=e[5]=e[6]=e[7]=e[8]=e[9]=e[10]=e[11]=e[12]=e[13]=e[14]=e[15]=0),e[14]=this.hBytes<<3|this.bytes>>>29,e[15]=this.bytes<<3,this.hash()}};jn.prototype.hash=function(){var e=this.h0,t=this.h1,r=this.h2,n=this.h3,i=this.h4,s=this.h5,o=this.h6,a=this.h7,c=this.blocks,u,l,p,f,d,m,h,b,_,y,x;for(u=16;u<64;++u)d=c[u-15],l=(d>>>7|d<<25)^(d>>>18|d<<14)^d>>>3,d=c[u-2],p=(d>>>17|d<<15)^(d>>>19|d<<13)^d>>>10,c[u]=c[u-16]+l+c[u-7]+p<<0;for(x=t&r,u=0;u<64;u+=4)this.first?(this.is224?(b=300032,d=c[0]-1413257819,a=d-150054599<<0,n=d+24177077<<0):(b=704751109,d=c[0]-210244248,a=d-1521486534<<0,n=d+143694565<<0),this.first=!1):(l=(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10),p=(i>>>6|i<<26)^(i>>>11|i<<21)^(i>>>25|i<<7),b=e&t,f=b^e&r^x,h=i&s^~i&o,d=a+p+h+Oh[u]+c[u],m=l+f,a=n+d<<0,n=d+m<<0),l=(n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10),p=(a>>>6|a<<26)^(a>>>11|a<<21)^(a>>>25|a<<7),_=n&e,f=_^n&t^b,h=o&a^~o&i,d=s+p+h+Oh[u+1]+c[u+1],m=l+f,o=r+d<<0,r=d+m<<0,l=(r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10),p=(o>>>6|o<<26)^(o>>>11|o<<21)^(o>>>25|o<<7),y=r&n,f=y^r&e^_,h=s&o^~s&a,d=i+p+h+Oh[u+2]+c[u+2],m=l+f,s=t+d<<0,t=d+m<<0,l=(t>>>2|t<<30)^(t>>>13|t<<19)^(t>>>22|t<<10),p=(s>>>6|s<<26)^(s>>>11|s<<21)^(s>>>25|s<<7),x=t&r,f=x^t&n^y,h=s&o^~s&a,d=i+p+h+Oh[u+3]+c[u+3],m=l+f,i=e+d<<0,e=d+m<<0,this.chromeBugWorkAround=!0;this.h0=this.h0+e<<0,this.h1=this.h1+t<<0,this.h2=this.h2+r<<0,this.h3=this.h3+n<<0,this.h4=this.h4+i<<0,this.h5=this.h5+s<<0,this.h6=this.h6+o<<0,this.h7=this.h7+a<<0};jn.prototype.hex=function(){this.finalize();var e=this.h0,t=this.h1,r=this.h2,n=this.h3,i=this.h4,s=this.h5,o=this.h6,a=this.h7,c=te[e>>>28&15]+te[e>>>24&15]+te[e>>>20&15]+te[e>>>16&15]+te[e>>>12&15]+te[e>>>8&15]+te[e>>>4&15]+te[e&15]+te[t>>>28&15]+te[t>>>24&15]+te[t>>>20&15]+te[t>>>16&15]+te[t>>>12&15]+te[t>>>8&15]+te[t>>>4&15]+te[t&15]+te[r>>>28&15]+te[r>>>24&15]+te[r>>>20&15]+te[r>>>16&15]+te[r>>>12&15]+te[r>>>8&15]+te[r>>>4&15]+te[r&15]+te[n>>>28&15]+te[n>>>24&15]+te[n>>>20&15]+te[n>>>16&15]+te[n>>>12&15]+te[n>>>8&15]+te[n>>>4&15]+te[n&15]+te[i>>>28&15]+te[i>>>24&15]+te[i>>>20&15]+te[i>>>16&15]+te[i>>>12&15]+te[i>>>8&15]+te[i>>>4&15]+te[i&15]+te[s>>>28&15]+te[s>>>24&15]+te[s>>>20&15]+te[s>>>16&15]+te[s>>>12&15]+te[s>>>8&15]+te[s>>>4&15]+te[s&15]+te[o>>>28&15]+te[o>>>24&15]+te[o>>>20&15]+te[o>>>16&15]+te[o>>>12&15]+te[o>>>8&15]+te[o>>>4&15]+te[o&15];return this.is224||(c+=te[a>>>28&15]+te[a>>>24&15]+te[a>>>20&15]+te[a>>>16&15]+te[a>>>12&15]+te[a>>>8&15]+te[a>>>4&15]+te[a&15]),c};jn.prototype.toString=jn.prototype.hex;jn.prototype.digest=function(){this.finalize();var e=this.h0,t=this.h1,r=this.h2,n=this.h3,i=this.h4,s=this.h5,o=this.h6,a=this.h7,c=[e>>>24&255,e>>>16&255,e>>>8&255,e&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255,r>>>24&255,r>>>16&255,r>>>8&255,r&255,n>>>24&255,n>>>16&255,n>>>8&255,n&255,i>>>24&255,i>>>16&255,i>>>8&255,i&255,s>>>24&255,s>>>16&255,s>>>8&255,s&255,o>>>24&255,o>>>16&255,o>>>8&255,o&255];return this.is224||c.push(a>>>24&255,a>>>16&255,a>>>8&255,a&255),c};jn.prototype.array=jn.prototype.digest;jn.prototype.arrayBuffer=function(){this.finalize();var e=new ArrayBuffer(this.is224?28:32),t=new DataView(e);return t.setUint32(0,this.h0),t.setUint32(4,this.h1),t.setUint32(8,this.h2),t.setUint32(12,this.h3),t.setUint32(16,this.h4),t.setUint32(20,this.h5),t.setUint32(24,this.h6),this.is224||t.setUint32(28,this.h7),e};var Vc=(...e)=>new jn(!1,!0).update(e.join("")).hex();var f0={};M(f0,{sha256:()=>Vc});var m0={};M(m0,{BaseCache:()=>jN,InMemoryCache:()=>h0,defaultHashKeyEncoder:()=>MN,deserializeStoredGeneration:()=>LZ,serializeGeneration:()=>UZ});var MN=(...e)=>Vc(e.join("_"));function LZ(e){return e.message!==void 0?{text:e.text,message:Ml(e.message)}:{text:e.text}}function UZ(e){let t={text:e.text};return e.message!==void 0&&(t.message=e.message.toDict()),t}var jN=class{keyEncoder=MN;makeDefaultKeyEncoder(e){this.keyEncoder=e}},FZ=new Map,h0=class DN extends jN{cache;constructor(t){super(),this.cache=t??new Map}lookup(t,r){return Promise.resolve(this.cache.get(this.keyEncoder(t,r))??null)}async update(t,r,n){this.cache.set(this.keyEncoder(t,r),n)}static global(){return new DN(FZ)}};var g0={};M(g0,{BaseDocumentLoader:()=>_0});var _0=class{};var y0={};M(y0,{LangSmithLoader:()=>BZ});var BZ=class extends _0{datasetId;datasetName;exampleIds;asOf;splits;inlineS3Urls;offset;limit;metadata;filter;contentKey;formatContent;client;constructor(e){if(super(),e.client&&e.clientConfig)throw new Error("client and clientConfig cannot both be provided.");this.client=e.client??new Bi(e?.clientConfig),this.contentKey=e.contentKey?e.contentKey.split("."):[],this.formatContent=e.formatContent??VZ,this.datasetId=e.datasetId,this.datasetName=e.datasetName,this.exampleIds=e.exampleIds,this.asOf=e.asOf,this.splits=e.splits,this.inlineS3Urls=e.inlineS3Urls,this.offset=e.offset,this.limit=e.limit,this.metadata=e.metadata,this.filter=e.filter}async load(){let e=[];for await(let t of this.client.listExamples({datasetId:this.datasetId,datasetName:this.datasetName,exampleIds:this.exampleIds,asOf:this.asOf,splits:this.splits,inlineS3Urls:this.inlineS3Urls,offset:this.offset,limit:this.limit,metadata:this.metadata,filter:this.filter})){let r=t.inputs;for(let s of this.contentKey)r=r[s];let n=this.formatContent(r),i=t;["created_at","modified_at"].forEach(s=>{s in i&&typeof i[s]=="object"&&(i[s]=i[s].toString())}),e.push({pageContent:n,metadata:i})}return e}};function VZ(e){if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}var qr=class{pageContent;metadata;id;constructor(e){this.pageContent=e.pageContent!==void 0?e.pageContent.toString():"",this.metadata=e.metadata??{},this.id=e.id}};var v0=class extends ce{lc_namespace=["langchain_core","documents","transformers"];invoke(e,t){return this.transformDocuments(e)}},zN=class extends v0{async transformDocuments(e){let t=[];for(let r of e){let n=await this._transformDocument(r);t.push(n)}return t}};var b0={};M(b0,{BaseDocumentTransformer:()=>v0,Document:()=>qr,MappingDocumentTransformer:()=>zN});var Zc=class extends vt{lc_namespace=["langchain_core","example_selectors","base"]};var w0=class{async getPromptAsync(e,t){return this.getPrompt(e).partial(t?.partialVariables??{})}},LN=class extends w0{defaultPrompt;conditionals;constructor(e,t=[]){super(),this.defaultPrompt=e,this.conditionals=t}getPrompt(e){for(let[t,r]of this.conditionals)if(t(e))return r;return this.defaultPrompt}};function UN(e){return e._modelType()==="base_llm"}function FN(e){return e._modelType()==="base_chat_model"}function BN(e){return e.split(/\n| /).length}var VN=class ZN extends Zc{examples=[];examplePrompt;getTextLength=BN;maxLength=2048;exampleTextLengths=[];constructor(t){super(t),this.examplePrompt=t.examplePrompt,this.maxLength=t.maxLength??2048,this.getTextLength=t.getTextLength??BN}async addExample(t){this.examples.push(t);let r=await this.examplePrompt.format(t);this.exampleTextLengths.push(this.getTextLength(r))}async calculateExampleTextLengths(t,r){if(t.length>0)return t;let{examples:n,examplePrompt:i}=r;return(await Promise.all(n.map(o=>i.format(o)))).map(o=>this.getTextLength(o))}async selectExamples(t){let r=Object.values(t).join(" "),n=this.maxLength-this.getTextLength(r),i=0,s=[];for(;n>0&&i<this.examples.length;){let o=n-this.exampleTextLengths[i];if(o<0)break;s.push(this.examples[i]),n=o,i+=1}return s}static async fromExamples(t,r){let n=new ZN(r);return await Promise.all(t.map(i=>n.addExample(i))),n}};function x0(e){return Object.keys(e).sort().map(t=>e[t])}var GN=class KN extends Zc{vectorStoreRetriever;exampleKeys;inputKeys;constructor(t){if(super(t),this.exampleKeys=t.exampleKeys,this.inputKeys=t.inputKeys,t.vectorStore!==void 0)this.vectorStoreRetriever=t.vectorStore.asRetriever({k:t.k??4,filter:t.filter});else if(t.vectorStoreRetriever)this.vectorStoreRetriever=t.vectorStoreRetriever;else throw new Error('You must specify one of "vectorStore" and "vectorStoreRetriever".')}async addExample(t){let r=this.inputKeys??Object.keys(t),n=x0(r.reduce((i,s)=>({...i,[s]:t[s]}),{})).join(" ");await this.vectorStoreRetriever.addDocuments([new qr({pageContent:n,metadata:t})])}async selectExamples(t){let r=this.inputKeys??Object.keys(t),n=x0(r.reduce((o,a)=>({...o,[a]:t[a]}),{})).join(" "),s=(await this.vectorStoreRetriever.invoke(n)).map(o=>o.metadata);return this.exampleKeys?s.map(o=>this.exampleKeys.reduce((a,c)=>({...a,[c]:o[c]}),{})):s}static async fromExamples(t,r,n,i={}){let s=i.inputKeys??null,o=t.map(c=>x0(s?s.reduce((u,l)=>({...u,[l]:c[l]}),{}):c).join(" ")),a=await n.fromTexts(o,t,r,i);return new KN({vectorStore:a,k:i.k??4,exampleKeys:i.exampleKeys,inputKeys:i.inputKeys})}};var I0={};M(I0,{BaseExampleSelector:()=>Zc,BasePromptSelector:()=>w0,ConditionalPromptSelector:()=>LN,LengthBasedExampleSelector:()=>VN,SemanticSimilarityExampleSelector:()=>GN,isChatModel:()=>FN,isLLM:()=>UN});var Np="10f90ea3-90a4-4962-bf75-83a0f3c1c62a",qN=class extends vt{lc_namespace=["langchain","recordmanagers"]};var S0=class{uid;hash_;contentHash;metadataHash;pageContent;metadata;keyEncoder=Vc;constructor(e){this.uid=e.uid,this.pageContent=e.pageContent,this.metadata=e.metadata}makeDefaultKeyEncoder(e){this.keyEncoder=e}calculateHashes(){let e=["hash_","content_hash","metadata_hash"];for(let r of e)if(r in this.metadata)throw new Error(`Metadata cannot contain key ${r} as it is reserved for internal use. Restricted keys: [${e.join(", ")}]`);let t=this._hashStringToUUID(this.pageContent);try{let r=this._hashNestedDictToUUID(this.metadata);this.contentHash=t,this.metadataHash=r}catch(r){throw new Error(`Failed to hash metadata: ${r}. Please use a dict that can be serialized using json.`)}this.hash_=this._hashStringToUUID(this.contentHash+this.metadataHash),this.uid||(this.uid=this.hash_)}toDocument(){return new qr({pageContent:this.pageContent,metadata:this.metadata})}static fromDocument(e,t){let r=new this({pageContent:e.pageContent,metadata:e.metadata,uid:t||e.uid});return r.calculateHashes(),r}_hashStringToUUID(e){let t=this.keyEncoder(e);return nn(t,Np)}_hashNestedDictToUUID(e){let t=JSON.stringify(e,Object.keys(e).sort()),r=this.keyEncoder(t);return nn(r,Np)}};function E0(e,t){let r=[],n=[];return t.forEach(i=>{n.push(i),n.length>=e&&(r.push(n),n=[])}),n.length>0&&r.push(n),r}function k0(e){let t=new Set,r=[];for(let n of e){if(!n.hash_)throw new Error("Hashed document does not have a hash");t.has(n.hash_)||(t.add(n.hash_),r.push(n))}return r}function A0(e){if(e===null)return t=>null;if(typeof e=="string")return t=>t.metadata[e];if(typeof e=="function")return e;throw new Error(`sourceIdKey should be null, a string or a function, got ${typeof e}`)}var T0=e=>"load"in e&&typeof e.load=="function"&&"loadAndSplit"in e&&typeof e.loadAndSplit=="function";async function HN(e){let{docsSource:t,recordManager:r,vectorStore:n,options:i}=e,{batchSize:s=100,cleanup:o,sourceIdKey:a,cleanupBatchSize:c=1e3,forceUpdate:u=!1}=i??{};if(o==="incremental"&&!a)throw new Error("sourceIdKey is required when cleanup mode is incremental. Please provide through 'options.sourceIdKey'.");let l=T0(t)?await t.load():t,p=A0(a??null),f=await r.getTime(),d=0,m=0,h=0,b=0,_=E0(s??100,l);for(let y of _){let x=k0(y.map(P=>S0.fromDocument(P))),I=x.map(P=>p(P));o==="incremental"&&x.forEach((P,V)=>{if(I[V]===null)throw new Error("sourceIdKey must be provided when cleanup is incremental")});let A=await r.exists(x.map(P=>P.uid)),j=[],O=[],w=[],F=new Set;if(x.forEach((P,V)=>{if(A[V])if(u)F.add(P.uid);else{w.push(P.uid);return}j.push(P.uid),O.push(P.toDocument())}),w.length>0&&(await r.update(w,{timeAtLeast:f}),b+=w.length),O.length>0&&(await n.addDocuments(O,{ids:j}),d+=O.length-F.size,h+=F.size),await r.update(x.map(P=>P.uid),{timeAtLeast:f,groupIds:I}),o==="incremental"){I.forEach(V=>{if(!V)throw new Error("Source id cannot be null")});let P=await r.listKeys({before:f,groupIds:I});P.length>0&&(await n.delete({ids:P}),await r.deleteKeys(P),m+=P.length)}}if(o==="full"){let y=await r.listKeys({before:f,limit:c});for(;y.length>0;)await n.delete({ids:y}),await r.deleteKeys(y),m+=y.length,y=await r.listKeys({before:f,limit:c})}return{numAdded:d,numDeleted:m,numUpdated:h,numSkipped:b}}var O0={};M(O0,{RecordManager:()=>qN,UUIDV5_NAMESPACE:()=>Np,_HashedDocument:()=>S0,_batch:()=>E0,_deduplicateInOrder:()=>k0,_getSourceIdAssigner:()=>A0,_isBaseDocumentLoader:()=>T0,index:()=>HN});var YN=Ps(XN(),1),XZ=Object.defineProperty,YZ=(e,t,r)=>t in e?XZ(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,QZ=(e,t,r)=>(YZ(e,typeof t!="symbol"?t+"":t,r),r);function e9(e,t){let r=Array.from({length:e.length},(n,i)=>({start:i,end:i+1}));for(;r.length>1;){let n=null;for(let i=0;i<r.length-1;i++){let s=e.slice(r[i].start,r[i+1].end),o=t.get(s.join(","));o!=null&&(n==null||o<n[0])&&(n=[o,i])}if(n!=null){let i=n[1];r[i]={start:r[i].start,end:r[i+1].end},r.splice(i+1,1)}else break}return r}function t9(e,t){return e.length===1?[t.get(e.join(","))]:e9(e,t).map(r=>t.get(e.slice(r.start,r.end).join(","))).filter(r=>r!=null)}function r9(e){return e.replace(/[\\^$*+?.()|[\]{}]/g,"\\$&")}var C0=class{specialTokens;inverseSpecialTokens;patStr;textEncoder=new TextEncoder;textDecoder=new TextDecoder("utf-8");rankMap=new Map;textMap=new Map;constructor(e,t){this.patStr=e.pat_str;let r=e.bpe_ranks.split(`
|
|
113
|
+
`).filter(Boolean).reduce((n,i)=>{let[s,o,...a]=i.split(" "),c=Number.parseInt(o,10);return a.forEach((u,l)=>n[u]=c+l),n},{});for(let[n,i]of Object.entries(r)){let s=YN.default.toByteArray(n);this.rankMap.set(s.join(","),i),this.textMap.set(i,s)}this.specialTokens={...e.special_tokens,...t},this.inverseSpecialTokens=Object.entries(this.specialTokens).reduce((n,[i,s])=>(n[s]=this.textEncoder.encode(i),n),{})}encode(e,t=[],r="all"){let n=new RegExp(this.patStr,"ug"),i=C0.specialTokenRegex(Object.keys(this.specialTokens)),s=[],o=new Set(t==="all"?Object.keys(this.specialTokens):t),a=new Set(r==="all"?Object.keys(this.specialTokens).filter(u=>!o.has(u)):r);if(a.size>0){let u=C0.specialTokenRegex([...a]),l=e.match(u);if(l!=null)throw new Error(`The text contains a special token that is not allowed: ${l[0]}`)}let c=0;for(;;){let u=null,l=c;for(;i.lastIndex=l,u=i.exec(e),!(u==null||o.has(u[0]));)l=u.index+1;let p=u?.index??e.length;for(let d of e.substring(c,p).matchAll(n)){let m=this.textEncoder.encode(d[0]),h=this.rankMap.get(m.join(","));if(h!=null){s.push(h);continue}s.push(...t9(m,this.rankMap))}if(u==null)break;let f=this.specialTokens[u[0]];s.push(f),c=u.index+u[0].length}return s}decode(e){let t=[],r=0;for(let s=0;s<e.length;++s){let o=e[s],a=this.textMap.get(o)??this.inverseSpecialTokens[o];a!=null&&(t.push(a),r+=a.length)}let n=new Uint8Array(r),i=0;for(let s of t)n.set(s,i),i+=s.length;return this.textDecoder.decode(n)}},Ch=C0;QZ(Ch,"specialTokenRegex",e=>new RegExp(e.map(t=>r9(t)).join("|"),"g"));function P0(e){switch(e){case"gpt2":return"gpt2";case"code-cushman-001":case"code-cushman-002":case"code-davinci-001":case"code-davinci-002":case"cushman-codex":case"davinci-codex":case"davinci-002":case"text-davinci-002":case"text-davinci-003":return"p50k_base";case"code-davinci-edit-001":case"text-davinci-edit-001":return"p50k_edit";case"ada":case"babbage":case"babbage-002":case"code-search-ada-code-001":case"code-search-babbage-code-001":case"curie":case"davinci":case"text-ada-001":case"text-babbage-001":case"text-curie-001":case"text-davinci-001":case"text-search-ada-doc-001":case"text-search-babbage-doc-001":case"text-search-curie-doc-001":case"text-search-davinci-doc-001":case"text-similarity-ada-001":case"text-similarity-babbage-001":case"text-similarity-curie-001":case"text-similarity-davinci-001":return"r50k_base";case"gpt-3.5-turbo-instruct-0914":case"gpt-3.5-turbo-instruct":case"gpt-3.5-turbo-16k-0613":case"gpt-3.5-turbo-16k":case"gpt-3.5-turbo-0613":case"gpt-3.5-turbo-0301":case"gpt-3.5-turbo":case"gpt-4-32k-0613":case"gpt-4-32k-0314":case"gpt-4-32k":case"gpt-4-0613":case"gpt-4-0314":case"gpt-4":case"gpt-3.5-turbo-1106":case"gpt-35-turbo":case"gpt-4-1106-preview":case"gpt-4-vision-preview":case"gpt-3.5-turbo-0125":case"gpt-4-turbo":case"gpt-4-turbo-2024-04-09":case"gpt-4-turbo-preview":case"gpt-4-0125-preview":case"text-embedding-ada-002":case"text-embedding-3-small":case"text-embedding-3-large":return"cl100k_base";case"gpt-4o":case"gpt-4o-2024-05-13":case"gpt-4o-2024-08-06":case"gpt-4o-2024-11-20":case"gpt-4o-mini-2024-07-18":case"gpt-4o-mini":case"gpt-4o-search-preview":case"gpt-4o-search-preview-2025-03-11":case"gpt-4o-mini-search-preview":case"gpt-4o-mini-search-preview-2025-03-11":case"gpt-4o-audio-preview":case"gpt-4o-audio-preview-2024-12-17":case"gpt-4o-audio-preview-2024-10-01":case"gpt-4o-mini-audio-preview":case"gpt-4o-mini-audio-preview-2024-12-17":case"o1":case"o1-2024-12-17":case"o1-mini":case"o1-mini-2024-09-12":case"o1-preview":case"o1-preview-2024-09-12":case"o1-pro":case"o1-pro-2025-03-19":case"o3":case"o3-2025-04-16":case"o3-mini":case"o3-mini-2025-01-31":case"o4-mini":case"o4-mini-2025-04-16":case"chatgpt-4o-latest":case"gpt-4o-realtime":case"gpt-4o-realtime-preview-2024-10-01":case"gpt-4o-realtime-preview-2024-12-17":case"gpt-4o-mini-realtime-preview":case"gpt-4o-mini-realtime-preview-2024-12-17":case"gpt-4.1":case"gpt-4.1-2025-04-14":case"gpt-4.1-mini":case"gpt-4.1-mini-2025-04-14":case"gpt-4.1-nano":case"gpt-4.1-nano-2025-04-14":case"gpt-4.5-preview":case"gpt-4.5-preview-2025-02-27":case"gpt-5":case"gpt-5-2025-08-07":case"gpt-5-nano":case"gpt-5-nano-2025-08-07":case"gpt-5-mini":case"gpt-5-mini-2025-08-07":case"gpt-5-chat-latest":return"o200k_base";default:throw new Error("Unknown model")}}var N0={};M(N0,{encodingForModel:()=>Nh,getEncoding:()=>QN});var Ph={},n9=new Hi({});async function QN(e){return e in Ph||(Ph[e]=n9.fetch(`https://tiktoken.pages.dev/js/${e}.json`).then(t=>t.json()).then(t=>new Ch(t)).catch(t=>{throw delete Ph[e],t})),await Ph[e]}async function Nh(e){return QN(P0(e))}var R0={};M(R0,{BaseLangChain:()=>Mh,BaseLanguageModel:()=>Mp,calculateMaxTokens:()=>tR,getEmbeddingContextSize:()=>i9,getModelContextSize:()=>eR,getModelNameForTiktoken:()=>Rh,isOpenAITool:()=>Rp});var Rh=e=>e.startsWith("gpt-5")?"gpt-5":e.startsWith("gpt-3.5-turbo-16k")?"gpt-3.5-turbo-16k":e.startsWith("gpt-3.5-turbo-")?"gpt-3.5-turbo":e.startsWith("gpt-4-32k")?"gpt-4-32k":e.startsWith("gpt-4-")?"gpt-4":e.startsWith("gpt-4o")?"gpt-4o":e,i9=e=>{switch(e){case"text-embedding-ada-002":return 8191;default:return 2046}},eR=e=>{switch(Rh(e)){case"gpt-5":case"gpt-5-turbo":case"gpt-5-turbo-preview":return 4e5;case"gpt-4o":case"gpt-4o-mini":case"gpt-4o-2024-05-13":case"gpt-4o-2024-08-06":return 128e3;case"gpt-4-turbo":case"gpt-4-turbo-preview":case"gpt-4-turbo-2024-04-09":case"gpt-4-0125-preview":case"gpt-4-1106-preview":return 128e3;case"gpt-4-32k":case"gpt-4-32k-0314":case"gpt-4-32k-0613":return 32768;case"gpt-4":case"gpt-4-0314":case"gpt-4-0613":return 8192;case"gpt-3.5-turbo-16k":case"gpt-3.5-turbo-16k-0613":return 16384;case"gpt-3.5-turbo":case"gpt-3.5-turbo-0301":case"gpt-3.5-turbo-0613":case"gpt-3.5-turbo-1106":case"gpt-3.5-turbo-0125":return 4096;case"text-davinci-003":case"text-davinci-002":return 4097;case"text-davinci-001":return 2049;case"text-curie-001":case"text-babbage-001":case"text-ada-001":return 2048;case"code-davinci-002":case"code-davinci-001":return 8e3;case"code-cushman-001":return 2048;case"claude-3-5-sonnet-20241022":case"claude-3-5-sonnet-20240620":case"claude-3-opus-20240229":case"claude-3-sonnet-20240229":case"claude-3-haiku-20240307":case"claude-2.1":return 2e5;case"claude-2.0":case"claude-instant-1.2":return 1e5;case"gemini-1.5-pro":case"gemini-1.5-pro-latest":case"gemini-1.5-flash":case"gemini-1.5-flash-latest":return 1e6;case"gemini-pro":case"gemini-pro-vision":return 32768;default:return 4097}};function Rp(e){return typeof e!="object"||!e?!1:!!("type"in e&&e.type==="function"&&"function"in e&&typeof e.function=="object"&&e.function&&"name"in e.function&&"parameters"in e.function)}var tR=async({prompt:e,modelName:t})=>{let r;try{r=(await Nh(Rh(t))).encode(e).length}catch{console.warn("Failed to calculate number of tokens, falling back to approximate count"),r=Math.ceil(e.length/4)}return eR(t)-r},s9=()=>!1,Mh=class extends ce{verbose;callbacks;tags;metadata;get lc_attributes(){return{callbacks:void 0,verbose:void 0}}constructor(e){super(e),this.verbose=e.verbose??s9(),this.callbacks=e.callbacks,this.tags=e.tags??[],this.metadata=e.metadata??{}}},Mp=class extends Mh{get callKeys(){return["stop","timeout","signal","tags","metadata","callbacks"]}caller;cache;constructor({callbacks:e,callbackManager:t,...r}){let{cache:n,...i}=r;super({callbacks:e??t,...i}),typeof n=="object"?this.cache=n:n?this.cache=h0.global():this.cache=void 0,this.caller=new Hi(r??{})}_encoding;async getNumTokens(e){let t;typeof e=="string"?t=e:t=e.map(n=>typeof n=="string"?n:n.type==="text"&&"text"in n?n.text:"").join("");let r=Math.ceil(t.length/4);if(!this._encoding)try{this._encoding=await Nh("modelName"in this?Rh(this.modelName):"gpt2")}catch(n){console.warn("Failed to calculate number of tokens, falling back to approximate count",n)}if(this._encoding)try{r=this._encoding.encode(t).length}catch(n){console.warn("Failed to calculate number of tokens, falling back to approximate count",n)}return r}static _convertInputToPromptValue(e){return typeof e=="string"?new $p(e):Array.isArray(e)?new Cp(e.map(Qt)):e}_identifyingParams(){return{}}_getSerializedCacheKeyParametersForCall({config:e,...t}){let r={...this._identifyingParams(),...t,_type:this._llmType(),_model:this._modelType()};return Object.entries(r).filter(([s,o])=>o!==void 0).map(([s,o])=>`${s}:${JSON.stringify(o)}`).sort().join(",")}serialize(){return{...this._identifyingParams(),_type:this._llmType(),_model:this._modelType()}}static async deserialize(e){throw new Error("Use .toJSON() instead")}get profile(){return{}}};var yn=class extends ce{static lc_name(){return"RunnablePassthrough"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;func;constructor(e){super(e),e&&(this.func=e.func)}async invoke(e,t){let r=$e(t);return this.func&&await this.func(e,r),this._callWithConfig(n=>Promise.resolve(n),e,r)}async*transform(e,t){let r=$e(t),n,i=!0;for await(let s of this._transformStreamWithConfig(e,o=>o,r))if(yield s,i)if(n===void 0)n=s;else try{n=Vr(n,s)}catch{n=void 0,i=!1}this.func&&n!==void 0&&await this.func(n,r)}static assign(e){return new Op(new eo({steps:e}))}};var rR=e=>e();function jh(e){let t=e.constructor;return new t({...e,content:e.contentBlocks,response_metadata:{...e.response_metadata,output_version:"v1"}})}var j0={};M(j0,{BaseChatModel:()=>to,SimpleChatModel:()=>o9});function M0(e){let t=[];for(let r of e){let n=r;if(Array.isArray(r.content))for(let i=0;i<r.content.length;i++){let s=r.content[i];(lc(s)||pc(s))&&n===r&&(n=new r.constructor({...n,content:[...r.content.slice(0,i),ff(s),...r.content.slice(i+1)]}))}t.push(n)}return t}var to=class ba extends Mp{lc_namespace=["langchain","chat_models",this._llmType()];disableStreaming=!1;outputVersion;get callKeys(){return[...super.callKeys,"outputVersion"]}constructor(t){super(t),this.outputVersion=rR(()=>{let r=t.outputVersion??Pe("LC_OUTPUT_VERSION");return r&&["v0","v1"].includes(r)?r:"v0"})}_separateRunnableConfigFromCallOptionsCompat(t){let[r,n]=super._separateRunnableConfigFromCallOptions(t);return n.signal=r.signal,[r,n]}async invoke(t,r){let n=ba._convertInputToPromptValue(t);return(await this.generatePrompt([n],r,r?.callbacks)).generations[0][0].message}async*_streamResponseChunks(t,r,n){throw new Error("Not implemented.")}async*_streamIterator(t,r){if(this._streamResponseChunks===ba.prototype._streamResponseChunks||this.disableStreaming)yield this.invoke(t,r);else{let i=ba._convertInputToPromptValue(t).toChatMessages(),[s,o]=this._separateRunnableConfigFromCallOptionsCompat(r),a={...s.metadata,...this.getLsParams(o)},c=await xt.configure(s.callbacks,this.callbacks,s.tags,this.tags,a,this.metadata,{verbose:this.verbose}),u={options:o,invocation_params:this?.invocationParams(o),batch_size:1},l=o.outputVersion??this.outputVersion,p=await c?.handleChatModelStart(this.toJSON(),[M0(i)],s.runId,void 0,u,void 0,void 0,s.runName),f,d;try{for await(let m of this._streamResponseChunks(i,o,p?.[0])){if(m.message.id==null){let h=p?.at(0)?.runId;h!=null&&m.message._updateId(`run-${h}`)}m.message.response_metadata={...m.generationInfo,...m.message.response_metadata},l==="v1"?yield jh(m.message):yield m.message,f?f=f.concat(m):f=m,jl(m.message)&&m.message.usage_metadata!==void 0&&(d={tokenUsage:{promptTokens:m.message.usage_metadata.input_tokens,completionTokens:m.message.usage_metadata.output_tokens,totalTokens:m.message.usage_metadata.total_tokens}})}}catch(m){throw await Promise.all((p??[]).map(h=>h?.handleLLMError(m))),m}await Promise.all((p??[]).map(m=>m?.handleLLMEnd({generations:[[f]],llmOutput:d})))}}getLsParams(t){let r=this.getName().startsWith("Chat")?this.getName().replace("Chat",""):this.getName();return{ls_model_type:"chat",ls_stop:t.stop,ls_provider:r}}async _generateUncached(t,r,n,i){let s=t.map(f=>f.map(Qt)),o;if(i!==void 0&&i.length===s.length)o=i;else{let f={...n.metadata,...this.getLsParams(r)},d=await xt.configure(n.callbacks,this.callbacks,n.tags,this.tags,f,this.metadata,{verbose:this.verbose}),m={options:r,invocation_params:this?.invocationParams(r),batch_size:1};o=await d?.handleChatModelStart(this.toJSON(),s.map(M0),n.runId,void 0,m,void 0,void 0,n.runName)}let a=r.outputVersion??this.outputVersion,c=[],u=[];if(!!o?.[0].handlers.find(vl)&&!this.disableStreaming&&s.length===1&&this._streamResponseChunks!==ba.prototype._streamResponseChunks)try{let f=await this._streamResponseChunks(s[0],r,o?.[0]),d,m;for await(let h of f){if(h.message.id==null){let b=o?.at(0)?.runId;b!=null&&h.message._updateId(`run-${b}`)}d===void 0?d=h:d=Vr(d,h),jl(h.message)&&h.message.usage_metadata!==void 0&&(m={tokenUsage:{promptTokens:h.message.usage_metadata.input_tokens,completionTokens:h.message.usage_metadata.output_tokens,totalTokens:h.message.usage_metadata.total_tokens}})}if(d===void 0)throw new Error("Received empty response from chat model call.");c.push([d]),await o?.[0].handleLLMEnd({generations:c,llmOutput:m})}catch(f){throw await o?.[0].handleLLMError(f),f}else{let f=await Promise.allSettled(s.map(async(d,m)=>{let h=await this._generate(d,{...r,promptIndex:m},o?.[m]);if(a==="v1")for(let b of h.generations)b.message=jh(b.message);return h}));await Promise.all(f.map(async(d,m)=>{if(d.status==="fulfilled"){let h=d.value;for(let b of h.generations){if(b.message.id==null){let _=o?.at(0)?.runId;_!=null&&b.message._updateId(`run-${_}`)}b.message.response_metadata={...b.generationInfo,...b.message.response_metadata}}return h.generations.length===1&&(h.generations[0].message.response_metadata={...h.llmOutput,...h.generations[0].message.response_metadata}),c[m]=h.generations,u[m]=h.llmOutput,o?.[m]?.handleLLMEnd({generations:[h.generations],llmOutput:h.llmOutput})}else return await o?.[m]?.handleLLMError(d.reason),Promise.reject(d.reason)}))}let p={generations:c,llmOutput:u.length?this._combineLLMOutput?.(...u):void 0};return Object.defineProperty(p,Zo,{value:o?{runIds:o?.map(f=>f.runId)}:void 0,configurable:!0}),p}async _generateCached({messages:t,cache:r,llmStringKey:n,parsedOptions:i,handledOptions:s}){let o=t.map(_=>_.map(Qt)),a={...s.metadata,...this.getLsParams(i)},c=await xt.configure(s.callbacks,this.callbacks,s.tags,this.tags,a,this.metadata,{verbose:this.verbose}),u={options:i,invocation_params:this?.invocationParams(i),batch_size:1},l=await c?.handleChatModelStart(this.toJSON(),o.map(M0),s.runId,void 0,u,void 0,void 0,s.runName),p=[],d=(await Promise.allSettled(o.map(async(_,y)=>{let x=ba._convertInputToPromptValue(_).toString(),I=await r.lookup(x,n);return I==null&&p.push(y),I}))).map((_,y)=>({result:_,runManager:l?.[y]})).filter(({result:_})=>_.status==="fulfilled"&&_.value!=null||_.status==="rejected"),m=i.outputVersion??this.outputVersion,h=[];await Promise.all(d.map(async({result:_,runManager:y},x)=>{if(_.status==="fulfilled"){let I=_.value;return h[x]=I.map(A=>("message"in A&&ot(A.message)&&ci(A.message)&&(A.message.usage_metadata={input_tokens:0,output_tokens:0,total_tokens:0},m==="v1"&&(A.message=jh(A.message))),A.generationInfo={...A.generationInfo,tokenUsage:{}},A)),I.length&&await y?.handleLLMNewToken(I[0].text),y?.handleLLMEnd({generations:[I]},void 0,void 0,void 0,{cached:!0})}else return await y?.handleLLMError(_.reason,void 0,void 0,void 0,{cached:!0}),Promise.reject(_.reason)}));let b={generations:h,missingPromptIndices:p,startedRunManagers:l};return Object.defineProperty(b,Zo,{value:l?{runIds:l?.map(_=>_.runId)}:void 0,configurable:!0}),b}async generate(t,r,n){let i;Array.isArray(r)?i={stop:r}:i=r;let s=t.map(m=>m.map(Qt)),[o,a]=this._separateRunnableConfigFromCallOptionsCompat(i);if(o.callbacks=o.callbacks??n,!this.cache)return this._generateUncached(s,a,o);let{cache:c}=this,u=this._getSerializedCacheKeyParametersForCall(a),{generations:l,missingPromptIndices:p,startedRunManagers:f}=await this._generateCached({messages:s,cache:c,llmStringKey:u,parsedOptions:a,handledOptions:o}),d={};if(p.length>0){let m=await this._generateUncached(p.map(h=>s[h]),a,o,f!==void 0?p.map(h=>f?.[h]):void 0);await Promise.all(m.generations.map(async(h,b)=>{let _=p[b];l[_]=h;let y=ba._convertInputToPromptValue(s[_]).toString();return c.update(y,u,h)})),d=m.llmOutput??{}}return{generations:l,llmOutput:d}}invocationParams(t){return{}}_modelType(){return"base_chat_model"}async generatePrompt(t,r,n){let i=t.map(s=>s.toChatMessages());return this.generate(i,r,n)}withStructuredOutput(t,r){if(typeof this.bindTools!="function")throw new Error('Chat model must implement ".bindTools()" to use withStructuredOutput.');if(r?.strict)throw new Error('"strict" mode is not supported for this model by default.');let n=t,i=r?.name,s=$n(n)??"A function available to call.",o=r?.method,a=r?.includeRaw;if(o==="jsonMode")throw new Error('Base withStructuredOutput implementation only supports "functionCalling" as a method.');let c=i??"extract",u;_r(n)?u=[{type:"function",function:{name:c,description:s,parameters:Ye(n)}}]:("name"in n&&(c=n.name),u=[{type:"function",function:{name:c,description:s,parameters:n}}]);let l=this.bindTools(u),p=tr.from(h=>{if(!nt.isInstance(h))throw new Error("Input is not an AIMessageChunk.");if(!h.tool_calls||h.tool_calls.length===0)throw new Error("No tool calls found in the response.");let b=h.tool_calls.find(_=>_.name===c);if(!b)throw new Error(`No tool call found with name ${c}.`);return b.args});if(!a)return l.pipe(p).withConfig({runName:"StructuredOutput"});let f=yn.assign({parsed:(h,b)=>p.invoke(h.raw,b)}),d=yn.assign({parsed:()=>null}),m=f.withFallbacks({fallbacks:[d]});return br.from([{raw:l},m]).withConfig({runName:"StructuredOutputRunnable"})}},o9=class extends to{async _generate(e,t,r){let n=await this._call(e,t,r),i=new Oe(n);if(typeof i.content!="string")throw new Error("Cannot generate with a simple chat model when output is not a string.");return{generations:[{text:i.content,message:i}]}}};var D0={};M(D0,{BaseLLM:()=>z0,LLM:()=>Dh});var z0=class jp extends Mp{lc_namespace=["langchain","llms",this._llmType()];async invoke(t,r){let n=jp._convertInputToPromptValue(t);return(await this.generatePrompt([n],r,r?.callbacks)).generations[0][0].text}async*_streamResponseChunks(t,r,n){throw new Error("Not implemented.")}_separateRunnableConfigFromCallOptionsCompat(t){let[r,n]=super._separateRunnableConfigFromCallOptions(t);return n.signal=r.signal,[r,n]}async*_streamIterator(t,r){if(this._streamResponseChunks===jp.prototype._streamResponseChunks)yield this.invoke(t,r);else{let n=jp._convertInputToPromptValue(t),[i,s]=this._separateRunnableConfigFromCallOptionsCompat(r),o=await xt.configure(i.callbacks,this.callbacks,i.tags,this.tags,i.metadata,this.metadata,{verbose:this.verbose}),a={options:s,invocation_params:this?.invocationParams(s),batch_size:1},c=await o?.handleLLMStart(this.toJSON(),[n.toString()],i.runId,void 0,a,void 0,void 0,i.runName),u=new li({text:""});try{for await(let l of this._streamResponseChunks(n.toString(),s,c?.[0]))u?u=u.concat(l):u=l,typeof l.text=="string"&&(yield l.text)}catch(l){throw await Promise.all((c??[]).map(p=>p?.handleLLMError(l))),l}await Promise.all((c??[]).map(l=>l?.handleLLMEnd({generations:[[u]]})))}}async generatePrompt(t,r,n){let i=t.map(s=>s.toString());return this.generate(i,r,n)}invocationParams(t){return{}}_flattenLLMResult(t){let r=[];for(let n=0;n<t.generations.length;n+=1){let i=t.generations[n];if(n===0)r.push({generations:[i],llmOutput:t.llmOutput});else{let s=t.llmOutput?{...t.llmOutput,tokenUsage:{}}:void 0;r.push({generations:[i],llmOutput:s})}}return r}async _generateUncached(t,r,n,i){let s;if(i!==void 0&&i.length===t.length)s=i;else{let u=await xt.configure(n.callbacks,this.callbacks,n.tags,this.tags,n.metadata,this.metadata,{verbose:this.verbose}),l={options:r,invocation_params:this?.invocationParams(r),batch_size:t.length};s=await u?.handleLLMStart(this.toJSON(),t,n.runId,void 0,l,void 0,void 0,n?.runName)}let o=!!s?.[0].handlers.find(vl),a;if(o&&t.length===1&&this._streamResponseChunks!==jp.prototype._streamResponseChunks)try{let u=await this._streamResponseChunks(t[0],r,s?.[0]),l;for await(let p of u)l===void 0?l=p:l=Vr(l,p);if(l===void 0)throw new Error("Received empty response from chat model call.");a={generations:[[l]],llmOutput:{}},await s?.[0].handleLLMEnd(a)}catch(u){throw await s?.[0].handleLLMError(u),u}else{try{a=await this._generate(t,r,s?.[0])}catch(l){throw await Promise.all((s??[]).map(p=>p?.handleLLMError(l))),l}let u=this._flattenLLMResult(a);await Promise.all((s??[]).map((l,p)=>l?.handleLLMEnd(u[p])))}let c=s?.map(u=>u.runId)||void 0;return Object.defineProperty(a,Zo,{value:c?{runIds:c}:void 0,configurable:!0}),a}async _generateCached({prompts:t,cache:r,llmStringKey:n,parsedOptions:i,handledOptions:s,runId:o}){let a=await xt.configure(s.callbacks,this.callbacks,s.tags,this.tags,s.metadata,this.metadata,{verbose:this.verbose}),c={options:i,invocation_params:this?.invocationParams(i),batch_size:t.length},u=await a?.handleLLMStart(this.toJSON(),t,o,void 0,c,void 0,void 0,s?.runName),l=[],f=(await Promise.allSettled(t.map(async(h,b)=>{let _=await r.lookup(h,n);return _==null&&l.push(b),_}))).map((h,b)=>({result:h,runManager:u?.[b]})).filter(({result:h})=>h.status==="fulfilled"&&h.value!=null||h.status==="rejected"),d=[];await Promise.all(f.map(async({result:h,runManager:b},_)=>{if(h.status==="fulfilled"){let y=h.value;return d[_]=y.map(x=>(x.generationInfo={...x.generationInfo,tokenUsage:{}},x)),y.length&&await b?.handleLLMNewToken(y[0].text),b?.handleLLMEnd({generations:[y]},void 0,void 0,void 0,{cached:!0})}else return await b?.handleLLMError(h.reason,void 0,void 0,void 0,{cached:!0}),Promise.reject(h.reason)}));let m={generations:d,missingPromptIndices:l,startedRunManagers:u};return Object.defineProperty(m,Zo,{value:u?{runIds:u?.map(h=>h.runId)}:void 0,configurable:!0}),m}async generate(t,r,n){if(!Array.isArray(t))throw new Error("Argument 'prompts' is expected to be a string[]");let i;Array.isArray(r)?i={stop:r}:i=r;let[s,o]=this._separateRunnableConfigFromCallOptionsCompat(i);if(s.callbacks=s.callbacks??n,!this.cache)return this._generateUncached(t,o,s);let{cache:a}=this,c=this._getSerializedCacheKeyParametersForCall(o),{generations:u,missingPromptIndices:l,startedRunManagers:p}=await this._generateCached({prompts:t,cache:a,llmStringKey:c,parsedOptions:o,handledOptions:s,runId:s.runId}),f={};if(l.length>0){let d=await this._generateUncached(l.map(m=>t[m]),o,s,p!==void 0?l.map(m=>p?.[m]):void 0);await Promise.all(d.generations.map(async(m,h)=>{let b=l[h];return u[b]=m,a.update(t[b],c,m)})),f=d.llmOutput??{}}return{generations:u,llmOutput:f}}_identifyingParams(){return{}}_modelType(){return"base_llm"}},Dh=class extends z0{async _generate(e,t,r){return{generations:await Promise.all(e.map((i,s)=>this._call(i,{...t,promptIndex:s},r).then(o=>[{text:o}])))}}};var nR={};var iR=class extends ce{static lc_name(){return"RouterRunnable"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;runnables;constructor(e){super(e),this.runnables=e.runnables}async invoke(e,t){let{key:r,input:n}=e,i=this.runnables[r];if(i===void 0)throw new Error(`No runnable associated with key "${r}".`);return i.invoke(n,$e(t))}async batch(e,t,r){let n=e.map(p=>p.key),i=e.map(p=>p.input);if(n.find(p=>this.runnables[p]===void 0)!==void 0)throw new Error("One or more keys do not have a corresponding runnable.");let o=n.map(p=>this.runnables[p]),a=this._getOptionsList(t??{},e.length),c=a[0]?.maxConcurrency??r?.maxConcurrency,u=c&&c>0?c:e.length,l=[];for(let p=0;p<i.length;p+=u){let f=i.slice(p,p+u).map((m,h)=>o[h].invoke(m,a[h])),d=await Promise.all(f);l.push(d)}return l.flat()}async stream(e,t){let{key:r,input:n}=e,i=this.runnables[r];if(i===void 0)throw new Error(`No runnable associated with key "${r}".`);return i.stream(n,t)}};var sR=class extends ce{static lc_name(){return"RunnableBranch"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;default;branches;constructor(e){super(e),this.branches=e.branches,this.default=e.default}static from(e){if(e.length<1)throw new Error("RunnableBranch requires at least one branch");let r=e.slice(0,-1).map(([i,s])=>[dt(i),dt(s)]),n=dt(e[e.length-1]);return new this({branches:r,default:n})}async _invoke(e,t,r){let n;for(let i=0;i<this.branches.length;i+=1){let[s,o]=this.branches[i];if(await s.invoke(e,Ne(t,{callbacks:r?.getChild(`condition:${i+1}`)}))){n=await o.invoke(e,Ne(t,{callbacks:r?.getChild(`branch:${i+1}`)}));break}}return n||(n=await this.default.invoke(e,Ne(t,{callbacks:r?.getChild("branch:default")}))),n}async invoke(e,t={}){return this._callWithConfig(this._invoke,e,t)}async*_streamIterator(e,t){let n=await(await Et(t))?.handleChainStart(this.toJSON(),Tt(e,"input"),t?.runId,void 0,void 0,void 0,t?.runName),i,s=!0,o;try{for(let a=0;a<this.branches.length;a+=1){let[c,u]=this.branches[a];if(await c.invoke(e,Ne(t,{callbacks:n?.getChild(`condition:${a+1}`)}))){o=await u.stream(e,Ne(t,{callbacks:n?.getChild(`branch:${a+1}`)}));for await(let p of o)if(yield p,s)if(i===void 0)i=p;else try{i=Vr(i,p)}catch{i=void 0,s=!1}break}}if(o===void 0){o=await this.default.stream(e,Ne(t,{callbacks:n?.getChild("branch:default")}));for await(let a of o)if(yield a,s)if(i===void 0)i=a;else try{i=Vr(i,a)}catch{i=void 0,s=!1}}}catch(a){throw await n?.handleChainError(a),a}await n?.handleChainEnd(i??{})}};var oR=class extends gn{runnable;inputMessagesKey;outputMessagesKey;historyMessagesKey;getMessageHistory;constructor(e){let t=tr.from((s,o)=>this._enterHistory(s,o??{})).withConfig({runName:"loadHistory"}),r=e.historyMessagesKey??e.inputMessagesKey;r&&(t=yn.assign({[r]:t}).withConfig({runName:"insertHistory"}));let n=t.pipe(e.runnable.withListeners({onEnd:(s,o)=>this._exitHistory(s,o??{})})).withConfig({runName:"RunnableWithMessageHistory"}),i=e.config??{};super({...e,config:i,bound:n}),this.runnable=e.runnable,this.getMessageHistory=e.getMessageHistory,this.inputMessagesKey=e.inputMessagesKey,this.outputMessagesKey=e.outputMessagesKey,this.historyMessagesKey=e.historyMessagesKey}_getInputMessages(e){let t;if(typeof e=="object"&&!Array.isArray(e)&&!ot(e)){let r;this.inputMessagesKey?r=this.inputMessagesKey:Object.keys(e).length===1?r=Object.keys(e)[0]:r="input",Array.isArray(e[r])&&Array.isArray(e[r][0])?t=e[r][0]:t=e[r]}else t=e;if(typeof t=="string")return[new at(t)];if(Array.isArray(t))return t;if(ot(t))return[t];throw new Error(`Expected a string, BaseMessage, or array of BaseMessages.
|
|
114
|
+
Got ${JSON.stringify(t,null,2)}`)}_getOutputMessages(e){let t;if(!Array.isArray(e)&&!ot(e)&&typeof e!="string"){let r;this.outputMessagesKey!==void 0?r=this.outputMessagesKey:Object.keys(e).length===1?r=Object.keys(e)[0]:r="output",e.generations!==void 0?t=e.generations[0][0].message:t=e[r]}else t=e;if(typeof t=="string")return[new Oe(t)];if(Array.isArray(t))return t;if(ot(t))return[t];throw new Error(`Expected a string, BaseMessage, or array of BaseMessages. Received: ${JSON.stringify(t,null,2)}`)}async _enterHistory(e,t){let n=await(t?.configurable?.messageHistory).getMessages();return this.historyMessagesKey===void 0?n.concat(this._getInputMessages(e)):n}async _exitHistory(e,t){let r=t.configurable?.messageHistory,n;Array.isArray(e.inputs)&&Array.isArray(e.inputs[0])?n=e.inputs[0]:n=e.inputs;let i=this._getInputMessages(n);if(this.historyMessagesKey===void 0){let a=await r.getMessages();i=i.slice(a.length)}let s=e.outputs;if(!s)throw new Error(`Output values from 'Run' undefined. Run: ${JSON.stringify(e,null,2)}`);let o=this._getOutputMessages(s);await r.addMessages([...i,...o])}async _mergeConfig(...e){let t=await super._mergeConfig(...e);if(!t.configurable||!t.configurable.sessionId){let n={[this.inputMessagesKey??"input"]:"foo"},i={configurable:{sessionId:"123"}};throw new Error(`sessionId is required. Pass it in as part of the config argument to .invoke() or .stream()
|
|
115
|
+
eg. chain.invoke(${JSON.stringify(n)}, ${JSON.stringify(i)})`)}let{sessionId:r}=t.configurable;return t.configurable.messageHistory=await this.getMessageHistory(r),t}};var L0={};M(L0,{RouterRunnable:()=>iR,Runnable:()=>ce,RunnableAssign:()=>Op,RunnableBinding:()=>gn,RunnableBranch:()=>sR,RunnableEach:()=>hN,RunnableLambda:()=>tr,RunnableMap:()=>eo,RunnableParallel:()=>bN,RunnablePassthrough:()=>yn,RunnablePick:()=>e0,RunnableRetry:()=>Ih,RunnableSequence:()=>br,RunnableToolLike:()=>xh,RunnableWithFallbacks:()=>Qx,RunnableWithMessageHistory:()=>oR,_coerceToRunnable:()=>dt,ensureConfig:()=>$e,getCallbackManagerForConfig:()=>Et,mergeConfigs:()=>Dt,patchConfig:()=>Ne,pickRunnableConfigKeys:()=>hr,raceWithSignal:()=>ln});var U0={};M(U0,{applyPatch:()=>Bs,compare:()=>Vs});var Gc=class extends ce{parseResultWithPrompt(e,t,r){return this.parseResult(e,r)}_baseMessageToString(e){return typeof e.content=="string"?e.content:this._baseMessageContentToString(e.content)}_baseMessageContentToString(e){return JSON.stringify(e)}async invoke(e,t){return typeof e=="string"?this._callWithConfig(async(r,n)=>this.parseResult([{text:r}],n?.callbacks),e,{...t,runType:"parser"}):this._callWithConfig(async(r,n)=>this.parseResult([{message:r,text:this._baseMessageToString(r)}],n?.callbacks),e,{...t,runType:"parser"})}},is=class extends Gc{parseResult(e,t){return this.parse(e[0].text,t)}async parseWithPrompt(e,t,r){return this.parse(e,r)}_type(){throw new Error("_type not implemented")}},Hr=class extends Error{llmOutput;observation;sendToLLM;constructor(e,t,r,n=!1){if(super(e),this.llmOutput=t,this.observation=r,this.sendToLLM=n,n&&(r===void 0||t===void 0))throw new Error("Arguments 'observation' & 'llmOutput' are required if 'sendToLlm' is true");js(this,"OUTPUT_PARSING_FAILURE")}};var ss=class extends is{async*_transform(e){for await(let t of e)typeof t=="string"?yield this.parseResult([{text:t}]):yield this.parseResult([{message:t,text:this._baseMessageToString(t)}])}async*transform(e,t){yield*this._transformStreamWithConfig(e,this._transform.bind(this),{...t,runType:"parser"})}},vi=class extends ss{diff=!1;constructor(e){super(e),this.diff=e?.diff??this.diff}async*_transform(e){let t,r;for await(let n of e){if(typeof n!="string"&&typeof n.content!="string")throw new Error("Cannot handle non-string output.");let i;if(Ui(n)){if(typeof n.content!="string")throw new Error("Cannot handle non-string message output.");i=new Zr({message:n,text:n.content})}else if(ot(n)){if(typeof n.content!="string")throw new Error("Cannot handle non-string message output.");i=new Zr({message:Uo(n),text:n.content})}else i=new li({text:n});r===void 0?r=i:r=r.concat(i);let s=await this.parsePartialResult([r]);s!=null&&!gi(s,t)&&(this.diff?yield this._diff(t,s):yield s,t=s)}}getFormatInstructions(){return""}};var aR=class extends ss{static lc_name(){return"BytesOutputParser"}lc_namespace=["langchain_core","output_parsers","bytes"];lc_serializable=!0;textEncoder=new TextEncoder;parse(e){return Promise.resolve(this.textEncoder.encode(e))}getFormatInstructions(){return""}};var Kc=class extends ss{re;async*_transform(e){let t="";for await(let r of e)if(typeof r=="string"?t+=r:t+=r.content,this.re){let n=[...t.matchAll(this.re)];if(n.length>1){let i=0;for(let s of n.slice(0,-1))yield[s[1]],i+=(s.index??0)+s[0].length;t=t.slice(i)}}else{let n=await this.parse(t);if(n.length>1){for(let i of n.slice(0,-1))yield[i];t=n[n.length-1]}}for(let r of await this.parse(t))yield[r]}},cR=class extends Kc{static lc_name(){return"CommaSeparatedListOutputParser"}lc_namespace=["langchain_core","output_parsers","list"];lc_serializable=!0;async parse(e){try{return e.trim().split(",").map(t=>t.trim())}catch{throw new Hr(`Could not parse output: ${e}`,e)}}getFormatInstructions(){return"Your response should be a list of comma separated values, eg: `foo, bar, baz`"}},uR=class extends Kc{lc_namespace=["langchain_core","output_parsers","list"];length;separator;constructor({length:e,separator:t}){super(...arguments),this.length=e,this.separator=t||","}async parse(e){try{let t=e.trim().split(this.separator).map(r=>r.trim());if(this.length!==void 0&&t.length!==this.length)throw new Hr(`Incorrect number of items. Expected ${this.length}, got ${t.length}.`);return t}catch(t){throw Object.getPrototypeOf(t)===Hr.prototype?t:new Hr(`Could not parse output: ${e}`)}}getFormatInstructions(){return`Your response should be a list of ${this.length===void 0?"":`${this.length} `}items separated by "${this.separator}" (eg: \`foo${this.separator} bar${this.separator} baz\`)`}},lR=class extends Kc{static lc_name(){return"NumberedListOutputParser"}lc_namespace=["langchain_core","output_parsers","list"];lc_serializable=!0;getFormatInstructions(){return`Your response should be a numbered list with each item on a new line. For example:
|
|
116
|
+
|
|
117
|
+
1. foo
|
|
118
|
+
|
|
119
|
+
2. bar
|
|
120
|
+
|
|
121
|
+
3. baz`}re=/\d+\.\s([^\n]+)/g;async parse(e){return[...e.matchAll(this.re)??[]].map(t=>t[1])}},pR=class extends Kc{static lc_name(){return"NumberedListOutputParser"}lc_namespace=["langchain_core","output_parsers","list"];lc_serializable=!0;getFormatInstructions(){return`Your response should be a numbered list with each item on a new line. For example:
|
|
122
|
+
|
|
123
|
+
1. foo
|
|
124
|
+
|
|
125
|
+
2. bar
|
|
126
|
+
|
|
127
|
+
3. baz`}re=/^\s*[-*]\s([^\n]+)$/gm;async parse(e){return[...e.matchAll(this.re)??[]].map(t=>t[1])}};var dR=class extends ss{static lc_name(){return"StrOutputParser"}lc_namespace=["langchain_core","output_parsers","string"];lc_serializable=!0;parse(e){return Promise.resolve(e)}getFormatInstructions(){return""}_textContentToString(e){return e.text}_imageUrlContentToString(e){throw new Error('Cannot coerce a multimodal "image_url" message part into a string.')}_messageContentToString(e){switch(e.type){case"text":case"text_delta":if("text"in e)return this._textContentToString(e);break;case"image_url":if("image_url"in e)return this._imageUrlContentToString(e);break;default:throw new Error(`Cannot coerce "${e.type}" message part into a string.`)}throw new Error(`Invalid content type: ${e.type}`)}_baseMessageContentToString(e){return e.reduce((t,r)=>t+this._messageContentToString(r),"")}};var qc=class extends is{static lc_name(){return"StructuredOutputParser"}lc_namespace=["langchain","output_parsers","structured"];toJSON(){return this.toJSONNotImplemented()}constructor(e){super(e),this.schema=e}static fromZodSchema(e){return new this(e)}static fromNamesAndDescriptions(e){let t=Ge.object(Object.fromEntries(Object.entries(e).map(([r,n])=>[r,Ge.string().describe(n)])));return new this(t)}getFormatInstructions(){return`You must format your output as a JSON value that adheres to a given "JSON Schema" instance.
|
|
128
|
+
|
|
129
|
+
"JSON Schema" is a declarative language that allows you to annotate and validate JSON documents.
|
|
130
|
+
|
|
131
|
+
For example, the example "JSON Schema" instance {{"properties": {{"foo": {{"description": "a list of test words", "type": "array", "items": {{"type": "string"}}}}}}, "required": ["foo"]}}
|
|
132
|
+
would match an object with one required property, "foo". The "type" property specifies "foo" must be an "array", and the "description" property semantically describes it as "a list of test words". The items within "foo" must be strings.
|
|
133
|
+
Thus, the object {{"foo": ["bar", "baz"]}} is a well-formatted instance of this example "JSON Schema". The object {{"properties": {{"foo": ["bar", "baz"]}}}} is not well-formatted.
|
|
134
|
+
|
|
135
|
+
Your output will be parsed and type-checked according to the provided schema instance, so make sure all fields in your output match the schema exactly and there are no trailing commas!
|
|
136
|
+
|
|
137
|
+
Here is the JSON Schema instance your output must adhere to. Include the enclosing markdown codeblock:
|
|
138
|
+
\`\`\`json
|
|
139
|
+
${JSON.stringify(Ye(this.schema))}
|
|
140
|
+
\`\`\`
|
|
141
|
+
`}async parse(e){try{let t=e.trim(),n=(t.match(/^```(?:json)?\s*([\s\S]*?)```/)?.[1]||t.match(/```json\s*([\s\S]*?)```/)?.[1]||t).replace(/"([^"\\]*(\\.[^"\\]*)*)"/g,(i,s)=>`"${s.replace(/\n/g,"\\n")}"`).replace(/\n/g,"");return await Ws(this.schema,JSON.parse(n))}catch(t){throw new Hr(`Failed to parse. Text: "${e}". Error: ${t}`,e)}}},F0=class extends qc{static lc_name(){return"JsonMarkdownStructuredOutputParser"}getFormatInstructions(e){let t=e?.interpolationDepth??1;if(t<1)throw new Error("f string interpolation depth must be at least 1");return`Return a markdown code snippet with a JSON object formatted to look like:
|
|
142
|
+
\`\`\`json
|
|
143
|
+
${this._schemaToInstruction(Ye(this.schema)).replaceAll("{","{".repeat(t)).replaceAll("}","}".repeat(t))}
|
|
144
|
+
\`\`\``}_schemaToInstruction(e,t=2){let r=e;if("type"in r){let n=!1,i;if(Array.isArray(r.type)){let a=r.type.findIndex(c=>c==="null");a!==-1&&(n=!0,r.type.splice(a,1)),i=r.type.join(" | ")}else i=r.type;if(r.type==="object"&&r.properties){let a=r.description?` // ${r.description}`:"";return`{
|
|
145
|
+
${Object.entries(r.properties).map(([u,l])=>{let p=r.required?.includes(u)?"":" (optional)";return`${" ".repeat(t)}"${u}": ${this._schemaToInstruction(l,t+2)}${p}`}).join(`
|
|
146
|
+
`)}
|
|
147
|
+
${" ".repeat(t-2)}}${a}`}if(r.type==="array"&&r.items){let a=r.description?` // ${r.description}`:"";return`array[
|
|
148
|
+
${" ".repeat(t)}${this._schemaToInstruction(r.items,t+2)}
|
|
149
|
+
${" ".repeat(t-2)}] ${a}`}let s=n?" (nullable)":"",o=r.description?` // ${r.description}`:"";return`${i}${o}${s}`}if("anyOf"in r)return r.anyOf.map(n=>this._schemaToInstruction(n,t)).join(`
|
|
150
|
+
${" ".repeat(t-2)}`);throw new Error("unsupported schema type")}static fromZodSchema(e){return new this(e)}static fromNamesAndDescriptions(e){let t=Ge.object(Object.fromEntries(Object.entries(e).map(([r,n])=>[r,Ge.string().describe(n)])));return new this(t)}},fR=class extends is{structuredInputParser;constructor({inputSchema:e}){super(...arguments),this.structuredInputParser=new F0(e)}async parse(e){let t;try{t=await this.structuredInputParser.parse(e)}catch(r){throw new Hr(`Failed to parse. Text: "${e}". Error: ${r}`,e)}return this.outputProcessor(t)}getFormatInstructions(){return this.structuredInputParser.getFormatInstructions()}};var Dp=class extends vi{static lc_name(){return"JsonOutputParser"}lc_namespace=["langchain_core","output_parsers"];lc_serializable=!0;_concatOutputChunks(e,t){return this.diff?super._concatOutputChunks(e,t):t}_diff(e,t){if(t)return e?Vs(e,t):[{op:"replace",path:"",value:t}]}async parsePartialResult(e){return Rl(e[0].text)}async parse(e){return Rl(e,JSON.parse)}getFormatInstructions(){return""}_baseMessageToString(e){return e.text}};var a9=function(){let e={};e.parser=function(v,g){return new r(v,g)},e.SAXParser=r,e.SAXStream=u,e.createStream=c,e.MAX_BUFFER_LENGTH=65536;let t=["comment","sgmlDecl","textNode","tagName","doctype","procInstName","procInstBody","entity","attribName","attribValue","cdata","script"];e.EVENTS=["text","processinginstruction","sgmldeclaration","doctype","comment","opentagstart","attribute","opentag","closetag","opencdata","cdata","closecdata","error","end","ready","script","opennamespace","closenamespace"];function r(v,g){if(!(this instanceof r))return new r(v,g);var R=this;i(R),R.q=R.c="",R.bufferCheckPosition=e.MAX_BUFFER_LENGTH,R.opt=g||{},R.opt.lowercase=R.opt.lowercase||R.opt.lowercasetags,R.looseCase=R.opt.lowercase?"toLowerCase":"toUpperCase",R.tags=[],R.closed=R.closedRoot=R.sawRoot=!1,R.tag=R.error=null,R.strict=!!v,R.noscript=!!(v||R.opt.noscript),R.state=w.BEGIN,R.strictEntities=R.opt.strictEntities,R.ENTITIES=R.strictEntities?Object.create(e.XML_ENTITIES):Object.create(e.ENTITIES),R.attribList=[],R.opt.xmlns&&(R.ns=Object.create(m)),R.trackPosition=R.opt.position!==!1,R.trackPosition&&(R.position=R.line=R.column=0),P(R,"onready")}Object.create||(Object.create=function(v){function g(){}g.prototype=v;var R=new g;return R}),Object.keys||(Object.keys=function(v){var g=[];for(var R in v)v.hasOwnProperty(R)&&g.push(R);return g});function n(v){for(var g=Math.max(e.MAX_BUFFER_LENGTH,10),R=0,E=0,je=t.length;E<je;E++){var He=v[t[E]].length;if(He>g)switch(t[E]){case"textNode":Te(v);break;case"cdata":V(v,"oncdata",v.cdata),v.cdata="";break;case"script":V(v,"onscript",v.script),v.script="";break;default:cr(v,"Max buffer length exceeded: "+t[E])}R=Math.max(R,He)}var tt=e.MAX_BUFFER_LENGTH-R;v.bufferCheckPosition=tt+v.position}function i(v){for(var g=0,R=t.length;g<R;g++)v[t[g]]=""}function s(v){Te(v),v.cdata!==""&&(V(v,"oncdata",v.cdata),v.cdata=""),v.script!==""&&(V(v,"onscript",v.script),v.script="")}r.prototype={end:function(){Lr(this)},write:Sn,resume:function(){return this.error=null,this},close:function(){return this.write(null)},flush:function(){s(this)}};var o=ReadableStream;o||(o=function(){});var a=e.EVENTS.filter(function(v){return v!=="error"&&v!=="end"});function c(v,g){return new u(v,g)}function u(v,g){if(!(this instanceof u))return new u(v,g);o.apply(this),this._parser=new r(v,g),this.writable=!0,this.readable=!0;var R=this;this._parser.onend=function(){R.emit("end")},this._parser.onerror=function(E){R.emit("error",E),R._parser.error=null},this._decoder=null,a.forEach(function(E){Object.defineProperty(R,"on"+E,{get:function(){return R._parser["on"+E]},set:function(je){if(!je)return R.removeAllListeners(E),R._parser["on"+E]=je,je;R.on(E,je)},enumerable:!0,configurable:!1})})}u.prototype=Object.create(o.prototype,{constructor:{value:u}}),u.prototype.write=function(v){return this._parser.write(v.toString()),this.emit("data",v),!0},u.prototype.end=function(v){return v&&v.length&&this.write(v),this._parser.end(),!0},u.prototype.on=function(v,g){var R=this;return!R._parser["on"+v]&&a.indexOf(v)!==-1&&(R._parser["on"+v]=function(){var E=arguments.length===1?[arguments[0]]:Array.apply(null,arguments);E.splice(0,0,v),R.emit.apply(R,E)}),o.prototype.on.call(R,v,g)};var l="[CDATA[",p="DOCTYPE",f="http://www.w3.org/XML/1998/namespace",d="http://www.w3.org/2000/xmlns/",m={xml:f,xmlns:d},h=/[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,b=/[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/,_=/[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,y=/[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/;function x(v){return v===" "||v===`
|
|
151
|
+
`||v==="\r"||v===" "}function I(v){return v==='"'||v==="'"}function A(v){return v===">"||x(v)}function j(v,g){return v.test(g)}function O(v,g){return!j(v,g)}var w=0;e.STATE={BEGIN:w++,BEGIN_WHITESPACE:w++,TEXT:w++,TEXT_ENTITY:w++,OPEN_WAKA:w++,SGML_DECL:w++,SGML_DECL_QUOTED:w++,DOCTYPE:w++,DOCTYPE_QUOTED:w++,DOCTYPE_DTD:w++,DOCTYPE_DTD_QUOTED:w++,COMMENT_STARTING:w++,COMMENT:w++,COMMENT_ENDING:w++,COMMENT_ENDED:w++,CDATA:w++,CDATA_ENDING:w++,CDATA_ENDING_2:w++,PROC_INST:w++,PROC_INST_BODY:w++,PROC_INST_ENDING:w++,OPEN_TAG:w++,OPEN_TAG_SLASH:w++,ATTRIB:w++,ATTRIB_NAME:w++,ATTRIB_NAME_SAW_WHITE:w++,ATTRIB_VALUE:w++,ATTRIB_VALUE_QUOTED:w++,ATTRIB_VALUE_CLOSED:w++,ATTRIB_VALUE_UNQUOTED:w++,ATTRIB_VALUE_ENTITY_Q:w++,ATTRIB_VALUE_ENTITY_U:w++,CLOSE_TAG:w++,CLOSE_TAG_SAW_WHITE:w++,SCRIPT:w++,SCRIPT_ENDING:w++},e.XML_ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'"},e.ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'",AElig:198,Aacute:193,Acirc:194,Agrave:192,Aring:197,Atilde:195,Auml:196,Ccedil:199,ETH:208,Eacute:201,Ecirc:202,Egrave:200,Euml:203,Iacute:205,Icirc:206,Igrave:204,Iuml:207,Ntilde:209,Oacute:211,Ocirc:212,Ograve:210,Oslash:216,Otilde:213,Ouml:214,THORN:222,Uacute:218,Ucirc:219,Ugrave:217,Uuml:220,Yacute:221,aacute:225,acirc:226,aelig:230,agrave:224,aring:229,atilde:227,auml:228,ccedil:231,eacute:233,ecirc:234,egrave:232,eth:240,euml:235,iacute:237,icirc:238,igrave:236,iuml:239,ntilde:241,oacute:243,ocirc:244,ograve:242,oslash:248,otilde:245,ouml:246,szlig:223,thorn:254,uacute:250,ucirc:251,ugrave:249,uuml:252,yacute:253,yuml:255,copy:169,reg:174,nbsp:160,iexcl:161,cent:162,pound:163,curren:164,yen:165,brvbar:166,sect:167,uml:168,ordf:170,laquo:171,not:172,shy:173,macr:175,deg:176,plusmn:177,sup1:185,sup2:178,sup3:179,acute:180,micro:181,para:182,middot:183,cedil:184,ordm:186,raquo:187,frac14:188,frac12:189,frac34:190,iquest:191,times:215,divide:247,OElig:338,oelig:339,Scaron:352,scaron:353,Yuml:376,fnof:402,circ:710,tilde:732,Alpha:913,Beta:914,Gamma:915,Delta:916,Epsilon:917,Zeta:918,Eta:919,Theta:920,Iota:921,Kappa:922,Lambda:923,Mu:924,Nu:925,Xi:926,Omicron:927,Pi:928,Rho:929,Sigma:931,Tau:932,Upsilon:933,Phi:934,Chi:935,Psi:936,Omega:937,alpha:945,beta:946,gamma:947,delta:948,epsilon:949,zeta:950,eta:951,theta:952,iota:953,kappa:954,lambda:955,mu:956,nu:957,xi:958,omicron:959,pi:960,rho:961,sigmaf:962,sigma:963,tau:964,upsilon:965,phi:966,chi:967,psi:968,omega:969,thetasym:977,upsih:978,piv:982,ensp:8194,emsp:8195,thinsp:8201,zwnj:8204,zwj:8205,lrm:8206,rlm:8207,ndash:8211,mdash:8212,lsquo:8216,rsquo:8217,sbquo:8218,ldquo:8220,rdquo:8221,bdquo:8222,dagger:8224,Dagger:8225,bull:8226,hellip:8230,permil:8240,prime:8242,Prime:8243,lsaquo:8249,rsaquo:8250,oline:8254,frasl:8260,euro:8364,image:8465,weierp:8472,real:8476,trade:8482,alefsym:8501,larr:8592,uarr:8593,rarr:8594,darr:8595,harr:8596,crarr:8629,lArr:8656,uArr:8657,rArr:8658,dArr:8659,hArr:8660,forall:8704,part:8706,exist:8707,empty:8709,nabla:8711,isin:8712,notin:8713,ni:8715,prod:8719,sum:8721,minus:8722,lowast:8727,radic:8730,prop:8733,infin:8734,ang:8736,and:8743,or:8744,cap:8745,cup:8746,int:8747,there4:8756,sim:8764,cong:8773,asymp:8776,ne:8800,equiv:8801,le:8804,ge:8805,sub:8834,sup:8835,nsub:8836,sube:8838,supe:8839,oplus:8853,otimes:8855,perp:8869,sdot:8901,lceil:8968,rceil:8969,lfloor:8970,rfloor:8971,lang:9001,rang:9002,loz:9674,spades:9824,clubs:9827,hearts:9829,diams:9830},Object.keys(e.ENTITIES).forEach(function(v){var g=e.ENTITIES[v],R=typeof g=="number"?String.fromCharCode(g):g;e.ENTITIES[v]=R});for(var F in e.STATE)e.STATE[e.STATE[F]]=F;w=e.STATE;function P(v,g,R){v[g]&&v[g](R)}function V(v,g,R){v.textNode&&Te(v),P(v,g,R)}function Te(v){v.textNode=qe(v.opt,v.textNode),v.textNode&&P(v,"ontext",v.textNode),v.textNode=""}function qe(v,g){return v.trim&&(g=g.trim()),v.normalize&&(g=g.replace(/\s+/g," ")),g}function cr(v,g){return Te(v),v.trackPosition&&(g+=`
|
|
152
|
+
Line: `+v.line+`
|
|
153
|
+
Column: `+v.column+`
|
|
154
|
+
Char: `+v.c),g=new Error(g),v.error=g,P(v,"onerror",g),v}function Lr(v){return v.sawRoot&&!v.closedRoot&&Me(v,"Unclosed root tag"),v.state!==w.BEGIN&&v.state!==w.BEGIN_WHITESPACE&&v.state!==w.TEXT&&cr(v,"Unexpected end"),Te(v),v.c="",v.closed=!0,P(v,"onend"),r.call(v,v.strict,v.opt),v}function Me(v,g){if(typeof v!="object"||!(v instanceof r))throw new Error("bad call to strictFail");v.strict&&cr(v,g)}function To(v){v.strict||(v.tagName=v.tagName[v.looseCase]());var g=v.tags[v.tags.length-1]||v,R=v.tag={name:v.tagName,attributes:{}};v.opt.xmlns&&(R.ns=g.ns),v.attribList.length=0,V(v,"onopentagstart",R)}function Ni(v,g){var R=v.indexOf(":"),E=R<0?["",v]:v.split(":"),je=E[0],He=E[1];return g&&v==="xmlns"&&(je="xmlns",He=""),{prefix:je,local:He}}function Oo(v){if(v.strict||(v.attribName=v.attribName[v.looseCase]()),v.attribList.indexOf(v.attribName)!==-1||v.tag.attributes.hasOwnProperty(v.attribName)){v.attribName=v.attribValue="";return}if(v.opt.xmlns){var g=Ni(v.attribName,!0),R=g.prefix,E=g.local;if(R==="xmlns")if(E==="xml"&&v.attribValue!==f)Me(v,"xml: prefix must be bound to "+f+`
|
|
155
|
+
Actual: `+v.attribValue);else if(E==="xmlns"&&v.attribValue!==d)Me(v,"xmlns: prefix must be bound to "+d+`
|
|
156
|
+
Actual: `+v.attribValue);else{var je=v.tag,He=v.tags[v.tags.length-1]||v;je.ns===He.ns&&(je.ns=Object.create(He.ns)),je.ns[E]=v.attribValue}v.attribList.push([v.attribName,v.attribValue])}else v.tag.attributes[v.attribName]=v.attribValue,V(v,"onattribute",{name:v.attribName,value:v.attribValue});v.attribName=v.attribValue=""}function In(v,g){if(v.opt.xmlns){var R=v.tag,E=Ni(v.tagName);R.prefix=E.prefix,R.local=E.local,R.uri=R.ns[E.prefix]||"",R.prefix&&!R.uri&&(Me(v,"Unbound namespace prefix: "+JSON.stringify(v.tagName)),R.uri=E.prefix);var je=v.tags[v.tags.length-1]||v;R.ns&&je.ns!==R.ns&&Object.keys(R.ns).forEach(function($o){V(v,"onopennamespace",{prefix:$o,uri:R.ns[$o]})});for(var He=0,tt=v.attribList.length;He<tt;He++){var St=v.attribList[He],Bt=St[0],En=St[1],mt=Ni(Bt,!0),tn=mt.prefix,ac=mt.local,Wd=tn===""?"":R.ns[tn]||"",J={name:Bt,value:En,prefix:tn,local:ac,uri:Wd};tn&&tn!=="xmlns"&&!Wd&&(Me(v,"Unbound namespace prefix: "+JSON.stringify(tn)),J.uri=tn),v.tag.attributes[Bt]=J,V(v,"onattribute",J)}v.attribList.length=0}v.tag.isSelfClosing=!!g,v.sawRoot=!0,v.tags.push(v.tag),V(v,"onopentag",v.tag),g||(!v.noscript&&v.tagName.toLowerCase()==="script"?v.state=w.SCRIPT:v.state=w.TEXT,v.tag=null,v.tagName=""),v.attribName=v.attribValue="",v.attribList.length=0}function Ri(v){if(!v.tagName){Me(v,"Weird empty close tag."),v.textNode+="</>",v.state=w.TEXT;return}if(v.script){if(v.tagName!=="script"){v.script+="</"+v.tagName+">",v.tagName="",v.state=w.SCRIPT;return}V(v,"onscript",v.script),v.script=""}var g=v.tags.length,R=v.tagName;v.strict||(R=R[v.looseCase]());for(var E=R;g--;){var je=v.tags[g];if(je.name!==E)Me(v,"Unexpected close tag");else break}if(g<0){Me(v,"Unmatched closing tag: "+v.tagName),v.textNode+="</"+v.tagName+">",v.state=w.TEXT;return}v.tagName=R;for(var He=v.tags.length;He-- >g;){var tt=v.tag=v.tags.pop();v.tagName=v.tag.name,V(v,"onclosetag",v.tagName);var St={};for(var Bt in tt.ns)St[Bt]=tt.ns[Bt];var En=v.tags[v.tags.length-1]||v;v.opt.xmlns&&tt.ns!==En.ns&&Object.keys(tt.ns).forEach(function(mt){var tn=tt.ns[mt];V(v,"onclosenamespace",{prefix:mt,uri:tn})})}g===0&&(v.closedRoot=!0),v.tagName=v.attribValue=v.attribName="",v.attribList.length=0,v.state=w.TEXT}function ll(v){var g=v.entity,R=g.toLowerCase(),E,je="";return v.ENTITIES[g]?v.ENTITIES[g]:v.ENTITIES[R]?v.ENTITIES[R]:(g=R,g.charAt(0)==="#"&&(g.charAt(1)==="x"?(g=g.slice(2),E=parseInt(g,16),je=E.toString(16)):(g=g.slice(1),E=parseInt(g,10),je=E.toString(10))),g=g.replace(/^0+/,""),isNaN(E)||je.toLowerCase()!==g?(Me(v,"Invalid character entity"),"&"+v.entity+";"):String.fromCodePoint(E))}function pl(v,g){g==="<"?(v.state=w.OPEN_WAKA,v.startTagPosition=v.position):x(g)||(Me(v,"Non-whitespace before first tag."),v.textNode=g,v.state=w.TEXT)}function dl(v,g){var R="";return g<v.length&&(R=v.charAt(g)),R}function Sn(v){var g=this;if(this.error)throw this.error;if(g.closed)return cr(g,"Cannot write after close. Assign an onready handler.");if(v===null)return Lr(g);typeof v=="object"&&(v=v.toString());for(var R=0,E="";E=dl(v,R++),g.c=E,!!E;)switch(g.trackPosition&&(g.position++,E===`
|
|
157
|
+
`?(g.line++,g.column=0):g.column++),g.state){case w.BEGIN:if(g.state=w.BEGIN_WHITESPACE,E==="\uFEFF")continue;pl(g,E);continue;case w.BEGIN_WHITESPACE:pl(g,E);continue;case w.TEXT:if(g.sawRoot&&!g.closedRoot){for(var je=R-1;E&&E!=="<"&&E!=="&";)E=dl(v,R++),E&&g.trackPosition&&(g.position++,E===`
|
|
158
|
+
`?(g.line++,g.column=0):g.column++);g.textNode+=v.substring(je,R-1)}E==="<"&&!(g.sawRoot&&g.closedRoot&&!g.strict)?(g.state=w.OPEN_WAKA,g.startTagPosition=g.position):(!x(E)&&(!g.sawRoot||g.closedRoot)&&Me(g,"Text data outside of root node."),E==="&"?g.state=w.TEXT_ENTITY:g.textNode+=E);continue;case w.SCRIPT:E==="<"?g.state=w.SCRIPT_ENDING:g.script+=E;continue;case w.SCRIPT_ENDING:E==="/"?g.state=w.CLOSE_TAG:(g.script+="<"+E,g.state=w.SCRIPT);continue;case w.OPEN_WAKA:if(E==="!")g.state=w.SGML_DECL,g.sgmlDecl="";else if(!x(E))if(j(h,E))g.state=w.OPEN_TAG,g.tagName=E;else if(E==="/")g.state=w.CLOSE_TAG,g.tagName="";else if(E==="?")g.state=w.PROC_INST,g.procInstName=g.procInstBody="";else{if(Me(g,"Unencoded <"),g.startTagPosition+1<g.position){var He=g.position-g.startTagPosition;E=new Array(He).join(" ")+E}g.textNode+="<"+E,g.state=w.TEXT}continue;case w.SGML_DECL:(g.sgmlDecl+E).toUpperCase()===l?(V(g,"onopencdata"),g.state=w.CDATA,g.sgmlDecl="",g.cdata=""):g.sgmlDecl+E==="--"?(g.state=w.COMMENT,g.comment="",g.sgmlDecl=""):(g.sgmlDecl+E).toUpperCase()===p?(g.state=w.DOCTYPE,(g.doctype||g.sawRoot)&&Me(g,"Inappropriately located doctype declaration"),g.doctype="",g.sgmlDecl=""):E===">"?(V(g,"onsgmldeclaration",g.sgmlDecl),g.sgmlDecl="",g.state=w.TEXT):(I(E)&&(g.state=w.SGML_DECL_QUOTED),g.sgmlDecl+=E);continue;case w.SGML_DECL_QUOTED:E===g.q&&(g.state=w.SGML_DECL,g.q=""),g.sgmlDecl+=E;continue;case w.DOCTYPE:E===">"?(g.state=w.TEXT,V(g,"ondoctype",g.doctype),g.doctype=!0):(g.doctype+=E,E==="["?g.state=w.DOCTYPE_DTD:I(E)&&(g.state=w.DOCTYPE_QUOTED,g.q=E));continue;case w.DOCTYPE_QUOTED:g.doctype+=E,E===g.q&&(g.q="",g.state=w.DOCTYPE);continue;case w.DOCTYPE_DTD:g.doctype+=E,E==="]"?g.state=w.DOCTYPE:I(E)&&(g.state=w.DOCTYPE_DTD_QUOTED,g.q=E);continue;case w.DOCTYPE_DTD_QUOTED:g.doctype+=E,E===g.q&&(g.state=w.DOCTYPE_DTD,g.q="");continue;case w.COMMENT:E==="-"?g.state=w.COMMENT_ENDING:g.comment+=E;continue;case w.COMMENT_ENDING:E==="-"?(g.state=w.COMMENT_ENDED,g.comment=qe(g.opt,g.comment),g.comment&&V(g,"oncomment",g.comment),g.comment=""):(g.comment+="-"+E,g.state=w.COMMENT);continue;case w.COMMENT_ENDED:E!==">"?(Me(g,"Malformed comment"),g.comment+="--"+E,g.state=w.COMMENT):g.state=w.TEXT;continue;case w.CDATA:E==="]"?g.state=w.CDATA_ENDING:g.cdata+=E;continue;case w.CDATA_ENDING:E==="]"?g.state=w.CDATA_ENDING_2:(g.cdata+="]"+E,g.state=w.CDATA);continue;case w.CDATA_ENDING_2:E===">"?(g.cdata&&V(g,"oncdata",g.cdata),V(g,"onclosecdata"),g.cdata="",g.state=w.TEXT):E==="]"?g.cdata+="]":(g.cdata+="]]"+E,g.state=w.CDATA);continue;case w.PROC_INST:E==="?"?g.state=w.PROC_INST_ENDING:x(E)?g.state=w.PROC_INST_BODY:g.procInstName+=E;continue;case w.PROC_INST_BODY:if(!g.procInstBody&&x(E))continue;E==="?"?g.state=w.PROC_INST_ENDING:g.procInstBody+=E;continue;case w.PROC_INST_ENDING:E===">"?(V(g,"onprocessinginstruction",{name:g.procInstName,body:g.procInstBody}),g.procInstName=g.procInstBody="",g.state=w.TEXT):(g.procInstBody+="?"+E,g.state=w.PROC_INST_BODY);continue;case w.OPEN_TAG:j(b,E)?g.tagName+=E:(To(g),E===">"?In(g):E==="/"?g.state=w.OPEN_TAG_SLASH:(x(E)||Me(g,"Invalid character in tag name"),g.state=w.ATTRIB));continue;case w.OPEN_TAG_SLASH:E===">"?(In(g,!0),Ri(g)):(Me(g,"Forward-slash in opening tag not followed by >"),g.state=w.ATTRIB);continue;case w.ATTRIB:if(x(E))continue;E===">"?In(g):E==="/"?g.state=w.OPEN_TAG_SLASH:j(h,E)?(g.attribName=E,g.attribValue="",g.state=w.ATTRIB_NAME):Me(g,"Invalid attribute name");continue;case w.ATTRIB_NAME:E==="="?g.state=w.ATTRIB_VALUE:E===">"?(Me(g,"Attribute without value"),g.attribValue=g.attribName,Oo(g),In(g)):x(E)?g.state=w.ATTRIB_NAME_SAW_WHITE:j(b,E)?g.attribName+=E:Me(g,"Invalid attribute name");continue;case w.ATTRIB_NAME_SAW_WHITE:if(E==="=")g.state=w.ATTRIB_VALUE;else{if(x(E))continue;Me(g,"Attribute without value"),g.tag.attributes[g.attribName]="",g.attribValue="",V(g,"onattribute",{name:g.attribName,value:""}),g.attribName="",E===">"?In(g):j(h,E)?(g.attribName=E,g.state=w.ATTRIB_NAME):(Me(g,"Invalid attribute name"),g.state=w.ATTRIB)}continue;case w.ATTRIB_VALUE:if(x(E))continue;I(E)?(g.q=E,g.state=w.ATTRIB_VALUE_QUOTED):(Me(g,"Unquoted attribute value"),g.state=w.ATTRIB_VALUE_UNQUOTED,g.attribValue=E);continue;case w.ATTRIB_VALUE_QUOTED:if(E!==g.q){E==="&"?g.state=w.ATTRIB_VALUE_ENTITY_Q:g.attribValue+=E;continue}Oo(g),g.q="",g.state=w.ATTRIB_VALUE_CLOSED;continue;case w.ATTRIB_VALUE_CLOSED:x(E)?g.state=w.ATTRIB:E===">"?In(g):E==="/"?g.state=w.OPEN_TAG_SLASH:j(h,E)?(Me(g,"No whitespace between attributes"),g.attribName=E,g.attribValue="",g.state=w.ATTRIB_NAME):Me(g,"Invalid attribute name");continue;case w.ATTRIB_VALUE_UNQUOTED:if(!A(E)){E==="&"?g.state=w.ATTRIB_VALUE_ENTITY_U:g.attribValue+=E;continue}Oo(g),E===">"?In(g):g.state=w.ATTRIB;continue;case w.CLOSE_TAG:if(g.tagName)E===">"?Ri(g):j(b,E)?g.tagName+=E:g.script?(g.script+="</"+g.tagName,g.tagName="",g.state=w.SCRIPT):(x(E)||Me(g,"Invalid tagname in closing tag"),g.state=w.CLOSE_TAG_SAW_WHITE);else{if(x(E))continue;O(h,E)?g.script?(g.script+="</"+E,g.state=w.SCRIPT):Me(g,"Invalid tagname in closing tag."):g.tagName=E}continue;case w.CLOSE_TAG_SAW_WHITE:if(x(E))continue;E===">"?Ri(g):Me(g,"Invalid characters in closing tag");continue;case w.TEXT_ENTITY:case w.ATTRIB_VALUE_ENTITY_Q:case w.ATTRIB_VALUE_ENTITY_U:var tt,St;switch(g.state){case w.TEXT_ENTITY:tt=w.TEXT,St="textNode";break;case w.ATTRIB_VALUE_ENTITY_Q:tt=w.ATTRIB_VALUE_QUOTED,St="attribValue";break;case w.ATTRIB_VALUE_ENTITY_U:tt=w.ATTRIB_VALUE_UNQUOTED,St="attribValue";break}if(E===";")if(g.opt.unparsedEntities){var Bt=ll(g);g.entity="",g.state=tt,g.write(Bt)}else g[St]+=ll(g),g.entity="",g.state=tt;else j(g.entity.length?y:_,E)?g.entity+=E:(Me(g,"Invalid character in entity name"),g[St]+="&"+g.entity+E,g.entity="",g.state=tt);continue;default:throw new Error(g,"Unknown state: "+g.state)}return g.position>=g.bufferCheckPosition&&n(g),g}return String.fromCodePoint||(function(){var v=String.fromCharCode,g=Math.floor,R=function(){var E=16384,je=[],He,tt,St=-1,Bt=arguments.length;if(!Bt)return"";for(var En="";++St<Bt;){var mt=Number(arguments[St]);if(!isFinite(mt)||mt<0||mt>1114111||g(mt)!==mt)throw RangeError("Invalid code point: "+mt);mt<=65535?je.push(mt):(mt-=65536,He=(mt>>10)+55296,tt=mt%1024+56320,je.push(He,tt)),(St+1===Bt||je.length>E)&&(En+=v.apply(null,je),je.length=0)}return En};Object.defineProperty?Object.defineProperty(String,"fromCodePoint",{value:R,configurable:!0,writable:!0}):String.fromCodePoint=R})(),e},mR=a9();var zh=`The output should be formatted as a XML file.
|
|
159
|
+
1. Output should conform to the tags below.
|
|
160
|
+
2. If tags are not given, make them on your own.
|
|
161
|
+
3. Remember to always open and close all the tags.
|
|
162
|
+
|
|
163
|
+
As an example, for the tags ["foo", "bar", "baz"]:
|
|
164
|
+
1. String "<foo>
|
|
165
|
+
<bar>
|
|
166
|
+
<baz></baz>
|
|
167
|
+
</bar>
|
|
168
|
+
</foo>" is a well-formatted instance of the schema.
|
|
169
|
+
2. String "<foo>
|
|
170
|
+
<bar>
|
|
171
|
+
</foo>" is a badly-formatted instance.
|
|
172
|
+
3. String "<foo>
|
|
173
|
+
<tag>
|
|
174
|
+
</tag>
|
|
175
|
+
</foo>" is a badly-formatted instance.
|
|
176
|
+
|
|
177
|
+
Here are the output tags:
|
|
178
|
+
\`\`\`
|
|
179
|
+
{tags}
|
|
180
|
+
\`\`\``,hR=class extends vi{tags;constructor(e){super(e),this.tags=e?.tags}static lc_name(){return"XMLOutputParser"}lc_namespace=["langchain_core","output_parsers"];lc_serializable=!0;_diff(e,t){if(t)return e?Vs(e,t):[{op:"replace",path:"",value:t}]}async parsePartialResult(e){return Lh(e[0].text)}async parse(e){return Lh(e)}getFormatInstructions(){return!!(this.tags&&this.tags.length>0)?zh.replace("{tags}",this.tags?.join(", ")??""):zh}},c9=e=>e.split(`
|
|
181
|
+
`).map(t=>t.replace(/^\s+/,"")).join(`
|
|
182
|
+
`).trim(),gR=e=>{if(Object.keys(e).length===0)return{};let t={};return e.children.length>0?(t[e.name]=e.children.map(gR),t):(t[e.name]=e.text??void 0,t)};function Lh(e){let t=c9(e),r=mR.parser(!0),n={},i=[];r.onopentag=a=>{let c={name:a.name,attributes:a.attributes,children:[],text:"",isSelfClosing:a.isSelfClosing};i.length>0?i[i.length-1].children.push(c):n=c,a.isSelfClosing||i.push(c)},r.onclosetag=()=>{if(i.length>0){let a=i.pop();i.length===0&&a&&(n=a)}},r.ontext=a=>{if(i.length>0){let c=i[i.length-1];c.text+=a}},r.onattribute=a=>{if(i.length>0){let c=i[i.length-1];c.attributes[a.name]=a.value}};let s=/```(xml)?(.*)```/s.exec(t),o=s?s[2]:t;return r.write(o).close(),n&&n.name==="?xml"&&(n=n.children[0]),gR(n)}var B0={};M(B0,{AsymmetricStructuredOutputParser:()=>fR,BaseCumulativeTransformOutputParser:()=>vi,BaseLLMOutputParser:()=>Gc,BaseOutputParser:()=>is,BaseTransformOutputParser:()=>ss,BytesOutputParser:()=>aR,CommaSeparatedListOutputParser:()=>cR,CustomListOutputParser:()=>uR,JsonMarkdownStructuredOutputParser:()=>F0,JsonOutputParser:()=>Dp,ListOutputParser:()=>Kc,MarkdownListOutputParser:()=>pR,NumberedListOutputParser:()=>lR,OutputParserException:()=>Hr,StringOutputParser:()=>dR,StructuredOutputParser:()=>qc,XMLOutputParser:()=>hR,XML_FORMAT_INSTRUCTIONS:()=>zh,parseJsonMarkdown:()=>Rl,parsePartialJson:()=>ai,parseXMLMarkdown:()=>Lh});var V0=class extends Gc{static lc_name(){return"OutputFunctionsParser"}lc_namespace=["langchain","output_parsers","openai_functions"];lc_serializable=!0;argsOnly=!0;constructor(e){super(),this.argsOnly=e?.argsOnly??this.argsOnly}async parseResult(e){if("message"in e[0]){let r=e[0].message.additional_kwargs.function_call;if(!r)throw new Error(`No function_call in message ${JSON.stringify(e)}`);if(!r.arguments)throw new Error(`No arguments in function_call ${JSON.stringify(e)}`);return this.argsOnly?r.arguments:JSON.stringify(r)}else throw new Error(`No message in generations ${JSON.stringify(e)}`)}},Z0=class extends vi{static lc_name(){return"JsonOutputFunctionsParser"}lc_namespace=["langchain","output_parsers","openai_functions"];lc_serializable=!0;outputParser;argsOnly=!0;constructor(e){super(e),this.argsOnly=e?.argsOnly??this.argsOnly,this.outputParser=new V0(e)}_diff(e,t){return t?Vs(e??{},t):void 0}async parsePartialResult(e){let t=e[0];if(!t.message)return;let{message:r}=t,n=r.additional_kwargs.function_call;if(n)return this.argsOnly?ai(n.arguments):{...n,arguments:ai(n.arguments)}}async parseResult(e){let t=await this.outputParser.parseResult(e);if(!t)throw new Error(`No result from "OutputFunctionsParser" ${JSON.stringify(e)}`);return this.parse(t)}async parse(e){let t=JSON.parse(e);return this.argsOnly||(t.arguments=JSON.parse(t.arguments)),t}getFormatInstructions(){return""}},_R=class extends Gc{static lc_name(){return"JsonKeyOutputFunctionsParser"}lc_namespace=["langchain","output_parsers","openai_functions"];lc_serializable=!0;outputParser=new Z0;attrName;get lc_aliases(){return{attrName:"key_name"}}constructor(e){super(e),this.attrName=e.attrName}async parseResult(e){return(await this.outputParser.parseResult(e))[this.attrName]}};var G0={};M(G0,{JsonKeyOutputFunctionsParser:()=>_R,JsonOutputFunctionsParser:()=>Z0,OutputFunctionsParser:()=>V0});function wa(e,t){if(e.function===void 0)return;let r;if(t?.partial)try{r=ai(e.function.arguments??"{}")}catch{return}else try{r=JSON.parse(e.function.arguments)}catch(i){throw new Hr([`Function "${e.function.name}" arguments:`,"",e.function.arguments,"","are not valid JSON.",`Error: ${i.message}`].join(`
|
|
183
|
+
`))}let n={name:e.function.name,args:r,type:"tool_call"};return t?.returnId&&(n.id=e.id),n}function Uh(e){if(e.id===void 0)throw new Error('All OpenAI tool calls must have an "id" field.');return{id:e.id,type:"function",function:{name:e.name,arguments:JSON.stringify(e.args)}}}function ro(e,t){return{name:e.function?.name,args:e.function?.arguments,id:e.id,error:t,type:"invalid_tool_call"}}var K0=class extends vi{static lc_name(){return"JsonOutputToolsParser"}returnId=!1;lc_namespace=["langchain","output_parsers","openai_tools"];lc_serializable=!0;constructor(e){super(e),this.returnId=e?.returnId??this.returnId}_diff(){throw new Error("Not supported.")}async parse(){throw new Error("Not implemented.")}async parseResult(e){return await this.parsePartialResult(e,!1)}async parsePartialResult(e,t=!0){let r=e[0].message,n;if(ci(r)&&r.tool_calls?.length?n=r.tool_calls.map(s=>{let{id:o,...a}=s;return this.returnId?{id:o,...a}:a}):r.additional_kwargs.tool_calls!==void 0&&(n=JSON.parse(JSON.stringify(r.additional_kwargs.tool_calls)).map(o=>wa(o,{returnId:this.returnId,partial:t}))),!n)return[];let i=[];for(let s of n)if(s!==void 0){let o={type:s.name,args:s.args,id:s.id};i.push(o)}return i}},zp=class extends K0{static lc_name(){return"JsonOutputKeyToolsParser"}lc_namespace=["langchain","output_parsers","openai_tools"];lc_serializable=!0;returnId=!1;keyName;returnSingle=!1;zodSchema;constructor(e){super(e),this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,this.zodSchema=e.zodSchema}async _validateResult(e){if(this.zodSchema===void 0)return e;let t=await nh(this.zodSchema,e);if(t.success)return t.data;throw new Hr(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(t.error?.issues)}`,JSON.stringify(e,null,2))}async parsePartialResult(e){let r=(await super.parsePartialResult(e)).filter(i=>i.type===this.keyName),n=r;if(r.length)return this.returnId||(n=r.map(i=>i.args)),this.returnSingle?n[0]:n}async parseResult(e){let r=(await super.parsePartialResult(e,!1)).filter(s=>s.type===this.keyName),n=r;return r.length?(this.returnId||(n=r.map(s=>s.args)),this.returnSingle?this._validateResult(n[0]):await Promise.all(n.map(s=>this._validateResult(s)))):void 0}};var q0={};M(q0,{JsonOutputKeyToolsParser:()=>zp,JsonOutputToolsParser:()=>K0,convertLangChainToolCallToOpenAI:()=>Uh,makeInvalidToolCall:()=>ro,parseToolCall:()=>wa});var bi=class extends ce{lc_serializable=!0;lc_namespace=["langchain_core","prompts",this._getPromptType()];get lc_attributes(){return{partialVariables:void 0}}inputVariables;outputParser;partialVariables;metadata;tags;constructor(e){super(e);let{inputVariables:t}=e;if(t.includes("stop"))throw new Error("Cannot have an input variable named 'stop', as it is used internally, please rename.");Object.assign(this,e)}async mergePartialAndUserVariables(e){let t=this.partialVariables??{},r={};for(let[i,s]of Object.entries(t))typeof s=="string"?r[i]=s:r[i]=await s();return{...r,...e}}async invoke(e,t){let r={...this.metadata,...t?.metadata},n=[...this.tags??[],...t?.tags??[]];return this._callWithConfig(i=>this.formatPromptValue(i),e,{...t,tags:n,metadata:r,runType:"prompt"})}};var os=class extends bi{async formatPromptValue(e){let t=await this.format(e);return new $p(t)}};var u9=Object.prototype.toString,Wc=Array.isArray||function(t){return u9.call(t)==="[object Array]"};function W0(e){return typeof e=="function"}function l9(e){return Wc(e)?"array":typeof e}function H0(e){return e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function yR(e,t){return e!=null&&typeof e=="object"&&t in e}function p9(e,t){return e!=null&&typeof e!="object"&&e.hasOwnProperty&&e.hasOwnProperty(t)}var d9=RegExp.prototype.test;function f9(e,t){return d9.call(e,t)}var m9=/\S/;function h9(e){return!f9(m9,e)}var g9={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/","`":"`","=":"="};function _9(e){return String(e).replace(/[&<>"'`=\/]/g,function(r){return g9[r]})}var y9=/\s*/,v9=/\s+/,vR=/\s*=/,b9=/\s*\}/,w9=/#|\^|\/|>|\{|&|=|!/;function x9(e,t){if(!e)return[];var r=!1,n=[],i=[],s=[],o=!1,a=!1,c="",u=0;function l(){if(o&&!a)for(;s.length;)delete i[s.pop()];else s=[];o=!1,a=!1}var p,f,d;function m(w){if(typeof w=="string"&&(w=w.split(v9,2)),!Wc(w)||w.length!==2)throw new Error("Invalid tags: "+w);p=new RegExp(H0(w[0])+"\\s*"),f=new RegExp("\\s*"+H0(w[1])),d=new RegExp("\\s*"+H0("}"+w[1]))}m(t||vn.tags);for(var h=new Up(e),b,_,y,x,I,A;!h.eos();){if(b=h.pos,y=h.scanUntil(p),y)for(var j=0,O=y.length;j<O;++j)x=y.charAt(j),h9(x)?(s.push(i.length),c+=x):(a=!0,r=!0,c+=" "),i.push(["text",x,b,b+1]),b+=1,x===`
|
|
184
|
+
`&&(l(),c="",u=0,r=!1);if(!h.scan(p))break;if(o=!0,_=h.scan(w9)||"name",h.scan(y9),_==="="?(y=h.scanUntil(vR),h.scan(vR),h.scanUntil(f)):_==="{"?(y=h.scanUntil(d),h.scan(b9),h.scanUntil(f),_="&"):y=h.scanUntil(f),!h.scan(f))throw new Error("Unclosed tag at "+h.pos);if(_==">"?I=[_,y,b,h.pos,c,u,r]:I=[_,y,b,h.pos],u++,i.push(I),_==="#"||_==="^")n.push(I);else if(_==="/"){if(A=n.pop(),!A)throw new Error('Unopened section "'+y+'" at '+b);if(A[1]!==y)throw new Error('Unclosed section "'+A[1]+'" at '+b)}else _==="name"||_==="{"||_==="&"?a=!0:_==="="&&m(y)}if(l(),A=n.pop(),A)throw new Error('Unclosed section "'+A[1]+'" at '+h.pos);return S9(I9(i))}function I9(e){for(var t=[],r,n,i=0,s=e.length;i<s;++i)r=e[i],r&&(r[0]==="text"&&n&&n[0]==="text"?(n[1]+=r[1],n[3]=r[3]):(t.push(r),n=r));return t}function S9(e){for(var t=[],r=t,n=[],i,s,o=0,a=e.length;o<a;++o)switch(i=e[o],i[0]){case"#":case"^":r.push(i),n.push(i),r=i[4]=[];break;case"/":s=n.pop(),s[5]=i[2],r=n.length>0?n[n.length-1][4]:t;break;default:r.push(i)}return t}function Up(e){this.string=e,this.tail=e,this.pos=0}Up.prototype.eos=function(){return this.tail===""};Up.prototype.scan=function(t){var r=this.tail.match(t);if(!r||r.index!==0)return"";var n=r[0];return this.tail=this.tail.substring(n.length),this.pos+=n.length,n};Up.prototype.scanUntil=function(t){var r=this.tail.search(t),n;switch(r){case-1:n=this.tail,this.tail="";break;case 0:n="";break;default:n=this.tail.substring(0,r),this.tail=this.tail.substring(r)}return this.pos+=n.length,n};function Hc(e,t){this.view=e,this.cache={".":this.view},this.parent=t}Hc.prototype.push=function(t){return new Hc(t,this)};Hc.prototype.lookup=function(t){var r=this.cache,n;if(r.hasOwnProperty(t))n=r[t];else{for(var i=this,s,o,a,c=!1;i;){if(t.indexOf(".")>0)for(s=i.view,o=t.split("."),a=0;s!=null&&a<o.length;)a===o.length-1&&(c=yR(s,o[a])||p9(s,o[a])),s=s[o[a++]];else s=i.view[t],c=yR(i.view,t);if(c){n=s;break}i=i.parent}r[t]=n}return W0(n)&&(n=n.call(this.view)),n};function wr(){this.templateCache={_cache:{},set:function(t,r){this._cache[t]=r},get:function(t){return this._cache[t]},clear:function(){this._cache={}}}}wr.prototype.clearCache=function(){typeof this.templateCache<"u"&&this.templateCache.clear()};wr.prototype.parse=function(t,r){var n=this.templateCache,i=t+":"+(r||vn.tags).join(":"),s=typeof n<"u",o=s?n.get(i):void 0;return o==null&&(o=x9(t,r),s&&n.set(i,o)),o};wr.prototype.render=function(t,r,n,i){var s=this.getConfigTags(i),o=this.parse(t,s),a=r instanceof Hc?r:new Hc(r,void 0);return this.renderTokens(o,a,n,t,i)};wr.prototype.renderTokens=function(t,r,n,i,s){for(var o="",a,c,u,l=0,p=t.length;l<p;++l)u=void 0,a=t[l],c=a[0],c==="#"?u=this.renderSection(a,r,n,i,s):c==="^"?u=this.renderInverted(a,r,n,i,s):c===">"?u=this.renderPartial(a,r,n,s):c==="&"?u=this.unescapedValue(a,r):c==="name"?u=this.escapedValue(a,r,s):c==="text"&&(u=this.rawValue(a)),u!==void 0&&(o+=u);return o};wr.prototype.renderSection=function(t,r,n,i,s){var o=this,a="",c=r.lookup(t[1]);function u(f){return o.render(f,r,n,s)}if(c){if(Wc(c))for(var l=0,p=c.length;l<p;++l)a+=this.renderTokens(t[4],r.push(c[l]),n,i,s);else if(typeof c=="object"||typeof c=="string"||typeof c=="number")a+=this.renderTokens(t[4],r.push(c),n,i,s);else if(W0(c)){if(typeof i!="string")throw new Error("Cannot use higher-order sections without the original template");c=c.call(r.view,i.slice(t[3],t[5]),u),c!=null&&(a+=c)}else a+=this.renderTokens(t[4],r,n,i,s);return a}};wr.prototype.renderInverted=function(t,r,n,i,s){var o=r.lookup(t[1]);if(!o||Wc(o)&&o.length===0)return this.renderTokens(t[4],r,n,i,s)};wr.prototype.indentPartial=function(t,r,n){for(var i=r.replace(/[^ \t]/g,""),s=t.split(`
|
|
185
|
+
`),o=0;o<s.length;o++)s[o].length&&(o>0||!n)&&(s[o]=i+s[o]);return s.join(`
|
|
186
|
+
`)};wr.prototype.renderPartial=function(t,r,n,i){if(n){var s=this.getConfigTags(i),o=W0(n)?n(t[1]):n[t[1]];if(o!=null){var a=t[6],c=t[5],u=t[4],l=o;c==0&&u&&(l=this.indentPartial(o,u,a));var p=this.parse(l,s);return this.renderTokens(p,r,n,l,i)}}};wr.prototype.unescapedValue=function(t,r){var n=r.lookup(t[1]);if(n!=null)return n};wr.prototype.escapedValue=function(t,r,n){var i=this.getConfigEscape(n)||vn.escape,s=r.lookup(t[1]);if(s!=null)return typeof s=="number"&&i===vn.escape?String(s):i(s)};wr.prototype.rawValue=function(t){return t[1]};wr.prototype.getConfigTags=function(t){return Wc(t)?t:t&&typeof t=="object"?t.tags:void 0};wr.prototype.getConfigEscape=function(t){if(t&&typeof t=="object"&&!Wc(t))return t.escape};var vn={name:"mustache.js",version:"4.2.0",tags:["{{","}}"],clearCache:void 0,escape:void 0,parse:void 0,render:void 0,Scanner:void 0,Context:void 0,Writer:void 0,set templateCache(e){Lp.templateCache=e},get templateCache(){return Lp.templateCache}},Lp=new wr;vn.clearCache=function(){return Lp.clearCache()};vn.parse=function(t,r){return Lp.parse(t,r)};vn.render=function(t,r,n,i){if(typeof t!="string")throw new TypeError('Invalid template! Template should be a "string" but "'+l9(t)+'" was given as the first argument for mustache#render(template, view, partials)');return Lp.render(t,r,n,i)};vn.escape=_9;vn.Scanner=Up;vn.Context=Hc;vn.Writer=wr;var Fh=vn;function bR(){Fh.escape=e=>e}var xa=e=>{let t=e.split(""),r=[],n=(s,o)=>{for(let a=o;a<t.length;a+=1)if(s.includes(t[a]))return a;return-1},i=0;for(;i<t.length;)if(t[i]==="{"&&i+1<t.length&&t[i+1]==="{")r.push({type:"literal",text:"{"}),i+=2;else if(t[i]==="}"&&i+1<t.length&&t[i+1]==="}")r.push({type:"literal",text:"}"}),i+=2;else if(t[i]==="{"){let s=n("}",i);if(s<0)throw new Error("Unclosed '{' in template.");r.push({type:"variable",name:t.slice(i+1,s).join("")}),i=s+1}else{if(t[i]==="}")throw new Error("Single '}' in template.");{let s=n("{}",i),o=(s<0?t.slice(i):t.slice(i,s)).join("");r.push({type:"literal",text:o}),i=s<0?t.length:s}}return r},wR=(e,t=[])=>{let r=[];for(let n of e)if(n[0]==="name"){let i=n[1].includes(".")?n[1].split(".")[0]:n[1];r.push({type:"variable",name:i})}else if(["#","&","^",">"].includes(n[0])){if(r.push({type:"variable",name:n[1]}),n[0]==="#"&&n.length>4&&Array.isArray(n[4])){let i=[...t,n[1]],s=wR(n[4],i);r.push(...s)}}else r.push({type:"literal",text:n[1]});return r},Jc=e=>{bR();let t=Fh.parse(e);return wR(t)},J0=(e,t)=>xa(e).reduce((r,n)=>{if(n.type==="variable"){if(n.name in t){let i=typeof t[n.name]=="string"?t[n.name]:JSON.stringify(t[n.name]);return r+i}throw new Error(`(f-string) Missing value for input ${n.name}`)}return r+n.text},""),X0=(e,t)=>(bR(),Fh.render(e,t)),Fp={"f-string":J0,mustache:X0},Y0={"f-string":xa,mustache:Jc},rr=(e,t,r)=>{try{return Fp[t](e,r)}catch(n){throw js(n,"INVALID_PROMPT_INPUT")}},Ia=(e,t)=>Y0[t](e),as=(e,t,r)=>{if(!(t in Fp)){let n=Object.keys(Fp);throw new Error(`Invalid template format. Got \`${t}\`;
|
|
187
|
+
should be one of ${n}`)}try{let n=Object.fromEntries(r.map(i=>[i,"foo"]));Array.isArray(e)?e.forEach(i=>{if(i.type==="text"&&"text"in i&&typeof i.text=="string")rr(i.text,t,n);else if(i.type==="image_url"){if(typeof i.image_url=="string")rr(i.image_url,t,n);else if(typeof i.image_url=="object"&&i.image_url!==null&&"url"in i.image_url&&typeof i.image_url.url=="string"){let s=i.image_url.url;rr(s,t,n)}}else throw new Error(`Invalid message template received. ${JSON.stringify(i,null,2)}`)}):rr(e,t,n)}catch(n){throw new Error(`Invalid prompt schema: ${n.message}`)}};var Dn=class Bp extends os{static lc_name(){return"PromptTemplate"}template;templateFormat="f-string";validateTemplate=!0;additionalContentFields;constructor(t){if(super(t),t.templateFormat==="mustache"&&t.validateTemplate===void 0&&(this.validateTemplate=!1),Object.assign(this,t),this.validateTemplate){if(this.templateFormat==="mustache")throw new Error("Mustache templates cannot be validated.");let r=this.inputVariables;this.partialVariables&&(r=r.concat(Object.keys(this.partialVariables))),as(this.template,this.templateFormat,r)}}_getPromptType(){return"prompt"}async format(t){let r=await this.mergePartialAndUserVariables(t);return rr(this.template,this.templateFormat,r)}static fromExamples(t,r,n,i=`
|
|
188
|
+
|
|
189
|
+
`,s=""){let o=[s,...t,r].join(i);return new Bp({inputVariables:n,template:o})}static fromTemplate(t,r){let{templateFormat:n="f-string",...i}=r??{},s=new Set;return Ia(t,n).forEach(o=>{o.type==="variable"&&s.add(o.name)}),new Bp({inputVariables:[...s],templateFormat:n,template:t,...i})}async partial(t){let r=this.inputVariables.filter(s=>!(s in t)),n={...this.partialVariables??{},...t},i={...this,inputVariables:r,partialVariables:n};return new Bp(i)}serialize(){if(this.outputParser!==void 0)throw new Error("Cannot serialize a prompt template with an output parser");return{_type:this._getPromptType(),input_variables:this.inputVariables,template:this.template,template_format:this.templateFormat}}static async deserialize(t){if(!t.template)throw new Error("Prompt template must have a template");return new Bp({inputVariables:t.input_variables,template:t.template,templateFormat:t.template_format})}};var Xc=class xR extends bi{static lc_name(){return"ImagePromptTemplate"}lc_namespace=["langchain_core","prompts","image"];template;templateFormat="f-string";validateTemplate=!0;additionalContentFields;constructor(t){if(super(t),this.template=t.template,this.templateFormat=t.templateFormat??this.templateFormat,this.validateTemplate=t.validateTemplate??this.validateTemplate,this.additionalContentFields=t.additionalContentFields,this.validateTemplate){let r=this.inputVariables;this.partialVariables&&(r=r.concat(Object.keys(this.partialVariables))),as([{type:"image_url",image_url:this.template}],this.templateFormat,r)}}_getPromptType(){return"prompt"}async partial(t){let r=this.inputVariables.filter(s=>!(s in t)),n={...this.partialVariables??{},...t},i={...this,inputVariables:r,partialVariables:n};return new xR(i)}async format(t){let r={};for(let[o,a]of Object.entries(this.template))typeof a=="string"?r[o]=rr(a,this.templateFormat,t):r[o]=a;let n=t.url||r.url,i=t.detail||r.detail;if(!n)throw new Error("Must provide either an image URL.");if(typeof n!="string")throw new Error("url must be a string.");let s={url:n};return i&&(s.detail=i),s}async formatPromptValue(t){let r=await this.format(t);return new u0(r)}};var Vp=class extends ce{lc_namespace=["langchain_core","prompts","dict"];lc_serializable=!0;template;templateFormat;inputVariables;static lc_name(){return"DictPromptTemplate"}constructor(e){let t=e.templateFormat??"f-string",r=Q0(e.template,t);super({inputVariables:r,...e}),this.template=e.template,this.templateFormat=t,this.inputVariables=r}async format(e){return eI(this.template,e,this.templateFormat)}async invoke(e){return await this._callWithConfig(this.format.bind(this),e,{runType:"prompt"})}};function Q0(e,t){let r=[];for(let n of Object.values(e))if(typeof n=="string")Ia(n,t).forEach(i=>{i.type==="variable"&&r.push(i.name)});else if(Array.isArray(n))for(let i of n)typeof i=="string"?Ia(i,t).forEach(s=>{s.type==="variable"&&r.push(s.name)}):typeof i=="object"&&r.push(...Q0(i,t));else typeof n=="object"&&n!==null&&r.push(...Q0(n,t));return Array.from(new Set(r))}function eI(e,t,r){let n={};for(let[i,s]of Object.entries(e))if(typeof s=="string")n[i]=rr(s,r,t);else if(Array.isArray(s)){let o=[];for(let a of s)typeof a=="string"?o.push(rr(a,r,t)):typeof a=="object"&&o.push(eI(a,t,r));n[i]=o}else typeof s=="object"&&s!==null?n[i]=eI(s,t,r):n[i]=s;return n}var Zp=class extends ce{lc_namespace=["langchain_core","prompts","chat"];lc_serializable=!0;async invoke(e,t){return this._callWithConfig(r=>this.formatMessages(r),e,{...t,runType:"prompt"})}},Vh=class extends Zp{static lc_name(){return"MessagesPlaceholder"}variableName;optional;constructor(e){typeof e=="string"&&(e={variableName:e}),super(e),this.variableName=e.variableName,this.optional=e.optional??!1}get inputVariables(){return[this.variableName]}async formatMessages(e){let t=e[this.variableName];if(this.optional&&!t)return[];if(!t){let n=new Error(`Field "${this.variableName}" in prompt uses a MessagesPlaceholder, which expects an array of BaseMessages as an input value. Received: undefined`);throw n.name="InputFormatError",n}let r;try{Array.isArray(t)?r=t.map(Qt):r=[Qt(t)]}catch(n){let i=typeof t=="string"?t:JSON.stringify(t,null,2),s=new Error([`Field "${this.variableName}" in prompt uses a MessagesPlaceholder, which expects an array of BaseMessages or coerceable values as input.`,`Received value: ${i}`,`Additional message: ${n.message}`].join(`
|
|
190
|
+
|
|
191
|
+
`));throw s.name="InputFormatError",s.lc_error_code=n.lc_error_code,s}return r}},tI=class extends Zp{prompt;constructor(e){"prompt"in e||(e={prompt:e}),super(e),this.prompt=e.prompt}get inputVariables(){return this.prompt.inputVariables}async formatMessages(e){return[await this.format(e)]}},Gp=class extends bi{constructor(e){super(e)}async format(e){return(await this.formatPromptValue(e)).toString()}async formatPromptValue(e){let t=await this.formatMessages(e);return new Cp(t)}},rI=class extends tI{static lc_name(){return"ChatMessagePromptTemplate"}role;constructor(e,t){"prompt"in e||(e={prompt:e,role:t}),super(e),this.role=e.role}async format(e){return new mr(await this.prompt.format(e),this.role)}static fromTemplate(e,t,r){return new this(Dn.fromTemplate(e,{templateFormat:r?.templateFormat}),t)}};function E9(e){return e===null||typeof e!="object"||Array.isArray(e)?!1:Object.keys(e).length===1&&"text"in e&&typeof e.text=="string"}function k9(e){return e===null||typeof e!="object"||Array.isArray(e)?!1:"image_url"in e&&(typeof e.image_url=="string"||typeof e.image_url=="object"&&e.image_url!==null&&"url"in e.image_url&&typeof e.image_url.url=="string")}var nI=class extends Zp{lc_namespace=["langchain_core","prompts","chat"];lc_serializable=!0;inputVariables=[];additionalOptions={};prompt;messageClass;static _messageClass(){throw new Error("Can not invoke _messageClass from inside _StringImageMessagePromptTemplate")}chatMessageClass;constructor(e,t){if("prompt"in e||(e={prompt:e}),super(e),this.prompt=e.prompt,Array.isArray(this.prompt)){let r=[];this.prompt.forEach(n=>{"inputVariables"in n&&(r=r.concat(n.inputVariables))}),this.inputVariables=r}else this.inputVariables=this.prompt.inputVariables;this.additionalOptions=t??this.additionalOptions}createMessage(e){let t=this.constructor;if(t._messageClass()){let r=t._messageClass();return new r({content:e})}else if(t.chatMessageClass){let r=t.chatMessageClass();return new r({content:e,role:this.getRoleFromMessageClass(r.lc_name())})}else throw new Error("No message class defined")}getRoleFromMessageClass(e){switch(e){case"HumanMessage":return"human";case"AIMessage":return"ai";case"SystemMessage":return"system";case"ChatMessage":return"chat";default:throw new Error("Invalid message class name")}}static fromTemplate(e,t){if(typeof e=="string")return new this(Dn.fromTemplate(e,t));let r=[];for(let n of e)if(typeof n=="string")r.push(Dn.fromTemplate(n,t));else if(n!==null)if(E9(n)){let i="";typeof n.text=="string"&&(i=n.text??"");let s={...t,additionalContentFields:n};r.push(Dn.fromTemplate(i,s))}else if(k9(n)){let i=n.image_url??"",s,o=[];if(typeof i=="string"){let a;t?.templateFormat==="mustache"?a=Jc(i):a=xa(i);let c=a.flatMap(u=>u.type==="variable"?[u.name]:[]);if((c?.length??0)>0){if(c.length>1)throw new Error(`Only one format variable allowed per image template.
|
|
192
|
+
Got: ${c}
|
|
193
|
+
From: ${i}`);o=[c[0]]}else o=[];i={url:i},s=new Xc({template:i,inputVariables:o,templateFormat:t?.templateFormat,additionalContentFields:n})}else if(typeof i=="object"){if("url"in i){let a;t?.templateFormat==="mustache"?a=Jc(i.url):a=xa(i.url),o=a.flatMap(c=>c.type==="variable"?[c.name]:[])}else o=[];s=new Xc({template:i,inputVariables:o,templateFormat:t?.templateFormat,additionalContentFields:n})}else throw new Error("Invalid image template");r.push(s)}else typeof n=="object"&&r.push(new Vp({template:n,templateFormat:t?.templateFormat}));return new this({prompt:r,additionalOptions:t})}async format(e){if(this.prompt instanceof os){let t=await this.prompt.format(e);return this.createMessage(t)}else{let t=[];for(let r of this.prompt){let n={};if(!("inputVariables"in r))throw new Error(`Prompt ${r} does not have inputVariables defined.`);for(let i of r.inputVariables)n||(n={[i]:e[i]}),n={...n,[i]:e[i]};if(r instanceof os){let i=await r.format(n),s;"additionalContentFields"in r&&(s=r.additionalContentFields),i!==""&&t.push({...s,type:"text",text:i})}else if(r instanceof Xc){let i=await r.format(n),s;"additionalContentFields"in r&&(s=r.additionalContentFields),t.push({...s,type:"image_url",image_url:i})}else if(r instanceof Vp){let i=await r.format(n),s;"additionalContentFields"in r&&(s=r.additionalContentFields),t.push({...s,...i})}}return this.createMessage(t)}}async formatMessages(e){return[await this.format(e)]}},Zh=class extends nI{static _messageClass(){return at}static lc_name(){return"HumanMessagePromptTemplate"}},iI=class extends nI{static _messageClass(){return Oe}static lc_name(){return"AIMessagePromptTemplate"}},Kp=class extends nI{static _messageClass(){return Br}static lc_name(){return"SystemMessagePromptTemplate"}};function A9(e){return typeof e.formatMessages=="function"}function T9(e,t){if(A9(e)||ot(e))return e;if(Array.isArray(e)&&e[0]==="placeholder"){let i=e[1];if(t?.templateFormat==="mustache"&&typeof i=="string"&&i.slice(0,2)==="{{"&&i.slice(-2)==="}}"){let s=i.slice(2,-2);return new Vh({variableName:s,optional:!0})}else if(typeof i=="string"&&i[0]==="{"&&i[i.length-1]==="}"){let s=i.slice(1,-1);return new Vh({variableName:s,optional:!0})}throw new Error(`Invalid placeholder template for format ${t?.templateFormat??'"f-string"'}: "${e[1]}". Expected a variable name surrounded by ${t?.templateFormat==="mustache"?"double":"single"} curly braces.`)}let r=Qt(e),n;if(typeof r.content=="string"?n=r.content:n=r.content.map(i=>"text"in i?{...i,text:i.text}:"image_url"in i?{...i,image_url:i.image_url}:i),r._getType()==="human")return Zh.fromTemplate(n,t);if(r._getType()==="ai")return iI.fromTemplate(n,t);if(r._getType()==="system")return Kp.fromTemplate(n,t);if(mr.isInstance(r))return rI.fromTemplate(r.content,r.role,t);throw new Error(`Could not coerce message prompt template from input. Received message type: "${r._getType()}".`)}function O9(e){return e.constructor.lc_name()==="MessagesPlaceholder"}var no=class Bh extends Gp{static lc_name(){return"ChatPromptTemplate"}get lc_aliases(){return{promptMessages:"messages"}}promptMessages;validateTemplate=!0;templateFormat="f-string";constructor(t){if(super(t),t.templateFormat==="mustache"&&t.validateTemplate===void 0&&(this.validateTemplate=!1),Object.assign(this,t),this.validateTemplate){let r=new Set;for(let a of this.promptMessages)if(!(a instanceof bt))for(let c of a.inputVariables)r.add(c);let n=this.inputVariables,i=new Set(this.partialVariables?n.concat(Object.keys(this.partialVariables)):n),s=new Set([...i].filter(a=>!r.has(a)));if(s.size>0)throw new Error(`Input variables \`${[...s]}\` are not used in any of the prompt messages.`);let o=new Set([...r].filter(a=>!i.has(a)));if(o.size>0)throw new Error(`Input variables \`${[...o]}\` are used in prompt messages but not in the prompt template.`)}}_getPromptType(){return"chat"}async _parseImagePrompts(t,r){if(typeof t.content=="string")return t;let n=await Promise.all(t.content.map(async i=>{if(i.type!=="image_url")return i;let s="";typeof i.image_url=="string"?s=i.image_url:typeof i.image_url=="object"&&i.image_url!==null&&"url"in i.image_url&&typeof i.image_url.url=="string"&&(s=i.image_url.url);let a=await Dn.fromTemplate(s,{templateFormat:this.templateFormat}).format(r);return typeof i.image_url=="object"&&i.image_url!==null&&"url"in i.image_url?i.image_url.url=a:i.image_url=a,i}));return t.content=n,t}async formatMessages(t){let r=await this.mergePartialAndUserVariables(t),n=[];for(let i of this.promptMessages)if(i instanceof bt)n.push(await this._parseImagePrompts(i,r));else{let s;this.templateFormat==="mustache"?s={...r}:s=i.inputVariables.reduce((a,c)=>{if(!(c in r)&&!(O9(i)&&i.optional))throw js(new Error(`Missing value for input variable \`${c.toString()}\``),"INVALID_PROMPT_INPUT");return a[c]=r[c],a},{});let o=await i.formatMessages(s);n=n.concat(o)}return n}async partial(t){let r=this.inputVariables.filter(s=>!(s in t)),n={...this.partialVariables??{},...t},i={...this,inputVariables:r,partialVariables:n};return new Bh(i)}static fromTemplate(t,r){let n=Dn.fromTemplate(t,r),i=new Zh({prompt:n});return this.fromMessages([i])}static fromMessages(t,r){let n=t.reduce((o,a)=>o.concat(a instanceof Bh?a.promptMessages:[T9(a,r)]),[]),i=t.reduce((o,a)=>a instanceof Bh?Object.assign(o,a.partialVariables):o,Object.create(null)),s=new Set;for(let o of n)if(!(o instanceof bt))for(let a of o.inputVariables)a in i||s.add(a);return new this({...r,inputVariables:[...s],promptMessages:n,partialVariables:i,templateFormat:r?.templateFormat})}};var IR=class sI extends os{lc_serializable=!1;examples;exampleSelector;examplePrompt;suffix="";exampleSeparator=`
|
|
194
|
+
|
|
195
|
+
`;prefix="";templateFormat="f-string";validateTemplate=!0;constructor(t){if(super(t),Object.assign(this,t),this.examples!==void 0&&this.exampleSelector!==void 0)throw new Error("Only one of 'examples' and 'example_selector' should be provided");if(this.examples===void 0&&this.exampleSelector===void 0)throw new Error("One of 'examples' and 'example_selector' should be provided");if(this.validateTemplate){let r=this.inputVariables;this.partialVariables&&(r=r.concat(Object.keys(this.partialVariables))),as(this.prefix+this.suffix,this.templateFormat,r)}}_getPromptType(){return"few_shot"}static lc_name(){return"FewShotPromptTemplate"}async getExamples(t){if(this.examples!==void 0)return this.examples;if(this.exampleSelector!==void 0)return this.exampleSelector.selectExamples(t);throw new Error("One of 'examples' and 'example_selector' should be provided")}async partial(t){let r=this.inputVariables.filter(s=>!(s in t)),n={...this.partialVariables??{},...t},i={...this,inputVariables:r,partialVariables:n};return new sI(i)}async format(t){let r=await this.mergePartialAndUserVariables(t),n=await this.getExamples(r),i=await Promise.all(n.map(o=>this.examplePrompt.format(o))),s=[this.prefix,...i,this.suffix].join(this.exampleSeparator);return rr(s,this.templateFormat,r)}serialize(){if(this.exampleSelector||!this.examples)throw new Error("Serializing an example selector is not currently supported");if(this.outputParser!==void 0)throw new Error("Serializing an output parser is not currently supported");return{_type:this._getPromptType(),input_variables:this.inputVariables,example_prompt:this.examplePrompt.serialize(),example_separator:this.exampleSeparator,suffix:this.suffix,prefix:this.prefix,template_format:this.templateFormat,examples:this.examples}}static async deserialize(t){let{example_prompt:r}=t;if(!r)throw new Error("Missing example prompt");let n=await Dn.deserialize(r),i;if(Array.isArray(t.examples))i=t.examples;else throw new Error("Invalid examples format. Only list or string are supported.");return new sI({inputVariables:t.input_variables,examplePrompt:n,examples:i,exampleSeparator:t.example_separator,prefix:t.prefix,suffix:t.suffix,templateFormat:t.template_format})}},SR=class ER extends Gp{lc_serializable=!0;examples;exampleSelector;examplePrompt;suffix="";exampleSeparator=`
|
|
196
|
+
|
|
197
|
+
`;prefix="";templateFormat="f-string";validateTemplate=!0;_getPromptType(){return"few_shot_chat"}static lc_name(){return"FewShotChatMessagePromptTemplate"}constructor(t){if(super(t),this.examples=t.examples,this.examplePrompt=t.examplePrompt,this.exampleSeparator=t.exampleSeparator??`
|
|
198
|
+
|
|
199
|
+
`,this.exampleSelector=t.exampleSelector,this.prefix=t.prefix??"",this.suffix=t.suffix??"",this.templateFormat=t.templateFormat??"f-string",this.validateTemplate=t.validateTemplate??!0,this.examples!==void 0&&this.exampleSelector!==void 0)throw new Error("Only one of 'examples' and 'example_selector' should be provided");if(this.examples===void 0&&this.exampleSelector===void 0)throw new Error("One of 'examples' and 'example_selector' should be provided");if(this.validateTemplate){let r=this.inputVariables;this.partialVariables&&(r=r.concat(Object.keys(this.partialVariables))),as(this.prefix+this.suffix,this.templateFormat,r)}}async getExamples(t){if(this.examples!==void 0)return this.examples;if(this.exampleSelector!==void 0)return this.exampleSelector.selectExamples(t);throw new Error("One of 'examples' and 'example_selector' should be provided")}async formatMessages(t){let r=await this.mergePartialAndUserVariables(t),n=await this.getExamples(r);n=n.map(s=>{let o={};return this.examplePrompt.inputVariables.forEach(a=>{o[a]=s[a]}),o});let i=[];for(let s of n){let o=await this.examplePrompt.formatMessages(s);i.push(...o)}return i}async format(t){let r=await this.mergePartialAndUserVariables(t),n=await this.getExamples(r),s=(await Promise.all(n.map(a=>this.examplePrompt.formatMessages(a)))).flat().map(a=>a.content),o=[this.prefix,...s,this.suffix].join(this.exampleSeparator);return rr(o,this.templateFormat,r)}async partial(t){let r=this.inputVariables.filter(s=>!(s in t)),n={...this.partialVariables??{},...t},i={...this,inputVariables:r,partialVariables:n};return new ER(i)}};var kR=class Gh extends bi{static lc_name(){return"PipelinePromptTemplate"}pipelinePrompts;finalPrompt;constructor(t){super({...t,inputVariables:[]}),this.pipelinePrompts=t.pipelinePrompts,this.finalPrompt=t.finalPrompt,this.inputVariables=this.computeInputValues()}computeInputValues(){let t=this.pipelinePrompts.map(n=>n.name),r=this.pipelinePrompts.map(n=>n.prompt.inputVariables.filter(i=>!t.includes(i))).flat();return[...new Set(r)]}static extractRequiredInputValues(t,r){return r.reduce((n,i)=>(n[i]=t[i],n),{})}async formatPipelinePrompts(t){let r=await this.mergePartialAndUserVariables(t);for(let{name:n,prompt:i}of this.pipelinePrompts){let s=Gh.extractRequiredInputValues(r,i.inputVariables);i instanceof no?r[n]=await i.formatMessages(s):r[n]=await i.format(s)}return Gh.extractRequiredInputValues(r,this.finalPrompt.inputVariables)}async formatPromptValue(t){return this.finalPrompt.formatPromptValue(await this.formatPipelinePrompts(t))}async format(t){return this.finalPrompt.format(await this.formatPipelinePrompts(t))}async partial(t){let r={...this};return r.inputVariables=this.inputVariables.filter(n=>!(n in t)),r.partialVariables={...this.partialVariables??{},...t},new Gh(r)}serialize(){throw new Error("Not implemented.")}_getPromptType(){return"pipeline"}};function AR(e){return typeof e=="object"&&e!=null&&"withStructuredOutput"in e&&typeof e.withStructuredOutput=="function"}function $9(e){return typeof e=="object"&&e!=null&&"lc_id"in e&&Array.isArray(e.lc_id)&&e.lc_id.join("/")==="langchain_core/runnables/RunnableBinding"}var TR=class OR extends no{schema;method;lc_namespace=["langchain_core","prompts","structured"];get lc_aliases(){return{...super.lc_aliases,schema:"schema_"}}constructor(t){super(t),this.schema=t.schema,this.method=t.method}pipe(t){if(AR(t))return super.pipe(t.withStructuredOutput(this.schema));if($9(t)&&AR(t.bound))return super.pipe(new gn({bound:t.bound.withStructuredOutput(this.schema,...this.method?[{method:this.method}]:[]),kwargs:t.kwargs??{},config:t.config,configFactories:t.configFactories}));throw new Error('Structured prompts need to be piped to a language model that supports the "withStructuredOutput()" method.')}static fromMessagesAndSchema(t,r,n){return OR.fromMessages(t,{schema:r,method:n})}};var oI={};M(oI,{AIMessagePromptTemplate:()=>iI,BaseChatPromptTemplate:()=>Gp,BaseMessagePromptTemplate:()=>Zp,BaseMessageStringPromptTemplate:()=>tI,BasePromptTemplate:()=>bi,BaseStringPromptTemplate:()=>os,ChatMessagePromptTemplate:()=>rI,ChatPromptTemplate:()=>no,DEFAULT_FORMATTER_MAPPING:()=>Fp,DEFAULT_PARSER_MAPPING:()=>Y0,DictPromptTemplate:()=>Vp,FewShotChatMessagePromptTemplate:()=>SR,FewShotPromptTemplate:()=>IR,HumanMessagePromptTemplate:()=>Zh,ImagePromptTemplate:()=>Xc,MessagesPlaceholder:()=>Vh,PipelinePromptTemplate:()=>kR,PromptTemplate:()=>Dn,StructuredPrompt:()=>TR,SystemMessagePromptTemplate:()=>Kp,checkValidTemplate:()=>as,interpolateFString:()=>J0,interpolateMustache:()=>X0,parseFString:()=>xa,parseMustache:()=>Jc,parseTemplate:()=>Ia,renderTemplate:()=>rr});var aI={};M(aI,{BaseDocumentCompressor:()=>C9});var C9=class{static isBaseDocumentCompressor(e){return e?.compressDocuments!==void 0}};var zn={and:"and",or:"or",not:"not"},Re={eq:"eq",ne:"ne",lt:"lt",gt:"gt",lte:"lte",gte:"gte"},Kh=class{},qh=class{accept(e){if(this.exprName==="Operation")return e.visitOperation(this);if(this.exprName==="Comparison")return e.visitComparison(this);if(this.exprName==="StructuredQuery")return e.visitStructuredQuery(this);throw new Error("Unknown Expression type")}},Hh=class extends qh{},$R=class extends Hh{exprName="Comparison";constructor(e,t,r){super(),this.comparator=e,this.attribute=t,this.value=r}},CR=class extends Hh{exprName="Operation";constructor(e,t){super(),this.operator=e,this.args=t}},PR=class extends qh{exprName="StructuredQuery";constructor(e,t){super(),this.query=e,this.filter=t}};function cI(e){return e&&typeof e=="object"&&!Array.isArray(e)}function Mr(e){return e?typeof e=="string"&&e.length>0||typeof e=="function"?!1:cI(e)&&Object.keys(e).length===0:!0}function uI(e){if(typeof e=="number")return e%1===0;if(typeof e=="string"){let t=parseInt(e,10);return!Number.isNaN(t)&&t%1===0&&t.toString()===e}return!1}function lI(e){if(typeof e=="number")return e%1!==0;if(typeof e=="string"){let t=parseFloat(e);return!Number.isNaN(t)&&t%1!==0&&t.toString()===e}return!1}function pI(e){return typeof e=="string"&&(Number.isNaN(parseFloat(e))||parseFloat(e).toString()!==e)}function dI(e){return typeof e=="boolean"}function Yc(e){let t;if(pI(e))t=e;else if(uI(e))t=parseInt(e,10);else if(lI(e))t=parseFloat(e);else if(dI(e))t=!!e;else throw new Error("Unsupported value type");return t}var qp=class extends Kh{},NR=class extends qp{allowedOperators;allowedComparators;constructor(e){super(),this.allowedOperators=e?.allowedOperators??[zn.and,zn.or],this.allowedComparators=e?.allowedComparators??[Re.eq,Re.ne,Re.gt,Re.gte,Re.lt,Re.lte]}formatFunction(e){if(e in Re){if(this.allowedComparators.length>0&&this.allowedComparators.indexOf(e)===-1)throw new Error(`Comparator ${e} not allowed. Allowed comparators: ${this.allowedComparators.join(", ")}`)}else if(e in zn){if(this.allowedOperators.length>0&&this.allowedOperators.indexOf(e)===-1)throw new Error(`Operator ${e} not allowed. Allowed operators: ${this.allowedOperators.join(", ")}`)}else throw new Error("Unknown comparator or operator");return`$${e}`}visitOperation(e){let t=e.args?.map(r=>r.accept(this));return{[this.formatFunction(e.operator)]:t}}visitComparison(e){return{[e.attribute]:{[this.formatFunction(e.comparator)]:Yc(e.value)}}}visitStructuredQuery(e){let t={};return e.filter&&(t={filter:e.filter.accept(this)}),t}mergeFilters(e,t,r="and",n=!1){if(!(Mr(e)&&Mr(t))){if(Mr(e)||r==="replace")return Mr(t)?void 0:t;if(Mr(t))return n?e:r==="and"?void 0:e;if(r==="and")return{$and:[e,t]};if(r==="or")return{$or:[e,t]};throw new Error("Unknown merge type")}}};var RR=class extends qp{allowedOperators=[zn.and,zn.or];allowedComparators=[Re.eq,Re.ne,Re.gt,Re.gte,Re.lt,Re.lte];formatFunction(){throw new Error("Not implemented")}getAllowedComparatorsForType(e){switch(e){case"string":return[Re.eq,Re.ne,Re.gt,Re.gte,Re.lt,Re.lte];case"number":return[Re.eq,Re.ne,Re.gt,Re.gte,Re.lt,Re.lte];case"boolean":return[Re.eq,Re.ne];default:throw new Error(`Unsupported data type: ${e}`)}}getComparatorFunction(e){switch(e){case Re.eq:return(t,r)=>t===r;case Re.ne:return(t,r)=>t!==r;case Re.gt:return(t,r)=>t>r;case Re.gte:return(t,r)=>t>=r;case Re.lt:return(t,r)=>t<r;case Re.lte:return(t,r)=>t<=r;default:throw new Error("Unknown comparator")}}getOperatorFunction(e){switch(e){case zn.and:return(t,r)=>t&&r;case zn.or:return(t,r)=>t||r;default:throw new Error("Unknown operator")}}visitOperation(e){let{operator:t,args:r}=e;if(this.allowedOperators.includes(t)){let n=this.getOperatorFunction(t);return i=>r?r.reduce((s,o)=>{let a=o.accept(this);if(typeof a=="function")return n(s,a(i));throw new Error("Filter is not a function")},!0):!0}else throw new Error("Operator not allowed")}visitComparison(e){let{comparator:t,attribute:r,value:n}=e,i=[Re.ne];if(this.allowedComparators.includes(t)){if(!this.getAllowedComparatorsForType(typeof n).includes(t))throw new Error(`'${t}' comparator not allowed to be used with ${typeof n}`);let s=this.getComparatorFunction(t);return o=>{let a=o.metadata[r];return a===void 0?!!i.includes(t):s(a,Yc(n))}}else throw new Error("Comparator not allowed")}visitStructuredQuery(e){if(!e.filter)return{};let t=e.filter?.accept(this);if(typeof t!="function")throw new Error("Structured query filter is not a function");return{filter:t}}mergeFilters(e,t,r="and"){if(!(Mr(e)&&Mr(t))){if(Mr(e)||r==="replace")return Mr(t)?void 0:t;if(Mr(t))return r==="and"?void 0:e;if(r==="and")return n=>e(n)&&t(n);if(r==="or")return n=>e(n)||t(n);throw new Error("Unknown merge type")}}};var fI={};M(fI,{BaseTranslator:()=>qp,BasicTranslator:()=>NR,Comparators:()=>Re,Comparison:()=>$R,Expression:()=>qh,FilterDirective:()=>Hh,FunctionalTranslator:()=>RR,Operation:()=>CR,Operators:()=>zn,StructuredQuery:()=>PR,Visitor:()=>Kh,castValue:()=>Yc,isBoolean:()=>dI,isFilterEmpty:()=>Mr,isFloat:()=>lI,isInt:()=>uI,isObject:()=>cI,isString:()=>pI});function Hp(e){return e!==void 0&&Array.isArray(e.lc_namespace)}function Wp(e){return e!==void 0&&ce.isRunnable(e)&&"lc_name"in e.constructor&&typeof e.constructor.lc_name=="function"&&e.constructor.lc_name()==="RunnableToolLike"}function Jp(e){return!!e&&typeof e=="object"&&"name"in e&&"schema"in e&&(_r(e.schema)||e.schema!=null&&typeof e.schema=="object"&&"type"in e.schema&&typeof e.schema.type=="string"&&["null","boolean","object","array","number","string"].includes(e.schema.type))}function Sa(e){return Jp(e)||Wp(e)||Hp(e)}var Z={};Cs(Z,{$brand:()=>jv,$input:()=>Hw,$output:()=>qw,NEVER:()=>Mv,TimePrecision:()=>Xw,ZodAny:()=>ZR,ZodArray:()=>HR,ZodBase64:()=>zI,ZodBase64URL:()=>LI,ZodBigInt:()=>td,ZodBigIntFormat:()=>BI,ZodBoolean:()=>ed,ZodCIDRv4:()=>jI,ZodCIDRv6:()=>DI,ZodCUID:()=>OI,ZodCUID2:()=>$I,ZodCatch:()=>f1,ZodCustom:()=>ug,ZodCustomStringFormat:()=>DR,ZodDate:()=>og,ZodDefault:()=>a1,ZodDiscriminatedUnion:()=>WR,ZodE164:()=>UI,ZodEmail:()=>EI,ZodEmoji:()=>AI,ZodEnum:()=>Xp,ZodError:()=>N9,ZodFile:()=>s1,ZodGUID:()=>eg,ZodIPv4:()=>RI,ZodIPv6:()=>MI,ZodISODate:()=>Jh,ZodISODateTime:()=>Wh,ZodISODuration:()=>Yh,ZodISOTime:()=>Xh,ZodIntersection:()=>JR,ZodIssueCode:()=>D3,ZodJWT:()=>FI,ZodKSUID:()=>NI,ZodLazy:()=>v1,ZodLiteral:()=>n1,ZodMap:()=>e1,ZodNaN:()=>h1,ZodNanoID:()=>TI,ZodNever:()=>KR,ZodNonOptional:()=>WI,ZodNull:()=>BR,ZodNullable:()=>o1,ZodNumber:()=>Qp,ZodNumberFormat:()=>eu,ZodObject:()=>ag,ZodOptional:()=>HI,ZodPipe:()=>JI,ZodPrefault:()=>u1,ZodPromise:()=>w1,ZodReadonly:()=>g1,ZodRealError:()=>Qc,ZodRecord:()=>GI,ZodSet:()=>t1,ZodString:()=>Yp,ZodStringFormat:()=>Qe,ZodSuccess:()=>d1,ZodSymbol:()=>UR,ZodTemplateLiteral:()=>y1,ZodTransform:()=>KI,ZodTuple:()=>YR,ZodType:()=>Ce,ZodULID:()=>CI,ZodURL:()=>kI,ZodUUID:()=>cs,ZodUndefined:()=>FR,ZodUnion:()=>ZI,ZodUnknown:()=>GR,ZodVoid:()=>qR,ZodXID:()=>PI,_ZodString:()=>SI,_default:()=>c1,any:()=>f3,array:()=>VI,base64:()=>Q9,base64url:()=>e3,bigint:()=>c3,boolean:()=>LR,catch:()=>m1,check:()=>x1,cidrv4:()=>X9,cidrv6:()=>Y9,clone:()=>lt,coerce:()=>XI,config:()=>At,core:()=>Qi,cuid:()=>Z9,cuid2:()=>G9,custom:()=>P3,date:()=>h3,discriminatedUnion:()=>b3,e164:()=>t3,email:()=>M9,emoji:()=>B9,endsWith:()=>mp,enum:()=>r1,file:()=>k3,flattenError:()=>Xl,float32:()=>i3,float64:()=>s3,formatError:()=>Yl,function:()=>Rx,getErrorMap:()=>L3,globalRegistry:()=>ct,gt:()=>Xi,gte:()=>Pr,guid:()=>j9,includes:()=>dp,instanceof:()=>N3,int:()=>II,int32:()=>o3,int64:()=>u3,intersection:()=>XR,ipv4:()=>W9,ipv6:()=>J9,iso:()=>Qh,json:()=>M3,jwt:()=>r3,keyof:()=>g3,ksuid:()=>H9,lazy:()=>b1,length:()=>Tc,literal:()=>i1,locales:()=>sp,looseObject:()=>v3,lowercase:()=>lp,lt:()=>Ji,lte:()=>pn,map:()=>I3,maxLength:()=>Ac,maxSize:()=>kc,mime:()=>hp,minLength:()=>qs,minSize:()=>Qo,multipleOf:()=>Yo,nan:()=>O3,nanoid:()=>V9,nativeEnum:()=>E3,negative:()=>Sx,never:()=>sg,nonnegative:()=>kx,nonoptional:()=>p1,nonpositive:()=>Ex,normalize:()=>gp,null:()=>VR,nullable:()=>ng,nullish:()=>A3,number:()=>zR,object:()=>_3,optional:()=>rg,overwrite:()=>Yi,parse:()=>yI,parseAsync:()=>vI,partialRecord:()=>x3,pipe:()=>ig,positive:()=>Ix,prefault:()=>l1,preprocess:()=>j3,prettifyError:()=>Wv,promise:()=>C3,property:()=>Ax,readonly:()=>_1,record:()=>QR,refine:()=>I1,regex:()=>up,regexes:()=>Wo,registry:()=>Nm,safeParse:()=>bI,safeParseAsync:()=>wI,set:()=>S3,setErrorMap:()=>z3,size:()=>cp,startsWith:()=>fp,strictObject:()=>y3,string:()=>xI,stringFormat:()=>n3,stringbool:()=>R3,success:()=>T3,superRefine:()=>S1,symbol:()=>p3,templateLiteral:()=>$3,toJSONSchema:()=>Hs,toLowerCase:()=>yp,toUpperCase:()=>vp,transform:()=>qI,treeifyError:()=>Hv,trim:()=>_p,tuple:()=>w3,uint32:()=>a3,uint64:()=>l3,ulid:()=>K9,undefined:()=>d3,union:()=>cg,unknown:()=>tg,uppercase:()=>pp,url:()=>F9,uuid:()=>D9,uuidv4:()=>z9,uuidv6:()=>L9,uuidv7:()=>U9,void:()=>m3,xid:()=>q9});var Qh={};Cs(Qh,{ZodISODate:()=>Jh,ZodISODateTime:()=>Wh,ZodISODuration:()=>Yh,ZodISOTime:()=>Xh,date:()=>hI,datetime:()=>mI,duration:()=>_I,time:()=>gI});var Wh=S("ZodISODateTime",(e,t)=>{iw.init(e,t),Qe.init(e,t)});function mI(e){return Yw(Wh,e)}var Jh=S("ZodISODate",(e,t)=>{sw.init(e,t),Qe.init(e,t)});function hI(e){return Qw(Jh,e)}var Xh=S("ZodISOTime",(e,t)=>{ow.init(e,t),Qe.init(e,t)});function gI(e){return ex(Xh,e)}var Yh=S("ZodISODuration",(e,t)=>{aw.init(e,t),Qe.init(e,t)});function _I(e){return tx(Yh,e)}var jR=(e,t)=>{Jl.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>Yl(e,r)},flatten:{value:r=>Xl(e,r)},addIssue:{value:r=>e.issues.push(r)},addIssues:{value:r=>e.issues.push(...r)},isEmpty:{get(){return e.issues.length===0}}})},N9=S("ZodError",jR),Qc=S("ZodError",jR,{Parent:Error});var yI=bm(Qc),vI=wm(Qc),bI=xm(Qc),wI=Im(Qc);var Ce=S("ZodType",(e,t)=>(_e.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),e.clone=(r,n)=>lt(e,r,n),e.brand=()=>e,e.register=((r,n)=>(r.add(e,n),e)),e.parse=(r,n)=>yI(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>bI(e,r,n),e.parseAsync=async(r,n)=>vI(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>wI(e,r,n),e.spa=e.safeParseAsync,e.refine=(r,n)=>e.check(I1(r,n)),e.superRefine=r=>e.check(S1(r)),e.overwrite=r=>e.check(Yi(r)),e.optional=()=>rg(e),e.nullable=()=>ng(e),e.nullish=()=>rg(ng(e)),e.nonoptional=r=>p1(e,r),e.array=()=>VI(e),e.or=r=>cg([e,r]),e.and=r=>XR(e,r),e.transform=r=>ig(e,qI(r)),e.default=r=>c1(e,r),e.prefault=r=>l1(e,r),e.catch=r=>m1(e,r),e.pipe=r=>ig(e,r),e.readonly=()=>_1(e),e.describe=r=>{let n=e.clone();return ct.add(n,{description:r}),n},Object.defineProperty(e,"description",{get(){return ct.get(e)?.description},configurable:!0}),e.meta=(...r)=>{if(r.length===0)return ct.get(e);let n=e.clone();return ct.add(n,r[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),SI=S("_ZodString",(e,t)=>{Jo.init(e,t),Ce.init(e,t);let r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,e.regex=(...n)=>e.check(up(...n)),e.includes=(...n)=>e.check(dp(...n)),e.startsWith=(...n)=>e.check(fp(...n)),e.endsWith=(...n)=>e.check(mp(...n)),e.min=(...n)=>e.check(qs(...n)),e.max=(...n)=>e.check(Ac(...n)),e.length=(...n)=>e.check(Tc(...n)),e.nonempty=(...n)=>e.check(qs(1,...n)),e.lowercase=n=>e.check(lp(n)),e.uppercase=n=>e.check(pp(n)),e.trim=()=>e.check(_p()),e.normalize=(...n)=>e.check(gp(...n)),e.toLowerCase=()=>e.check(yp()),e.toUpperCase=()=>e.check(vp())}),Yp=S("ZodString",(e,t)=>{Jo.init(e,t),SI.init(e,t),e.email=r=>e.check(Rm(EI,r)),e.url=r=>e.check(Lm(kI,r)),e.jwt=r=>e.check(eh(FI,r)),e.emoji=r=>e.check(Um(AI,r)),e.guid=r=>e.check(op(eg,r)),e.uuid=r=>e.check(Mm(cs,r)),e.uuidv4=r=>e.check(jm(cs,r)),e.uuidv6=r=>e.check(Dm(cs,r)),e.uuidv7=r=>e.check(zm(cs,r)),e.nanoid=r=>e.check(Fm(TI,r)),e.guid=r=>e.check(op(eg,r)),e.cuid=r=>e.check(Bm(OI,r)),e.cuid2=r=>e.check(Vm($I,r)),e.ulid=r=>e.check(Zm(CI,r)),e.base64=r=>e.check(Xm(zI,r)),e.base64url=r=>e.check(Ym(LI,r)),e.xid=r=>e.check(Gm(PI,r)),e.ksuid=r=>e.check(Km(NI,r)),e.ipv4=r=>e.check(qm(RI,r)),e.ipv6=r=>e.check(Hm(MI,r)),e.cidrv4=r=>e.check(Wm(jI,r)),e.cidrv6=r=>e.check(Jm(DI,r)),e.e164=r=>e.check(Qm(UI,r)),e.datetime=r=>e.check(mI(r)),e.date=r=>e.check(hI(r)),e.time=r=>e.check(gI(r)),e.duration=r=>e.check(_I(r))});function xI(e){return Ww(Yp,e)}var Qe=S("ZodStringFormat",(e,t)=>{We.init(e,t),SI.init(e,t)}),EI=S("ZodEmail",(e,t)=>{Wb.init(e,t),Qe.init(e,t)});function M9(e){return Rm(EI,e)}var eg=S("ZodGUID",(e,t)=>{qb.init(e,t),Qe.init(e,t)});function j9(e){return op(eg,e)}var cs=S("ZodUUID",(e,t)=>{Hb.init(e,t),Qe.init(e,t)});function D9(e){return Mm(cs,e)}function z9(e){return jm(cs,e)}function L9(e){return Dm(cs,e)}function U9(e){return zm(cs,e)}var kI=S("ZodURL",(e,t)=>{Jb.init(e,t),Qe.init(e,t)});function F9(e){return Lm(kI,e)}var AI=S("ZodEmoji",(e,t)=>{Xb.init(e,t),Qe.init(e,t)});function B9(e){return Um(AI,e)}var TI=S("ZodNanoID",(e,t)=>{Yb.init(e,t),Qe.init(e,t)});function V9(e){return Fm(TI,e)}var OI=S("ZodCUID",(e,t)=>{Qb.init(e,t),Qe.init(e,t)});function Z9(e){return Bm(OI,e)}var $I=S("ZodCUID2",(e,t)=>{ew.init(e,t),Qe.init(e,t)});function G9(e){return Vm($I,e)}var CI=S("ZodULID",(e,t)=>{tw.init(e,t),Qe.init(e,t)});function K9(e){return Zm(CI,e)}var PI=S("ZodXID",(e,t)=>{rw.init(e,t),Qe.init(e,t)});function q9(e){return Gm(PI,e)}var NI=S("ZodKSUID",(e,t)=>{nw.init(e,t),Qe.init(e,t)});function H9(e){return Km(NI,e)}var RI=S("ZodIPv4",(e,t)=>{cw.init(e,t),Qe.init(e,t)});function W9(e){return qm(RI,e)}var MI=S("ZodIPv6",(e,t)=>{uw.init(e,t),Qe.init(e,t)});function J9(e){return Hm(MI,e)}var jI=S("ZodCIDRv4",(e,t)=>{lw.init(e,t),Qe.init(e,t)});function X9(e){return Wm(jI,e)}var DI=S("ZodCIDRv6",(e,t)=>{pw.init(e,t),Qe.init(e,t)});function Y9(e){return Jm(DI,e)}var zI=S("ZodBase64",(e,t)=>{fw.init(e,t),Qe.init(e,t)});function Q9(e){return Xm(zI,e)}var LI=S("ZodBase64URL",(e,t)=>{mw.init(e,t),Qe.init(e,t)});function e3(e){return Ym(LI,e)}var UI=S("ZodE164",(e,t)=>{hw.init(e,t),Qe.init(e,t)});function t3(e){return Qm(UI,e)}var FI=S("ZodJWT",(e,t)=>{gw.init(e,t),Qe.init(e,t)});function r3(e){return eh(FI,e)}var DR=S("ZodCustomStringFormat",(e,t)=>{_w.init(e,t),Qe.init(e,t)});function n3(e,t,r={}){return Nx(DR,e,t,r)}var Qp=S("ZodNumber",(e,t)=>{Om.init(e,t),Ce.init(e,t),e.gt=(n,i)=>e.check(Xi(n,i)),e.gte=(n,i)=>e.check(Pr(n,i)),e.min=(n,i)=>e.check(Pr(n,i)),e.lt=(n,i)=>e.check(Ji(n,i)),e.lte=(n,i)=>e.check(pn(n,i)),e.max=(n,i)=>e.check(pn(n,i)),e.int=n=>e.check(II(n)),e.safe=n=>e.check(II(n)),e.positive=n=>e.check(Xi(0,n)),e.nonnegative=n=>e.check(Pr(0,n)),e.negative=n=>e.check(Ji(0,n)),e.nonpositive=n=>e.check(pn(0,n)),e.multipleOf=(n,i)=>e.check(Yo(n,i)),e.step=(n,i)=>e.check(Yo(n,i)),e.finite=()=>e;let r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),e.isFinite=!0,e.format=r.format??null});function zR(e){return rx(Qp,e)}var eu=S("ZodNumberFormat",(e,t)=>{yw.init(e,t),Qp.init(e,t)});function II(e){return ix(eu,e)}function i3(e){return sx(eu,e)}function s3(e){return ox(eu,e)}function o3(e){return ax(eu,e)}function a3(e){return cx(eu,e)}var ed=S("ZodBoolean",(e,t)=>{ep.init(e,t),Ce.init(e,t)});function LR(e){return ux(ed,e)}var td=S("ZodBigInt",(e,t)=>{$m.init(e,t),Ce.init(e,t),e.gte=(n,i)=>e.check(Pr(n,i)),e.min=(n,i)=>e.check(Pr(n,i)),e.gt=(n,i)=>e.check(Xi(n,i)),e.gte=(n,i)=>e.check(Pr(n,i)),e.min=(n,i)=>e.check(Pr(n,i)),e.lt=(n,i)=>e.check(Ji(n,i)),e.lte=(n,i)=>e.check(pn(n,i)),e.max=(n,i)=>e.check(pn(n,i)),e.positive=n=>e.check(Xi(BigInt(0),n)),e.negative=n=>e.check(Ji(BigInt(0),n)),e.nonpositive=n=>e.check(pn(BigInt(0),n)),e.nonnegative=n=>e.check(Pr(BigInt(0),n)),e.multipleOf=(n,i)=>e.check(Yo(n,i));let r=e._zod.bag;e.minValue=r.minimum??null,e.maxValue=r.maximum??null,e.format=r.format??null});function c3(e){return px(td,e)}var BI=S("ZodBigIntFormat",(e,t)=>{vw.init(e,t),td.init(e,t)});function u3(e){return fx(BI,e)}function l3(e){return mx(BI,e)}var UR=S("ZodSymbol",(e,t)=>{bw.init(e,t),Ce.init(e,t)});function p3(e){return hx(UR,e)}var FR=S("ZodUndefined",(e,t)=>{ww.init(e,t),Ce.init(e,t)});function d3(e){return gx(FR,e)}var BR=S("ZodNull",(e,t)=>{xw.init(e,t),Ce.init(e,t)});function VR(e){return _x(BR,e)}var ZR=S("ZodAny",(e,t)=>{Iw.init(e,t),Ce.init(e,t)});function f3(){return yx(ZR)}var GR=S("ZodUnknown",(e,t)=>{Gs.init(e,t),Ce.init(e,t)});function tg(){return Ks(GR)}var KR=S("ZodNever",(e,t)=>{tp.init(e,t),Ce.init(e,t)});function sg(e){return ap(KR,e)}var qR=S("ZodVoid",(e,t)=>{Sw.init(e,t),Ce.init(e,t)});function m3(e){return vx(qR,e)}var og=S("ZodDate",(e,t)=>{Ew.init(e,t),Ce.init(e,t),e.min=(n,i)=>e.check(Pr(n,i)),e.max=(n,i)=>e.check(pn(n,i));let r=e._zod.bag;e.minDate=r.minimum?new Date(r.minimum):null,e.maxDate=r.maximum?new Date(r.maximum):null});function h3(e){return bx(og,e)}var HR=S("ZodArray",(e,t)=>{rp.init(e,t),Ce.init(e,t),e.element=t.element,e.min=(r,n)=>e.check(qs(r,n)),e.nonempty=r=>e.check(qs(1,r)),e.max=(r,n)=>e.check(Ac(r,n)),e.length=(r,n)=>e.check(Tc(r,n)),e.unwrap=()=>e.element});function VI(e,t){return bp(HR,e,t)}function g3(e){let t=e._zod.def.shape;return i1(Object.keys(t))}var ag=S("ZodObject",(e,t)=>{kw.init(e,t),Ce.init(e,t),G.defineLazy(e,"shape",()=>t.shape),e.keyof=()=>r1(Object.keys(e._zod.def.shape)),e.catchall=r=>e.clone({...e._zod.def,catchall:r}),e.passthrough=()=>e.clone({...e._zod.def,catchall:tg()}),e.loose=()=>e.clone({...e._zod.def,catchall:tg()}),e.strict=()=>e.clone({...e._zod.def,catchall:sg()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=r=>G.extend(e,r),e.merge=r=>G.merge(e,r),e.pick=r=>G.pick(e,r),e.omit=r=>G.omit(e,r),e.partial=(...r)=>G.partial(HI,e,r[0]),e.required=(...r)=>G.required(WI,e,r[0])});function _3(e,t){let r={type:"object",get shape(){return G.assignProp(this,"shape",{...e}),this.shape},...G.normalizeParams(t)};return new ag(r)}function y3(e,t){return new ag({type:"object",get shape(){return G.assignProp(this,"shape",{...e}),this.shape},catchall:sg(),...G.normalizeParams(t)})}function v3(e,t){return new ag({type:"object",get shape(){return G.assignProp(this,"shape",{...e}),this.shape},catchall:tg(),...G.normalizeParams(t)})}var ZI=S("ZodUnion",(e,t)=>{Cm.init(e,t),Ce.init(e,t),e.options=t.options});function cg(e,t){return new ZI({type:"union",options:e,...G.normalizeParams(t)})}var WR=S("ZodDiscriminatedUnion",(e,t)=>{ZI.init(e,t),Aw.init(e,t)});function b3(e,t,r){return new WR({type:"union",options:t,discriminator:e,...G.normalizeParams(r)})}var JR=S("ZodIntersection",(e,t)=>{Tw.init(e,t),Ce.init(e,t)});function XR(e,t){return new JR({type:"intersection",left:e,right:t})}var YR=S("ZodTuple",(e,t)=>{Xo.init(e,t),Ce.init(e,t),e.rest=r=>e.clone({...e._zod.def,rest:r})});function w3(e,t,r){let n=t instanceof _e,i=n?r:t,s=n?t:null;return new YR({type:"tuple",items:e,rest:s,...G.normalizeParams(i)})}var GI=S("ZodRecord",(e,t)=>{Ow.init(e,t),Ce.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function QR(e,t,r){return new GI({type:"record",keyType:e,valueType:t,...G.normalizeParams(r)})}function x3(e,t,r){return new GI({type:"record",keyType:cg([e,sg()]),valueType:t,...G.normalizeParams(r)})}var e1=S("ZodMap",(e,t)=>{$w.init(e,t),Ce.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function I3(e,t,r){return new e1({type:"map",keyType:e,valueType:t,...G.normalizeParams(r)})}var t1=S("ZodSet",(e,t)=>{Cw.init(e,t),Ce.init(e,t),e.min=(...r)=>e.check(Qo(...r)),e.nonempty=r=>e.check(Qo(1,r)),e.max=(...r)=>e.check(kc(...r)),e.size=(...r)=>e.check(cp(...r))});function S3(e,t){return new t1({type:"set",valueType:e,...G.normalizeParams(t)})}var Xp=S("ZodEnum",(e,t)=>{Pw.init(e,t),Ce.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);let r=new Set(Object.keys(t.entries));e.extract=(n,i)=>{let s={};for(let o of n)if(r.has(o))s[o]=t.entries[o];else throw new Error(`Key ${o} not found in enum`);return new Xp({...t,checks:[],...G.normalizeParams(i),entries:s})},e.exclude=(n,i)=>{let s={...t.entries};for(let o of n)if(r.has(o))delete s[o];else throw new Error(`Key ${o} not found in enum`);return new Xp({...t,checks:[],...G.normalizeParams(i),entries:s})}});function r1(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new Xp({type:"enum",entries:r,...G.normalizeParams(t)})}function E3(e,t){return new Xp({type:"enum",entries:e,...G.normalizeParams(t)})}var n1=S("ZodLiteral",(e,t)=>{Nw.init(e,t),Ce.init(e,t),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function i1(e,t){return new n1({type:"literal",values:Array.isArray(e)?e:[e],...G.normalizeParams(t)})}var s1=S("ZodFile",(e,t)=>{Rw.init(e,t),Ce.init(e,t),e.min=(r,n)=>e.check(Qo(r,n)),e.max=(r,n)=>e.check(kc(r,n)),e.mime=(r,n)=>e.check(hp(Array.isArray(r)?r:[r],n))});function k3(e){return Ox(s1,e)}var KI=S("ZodTransform",(e,t)=>{np.init(e,t),Ce.init(e,t),e._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(G.issue(s,r.value,t));else{let o=s;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=e),o.continue??(o.continue=!0),r.issues.push(G.issue(o))}};let i=t.transform(r.value,r);return i instanceof Promise?i.then(s=>(r.value=s,r)):(r.value=i,r)}});function qI(e){return new KI({type:"transform",transform:e})}var HI=S("ZodOptional",(e,t)=>{Sc.init(e,t),Ce.init(e,t),e.unwrap=()=>e._zod.def.innerType});function rg(e){return new HI({type:"optional",innerType:e})}var o1=S("ZodNullable",(e,t)=>{Mw.init(e,t),Ce.init(e,t),e.unwrap=()=>e._zod.def.innerType});function ng(e){return new o1({type:"nullable",innerType:e})}function A3(e){return rg(ng(e))}var a1=S("ZodDefault",(e,t)=>{jw.init(e,t),Ce.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function c1(e,t){return new a1({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}var u1=S("ZodPrefault",(e,t)=>{Dw.init(e,t),Ce.init(e,t),e.unwrap=()=>e._zod.def.innerType});function l1(e,t){return new u1({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}var WI=S("ZodNonOptional",(e,t)=>{zw.init(e,t),Ce.init(e,t),e.unwrap=()=>e._zod.def.innerType});function p1(e,t){return new WI({type:"nonoptional",innerType:e,...G.normalizeParams(t)})}var d1=S("ZodSuccess",(e,t)=>{Lw.init(e,t),Ce.init(e,t),e.unwrap=()=>e._zod.def.innerType});function T3(e){return new d1({type:"success",innerType:e})}var f1=S("ZodCatch",(e,t)=>{Uw.init(e,t),Ce.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function m1(e,t){return new f1({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}var h1=S("ZodNaN",(e,t)=>{Fw.init(e,t),Ce.init(e,t)});function O3(e){return xx(h1,e)}var JI=S("ZodPipe",(e,t)=>{ip.init(e,t),Ce.init(e,t),e.in=t.in,e.out=t.out});function ig(e,t){return new JI({type:"pipe",in:e,out:t})}var g1=S("ZodReadonly",(e,t)=>{Bw.init(e,t),Ce.init(e,t)});function _1(e){return new g1({type:"readonly",innerType:e})}var y1=S("ZodTemplateLiteral",(e,t)=>{Vw.init(e,t),Ce.init(e,t)});function $3(e,t){return new y1({type:"template_literal",parts:e,...G.normalizeParams(t)})}var v1=S("ZodLazy",(e,t)=>{Gw.init(e,t),Ce.init(e,t),e.unwrap=()=>e._zod.def.getter()});function b1(e){return new v1({type:"lazy",getter:e})}var w1=S("ZodPromise",(e,t)=>{Zw.init(e,t),Ce.init(e,t),e.unwrap=()=>e._zod.def.innerType});function C3(e){return new w1({type:"promise",innerType:e})}var ug=S("ZodCustom",(e,t)=>{Kw.init(e,t),Ce.init(e,t)});function x1(e){let t=new pt({check:"custom"});return t._zod.check=e,t}function P3(e,t){return $x(ug,e??(()=>!0),t)}function I1(e,t={}){return Cx(ug,e,t)}function S1(e){let t=x1(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(G.issue(n,r.value,t._zod.def));else{let i=n;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=t),i.continue??(i.continue=!t._zod.def.abort),r.issues.push(G.issue(i))}},e(r.value,r)));return t}function N3(e,t={error:`Input not instance of ${e.name}`}){let r=new ug({type:"custom",check:"custom",fn:n=>n instanceof e,abort:!0,...G.normalizeParams(t)});return r._zod.bag.Class=e,r}var R3=(...e)=>Px({Pipe:JI,Boolean:ed,String:Yp,Transform:KI},...e);function M3(e){let t=b1(()=>cg([xI(e),zR(),LR(),VR(),VI(t),QR(xI(),t)]));return t}function j3(e,t){return ig(qI(e),t)}var D3={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};function z3(e){At({customError:e})}function L3(){return At().customError}var XI={};Cs(XI,{bigint:()=>V3,boolean:()=>B3,date:()=>Z3,number:()=>F3,string:()=>U3});function U3(e){return Jw(Yp,e)}function F3(e){return nx(Qp,e)}function B3(e){return lx(ed,e)}function V3(e){return dx(td,e)}function Z3(e){return wx(og,e)}At(Pm());var YI={};M(YI,{BaseToolkit:()=>G3,DynamicStructuredTool:()=>E1,DynamicTool:()=>eS,StructuredTool:()=>rd,Tool:()=>QI,ToolInputParsingException:()=>gc,isLangChainTool:()=>Sa,isRunnableToolLike:()=>Wp,isStructuredTool:()=>Hp,isStructuredToolParams:()=>Jp,tool:()=>nd});var rd=class extends Mh{extras;returnDirect=!1;verboseParsingErrors=!1;get lc_namespace(){return["langchain","tools"]}responseFormat="content";defaultConfig;constructor(e){super(e??{}),this.verboseParsingErrors=e?.verboseParsingErrors??this.verboseParsingErrors,this.responseFormat=e?.responseFormat??this.responseFormat,this.defaultConfig=e?.defaultConfig??this.defaultConfig,this.metadata=e?.metadata??this.metadata,this.extras=e?.extras??this.extras}async invoke(e,t){let r,n=$e(Dt(this.defaultConfig,t));return Ds(e)?(r=e.args,n={...n,toolCall:e}):r=e,this.call(r,n)}async call(e,t,r){let n=Ds(e)?e.args:e,i;if(_r(this.schema))try{i=await Ws(this.schema,n)}catch(d){let m="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(m=`${m}
|
|
200
|
+
Details: ${d.message}`),ch(d)&&(m=`${m}
|
|
201
|
+
|
|
202
|
+
${Z.prettifyError(d)}`),new gc(m,JSON.stringify(e))}else{let d=Xe(n,this.schema);if(!d.valid){let m="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(m=`${m}
|
|
203
|
+
Details: ${d.errors.map(h=>`${h.keywordLocation}: ${h.error}`).join(`
|
|
204
|
+
`)}`),new gc(m,JSON.stringify(e))}i=n}let s=Bo(t),a=await xt.configure(s.callbacks,this.callbacks,s.tags||r,this.tags,s.metadata,this.metadata,{verbose:this.verbose})?.handleToolStart(this.toJSON(),typeof e=="string"?e:JSON.stringify(e),s.runId,void 0,void 0,void 0,s.runName);delete s.runId;let c;try{c=await this._call(i,a,s)}catch(d){throw await a?.handleToolError(d),d}let u,l;if(this.responseFormat==="content_and_artifact")if(Array.isArray(c)&&c.length===2)[u,l]=c;else throw new Error(`Tool response format is "content_and_artifact" but the output was not a two-tuple.
|
|
205
|
+
Result: ${JSON.stringify(c)}`);else u=c;let p;Ds(e)&&(p=e.id),!p&&g$(s)&&(p=s.toolCall.id);let f=K3({content:u,artifact:l,toolCallId:p,name:this.name,metadata:this.metadata});return await a?.handleToolEnd(f),f}},QI=class extends rd{schema=Ge.object({input:Ge.string().optional()}).transform(e=>e.input);constructor(e){super(e)}call(e,t){let r=typeof e=="string"||e==null?{input:e}:e;return super.call(r,t)}},eS=class extends QI{static lc_name(){return"DynamicTool"}name;description;func;constructor(e){super(e),this.name=e.name,this.description=e.description,this.func=e.func,this.returnDirect=e.returnDirect??this.returnDirect}async call(e,t){let r=Bo(t);return r.runName===void 0&&(r.runName=this.name),super.call(e,r)}async _call(e,t,r){return this.func(e,t,r)}},E1=class extends rd{static lc_name(){return"DynamicStructuredTool"}description;func;schema;constructor(e){super(e),this.name=e.name,this.description=e.description,this.func=e.func,this.returnDirect=e.returnDirect??this.returnDirect,this.schema=e.schema}async call(e,t,r){let n=Bo(t);return n.runName===void 0&&(n.runName=this.name),super.call(e,n,r)}_call(e,t,r){return this.func(e,t,r)}},G3=class{getTools(){return this.tools}};function nd(e,t){let r=Cc(t.schema),n=Fc(t.schema);if(!t.schema||r||n)return new eS({...t,description:t.description??t.schema?.description??`${t.name} tool`,func:async(o,a,c)=>new Promise((u,l)=>{let p=Ne(c,{callbacks:a?.getChild()});Ze.runWithConfig(hr(p),async()=>{try{u(e(o,p))}catch(f){l(f)}})})});let i=t.schema,s=t.description??t.schema.description??`${t.name} tool`;return new E1({...t,description:s,schema:i,func:async(o,a,c)=>new Promise((u,l)=>{let p,f=()=>{c?.signal&&p&&c.signal.removeEventListener("abort",p)};c?.signal&&(p=()=>{f(),l(Us(c.signal))},c.signal.addEventListener("abort",p));let d=Ne(c,{callbacks:a?.getChild()});Ze.runWithConfig(hr(d),async()=>{try{let m=await e(o,d);if(c?.signal?.aborted){f();return}f(),u(m)}catch(m){f(),l(m)}})})})}function K3(e){let{content:t,artifact:r,toolCallId:n,metadata:i}=e;return n&&!_l(t)?typeof t=="string"||Array.isArray(t)&&t.every(s=>typeof s=="object")?new Wt({status:"success",content:t,artifact:r,tool_call_id:n,name:e.name,metadata:i}):new Wt({status:"success",content:q3(t),artifact:r,tool_call_id:n,name:e.name,metadata:i}):t}function q3(e){try{return JSON.stringify(e)??""}catch{return`${e}`}}var tS={};M(tS,{RunCollectorCallbackHandler:()=>H3});var H3=class extends Zt{name="run_collector";exampleId;tracedRuns;constructor({exampleId:e}={}){super({_awaitHandler:!0}),this.exampleId=e,this.tracedRuns=[]}async persistRun(e){let t={...e};t.reference_example_id=this.exampleId,this.tracedRuns.push(t)}};var k1={};var rS={};M(rS,{chunkArray:()=>lg});var lg=(e,t)=>e.reduce((r,n,i)=>{let s=Math.floor(i/t),o=r[s]||[];return r[s]=o.concat([n]),r},[]);var nS={};M(nS,{context:()=>W3});function W3(e,...t){let r=e.raw,n="";for(let i=0;i<r.length;i++){let s=r[i].replace(/\\\n[ \t]*/g,"").replace(/\\`/g,"`").replace(/\\\$/g,"$").replace(/\\\{/g,"{");if(n+=s,i<t.length){let o=J3(t[i],n);n+=typeof o=="string"?o:JSON.stringify(o)}}return n=X3(n),n=n.trim(),n=n.replace(/\\n/g,`
|
|
206
|
+
`),n}function J3(e,t){if(typeof e!="string"||!e.includes(`
|
|
207
|
+
`))return e;let n=t.slice(t.lastIndexOf(`
|
|
208
|
+
`)+1).match(/^(\s+)/);if(n){let i=n[1];return e.replace(/\n/g,`
|
|
209
|
+
${i}`)}return e}function X3(e){let t=e.split(`
|
|
210
|
+
`),r=null;for(let n of t){let i=n.match(/^(\s+)\S+/);if(i){let s=i[1].length;r===null?r=s:r=Math.min(r,s)}}return r===null?e:t.map(n=>n[0]===" "||n[0]===" "?n.slice(r):n).join(`
|
|
211
|
+
`)}var sS={};M(sS,{EventStreamContentType:()=>Y3,convertEventStreamToIterableReadableDataStream:()=>eG,getBytes:()=>A1,getLines:()=>T1,getMessages:()=>O1});var Y3="text/event-stream";async function A1(e,t){if(e instanceof ReadableStream){let r=e.getReader();for(;;){let n=await r.read();if(n.done){t(new Uint8Array,!0);break}t(n.value)}}else try{for await(let r of e)t(new Uint8Array(r));t(new Uint8Array,!0)}catch(r){throw new Error(["Parsing event source stream failed.","Ensure your implementation of fetch returns a web or Node readable stream.",`Error: ${r.message}`].join(`
|
|
212
|
+
`))}}var tu=(function(e){return e[e.NewLine=10]="NewLine",e[e.CarriageReturn=13]="CarriageReturn",e[e.Space=32]="Space",e[e.Colon=58]="Colon",e})(tu||{});function T1(e){let t,r,n,i=!1;return function(o,a){if(a){e(o,0,!0);return}t===void 0?(t=o,r=0,n=-1):t=Q3(t,o);let c=t.length,u=0;for(;r<c;){i&&(t[r]===tu.NewLine&&(u=++r),i=!1);let l=-1;for(;r<c&&l===-1;++r)switch(t[r]){case tu.Colon:n===-1&&(n=r-u);break;case tu.CarriageReturn:i=!0;case tu.NewLine:l=r;break}if(l===-1)break;e(t.subarray(u,l),n),u=r,n=-1}u===c?t=void 0:u!==0&&(t=t.subarray(u),r-=u)}}function O1(e,t,r){let n=iS(),i=new TextDecoder;return function(o,a,c){if(c){tG(n)||(e?.(n),n=iS());return}if(o.length===0)e?.(n),n=iS();else if(a>0){let u=i.decode(o.subarray(0,a)),l=a+(o[a+1]===tu.Space?2:1),p=i.decode(o.subarray(l));switch(u){case"data":n.data=n.data?n.data+`
|
|
213
|
+
`+p:p;break;case"event":n.event=p;break;case"id":t?.(n.id=p);break;case"retry":{let f=parseInt(p,10);Number.isNaN(f)||r?.(n.retry=f);break}}}}}function Q3(e,t){let r=new Uint8Array(e.length+t.length);return r.set(e),r.set(t,e.length),r}function iS(){return{data:"",event:"",id:"",retry:void 0}}function eG(e,t){let r=new ReadableStream({async start(n){let i=O1(o=>{if(o.event==="error")throw new Error(o.data??"Unspecified event streaming error.");o.event==="metadata"?t?.(o):o.data&&n.enqueue(o.data)});await A1(e,T1((o,a,c)=>{i(o,a,c),c&&n.close()}))}});return kt.fromReadableStream(r)}function tG(e){return e.data===""&&e.event===""&&e.id===""&&e.retry===void 0}var $1={};var oS={};M(oS,{convertToOpenAIFunction:()=>C1,convertToOpenAITool:()=>aS,isLangChainTool:()=>Sa,isRunnableToolLike:()=>Wp,isStructuredTool:()=>Hp,isStructuredToolParams:()=>Jp});function C1(e,t){let r=typeof t=="number"?void 0:t;return{name:e.name,description:e.description,parameters:Ye(e.schema),...r?.strict!==void 0?{strict:r.strict}:{}}}function aS(e,t){let r=typeof t=="number"?void 0:t,n;return Sa(e)?n={type:"function",function:C1(e)}:n=e,r?.strict!==void 0&&(n.function.strict=r.strict),n}function pg(e,t){let r=0,n=0,i=0;for(let s=0;s<e.length;s++)r+=e[s]*t[s],n+=e[s]*e[s],i+=t[s]*t[s];return r/(Math.sqrt(n)*Math.sqrt(i))}function P1(e,t){let r=0;for(let n=0;n<e.length;n++)r+=e[n]*t[n];return r}function rG(e,t){let r=0;for(let n=0;n<e.length;n++)r+=(e[n]-t[n])*(e[n]-t[n]);return r}function N1(e,t){return Math.sqrt(rG(e,t))}var uS={};M(uS,{cosineSimilarity:()=>cS,euclideanDistance:()=>sG,innerProduct:()=>iG,matrixFunc:()=>dg,maximalMarginalRelevance:()=>oG,normalize:()=>nG});function dg(e,t,r){if(e.length===0||e[0].length===0||t.length===0||t[0].length===0)return[[]];if(e[0].length!==t[0].length)throw new Error(`Number of columns in X and Y must be the same. X has shape ${[e.length,e[0].length]} and Y has shape ${[t.length,t[0].length]}.`);return e.map(n=>t.map(i=>r(n,i)).map(i=>Number.isNaN(i)?0:i))}function nG(e,t=!1){let r=aG(e);return e.map(n=>n.map(i=>t?1-i/r:i/r))}function cS(e,t){return dg(e,t,pg)}function iG(e,t){return dg(e,t,P1)}function sG(e,t){return dg(e,t,N1)}function oG(e,t,r=.5,n=4){if(Math.min(n,t.length)<=0)return[];let i=Array.isArray(e[0])?e:[e],s=cS(i,t)[0],o=R1(s).maxIndex,a=[t[o]],c=[o];for(;c.length<Math.min(n,t.length);){let u=-1/0,l=-1,p=cS(t,a);s.forEach((f,d)=>{if(c.includes(d))return;let m=Math.max(...p[d]),h=r*f-(1-r)*m;h>u&&(u=h,l=d)}),a.push(t[l]),c.push(l)}return c}function R1(e){if(e.length===0)return{maxIndex:-1,maxValue:NaN};let t=e[0],r=0;for(let n=1;n<e.length;n+=1)e[n]>t&&(r=n,t=e[n]);return{maxIndex:r,maxValue:t}}function aG(e){return e.reduce((t,r)=>Math.max(t,R1(r).maxValue),0)}var M1=class extends to{_combineLLMOutput(){return[]}_llmType(){return"fake"}async _generate(e,t,r){if(t?.stop?.length)return{generations:[{message:new Oe(t.stop[0]),text:t.stop[0]}]};let n=e.map(i=>typeof i.content=="string"?i.content:JSON.stringify(i.content,null,2)).join(`
|
|
214
|
+
`);return await r?.handleLLMNewToken(n),{generations:[{message:new Oe(n),text:n}],llmOutput:{}}}},j1=class D1 extends to{sleep=50;responses=[];chunks=[];toolStyle="openai";thrownErrorString;tools=[];constructor({sleep:t=50,responses:r=[],chunks:n=[],toolStyle:i="openai",thrownErrorString:s,...o}){super(o),this.sleep=t,this.responses=r,this.chunks=n,this.toolStyle=i,this.thrownErrorString=s}_llmType(){return"fake"}bindTools(t){let r=[...this.tools,...t],n=r.map(o=>{switch(this.toolStyle){case"openai":return{type:"function",function:{name:o.name,description:o.description,parameters:Ye(o.schema)}};case"anthropic":return{name:o.name,description:o.description,input_schema:Ye(o.schema)};case"bedrock":return{toolSpec:{name:o.name,description:o.description,inputSchema:Ye(o.schema)}};case"google":return{name:o.name,description:o.description,parameters:Ye(o.schema)};default:throw new Error(`Unsupported tool style: ${this.toolStyle}`)}}),i=this.toolStyle==="google"?[{functionDeclarations:n}]:n,s=new D1({sleep:this.sleep,responses:this.responses,chunks:this.chunks,toolStyle:this.toolStyle,thrownErrorString:this.thrownErrorString});return s.tools=r,s.withConfig({tools:i})}async _generate(t,r,n){if(this.thrownErrorString)throw new Error(this.thrownErrorString);let i=this.responses?.[0]?.content??t[0].content??"";return{generations:[{text:"",message:new Oe({content:i,tool_calls:this.chunks?.[0]?.tool_calls})}]}}async*_streamResponseChunks(t,r,n){if(this.thrownErrorString)throw new Error(this.thrownErrorString);if(this.chunks?.length){for(let o of this.chunks){let a=new Zr({message:new nt({content:o.content,tool_calls:o.tool_calls,additional_kwargs:o.additional_kwargs??{}}),text:o.content?.toString()??""});if(r.signal?.aborted)break;yield a,await n?.handleLLMNewToken(o.content,void 0,void 0,void 0,void 0,{chunk:a})}return}let i=this.responses?.[0]??new Oe(typeof t[0].content=="string"?t[0].content:""),s=typeof i.content=="string"?i.content:"";for(let o of s){await new Promise(c=>setTimeout(c,this.sleep));let a=new Zr({message:new nt({content:o}),text:o});if(r.signal?.aborted)break;yield a,await n?.handleLLMNewToken(o,void 0,void 0,void 0,void 0,{chunk:a})}}},z1=class L1 extends to{static lc_name(){return"FakeListChatModel"}lc_serializable=!0;responses;i=0;sleep;emitCustomEvent=!1;generationInfo;tools=[];toolStyle="openai";constructor(t){super(t);let{responses:r,sleep:n,emitCustomEvent:i,generationInfo:s}=t;this.responses=r,this.sleep=n,this.emitCustomEvent=i??this.emitCustomEvent,this.generationInfo=s}_combineLLMOutput(){return[]}_llmType(){return"fake-list"}async _generate(t,r,n){if(await this._sleepIfRequested(),r?.thrownErrorString)throw new Error(r.thrownErrorString);if(this.emitCustomEvent&&await n?.handleCustomEvent("some_test_event",{someval:!0}),r?.stop?.length)return{generations:[this._formatGeneration(r.stop[0])]};{let i=this._currentResponse();return this._incrementResponse(),{generations:[this._formatGeneration(i)],llmOutput:{}}}}_formatGeneration(t){return{message:new Oe(t),text:t}}async*_streamResponseChunks(t,r,n){let i=this._currentResponse();this._incrementResponse(),this.emitCustomEvent&&await n?.handleCustomEvent("some_test_event",{someval:!0});let s=[...i];for(let o=0;o<s.length;o++){let a=s[o],c=o===s.length-1;if(await this._sleepIfRequested(),r?.thrownErrorString)throw new Error(r.thrownErrorString);let u=this._createResponseChunk(a,c?this.generationInfo:void 0);if(r.signal?.aborted)break;yield u,n?.handleLLMNewToken(a)}}async _sleepIfRequested(){this.sleep!==void 0&&await this._sleep()}async _sleep(){return new Promise(t=>{setTimeout(()=>t(),this.sleep)})}_createResponseChunk(t,r){return new Zr({message:new nt({content:t}),text:t,generationInfo:r})}_currentResponse(){return this.responses[this.i]}_incrementResponse(){this.i<this.responses.length-1?this.i+=1:this.i=0}bindTools(t){let r=[...this.tools,...t],n=r.map(o=>{switch(this.toolStyle){case"openai":return{type:"function",function:{name:o.name,description:o.description,parameters:Ye(o.schema)}};case"anthropic":return{name:o.name,description:o.description,input_schema:Ye(o.schema)};case"bedrock":return{toolSpec:{name:o.name,description:o.description,inputSchema:Ye(o.schema)}};case"google":return{name:o.name,description:o.description,parameters:Ye(o.schema)};default:throw new Error(`Unsupported tool style: ${this.toolStyle}`)}}),i=this.toolStyle==="google"?[{functionDeclarations:n}]:n,s=new L1({responses:this.responses,sleep:this.sleep,emitCustomEvent:this.emitCustomEvent,generationInfo:this.generationInfo});return s.tools=r,s.toolStyle=this.toolStyle,s.i=this.i,s.withConfig({tools:i})}withStructuredOutput(t,r){return tr.from(async n=>{let i=await this.invoke(n);if(i.tool_calls?.[0]?.args)return i.tool_calls[0].args;if(typeof i.content=="string")return JSON.parse(i.content);throw new Error("No structured output found")})}};var U1=class extends Bc{vectorSize;constructor(e){super(e??{}),this.vectorSize=e?.vectorSize??4}async embedDocuments(e){return Promise.all(e.map(t=>this.embedQuery(t)))}async embedQuery(e){let t=e;t=t.toLowerCase().replaceAll(/[^a-z ]/g,"");let r=t.length%this.vectorSize,n=r===0?0:this.vectorSize-r,i=t.length+n;t=t.padEnd(i," ");let s=t.length/this.vectorSize,o=[];for(let c=0;c<t.length;c+=s)o.push(t.slice(c,c+s));return o.map(c=>{let u=0;for(let p=0;p<c.length;p+=1)u+=c===" "?0:c.charCodeAt(p);return u%26/26})}},F1=class extends Bc{constructor(e){super(e??{})}embedDocuments(e){return Promise.resolve(e.map(()=>[.1,.2,.3,.4]))}embedQuery(e){return Promise.resolve([.1,.2,.3,.4])}};var B1=class extends Dh{response;thrownErrorString;constructor(e){super(e),this.response=e.response,this.thrownErrorString=e.thrownErrorString}_llmType(){return"fake"}async _call(e,t,r){if(this.thrownErrorString)throw new Error(this.thrownErrorString);let n=this.response??e;return await r?.handleLLMNewToken(n),n}},V1=class extends Dh{sleep=50;responses;thrownErrorString;constructor(e){super(e),this.sleep=e.sleep??this.sleep,this.responses=e.responses,this.thrownErrorString=e.thrownErrorString}_llmType(){return"fake"}async _call(e){if(this.thrownErrorString)throw new Error(this.thrownErrorString);let t=this.responses?.[0];return this.responses=this.responses?.slice(1),t??e}async*_streamResponseChunks(e,t,r){if(this.thrownErrorString)throw new Error(this.thrownErrorString);let n=this.responses?.[0];this.responses=this.responses?.slice(1);for(let i of n??e)await new Promise(s=>setTimeout(s,this.sleep)),yield{text:i,generationInfo:{}},await r?.handleLLMNewToken(i)}};var Z1=class extends s0{lc_namespace=["langchain_core","message","fake"];messages=[];constructor(){super()}async getMessages(){return this.messages}async addMessage(e){this.messages.push(e)}async addUserMessage(e){this.messages.push(new at(e))}async addAIMessage(e){this.messages.push(new Oe(e))}async clear(){this.messages=[]}},G1=class extends Eh{lc_namespace=["langchain_core","message","fake"];messages=[];constructor(){super()}async addMessage(e){this.messages.push(e)}async getMessages(){return this.messages}},K1=class extends Zt{name="fake_tracer";runs=[];constructor(){super()}persistRun(e){return this.runs.push(e),Promise.resolve()}};var q1=class extends is{lc_namespace=["tests","fake"];getFormatInstructions(){return""}async parse(e){return e.split(",").map(t=>t.trim())}};var H1=class extends Pp{lc_namespace=["test","fake"];output=[new qr({pageContent:"foo"}),new qr({pageContent:"bar"})];constructor(e){super(),this.output=e?.output??this.output}async _getRelevantDocuments(e){return this.output}};var W1=class extends ce{lc_namespace=["tests","fake"];returnOptions;constructor(e){super(e),this.returnOptions=e.returnOptions}async invoke(e,t){return this.returnOptions?t??{}:{input:e}}};var J1=class extends rd{name;description;schema;constructor(e){super(e),this.name=e.name,this.description=e.description,this.schema=e.schema}async _call(e,t){return JSON.stringify(e)}};var X1=class extends Zt{runPromiseResolver;runPromise;name="single_run_extractor";constructor(){super(),this.runPromise=new Promise(e=>{this.runPromiseResolver=e})}async persistRun(e){this.runPromiseResolver(e)}async extract(){return this.runPromise}};var Y1=class Q1 extends Th{memoryVectors=[];similarity;_vectorstoreType(){return"memory"}constructor(t,{similarity:r,...n}={}){super(t,n),this.similarity=r??pg}async addDocuments(t){let r=t.map(({pageContent:n})=>n);return this.addVectors(await this.embeddings.embedDocuments(r),t)}async addVectors(t,r){let n=t.map((i,s)=>({content:r[s].pageContent,embedding:i,metadata:r[s].metadata}));this.memoryVectors=this.memoryVectors.concat(n)}async similaritySearchVectorWithScore(t,r,n){let i=c=>{if(!n)return!0;let u=new qr({metadata:c.metadata,pageContent:c.content});return n(u)},s=this.memoryVectors.filter(i);return s.map((c,u)=>({similarity:this.similarity(t,c.embedding),index:u})).sort((c,u)=>c.similarity>u.similarity?-1:0).slice(0,r).map(c=>[new qr({metadata:s[c.index].metadata,pageContent:s[c.index].content}),c.similarity])}static async fromTexts(t,r,n,i){let s=[];for(let o=0;o<t.length;o+=1){let a=Array.isArray(r)?r[o]:r,c=new qr({pageContent:t[o],metadata:a});s.push(c)}return Q1.fromDocuments(s,n,i)}static async fromDocuments(t,r,n){let i=new this(r,n);return await i.addDocuments(t),i}static async fromExistingIndex(t,r){return new this(t,r)}};var lS={};M(lS,{FakeChatMessageHistory:()=>Z1,FakeChatModel:()=>M1,FakeEmbeddings:()=>F1,FakeLLM:()=>B1,FakeListChatMessageHistory:()=>G1,FakeListChatModel:()=>z1,FakeRetriever:()=>H1,FakeRunnable:()=>W1,FakeSplitIntoListParser:()=>q1,FakeStreamingChatModel:()=>j1,FakeStreamingLLM:()=>V1,FakeTool:()=>J1,FakeTracer:()=>K1,FakeVectorStore:()=>Y1,SingleRunExtractor:()=>X1,SyntheticEmbeddings:()=>U1});var pS={};M(pS,{extendInteropZodObject:()=>sh,getInteropZodDefaultGetter:()=>oh,getInteropZodObjectShape:()=>ta,getSchemaDescription:()=>$n,interopParse:()=>$c,interopParseAsync:()=>Ws,interopSafeParse:()=>oP,interopSafeParseAsync:()=>nh,interopZodObjectMakeFieldsOptional:()=>cP,interopZodObjectPartial:()=>Pc,interopZodObjectPassthrough:()=>rh,interopZodObjectStrict:()=>Oc,interopZodTransformInputSchema:()=>ah,isInteropZodError:()=>ch,isInteropZodLiteral:()=>sP,isInteropZodObject:()=>yr,isInteropZodSchema:()=>_r,isShapelessZodSchema:()=>aP,isSimpleStringZodSchema:()=>Cc,isZodArrayV4:()=>xp,isZodLiteralV3:()=>Mx,isZodLiteralV4:()=>jx,isZodNullableV4:()=>zx,isZodObjectV3:()=>ih,isZodObjectV4:()=>dn,isZodOptionalV4:()=>Dx,isZodSchema:()=>iP,isZodSchemaV3:()=>it,isZodSchemaV4:()=>Je});var dS={};M(dS,{agents:()=>Dk,caches:()=>m0,callbacks__base:()=>iy,callbacks__manager:()=>xv,callbacks__promises:()=>vv,chat_history:()=>i0,document_loaders__base:()=>g0,document_loaders__langsmith:()=>y0,documents:()=>b0,embeddings:()=>o0,example_selectors:()=>I0,index:()=>PN,indexing:()=>O0,language_models__base:()=>R0,language_models__chat_models:()=>j0,language_models__llms:()=>D0,language_models__profile:()=>nR,load__serializable:()=>W_,memory:()=>a0,messages:()=>n0,messages__tool:()=>ry,output_parsers:()=>B0,output_parsers__openai_functions:()=>G0,output_parsers__openai_tools:()=>q0,outputs:()=>Nv,prompt_values:()=>c0,prompts:()=>oI,retrievers:()=>p0,retrievers__document_compressors:()=>aI,runnables:()=>L0,runnables__graph:()=>Wx,singletons:()=>Sv,stores:()=>l0,structured_query:()=>fI,tools:()=>YI,tracers__base:()=>cv,tracers__console:()=>lv,tracers__log_stream:()=>Cv,tracers__run_collector:()=>tS,tracers__tracer_langchain:()=>yv,types__stream:()=>k1,utils__async_caller:()=>Rv,utils__chunk_array:()=>rS,utils__context:()=>nS,utils__env:()=>X_,utils__event_source_parse:()=>sS,utils__format:()=>$1,utils__function_calling:()=>oS,utils__hash:()=>f0,utils__json_patch:()=>U0,utils__json_schema:()=>qx,utils__math:()=>uS,utils__stream:()=>kv,utils__testing:()=>lS,utils__tiktoken:()=>N0,utils__types:()=>pS,vectorstores:()=>d0});var cG=50;function uG(e){let t={};for(let r=e;r&&r.prototype;r=Object.getPrototypeOf(r))Object.assign(t,Reflect.get(r.prototype,"lc_aliases"));return Object.entries(t).reduce((r,[n,i])=>(r[i]=n,r),{})}async function fg(e){let{optionalImportsMap:t,optionalImportEntrypoints:r,importMap:n,secretsMap:i,secretsFromEnv:s,path:o,depth:a,maxDepth:c}=this,u=o.join(".");if(a>c)throw new Error(`Maximum recursion depth (${c}) exceeded during deserialization. This may indicate a malicious payload or you may need to increase maxDepth.`);if(typeof e!="object"||e==null)return e;if(Array.isArray(e))return Promise.all(e.map((f,d)=>fg.call({...this,path:[...o,`${d}`],depth:a+1},f)));let l=e;if(H_(l))return cf(l);if("lc"in l&&"type"in l&&"id"in l&&l.lc===1&&l.type==="secret"){let f=l,[d]=f.id;if(d in i)return i[d];if(s){let m=Pe(d);if(m)return m}throw new Error(`Missing secret "${d}" at ${u}`)}if("lc"in l&&"type"in l&&"id"in l&&l.lc===1&&l.type==="not_implemented"){let d=JSON.stringify(l);throw new Error(`Trying to load an object that doesn't implement serialization: ${u} -> ${d}`)}if("lc"in l&&"type"in l&&"id"in l&&"kwargs"in l&&l.lc===1&&l.type==="constructor"){let f=l,d=JSON.stringify(f),[m,...h]=f.id.slice().reverse(),b=h.reverse(),_={langchain_core:dS,langchain:n},y=null,x=[b.join("/")];b[0]==="langchain_community"&&x.push(["langchain",...b.slice(1)].join("/"));let I=x.find(w=>w in t);if(jk.concat(r).includes(b.join("/"))||I)if(I!==void 0)y=await t[I];else throw new Error(`Missing key "${b.join("/")}" for ${u} in load(optionalImportsMap={})`);else{let w;if(b[0]==="langchain"||b[0]==="langchain_core")w=_[b[0]],b.shift();else throw new Error(`Invalid namespace: ${u} -> ${d}`);if(b.length===0)throw new Error(`Invalid namespace: ${u} -> ${d}`);let F;do{if(F=b.join("__"),F in w)break;b.pop()}while(b.length>0);F in w&&(y=w[F])}if(typeof y!="object"||y===null)throw new Error(`Invalid namespace: ${u} -> ${d}`);let A=y[m]??Object.values(y).find(w=>typeof w=="function"&&uc(w)===m);if(typeof A!="function")throw new Error(`Invalid identifer: ${u} -> ${d}`);let j=await fg.call({...this,path:[...o,"kwargs"],depth:a+1},f.kwargs),O=new A(of(j,Ok,uG(A)));return Object.defineProperty(O.constructor,"name",{value:m}),O}let p={};for(let[f,d]of Object.entries(l))p[f]=await fg.call({...this,path:[...o,f],depth:a+1},d);return p}async function eM(e,t){let r=JSON.parse(e),n={optionalImportsMap:t?.optionalImportsMap??{},optionalImportEntrypoints:t?.optionalImportEntrypoints??[],secretsMap:t?.secretsMap??{},secretsFromEnv:t?.secretsFromEnv??!1,importMap:t?.importMap??{},path:["$"],depth:0,maxDepth:t?.maxDepth??cG};return fg.call(n,r)}function lG(e){return e!==null&&e.lc===1&&e.type==="constructor"&&Array.isArray(e.id)}async function mS(e){if(e&&typeof e=="object"){if(Array.isArray(e))return await Promise.all(e.map(r=>mS(r)));{let t={};for(let[r,n]of Object.entries(e))t[r]=await mS(n);if(t.lc===2&&t.type==="undefined")return;if(t.lc===2&&t.type==="constructor"&&Array.isArray(t.id))try{let r=t.id[t.id.length-1],n;switch(r){case"Set":n=Set;break;case"Map":n=Map;break;case"RegExp":n=RegExp;break;case"Error":n=Error;break;default:return t}return t.method?n[t.method](...t.args||[]):new n(...t.args||[])}catch{return t}else if(lG(t))return eM(JSON.stringify(t));return t}}return e}function fS(e,t,r,n){return{lc:2,type:"constructor",id:[e.name],method:t??null,args:r??[],kwargs:n??{}}}function pG(e){return e===void 0?{lc:2,type:"undefined"}:e instanceof Set||e instanceof Map?fS(e.constructor,void 0,[Array.from(e)]):e instanceof RegExp?fS(RegExp,void 0,[e.source,e.flags]):e instanceof Error?fS(e.constructor,void 0,[e.message]):e?.lg_name==="Send"?{node:e.node,args:e.args}:e}var mg=class{_dumps(e){return new TextEncoder().encode(gk(e,(r,n)=>pG(n)))}async dumpsTyped(e){return e instanceof Uint8Array?["bytes",e]:["json",this._dumps(e)]}async _loads(e){let t=JSON.parse(e);return mS(t)}async loadsTyped(e,t){if(e==="bytes")return typeof t=="string"?new TextEncoder().encode(t):t;if(e==="json")return this._loads(typeof t=="string"?t:new TextDecoder().decode(t));throw new Error(`Unknown serialization type: ${e}`)}};function hS(e){if(typeof e!="object"||e===null)return e;let t=Array.isArray(e)?[]:{};for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=hS(e[r]));return t}function ru(){return{v:4,id:ml(-2),ts:new Date().toISOString(),channel_values:{},channel_versions:{},versions_seen:{}}}function Ln(e){return{v:e.v,id:e.id,ts:e.ts,channel_values:{...e.channel_values},channel_versions:{...e.channel_versions},versions_seen:hS(e.versions_seen)}}var hg=class{serde=new mg;constructor(e){this.serde=e||this.serde}async get(e){let t=await this.getTuple(e);return t?t.checkpoint:void 0}getNextVersion(e){if(typeof e=="string")throw new Error("Please override this method to use string versions.");return e!==void 0&&typeof e=="number"?e+1:1}};function gg(e,t){return typeof e=="number"&&typeof t=="number"?Math.sign(e-t):String(e).localeCompare(String(t))}function id(...e){return e.reduce((t,r,n)=>n===0?r:gg(t,r)>=0?t:r)}var sd={[B_]:-1,[Ro]:-2,[V_]:-3,[Z_]:-4};function gS(e){return e.configurable?.checkpoint_id||e.configurable?.thread_ts||""}function od(e,t,r){return JSON.stringify([e,t,r])}function dG(e){let[t,r,n]=JSON.parse(e);return{threadId:t,checkpointNamespace:r,checkpointId:n}}var _g=class extends hg{storage={};writes={};constructor(e){super(e)}async _migratePendingSends(e,t,r,n){let i=e,s=od(t,r,n),o=await Promise.all(Object.values(this.writes[s]??{}).filter(([a,c])=>c===hl).map(async([a,c,u])=>await this.serde.loadsTyped("json",u)));i.channel_values??={},i.channel_values[hl]=o,i.channel_versions??={},i.channel_versions[hl]=Object.keys(i.channel_versions).length>0?id(...Object.values(i.channel_versions)):this.getNextVersion(void 0)}async getTuple(e){let t=e.configurable?.thread_id,r=e.configurable?.checkpoint_ns??"",n=gS(e);if(n){let i=this.storage[t]?.[r]?.[n];if(i!==void 0){let[s,o,a]=i,c=od(t,r,n),u=await this.serde.loadsTyped("json",s);u.v<4&&a!==void 0&&await this._migratePendingSends(u,t,r,a);let l=await Promise.all(Object.values(this.writes[c]||{}).map(async([f,d,m])=>[f,d,await this.serde.loadsTyped("json",m)])),p={config:e,checkpoint:u,metadata:await this.serde.loadsTyped("json",o),pendingWrites:l};return a!==void 0&&(p.parentConfig={configurable:{thread_id:t,checkpoint_ns:r,checkpoint_id:a}}),p}}else{let i=this.storage[t]?.[r];if(i!==void 0){n=Object.keys(i).sort((d,m)=>m.localeCompare(d))[0];let s=i[n],[o,a,c]=s,u=od(t,r,n),l=await this.serde.loadsTyped("json",o);l.v<4&&c!==void 0&&await this._migratePendingSends(l,t,r,c);let p=await Promise.all(Object.values(this.writes[u]||{}).map(async([d,m,h])=>[d,m,await this.serde.loadsTyped("json",h)])),f={config:{configurable:{thread_id:t,checkpoint_id:n,checkpoint_ns:r}},checkpoint:l,metadata:await this.serde.loadsTyped("json",a),pendingWrites:p};return c!==void 0&&(f.parentConfig={configurable:{thread_id:t,checkpoint_ns:r,checkpoint_id:c}}),f}}}async*list(e,t){let{before:r,limit:n,filter:i}=t??{},s=e.configurable?.thread_id?[e.configurable?.thread_id]:Object.keys(this.storage),o=e.configurable?.checkpoint_ns,a=e.configurable?.checkpoint_id;for(let c of s)for(let u of Object.keys(this.storage[c]??{})){if(o!==void 0&&u!==o)continue;let l=this.storage[c]?.[u]??{},p=Object.entries(l).sort((f,d)=>d[0].localeCompare(f[0]));for(let[f,[d,m,h]]of p){if(a&&f!==a||r&&r.configurable?.checkpoint_id&&f>=r.configurable.checkpoint_id)continue;let b=await this.serde.loadsTyped("json",m);if(i&&!Object.entries(i).every(([j,O])=>b[j]===O))continue;if(n!==void 0){if(n<=0)break;n-=1}let _=od(c,u,f),y=Object.values(this.writes[_]||{}),x=await Promise.all(y.map(async([j,O,w])=>[j,O,await this.serde.loadsTyped("json",w)])),I=await this.serde.loadsTyped("json",d);I.v<4&&h!==void 0&&await this._migratePendingSends(I,c,u,h);let A={config:{configurable:{thread_id:c,checkpoint_ns:u,checkpoint_id:f}},checkpoint:I,metadata:b,pendingWrites:x};h!==void 0&&(A.parentConfig={configurable:{thread_id:c,checkpoint_ns:u,checkpoint_id:h}}),yield A}}}async put(e,t,r){let n=Ln(t),i=e.configurable?.thread_id,s=e.configurable?.checkpoint_ns??"";if(i===void 0)throw new Error('Failed to put checkpoint. The passed RunnableConfig is missing a required "thread_id" field in its "configurable" property.');this.storage[i]||(this.storage[i]={}),this.storage[i][s]||(this.storage[i][s]={});let[[,o],[,a]]=await Promise.all([this.serde.dumpsTyped(n),this.serde.dumpsTyped(r)]);return this.storage[i][s][t.id]=[o,a,e.configurable?.checkpoint_id],{configurable:{thread_id:i,checkpoint_ns:s,checkpoint_id:t.id}}}async putWrites(e,t,r){let n=e.configurable?.thread_id,i=e.configurable?.checkpoint_ns,s=e.configurable?.checkpoint_id;if(n===void 0)throw new Error('Failed to put writes. The passed RunnableConfig is missing a required "thread_id" field in its "configurable" property');if(s===void 0)throw new Error('Failed to put writes. The passed RunnableConfig is missing a required "checkpoint_id" field in its "configurable" property.');let o=od(n,i,s),a=this.writes[o];this.writes[o]===void 0&&(this.writes[o]={}),await Promise.all(t.map(async([c,u],l)=>{let[,p]=await this.serde.dumpsTyped(u),f=[r,sd[c]||l],d=`${f[0]},${f[1]}`;f[1]>=0&&a&&d in a||(this.writes[o][d]=[r,c,p])}))}async deleteThread(e){delete this.storage[e];for(let t of Object.keys(this.writes))dG(t).threadId===e&&delete this.writes[t]}};var nu=class extends Error{constructor(e){super(e),this.name="InvalidNamespaceError"}};function fG(e){if(e.length===0)throw new nu("Namespace cannot be empty.");for(let t of e){if(typeof t!="string")throw new nu(`Invalid namespace label '${t}' found in ${e}. Namespace labels must be strings, but got ${typeof t}.`);if(t.includes("."))throw new nu(`Invalid namespace label '${t}' found in ${e}. Namespace labels cannot contain periods ('.').`);if(t==="")throw new nu(`Namespace labels cannot be empty strings. Got ${t} in ${e}`)}if(e[0]==="langgraph")throw new nu(`Root label for namespace cannot be "langgraph". Got: ${e}`)}var ad=class{async get(e,t){return(await this.batch([{namespace:e,key:t}]))[0]}async search(e,t={}){let{filter:r,limit:n=10,offset:i=0,query:s}=t;return(await this.batch([{namespacePrefix:e,filter:r,limit:n,offset:i,query:s}]))[0]}async put(e,t,r,n){fG(e),await this.batch([{namespace:e,key:t,value:r,index:n}])}async delete(e,t){await this.batch([{namespace:e,key:t,value:null}])}async listNamespaces(e={}){let{prefix:t,suffix:r,maxDepth:n,limit:i=100,offset:s=0}=e,o=[];return t&&o.push({matchType:"prefix",path:t}),r&&o.push({matchType:"suffix",path:r}),(await this.batch([{matchConditions:o.length?o:void 0,maxDepth:n,limit:i,offset:s}]))[0]}start(){}stop(){}};var mG=e=>"lg_name"in e&&e.lg_name==="AsyncBatchedStore"?e.store:e,yg=class extends ad{lg_name="AsyncBatchedStore";store;queue=new Map;nextKey=0;running=!1;processingTask=null;constructor(e){super(),this.store=mG(e)}get isRunning(){return this.running}async batch(e){throw new Error("The `batch` method is not implemented on `AsyncBatchedStore`.\n Instead, it calls the `batch` method on the wrapped store.\n If you are seeing this error, something is wrong.")}async get(e,t){return this.enqueueOperation({namespace:e,key:t})}async search(e,t){let{filter:r,limit:n=10,offset:i=0,query:s}=t||{};return this.enqueueOperation({namespacePrefix:e,filter:r,limit:n,offset:i,query:s})}async put(e,t,r){return this.enqueueOperation({namespace:e,key:t,value:r})}async delete(e,t){return this.enqueueOperation({namespace:e,key:t,value:null})}start(){this.running||(this.running=!0,this.processingTask=this.processBatchQueue())}async stop(){this.running=!1,this.processingTask&&await this.processingTask}enqueueOperation(e){return new Promise((t,r)=>{let n=this.nextKey;this.nextKey+=1,this.queue.set(n,{operation:e,resolve:t,reject:r})})}async processBatchQueue(){for(;this.running;){if(await new Promise(t=>{setTimeout(t,0)}),this.queue.size===0)continue;let e=new Map(this.queue);this.queue.clear();try{let t=Array.from(e.values()).map(({operation:n})=>n),r=await this.store.batch(t);e.forEach(({resolve:n},i)=>{let s=Array.from(e.keys()).indexOf(i);n(r[s])})}catch(t){e.forEach(({reject:r})=>{r(t)})}}}toJSON(){return{queue:this.queue,nextKey:this.nextKey,running:this.running,store:"[LangGraphStore]"}}};var vg=class{serde=new mg;constructor(e){this.serde=e||this.serde}};function yS(e){return e!=null&&e.lg_is_channel===!0}var Lt=class{ValueType;UpdateType;lg_is_channel=!0;consume(){return!1}finish(){return!1}isAvailable(){try{return this.get(),!0}catch(e){if(e.name===Ve.unminifiable_name)return!1;throw e}}equals(e){return this===e}},_S=Symbol.for("LG_IS_ONLY_BASE_CHANNEL");function cd(e){if(e[_S]===!0)return e;let t={};for(let r in e){if(!Object.prototype.hasOwnProperty.call(e,r))continue;let n=e[r];yS(n)&&(t[r]=n)}return Object.assign(t,{[_S]:!0}),t}function io(e,t){let r=cd(e),n={};for(let i in r){if(!Object.prototype.hasOwnProperty.call(r,i))continue;let s=t.channel_values[i];n[i]=r[i].fromCheckpoint(s)}return Object.assign(n,{[_S]:!0}),n}function Un(e,t,r,n){let i;if(t===void 0)i=e.channel_values;else{i={};for(let s in t)if(Object.prototype.hasOwnProperty.call(t,s))try{i[s]=t[s].checkpoint()}catch(o){if(o.name!==Ve.unminifiable_name)throw o}}return{v:4,id:n?.id??ml(r),ts:new Date().toISOString(),channel_values:i,channel_versions:e.channel_versions,versions_seen:e.versions_seen}}var gG=e=>e!=null&&e.lc_graph_name==="BinaryOperatorAggregate",us=class tM extends Lt{lc_graph_name="BinaryOperatorAggregate";value;operator;initialValueFactory;constructor(t,r){super(),this.operator=t,this.initialValueFactory=r,this.value=r?.()}fromCheckpoint(t){let r=new tM(this.operator,this.initialValueFactory);return typeof t<"u"&&(r.value=t),r}update(t){let r=t;if(!r.length)return!1;this.value===void 0&&([this.value]=r,r=r.slice(1));for(let n of r)this.value!==void 0&&(this.value=this.operator(this.value,n));return!0}get(){if(this.value===void 0)throw new Ve;return this.value}checkpoint(){if(this.value===void 0)throw new Ve;return this.value}isAvailable(){return this.value!==void 0}equals(t){return this===t?!0:gG(t)?this.operator===t.operator:!1}};var Fn=class rM extends Lt{lc_graph_name="LastValue";value=[];constructor(t){super(),this.initialValueFactory=t,t&&(this.value=[t()])}fromCheckpoint(t){let r=new rM(this.initialValueFactory);return typeof t<"u"&&(r.value=[t]),r}update(t){if(t.length===0)return!1;if(t.length!==1)throw new De("LastValue can only receive one value per step.",{lc_error_code:"INVALID_CONCURRENT_GRAPH_UPDATE"});return this.value=[t[t.length-1]],!0}get(){if(this.value.length===0)throw new Ve;return this.value[0]}checkpoint(){if(this.value.length===0)throw new Ve;return this.value[0]}isAvailable(){return this.value.length!==0}},vS=class nM extends Lt{lc_graph_name="LastValueAfterFinish";value=[];finished=!1;fromCheckpoint(t){let r=new nM;if(typeof t<"u"){let[n,i]=t;r.value=[n],r.finished=i}return r}update(t){return t.length===0?!1:(this.finished=!1,this.value=[t[t.length-1]],!0)}get(){if(this.value.length===0||!this.finished)throw new Ve;return this.value[0]}checkpoint(){if(this.value.length!==0)return[this.value[0],this.finished]}consume(){return this.finished?(this.finished=!1,this.value=[],!0):!1}finish(){return!this.finished&&this.value.length>0?(this.finished=!0,!0):!1}isAvailable(){return this.value.length!==0&&this.finished}};var bg=class{lc_graph_name="AnnotationRoot";spec;constructor(e){this.spec=e}static isInstance(e){return typeof e=="object"&&e!==null&&"lc_graph_name"in e&&e.lc_graph_name==="AnnotationRoot"}},Bn=function(e){return e?wg(e):new Fn};Bn.Root=e=>new bg(e);function wg(e){return typeof e=="object"&&e&&"reducer"in e&&e.reducer?new us(e.reducer,e.default):typeof e=="object"&&e&&"value"in e&&e.value?new us(e.value,e.default):new Fn}var ke="__start__",we="__end__",Vn="__input__",sM="__copy__",Ot="__error__",xg="__pregel_ns_writes",bn="__pregel_send",ld="__pregel_call",Zn="__pregel_read",ft="__pregel_checkpointer",wi="__pregel_resuming",ka="__pregel_task_id",iu="__pregel_stream",_G="__pregel_resume_value",su="__pregel_resume_map",Wr="__pregel_scratchpad",ou="__pregel_previous",bS="__pregel_durability",Ig="checkpoint_id",Jr="checkpoint_ns",oM="__pregel_node_finished",xr="checkpoint_map",wS="__pregel_abort_signals",Ee="__interrupt__",Nt="__resume__",pd="__no_writes__",Gn="__return__",Aa="__previous__",Be="langsmith:hidden",aM="langsmith:nostream",xS="__self__",Ut="__pregel_tasks",nr="__pregel_push",dd="__pregel_pull",ir="00000000-0000-0000-0000-000000000000",cM=[Be,Vn,Ee,Nt,Ot,pd,bn,Zn,ft,bS,iu,wi,ka,ld,_G,Wr,ou,xr,Jr,Ig],et="|",Ir=":",iM=Symbol.for("langgraph.command"),yG=class{[iM];constructor(e){this[iM]=e}};function Sg(e){let t=e;return t!=null&&typeof t.node=="string"&&t.args!==void 0}var Ea=class{lg_name="Send";node;args;constructor(e,t){this.node=e,this.args=ud(t)}toJSON(){return{lg_name:this.lg_name,node:this.node,args:this.args}}};function $t(e){return e instanceof Ea}function fd(e){return!e||typeof e!="object"||!(Ee in e)?!1:Array.isArray(e[Ee])}var jr=class extends yG{lg_name="Command";lc_direct_tool_output=!0;graph;update;resume;goto=[];static PARENT="__parent__";constructor(e){super(e),this.resume=e.resume,this.graph=e.graph,this.update=e.update,e.goto&&(this.goto=Array.isArray(e.goto)?ud(e.goto):[ud(e.goto)])}_updateAsTuples(){return this.update&&typeof this.update=="object"&&!Array.isArray(this.update)?Object.entries(this.update):Array.isArray(this.update)&&this.update.every(e=>Array.isArray(e)&&e.length===2&&typeof e[0]=="string")?this.update:[["__root__",this.update]]}toJSON(){let e;return typeof this.goto=="string"?e=this.goto:$t(this.goto)?e=this.goto.toJSON():e=this.goto?.map(t=>typeof t=="string"?t:t.toJSON()),{lg_name:this.lg_name,update:this.update,resume:this.resume,goto:e}}};function Pt(e){return typeof e!="object"||e==null?!1:"lg_name"in e&&e.lg_name==="Command"}function ud(e,t=new Map){if(e!=null&&typeof e=="object"){if(t.has(e))return t.get(e);let r;if(Array.isArray(e))r=[],t.set(e,r),e.forEach((n,i)=>{r[i]=ud(n,t)});else if(Pt(e)&&!(e instanceof jr))r=new jr(e),t.set(e,r);else if(Sg(e)&&!(e instanceof Ea))r=new Ea(e.node,e.args),t.set(e,r);else if(Pt(e)||$t(e))r=e,t.set(e,r);else if("lc_serializable"in e&&e.lc_serializable)r=e,t.set(e,r);else{r={},t.set(e,r);for(let[n,i]of Object.entries(e))r[n]=ud(i,t)}return r}return e}var vG=["tags","metadata","callbacks","configurable"],bG=["tags","metadata","callbacks","runName","maxConcurrency","recursionLimit","configurable","runId","outputKeys","streamMode","store","writer","interrupt","context","interruptBefore","interruptAfter","checkpointDuring","durability","signal"],wG=25;function md(...e){let t={tags:[],metadata:{},callbacks:void 0,recursionLimit:wG,configurable:{}},r=Ze.getRunnableConfig();if(r!==void 0){for(let[n,i]of Object.entries(r))if(i!==void 0)if(vG.includes(n)){let s;Array.isArray(i)?s=[...i]:typeof i=="object"?n==="callbacks"&&"copy"in i&&typeof i.copy=="function"?s=i.copy():s={...i}:s=i,t[n]=s}else t[n]=i}for(let n of e)if(n!==void 0)for(let[i,s]of Object.entries(n))s!==void 0&&bG.includes(i)&&(t[i]=s);for(let[n,i]of Object.entries(t.configurable))t.metadata=t.metadata??{},!n.startsWith("__")&&(typeof i=="string"||typeof i=="number"||typeof i=="boolean")&&!(n in t.metadata)&&(t.metadata[n]=i);return t}function uM(){return Ze.getRunnableConfig()}function Eg(e){return e.split(et).filter(t=>!t.match(/^\d+$/)).map(t=>t.split(Ir)[0]).join(et)}function lM(e){let t=e.split(et);for(;t.length>1&&t[t.length-1].match(/^\d+$/);)t.pop();return t.slice(0,-1).join(et)}var sr=class extends ce{lc_namespace=["langgraph"];func;tags;config;trace=!0;recurse=!0;constructor(e){super(),this.name=e.name??e.func.name,this.func=e.func,this.config=e.tags?{tags:e.tags}:void 0,this.trace=e.trace??this.trace,this.recurse=e.recurse??this.recurse}async _tracedInvoke(e,t,r){return new Promise((n,i)=>{let s=Ne(t,{callbacks:r?.getChild()});Ze.runWithConfig(s,async()=>{try{n(await this.func(e,s))}catch(o){i(o)}})})}async invoke(e,t){let r,n=md(t),i=Dt(this.config,n);return this.trace?r=await this._callWithConfig(this._tracedInvoke,e,i):r=await Ze.runWithConfig(i,async()=>this.func(e,i)),ce.isRunnable(r)&&this.recurse?await Ze.runWithConfig(i,async()=>r.invoke(e,i)):r}};function*ls(e,t){if(t===void 0)yield*e;else for(let r of e)yield[t,r]}async function Kn(e){let t=[];for await(let r of await e)t.push(r);return t}function Ta(e){let t=[];for(let r of e)t.push(r);return t}function Oa(e,t){return e?"configurable"in e?{...e,configurable:{...e.configurable,...t}}:{...e,configurable:t}:{configurable:t}}function pM(e){return e!=null&&typeof e=="function"&&e instanceof Object.getPrototypeOf(async function*(){}).constructor}function dM(e){return e!=null&&typeof e=="function"&&e instanceof Object.getPrototypeOf(function*(){}).constructor}var Rve={[Symbol.for("LG_SKIP_WRITE")]:!0};function xG(e){return typeof e=="object"&&e?.[Symbol.for("LG_SKIP_WRITE")]!==void 0}var Dr={[Symbol.for("LG_PASSTHROUGH")]:!0};function kg(e){return typeof e=="object"&&e?.[Symbol.for("LG_PASSTHROUGH")]!==void 0}var IS=Symbol("IS_WRITER"),_t=class ES extends sr{writes;constructor(t,r){let n=`ChannelWrite<${t.map(i=>$t(i)?i.node:"channel"in i?i.channel:"...").join(",")}>`;super({writes:t,name:n,tags:r,func:async(i,s)=>this._write(i,s??{})}),this.writes=t}async _write(t,r){let n=this.writes.map(i=>SS(i)&&kg(i.value)?{mapper:i.mapper,value:t}:Ag(i)&&kg(i.value)?{channel:i.channel,value:t,skipNone:i.skipNone,mapper:i.mapper}:i);return await ES.doWrite(r,n),t}static async doWrite(t,r){for(let s of r){if(Ag(s)){if(s.channel===Ut)throw new De("Cannot write to the reserved channel TASKS");if(kg(s.value))throw new De("PASSTHROUGH value must be replaced")}if(SS(s)&&kg(s.value))throw new De("PASSTHROUGH value must be replaced")}let n=[];for(let s of r)if($t(s))n.push([Ut,s]);else if(SS(s)){let o=await s.mapper.invoke(s.value,t);o!=null&&o.length>0&&n.push(...o)}else if(Ag(s)){let o=s.mapper!==void 0?await s.mapper.invoke(s.value,t):s.value;if(xG(o)||s.skipNone&&o===void 0)continue;n.push([s.channel,o])}else throw new Error(`Invalid write entry: ${JSON.stringify(s)}`);let i=t.configurable?.[bn];i(n)}static isWriter(t){return t instanceof ES||IS in t&&!!t[IS]}static registerWriter(t){return Object.defineProperty(t,IS,{value:!0})}};function Ag(e){return e!==void 0&&typeof e.channel=="string"}function SS(e){return e!==void 0&&!Ag(e)&&ce.isRunnable(e.mapper)}var fM=class mM extends sr{lc_graph_name="ChannelRead";channel;fresh=!1;mapper;constructor(t,r,n=!1){super({func:(i,s)=>mM.doRead(s,this.channel,this.fresh,this.mapper)}),this.fresh=n,this.mapper=r,this.channel=t,this.name=Array.isArray(t)?`ChannelRead<${t.join(",")}>`:`ChannelRead<${t}>`}static doRead(t,r,n,i){let s=t.configurable?.[Zn];if(!s)throw new Error("Runnable is not configured with a read function. Make sure to call in the context of a Pregel process");return i?i(s(r,n)):s(r,n)}},au=new yn,qn=class hd extends gn{lc_graph_name="PregelNode";channels;triggers=[];mapper;writers=[];bound=au;kwargs={};metadata={};tags=[];retryPolicy;cachePolicy;subgraphs;ends;constructor(t){let{channels:r,triggers:n,mapper:i,writers:s,bound:o,kwargs:a,metadata:c,retryPolicy:u,cachePolicy:l,tags:p,subgraphs:f,ends:d}=t,m=[...t.config?.tags?t.config.tags:[],...p??[]];super({...t,bound:t.bound??au,config:{...t.config?t.config:{},tags:m}}),this.channels=r,this.triggers=n,this.mapper=i,this.writers=s??this.writers,this.bound=o??this.bound,this.kwargs=a??this.kwargs,this.metadata=c??this.metadata,this.tags=m,this.retryPolicy=u,this.cachePolicy=l,this.subgraphs=f,this.ends=d}getWriters(){let t=[...this.writers];for(;t.length>1&&t[t.length-1]instanceof _t&&t[t.length-2]instanceof _t;){let r=t.slice(-2),n=r[0].writes.concat(r[1].writes);t[t.length-2]=new _t(n,r[0].config?.tags),t.pop()}return t}getNode(){let t=this.getWriters();if(!(this.bound===au&&t.length===0))return this.bound===au&&t.length===1?t[0]:this.bound===au?new br({first:t[0],middle:t.slice(1,t.length-1),last:t[t.length-1],omitSequenceTags:!0}):t.length>0?new br({first:this.bound,middle:t.slice(0,t.length-1),last:t[t.length-1],omitSequenceTags:!0}):this.bound}join(t){if(!Array.isArray(t))throw new Error("channels must be a list");if(typeof this.channels!="object")throw new Error("all channels must be named when using .join()");return new hd({channels:{...this.channels,...Object.fromEntries(t.map(r=>[r,r]))},triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:this.bound,kwargs:this.kwargs,config:this.config,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy})}pipe(t){return _t.isWriter(t)?new hd({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:[...this.writers,t],bound:this.bound,config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy}):this.bound===au?new hd({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:dt(t),config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy}):new hd({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:this.bound.pipe(t),config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy})}};function IG(e){return"steps"in e&&Array.isArray(e.steps)}function gd(e){return"lg_is_pregel"in e&&e.lg_is_pregel===!0}function Tg(e){let t=[e];for(let r of t){if(gd(r))return r;IG(r)&&t.push(...r.steps)}}var L=e=>BigInt(e),Ke=(e,t=0)=>new DataView(e.buffer,e.byteOffset+t,e.byteLength-t),yM=L("0x9E3779B1"),vM=L("0x85EBCA77"),SG=L("0xC2B2AE3D"),so=L("0x9E3779B185EBCA87"),$a=L("0xC2B2AE3D27D4EB4F"),bM=L("0x165667B19E3779F9"),TS=L("0x85EBCA77C2B2AE63"),EG=L("0x27D4EB2F165667C5"),kG=L("0x165667919E3779F9"),AG=L("0x9FB21C651E98DF25"),TG=e=>{let t=e.length;if(t%2!==0)throw new Error("String should have an even number of characters");let r=t/2,n=new Uint8Array(r),i=0,s=0;for(;s<r;){let o=e.slice(i,i+=2);n[s]=Number.parseInt(o,16),s+=1}return Ke(n)},xi=TG("b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e"),cu=(L(1)<<L(128))-L(1),Ae=(L(1)<<L(64))-L(1),Pg=(L(1)<<L(32))-L(1),ps=64,wM=ps/8,OG=8,Og=4;function uu(e){if(!e)throw new Error("Assert failed")}function $G(e){let t=new DataView(new ArrayBuffer(8));return t.setBigUint64(0,e,!0),t.getBigUint64(0,!1)}function CG(e){let t=e;return t=(t&L(65535))<<L(16)|(t&L(4294901760))>>L(16),t=(t&L(16711935))<<L(8)|(t&L(4278255360))>>L(8),t}function PG(e,t){return(e&Pg)*(t&Pg)&Ae}function NG(e,t){return(e<<t|e>>L(32)-t)&Pg}function xM(e,t,r){for(let n=0;n<wM;n+=1){let i=t.getBigUint64(n*8,!0),s=i^r.getBigUint64(n*8,!0);e[n^1]+=i,e[n]+=PG(s,s>>L(32))}return e}function hM(e,t,r,n){for(let i=0;i<n;i+=1)xM(e,Ke(t,i*ps),Ke(r,i*8));return e}function RG(e,t){for(let r=0;r<wM;r+=1){let n=t.getBigUint64(r*8,!0),i=e[r];i=kS(i,L(47)),i^=n,i*=yM,e[r]=i&Ae}return e}function $g(e,t){return IM(e[0]^t.getBigUint64(0,!0),e[1]^t.getBigUint64(OG,!0))}function gM(e,t,r){let n=r;return n+=$g(e.slice(0),Ke(t,0*Og)),n+=$g(e.slice(2),Ke(t,4*Og)),n+=$g(e.slice(4),Ke(t,8*Og)),n+=$g(e.slice(6),Ke(t,12*Og)),Ii(n&Ae)}function MG(e,t,r,n,i){let s=e,o=Math.floor((r.byteLength-ps)/8),a=ps*o,c=Math.floor((t.byteLength-1)/a);for(let u=0;u<c;u+=1)s=hM(s,Ke(t,u*a),r,o),s=i(s,Ke(r,r.byteLength-ps));{let u=Math.floor((t.byteLength-1-a*c)/ps);s=hM(s,Ke(t,c*a),r,u),s=n(s,Ke(t,t.byteLength-ps),Ke(r,r.byteLength-ps-7))}return s}function jG(e,t){let r=new BigUint64Array([SG,so,$a,bM,TS,vM,EG,yM]);uu(e.byteLength>128),r=MG(r,e,t,xM,RG),uu(r.length*8===64);{let n=gM(r,Ke(t,11),L(e.byteLength)*so&Ae);return gM(r,Ke(t,t.byteLength-ps-11),~(L(e.byteLength)*$a)&Ae)<<L(64)|n}}function IM(e,t){let r=e*t&cu;return r&Ae^r>>L(64)}function _M(e,t,r){return IM((e.getBigUint64(0,!0)^t.getBigUint64(0,!0)+r)&Ae,(e.getBigUint64(8,!0)^t.getBigUint64(8,!0)-r)&Ae)}function Cg(e,t,r,n,i){let s=e&Ae,o=e>>L(64)&Ae;return s+=_M(t,n,i),s^=r.getBigUint64(0,!0)+r.getBigUint64(8,!0),s&=Ae,o+=_M(r,Ke(n,16),i),o^=t.getBigUint64(0,!0)+t.getBigUint64(8,!0),o&=Ae,o<<L(64)|s}function Ii(e){let t=e;return t^=t>>L(37),t*=kG,t&=Ae,t^=t>>L(32),t}function Ng(e){let t=e;return t^=t>>L(33),t*=$a,t&=Ae,t^=t>>L(29),t*=bM,t&=Ae,t^=t>>L(32),t}function DG(e,t,r){let n=e.byteLength;uu(n>0&&n<=3);let i=L(e.getUint8(n-1))|L(n<<8)|L(e.getUint8(0)<<16)|L(e.getUint8(n>>1)<<24),s=(i^(L(t.getUint32(0,!0))^L(t.getUint32(4,!0)))+r)&Ae,o=(L(t.getUint32(8,!0))^L(t.getUint32(12,!0)))-r;return(Ng((NG(CG(i),L(13))^o)&Ae)&Ae)<<L(64)|Ng(s)}function kS(e,t){return e^e>>t}function zG(e,t,r){let n=e.byteLength;uu(n>=4&&n<=8);{let i=e.getUint32(0,!0),s=e.getUint32(n-4,!0),o=((L(i)|L(s)<<L(32))^(t.getBigUint64(16,!0)^t.getBigUint64(24,!0))+r&Ae)*(so+(L(n)<<L(2)))&cu;return o+=(o&Ae)<<L(65),o&=cu,o^=o>>L(67),kS(kS(o&Ae,L(35))*AG&Ae,L(28))|Ii(o>>L(64))<<L(64)}}function LG(e,t,r){let n=e.byteLength;uu(n>=9&&n<=16);{let i=(t.getBigUint64(32,!0)^t.getBigUint64(40,!0))+r&Ae,s=(t.getBigUint64(48,!0)^t.getBigUint64(56,!0))-r&Ae,o=e.getBigUint64(0,!0),a=e.getBigUint64(n-8,!0),c=(o^a^i)*so,u=(c&Ae)+(L(n-1)<<L(54));c=c&(cu^Ae)|u,a^=s,c+=a+(a&Pg)*(vM-L(1))<<L(64),c&=cu,c^=$G(c>>L(64));let l=(c&Ae)*$a;return l+=(c>>L(64))*$a<<L(64),l&=cu,Ii(l&Ae)|Ii(l>>L(64))<<L(64)}}function UG(e,t){let r=e.byteLength;return uu(r<=16),r>8?LG(e,xi,t):r>=4?zG(e,xi,t):r>0?DG(e,xi,t):Ng(t^xi.getBigUint64(64,!0)^xi.getBigUint64(72,!0))|Ng(t^xi.getBigUint64(80,!0)^xi.getBigUint64(88,!0))<<L(64)}function AS(e){return~e+L(1)&Ae}function FG(e,t,r){let n=L(e.byteLength)*so&Ae,i=L(e.byteLength-1)/L(32);for(;i>=0;){let a=Number(i);n=Cg(n,Ke(e,16*a),Ke(e,e.byteLength-16*(a+1)),Ke(t,32*a),r),i-=L(1)}let s=n+(n>>L(64))&Ae;s=Ii(s);let o=(n&Ae)*so+(n>>L(64))*TS+(L(e.byteLength)-r&Ae)*$a;return o&=Ae,o=AS(Ii(o)),s|o<<L(64)}function BG(e,t,r){let n=L(e.byteLength)*so&Ae;for(let o=32;o<160;o+=32)n=Cg(n,Ke(e,o-32),Ke(e,o-16),Ke(t,o-32),r);n=Ii(n&Ae)|Ii(n>>L(64))<<L(64);for(let o=160;o<=e.byteLength;o+=32)n=Cg(n,Ke(e,o-32),Ke(e,o-16),Ke(t,3+o-160),r);n=Cg(n,Ke(e,e.byteLength-16),Ke(e,e.byteLength-32),Ke(t,103),AS(r));let i=n+(n>>L(64))&Ae;i=Ii(i);let s=(n&Ae)*so+(n>>L(64))*TS+(L(e.byteLength)-r&Ae)*$a;return s&=Ae,s=AS(Ii(s)),i|s<<L(64)}function ds(e,t=L(0)){let r=new TextEncoder,n=Ke(typeof e=="string"?r.encode(e):e),i=n.byteLength,s=o=>o.toString(16).padStart(32,"0");return i<=16?s(UG(n,t)):i<=128?s(FG(n,xi,t)):i<=240?s(BG(n,xi,t)):s(jG(n,xi))}function Rg(e){return/^[0-9a-f]{32}$/.test(e)}function Ca(e,t,r=!0,n=!1){try{return e[t].get()}catch(i){if(i.name===Ve.unminifiable_name){if(n)return i;if(r)return null}throw i}}function Hn(e,t,r=!0){if(Array.isArray(t)){let n={};for(let i of t)try{n[i]=Ca(e,i,!r)}catch(s){if(s.name===Ve.unminifiable_name)continue}return n}else return Ca(e,t)}function*SM(e,t){if(e.graph===jr.PARENT)throw new De("There is no parent graph.");if(e.goto){let r;Array.isArray(e.goto)?r=e.goto:r=[e.goto];for(let n of r)if($t(n))yield[ir,Ut,n];else if(typeof n=="string")yield[ir,`branch:to:${n}`,"__start__"];else throw new Error(`In Command.send, expected Send or string, got ${typeof n}`)}if(e.resume)if(typeof e.resume=="object"&&Object.keys(e.resume).length&&Object.keys(e.resume).every(Rg))for(let[r,n]of Object.entries(e.resume)){let i=t.filter(s=>s[0]===r&&s[1]===Nt).map(s=>s[2]).slice(0,1)??[];i.push(n),yield[r,Nt,i]}else yield[ir,Nt,e.resume];if(e.update){if(typeof e.update!="object"||!e.update)throw new Error("Expected cmd.update to be a dict mapping channel names to update values");if(Array.isArray(e.update))for(let[r,n]of e.update)yield[ir,r,n];else for(let[r,n]of Object.entries(e.update))yield[ir,r,n]}}function*Mg(e,t){if(t!=null)if(Array.isArray(e)&&typeof t=="object"&&!Array.isArray(t))for(let r in t)e.includes(r)&&(yield[r,t[r]]);else{if(Array.isArray(e))throw new Error('Input chunk must be an object when "inputChannels" is an array');yield[e,t]}}function*jg(e,t,r){Array.isArray(e)?(t===!0||t.find(([n,i])=>e.includes(n)))&&(yield Hn(r,e)):(t===!0||t.some(([n,i])=>n===e))&&(yield Ca(r,e))}function*EM(e,t,r){let n=t.filter(([a,c])=>(a.config===void 0||!a.config.tags?.includes(Be))&&c[0][0]!==Ot&&c[0][0]!==Ee);if(!n.length)return;let i;n.some(([a])=>a.writes.some(([c,u])=>c===Gn))?i=n.flatMap(([a])=>a.writes.filter(([c,u])=>c===Gn).map(([c,u])=>[a.name,u])):Array.isArray(e)?i=n.flatMap(([a])=>{let{writes:c}=a,u={};for(let[l]of c)e.includes(l)&&(u[l]=(u[l]||0)+1);return Object.values(u).some(l=>l>1)?c.filter(([l])=>e.includes(l)).map(([l,p])=>[a.name,{[l]:p}]):[[a.name,Object.fromEntries(c.filter(([l])=>e.includes(l)))]]}):i=n.flatMap(([a])=>a.writes.filter(([c,u])=>c===e).map(([c,u])=>[a.name,u]));let s={};for(let[a,c]of i)a in s||(s[a]=[]),s[a].push(c);let o={};for(let a in s)if(s[a].length===1){let[c]=s[a];o[a]=c}else o[a]=s[a];r&&(o.__metadata__={cached:r}),yield o}function Dg(e){let t=typeof e[ke];if(t==="number")return 0;if(t==="string")return"";for(let r in e){if(!Object.prototype.hasOwnProperty.call(e,r))continue;let n=typeof e[r];if(n==="number")return 0;if(n==="string")return"";break}}function lu(e,t){if(Object.keys(e).length>0){let r=Dg(t);return Object.fromEntries(Object.entries(t).filter(([n,i])=>i>(e[n]??r)))}else return t}function kM(e,t){return e&&!Array.isArray(e)&&!(e instanceof Date)&&typeof e=="object"?e:{[t]:e}}function zr(e,t){return e===null?{configurable:t}:e?.configurable===void 0?{...e,configurable:t}:{...e,configurable:{...e.configurable,...t}}}function oo(e,t){let r=t?.parents??{};return Object.keys(r).length>0?zr(e,{[xr]:{...r,[e.configurable?.checkpoint_ns??""]:e.configurable?.checkpoint_id}}):e}function pu(...e){let t=[...new Set(e.filter(Boolean))];if(t.length===0)return{signal:void 0,dispose:void 0};if(t.length===1)return{signal:t[0],dispose:void 0};let r=new AbortController,n=()=>{let s=t.find(o=>o.aborted)?.reason;r.abort(s),t.forEach(o=>o.removeEventListener("abort",n))};t.forEach(s=>s.addEventListener("abort",n,{once:!0}));let i=t.find(s=>s.aborted);return i&&r.abort(i.reason),{signal:r.signal,dispose:()=>{t.forEach(s=>s.removeEventListener("abort",n))}}}var AM=(e,t)=>{if(!(!e&&!t))return e?t?Array.isArray(e)&&Array.isArray(t)?[...e,...t]:Array.isArray(e)?[...e,t]:Array.isArray(t)?[e,...t]:[e,t]:e:t};var TM=class{func;name;input;retry;cache;callbacks;__lg_type="call";constructor({func:e,name:t,input:r,retry:n,cache:i,callbacks:s}){this.func=e,this.name=t,this.input=r,this.retry=n,this.cache=i,this.callbacks=s}};function OM(e){return typeof e=="object"&&e!==null&&"__lg_type"in e&&e.__lg_type==="call"}function $M(e,t){return new br({name:e,first:new sr({func:r=>t(...r),name:e,trace:!1,recurse:!1}),last:new _t([{channel:Gn,value:Dr}],[Be])})}function CM(e,t){return new sr({func:(r,n)=>t(r,n),name:e,trace:!1,recurse:!1})}var PM=e=>e!==void 0?e+1:1;function VG(e,t){if(t==null)return!1;for(let r of e)if(t[r])return!0;return!1}function ZG(e){let t;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t==null?t=e[r]:t=id(t,e[r]));return t}function yd(e,t,r){let n=Dg(e.channel_versions),i=e.versions_seen[Ee]??{},s=!1;if((e.channel_versions[ke]??n)>(i[ke]??n))s=!0;else for(let a in e.channel_versions)if(Object.prototype.hasOwnProperty.call(e.channel_versions,a)&&e.channel_versions[a]>(i[a]??n)){s=!0;break}let o=r.some(a=>t==="*"?!a.config?.tags?.includes(Be):t.includes(a.name));return s&&o}function _d(e,t,r,n,i=!1){let s=new Set;if(Array.isArray(n))s=new Set(n.filter(a=>r.writes.some(([c,u])=>c===a)));else{for(let[a]of r.writes)if(a===n){s=new Set([a]);break}s=s||new Set}let o;if(i&&s.size>0){let a=Object.fromEntries(Object.entries(t).filter(([l,p])=>s.has(l))),c=Un(e,a,-1),u=io(a,c);Sr(Ln(c),u,[r],void 0,void 0),o=Hn({...t,...u},n)}else o=Hn(t,n);return o}function OS(e,t,r){for(let[n,i]of r)if([nr,Ut].includes(n)&&i!=null){if(!$t(i))throw new De(`Invalid packet type, expected SendProtocol, got ${JSON.stringify(i)}`);if(!(i.node in t))throw new De(`Invalid node name "${i.node}" in Send packet`)}e(r)}var GG=new Set([pd,nr,Nt,Ee,Gn,Ot]);function Sr(e,t,r,n,i){r.sort((f,d)=>{let m=f.path?.slice(0,3)||[],h=d.path?.slice(0,3)||[];for(let b=0;b<Math.min(m.length,h.length);b+=1){if(m[b]<h[b])return-1;if(m[b]>h[b])return 1}return m.length-h.length});let s=r.some(f=>f.triggers.length>0),o=cd(t);for(let f of r){e.versions_seen[f.name]??={};for(let d of f.triggers)d in e.channel_versions&&(e.versions_seen[f.name][d]=e.channel_versions[d])}let a=ZG(e.channel_versions),c=new Set(r.flatMap(f=>f.triggers).filter(f=>!cM.includes(f))),u=!1;for(let f of c)f in o&&o[f].consume()&&n!==void 0&&(e.channel_versions[f]=n(a),u=!0);let l={};for(let f of r)for(let[d,m]of f.writes)GG.has(d)||d in o&&(l[d]??=[],l[d].push(m));a!=null&&n!=null&&(a=u?n(a):a);let p=new Set;for(let[f,d]of Object.entries(l))if(f in o){let m=o[f],h;try{h=m.update(d)}catch(b){if(b.name===De.unminifiable_name){let _=new De(`Invalid update for channel "${f}" with values ${JSON.stringify(d)}: ${b.message}`);throw _.lc_error_code=b.lc_error_code,_}else throw b}h&&n!==void 0&&(e.channel_versions[f]=n(a),m.isAvailable()&&p.add(f))}if(s)for(let f in o){if(!Object.prototype.hasOwnProperty.call(o,f))continue;let d=o[f];d.isAvailable()&&!p.has(f)&&d.update([])&&n!==void 0&&(e.channel_versions[f]=n(a),d.isAvailable()&&p.add(f))}if(s&&!VG(p,i))for(let f in o){if(!Object.prototype.hasOwnProperty.call(o,f))continue;let d=o[f];d.finish()&&n!==void 0&&(e.channel_versions[f]=n(a),d.isAvailable()&&p.add(f))}return p}function*KG(e,t,r){if(r.updatedChannels!=null&&r.triggerToNodes!=null){let n=new Set;for(let i of r.updatedChannels){let s=r.triggerToNodes[i];for(let o of s??[])n.add(o)}yield*[...n].sort();return}if(!(()=>{for(let n in e.channel_versions)if(e.channel_versions[n]!==null)return!1;return!0})())for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&(yield n)}function ao(e,t,r,n,i,s,o){let a={},c=n[Ut];if(c?.isAvailable()){let u=c.get().length;for(let l=0;l<u;l+=1){let p=zg([nr,l],e,t,r,n,i,s,o);p!==void 0&&(a[p.id]=p)}}for(let u of KG(e,r,o)){let l=zg([dd,u],e,t,r,n,i,s,o);l!==void 0&&(a[l.id]=l)}return a}function zg(e,t,r,n,i,s,o,a){let{step:c,checkpointer:u,manager:l}=a,p=s.configurable??{},f=p.checkpoint_ns??"";if(e[0]===nr&&OM(e[e.length-1])){let d=e[e.length-1],m=$M(d.name,d.func),h=[nr],b=f===""?d.name:`${f}${et}${d.name}`,_=zi(JSON.stringify([b,c.toString(),d.name,nr,e[1],e[2]]),t.id),y=`${b}${Ir}${_}`,x=[...e.slice(0,3),!0],I={langgraph_step:c,langgraph_node:d.name,langgraph_triggers:h,langgraph_path:x,langgraph_checkpoint_ns:y};if(o){let A=[];return{name:d.name,input:d.input,proc:m,writes:A,config:Ne(Dt(s,{metadata:I,store:a.store??s.store}),{runName:d.name,callbacks:l?.getChild(`graph:step:${c}`),configurable:{[ka]:_,[bn]:j=>OS(O=>A.push(...O),n,j),[Zn]:(j,O=!1)=>_d(t,i,{name:d.name,writes:A,triggers:h,path:x},j,O),[ft]:u??p[ft],[xr]:{...p[xr],[f]:t.id},[Wr]:$S({pendingWrites:r??[],taskId:_,currentTaskInput:d.input,resumeMap:s.configurable?.[su],namespaceHash:ds(y)}),[ou]:t.channel_values[Aa],checkpoint_id:void 0,checkpoint_ns:y}}),triggers:h,retry_policy:d.retry,cache_key:d.cache?{key:ds((d.cache.keyFunc??JSON.stringify)([d.input])),ns:[xg,d.name??"__dynamic__"],ttl:d.cache.ttl}:void 0,id:_,path:x,writers:[]}}else return{id:_,name:d.name,interrupts:[],path:x}}else if(e[0]===nr){let d=typeof e[1]=="number"?e[1]:parseInt(e[1],10);if(!i[Ut]?.isAvailable())return;let m=i[Ut].get();if(d<0||d>=m.length)return;let h=Sg(m[d])&&!$t(m[d])?new Ea(m[d].node,m[d].args):m[d];if(!Sg(h)){console.warn(`Ignoring invalid packet ${JSON.stringify(h)} in pending sends.`);return}if(!(h.node in n)){console.warn(`Ignoring unknown node name ${h.node} in pending sends.`);return}let b=[nr],_=f===""?h.node:`${f}${et}${h.node}`,y=zi(JSON.stringify([_,c.toString(),h.node,nr,d.toString()]),t.id),x=`${_}${Ir}${y}`,I={langgraph_step:c,langgraph_node:h.node,langgraph_triggers:b,langgraph_path:e.slice(0,3),langgraph_checkpoint_ns:x};if(o){let A=n[h.node],j=A.getNode();if(j!==void 0){A.metadata!==void 0&&(I={...I,...A.metadata});let O=[];return{name:h.node,input:h.args,proc:j,subgraphs:A.subgraphs,writes:O,config:Ne(Dt(s,{metadata:I,tags:A.tags,store:a.store??s.store}),{runName:h.node,callbacks:l?.getChild(`graph:step:${c}`),configurable:{[ka]:y,[bn]:w=>OS(F=>O.push(...F),n,w),[Zn]:(w,F=!1)=>_d(t,i,{name:h.node,writes:O,triggers:b,path:e},w,F),[ft]:u??p[ft],[xr]:{...p[xr],[f]:t.id},[Wr]:$S({pendingWrites:r??[],taskId:y,currentTaskInput:h.args,resumeMap:s.configurable?.[su],namespaceHash:ds(x)}),[ou]:t.channel_values[Aa],checkpoint_id:void 0,checkpoint_ns:x}}),triggers:b,retry_policy:A.retryPolicy,cache_key:A.cachePolicy?{key:ds((A.cachePolicy.keyFunc??JSON.stringify)([h.args])),ns:[xg,A.name??"__dynamic__",h.node],ttl:A.cachePolicy.ttl}:void 0,id:y,path:e,writers:A.getWriters()}}}else return{id:y,name:h.node,interrupts:[],path:e}}else if(e[0]===dd){let d=e[1].toString(),m=n[d];if(m===void 0)return;if(r?.length){let y=f===""?d:`${f}${et}${d}`,x=zi(JSON.stringify([y,c.toString(),d,dd,d]),t.id);if(r.some(I=>I[0]===x&&I[1]!==Ot))return}let h=Dg(t.channel_versions);if(h===void 0)return;let b=t.versions_seen[d]??{},_=m.triggers.find(y=>i[y].isAvailable()?(t.channel_versions[y]??h)>(b[y]??h):!1);if(_!==void 0){let y=qG(m,i,o);if(y===void 0)return;let x=f===""?d:`${f}${et}${d}`,I=zi(JSON.stringify([x,c.toString(),d,dd,[_]]),t.id),A=`${x}${Ir}${I}`,j={langgraph_step:c,langgraph_node:d,langgraph_triggers:[_],langgraph_path:e,langgraph_checkpoint_ns:A};if(o){let O=m.getNode();if(O!==void 0){m.metadata!==void 0&&(j={...j,...m.metadata});let w=[];return{name:d,input:y,proc:O,subgraphs:m.subgraphs,writes:w,config:Ne(Dt(s,{metadata:j,tags:m.tags,store:a.store??s.store}),{runName:d,callbacks:l?.getChild(`graph:step:${c}`),configurable:{[ka]:I,[bn]:F=>OS(P=>{w.push(...P)},n,F),[Zn]:(F,P=!1)=>_d(t,i,{name:d,writes:w,triggers:[_],path:e},F,P),[ft]:u??p[ft],[xr]:{...p[xr],[f]:t.id},[Wr]:$S({pendingWrites:r??[],taskId:I,currentTaskInput:y,resumeMap:s.configurable?.[su],namespaceHash:ds(A)}),[ou]:t.channel_values[Aa],checkpoint_id:void 0,checkpoint_ns:A}}),triggers:[_],retry_policy:m.retryPolicy,cache_key:m.cachePolicy?{key:ds((m.cachePolicy.keyFunc??JSON.stringify)([y])),ns:[xg,m.name??"__dynamic__",d],ttl:m.cachePolicy.ttl}:void 0,id:I,path:e,writers:m.getWriters()}}}else return{id:I,name:d,interrupts:[],path:e}}}}function qG(e,t,r){let n;if(typeof e.channels=="object"&&!Array.isArray(e.channels)){n={};for(let[i,s]of Object.entries(e.channels))if(e.triggers.includes(s))try{n[i]=Ca(t,s,!1)}catch(o){if(o.name===Ve.unminifiable_name)return;throw o}else if(s in t)try{n[i]=Ca(t,s,!1)}catch(o){if(o.name===Ve.unminifiable_name)continue;throw o}}else if(Array.isArray(e.channels)){let i=!1;for(let s of e.channels)try{n=Ca(t,s,!1),i=!0;break}catch(o){if(o.name===Ve.unminifiable_name)continue;throw o}if(!i)return}else throw new Error(`Invalid channels type, expected list or dict, got ${e.channels}`);return r&&e.mapper!==void 0&&(n=e.mapper(n)),n}function NM(e,t){if(typeof e.args!="object"||e.args===null)return e;let r={};for(let[n,i]of Object.entries(e.args)){let s=t[n];(!s||s.lc_graph_name!=="UntrackedValue")&&(r[n]=i)}return new Ea(e.node,r)}function $S({pendingWrites:e,taskId:t,currentTaskInput:r,resumeMap:n,namespaceHash:i}){let s=e.find(([a,c])=>a===ir&&c===Nt)?.[2],o={callCounter:0,interruptCounter:-1,resume:(()=>{let a=e.filter(([c,u])=>c===t&&u===Nt).flatMap(([c,u,l])=>l);if(n!=null&&i in n){let c=n[i];a.push(c)}return a})(),nullResume:s,subgraphCounter:0,currentTaskInput:r,consumeNullResume:()=>{if(o.nullResume)return delete o.nullResume,e.splice(e.findIndex(([a,c])=>a===ir&&c===Nt),1),s}};return o}var vd={blue:{start:"\x1B[34m",end:"\x1B[0m"},green:{start:"\x1B[32m",end:"\x1B[0m"},yellow:{start:"\x1B[33;1m",end:"\x1B[0m"}},bd=(e,t)=>`${e.start}${t}${e.end}`;function*CS(e){for(let{id:t,name:r,input:n,config:i,triggers:s,writes:o}of e)i?.tags?.includes(Be)||(yield{id:t,name:r,input:n,triggers:s,interrupts:o.filter(([a,c])=>a===t&&c===Ee).map(([,a])=>a)})}function HG(e){return typeof e!="object"||e===null?!1:"$writes"in e&&Array.isArray(e.$writes)}function RM(e){let t={};for(let[r,n]of e){let i=String(r);if(i in t){let s=HG(t[i])?t[i].$writes:[t[i]];s.push(n),t[i]={$writes:s}}else t[i]=n}return t}function*MM(e,t){for(let[{id:r,name:n,config:i},s]of e)i?.tags?.includes(Be)||(yield{id:r,name:n,result:RM(s.filter(([o])=>Array.isArray(t)?t.includes(o):o===t)),interrupts:s.filter(o=>o[0]===Ee).map(o=>o[1])})}function*jM(e,t,r,n,i,s,o,a){function c(p){let f={};return p.callbacks!=null&&(f.callbacks=p.callbacks),p.configurable!=null&&(f.configurable=p.configurable),p.maxConcurrency!=null&&(f.max_concurrency=p.maxConcurrency),p.metadata!=null&&(f.metadata=p.metadata),p.recursionLimit!=null&&(f.recursion_limit=p.recursionLimit),p.runId!=null&&(f.run_id=p.runId),p.runName!=null&&(f.run_name=p.runName),p.tags!=null&&(f.tags=p.tags),f}let u=e.configurable?.checkpoint_ns,l={};for(let p of i){if(!(p.subgraphs?.length?p.subgraphs:[p.proc]).find(Tg))continue;let f=`${p.name}:${p.id}`;u&&(f=`${u}|${f}`),l[p.id]={configurable:{thread_id:e.configurable?.thread_id,checkpoint_ns:f}}}yield{config:c(e),values:Hn(t,r),metadata:n,next:i.map(p=>p.name),tasks:PS(i,s,l,a),parentConfig:o?c(o):void 0}}function PS(e,t,r,n){return e.map(i=>{let s=t.find(([u,l])=>u===i.id&&l===Ot)?.[2],o=t.filter(([u,l])=>u===i.id&&l===Ee).map(([,,u])=>u),a=(()=>{if(s||o.length||!t.length)return;let u=t.findIndex(([l,p])=>l===i.id&&p===Gn);if(u>=0)return t[u][2];if(typeof n=="string")return t.find(([l,p])=>l===i.id&&p===n)?.[2];if(Array.isArray(n)){let l=t.filter(([p,f])=>p===i.id&&n.includes(f)).map(([,p,f])=>[p,f]);return l.length?RM(l):void 0}})();if(s)return{id:i.id,name:i.name,path:i.path,error:s,interrupts:o,result:a};let c=r?.[i.id];return{id:i.id,name:i.name,path:i.path,interrupts:o,...c!==void 0?{state:c}:{},result:a}})}function DM(e,t,r){console.log([`${bd(vd.blue,`[${e}:checkpoint]`)}`,`\x1B[1m State at the end of step ${e}:\x1B[0m
|
|
215
|
+
`,JSON.stringify(Hn(t,r),null,2)].join(""))}function Lg(e,t){let r=t.length;console.log([`${bd(vd.blue,`[${e}:tasks]`)}`,`\x1B[1m Starting step ${e} with ${r} task${r===1?"":"s"}:\x1B[0m
|
|
216
|
+
`,t.map(n=>`- ${bd(vd.green,String(n.name))} -> ${JSON.stringify(n.input,null,2)}`).join(`
|
|
217
|
+
`)].join(""))}function zM(e,t,r){let n={};for(let[i,s]of t)r.includes(i)&&(n[i]||(n[i]=[]),n[i].push(s));console.log([`${bd(vd.blue,`[${e}:writes]`)}`,`\x1B[1m Finished step ${e} with writes to ${Object.keys(n).length} channel${Object.keys(n).length!==1?"s":""}:\x1B[0m
|
|
218
|
+
`,Object.entries(n).map(([i,s])=>`- ${bd(vd.yellow,i)} -> ${s.map(o=>JSON.stringify(o)).join(", ")}`).join(`
|
|
219
|
+
`)].join(""))}var RS=class extends kt{_abortController;_innerReader;constructor(e,t){let r=e.getReader(),n=t??new AbortController;super({start(i){return s();function s(){return r.read().then(({done:o,value:a})=>{if(o){i.close();return}return i.enqueue(a),s()})}}}),this._abortController=n,this._innerReader=r}async cancel(e){this._abortController.abort(e),this._innerReader.releaseLock()}get signal(){return this._abortController.signal}},Ug=class extends kt{modes;controller;passthroughFn;_closed=!1;get closed(){return this._closed}constructor(e){let t,r=new Promise(n=>{t=n});super({start:n=>{t(n)}}),r.then(n=>{this.controller=n}),this.passthroughFn=e.passthroughFn,this.modes=e.modes}push(e){this.passthroughFn?.(e),this.controller.enqueue(e)}close(){try{this.controller.close()}catch{}finally{this._closed=!0}}error(e){this.controller.error(e)}};function WG(e){return JSON.stringify(e,function(t,r){let n=this[t];if(n!=null&&typeof n=="object"&&"toDict"in n&&typeof n.toDict=="function"){let{type:i,data:s}=n.toDict();return{...s,type:i}}return r})}function JG(e){return e instanceof Error?{error:e.name,message:e.message}:{error:"Error",message:JSON.stringify(e)}}function MS(e){return typeof e!="object"||e==null?!1:"configurable"in e&&typeof e.configurable=="object"&&e.configurable!=null}function NS(e){return!MS(e)||!e.configurable.thread_id?null:{thread_id:e.configurable.thread_id,checkpoint_ns:e.configurable.checkpoint_ns||"",checkpoint_id:e.configurable.checkpoint_id||null,checkpoint_map:e.configurable.checkpoint_map||null}}function LM(e){if(MS(e)){let t=Object.fromEntries(Object.entries(e.configurable).filter(([n])=>!n.startsWith("__"))),r={...e,configurable:t};return delete r.callbacks,r}return e}function UM(e){let t={...e,checkpoint:NS(e.config),parent_checkpoint:NS(e.parentConfig),config:LM(e.config),parent_config:LM(e.parentConfig),tasks:e.tasks.map(r=>{if(MS(r.state)){let n=NS(r.state);if(n!=null){let i={...r,checkpoint:n};return delete i.state,i}}return r})};return delete t.parentConfig,t}function FM(e){let t=new TextEncoder;return new ReadableStream({async start(r){let n=i=>{r.enqueue(t.encode(`event: ${i.event}
|
|
220
|
+
data: ${WG(i.data)}
|
|
221
|
+
|
|
222
|
+
`))};try{for await(let i of e){let[s,o,a]=i,c=a;if(o==="debug"){let u=a;u.type==="checkpoint"&&(c={...u,payload:UM(u.payload)})}o==="checkpoints"&&(c=UM(a)),n({event:s?.length?`${o}|${s.join("|")}`:o,data:c})}}catch(i){n({event:"error",data:JG(i)})}r.close()}})}var Fg=Symbol.for("INPUT_DONE"),jS=Symbol.for("INPUT_RESUMING"),XG=25;function YG(...e){return new Ug({passthroughFn:t=>{for(let r of e)r.modes.has(t[1])&&r.push(t)},modes:new Set(e.flatMap(t=>Array.from(t.modes)))})}var QG=class extends vg{cache;queue=Promise.resolve();constructor(e){super(),this.cache=e}async get(e){return this.enqueueOperation("get",e)}async set(e){return this.enqueueOperation("set",e)}async clear(e){return this.enqueueOperation("clear",e)}async stop(){await this.queue}enqueueOperation(e,...t){let r=this.queue.then(()=>this.cache[e](...t));return this.queue=r.then(()=>{},()=>{}),r}},BM=class VM{input;output;config;checkpointer;checkpointerGetNextVersion;channels;checkpoint;checkpointIdSaved;checkpointConfig;checkpointMetadata;checkpointNamespace;checkpointPendingWrites=[];checkpointPreviousVersions;step;stop;durability;outputKeys;streamKeys;nodes;skipDoneTasks;prevCheckpointConfig;updatedChannels;status="pending";tasks={};stream;checkpointerPromises=[];isNested;_checkpointerChainedPromise=Promise.resolve();store;cache;manager;interruptAfter;interruptBefore;toInterrupt=[];debug=!1;triggerToNodes;get isResuming(){let t=!1;if(ke in this.checkpoint.channel_versions)t=!0;else for(let a in this.checkpoint.channel_versions)if(Object.prototype.hasOwnProperty.call(this.checkpoint.channel_versions,a)){t=!0;break}let r=this.config.configurable?.[wi]!==void 0&&this.config.configurable?.[wi],n=this.input===null||this.input===void 0,i=Pt(this.input)&&this.input.resume!=null,s=this.input===jS,o=!this.isNested&&this.config.metadata?.run_id!==void 0&&this.checkpointMetadata?.run_id!==void 0&&this.config.metadata.run_id===this.checkpointMetadata?.run_id;return t&&(r||n||i||s||o)}constructor(t){this.input=t.input,this.checkpointer=t.checkpointer,this.checkpointer!==void 0?this.checkpointerGetNextVersion=this.checkpointer.getNextVersion.bind(this.checkpointer):this.checkpointerGetNextVersion=PM,this.checkpoint=t.checkpoint,this.checkpointMetadata=t.checkpointMetadata,this.checkpointPreviousVersions=t.checkpointPreviousVersions,this.channels=t.channels,this.checkpointPendingWrites=t.checkpointPendingWrites,this.step=t.step,this.stop=t.stop,this.config=t.config,this.checkpointConfig=t.checkpointConfig,this.isNested=t.isNested,this.manager=t.manager,this.outputKeys=t.outputKeys,this.streamKeys=t.streamKeys,this.nodes=t.nodes,this.skipDoneTasks=t.skipDoneTasks,this.store=t.store,this.cache=t.cache?new QG(t.cache):void 0,this.stream=t.stream,this.checkpointNamespace=t.checkpointNamespace,this.prevCheckpointConfig=t.prevCheckpointConfig,this.interruptAfter=t.interruptAfter,this.interruptBefore=t.interruptBefore,this.durability=t.durability,this.debug=t.debug,this.triggerToNodes=t.triggerToNodes}static async initialize(t){let{config:r,stream:n}=t;n!==void 0&&r.configurable?.[iu]!==void 0&&(n=YG(n,r.configurable[iu]));let i=r.configurable?!("checkpoint_id"in r.configurable):!0,s=r.configurable?.[Wr];r.configurable&&s&&(s.subgraphCounter>0&&(r=zr(r,{[Jr]:[r.configurable[Jr],s.subgraphCounter.toString()].join(et)})),s.subgraphCounter+=1);let o=Zn in(r.configurable??{});!o&&r.configurable?.checkpoint_ns!==void 0&&r.configurable?.checkpoint_ns!==""&&(r=zr(r,{checkpoint_ns:"",checkpoint_id:void 0}));let a=r;r.configurable?.[xr]!==void 0&&r.configurable?.[xr]?.[r.configurable?.checkpoint_ns]&&(a=zr(r,{checkpoint_id:r.configurable[xr][r.configurable?.checkpoint_ns]}));let c=r.configurable?.checkpoint_ns?.split(et)??[],u=await t.checkpointer?.getTuple(a)??{config:r,checkpoint:ru(),metadata:{source:"input",step:-2,parents:{}},pendingWrites:[]};a={...r,...u.config,configurable:{checkpoint_ns:"",...r.configurable,...u.config.configurable}};let l=u.parentConfig,p=Ln(u.checkpoint),f={...u.metadata},d=u.pendingWrites??[],m=io(t.channelSpecs,p),h=(f.step??0)+1,b=h+(r.recursionLimit??XG)+1,_={...p.channel_versions},y=t.store?new yg(t.store):void 0;return y&&await y.start(),new VM({input:t.input,config:r,checkpointer:t.checkpointer,checkpoint:p,checkpointMetadata:f,checkpointConfig:a,prevCheckpointConfig:l,checkpointNamespace:c,channels:m,isNested:o,manager:t.manager,skipDoneTasks:i,step:h,stop:b,checkpointPreviousVersions:_,checkpointPendingWrites:d,outputKeys:t.outputKeys??[],streamKeys:t.streamKeys??[],nodes:t.nodes,stream:n,store:y,cache:t.cache,interruptAfter:t.interruptAfter,interruptBefore:t.interruptBefore,durability:t.durability,debug:t.debug,triggerToNodes:t.triggerToNodes})}_checkpointerPutAfterPrevious(t){this._checkpointerChainedPromise=this._checkpointerChainedPromise.then(()=>this.checkpointer?.put(t.config,t.checkpoint,t.metadata,t.newVersions)),this.checkpointerPromises.push(this._checkpointerChainedPromise)}putWrites(t,r){let n=r;if(n.length===0)return;n.every(([c])=>c in sd)&&(n=Array.from(new Map(n.map(c=>[c[0],c])).values()));let i=!1;for(let c in this.channels)if(Object.prototype.hasOwnProperty.call(this.channels,c)&&this.channels[c].lc_graph_name==="UntrackedValue"){i=!0;break}let s=n;i&&(s=n.filter(([c])=>{let u=this.channels[c];return!u||u.lc_graph_name!=="UntrackedValue"}).map(([c,u])=>c===Ut&&$t(u)?[c,NM(u,this.channels)]:[c,u])),this.checkpointPendingWrites=this.checkpointPendingWrites.filter(c=>c[0]!==t);for(let[c,u]of s)this.checkpointPendingWrites.push([t,c,u]);let o=zr(this.checkpointConfig,{[Jr]:this.config.configurable?.checkpoint_ns??"",[Ig]:this.checkpoint.id});if(this.durability!=="exit"&&this.checkpointer!=null&&this.checkpointerPromises.push(this.checkpointer.putWrites(o,s,t)),this.tasks&&this._outputWrites(t,n),!r.length||!this.cache||!this.tasks)return;let a=this.tasks[t];a==null||a.cache_key==null||r[0][0]===Ot||r[0][0]===Ee||this.cache.set([{key:[a.cache_key.ns,a.cache_key.key],value:a.writes,ttl:a.cache_key.ttl}])}_outputWrites(t,r,n=!1){let i=this.tasks[t];if(i!==void 0){if(i.config!==void 0&&(i.config.tags??[]).includes(Be))return;if(r.length>0)if(r[0][0]===Ee){if(i.path?.[0]===nr&&i.path?.[i.path.length-1]===!0)return;let s=r.filter(o=>o[0]===Ee).flatMap(o=>o[1]);this._emit([["updates",{[Ee]:s}],["values",{[Ee]:s}]])}else r[0][0]!==Ot&&this._emit(Ta(ls(EM(this.outputKeys,[[i,r]],n),"updates")));n||this._emit(Ta(ls(MM([[i,r]],this.streamKeys),"tasks")))}}async _matchCachedWrites(){if(!this.cache)return[];let t=[],r=([o,a])=>`ns:${o.join(",")}|key:${a}`,n=[],i={};for(let o of Object.values(this.tasks))o.cache_key!=null&&!o.writes.length&&(n.push([o.cache_key.ns,o.cache_key.key]),i[r([o.cache_key.ns,o.cache_key.key])]=o);if(n.length===0)return[];let s=await this.cache.get(n);for(let{key:o,value:a}of s){let c=i[r(o)];c!=null&&(c.writes.push(...a),t.push({task:c,result:a}))}return t}async tick(t){this.store&&!this.store.isRunning&&await this.store?.start();let{inputKeys:r=[]}=t;if(this.status!=="pending")throw new Error(`Cannot tick when status is no longer "pending". Current status: "${this.status}"`);if(![Fg,jS].includes(this.input))await this._first(r);else{if(this.toInterrupt.length>0)throw this.status="interrupt_before",new ji;if(Object.values(this.tasks).every(i=>i.writes.length>0)){let i=Object.values(this.tasks).flatMap(o=>o.writes);this.updatedChannels=Sr(this.checkpoint,this.channels,Object.values(this.tasks),this.checkpointerGetNextVersion,this.triggerToNodes);let s=await Kn(ls(jg(this.outputKeys,i,this.channels),"values"));if(this._emit(s),this.checkpointPendingWrites=[],await this._putCheckpoint({source:"loop"}),yd(this.checkpoint,this.interruptAfter,Object.values(this.tasks)))throw this.status="interrupt_after",new ji;this.config.configurable?.[wi]!==void 0&&delete this.config.configurable?.[wi]}else return!1}if(this.step>this.stop)return this.status="out_of_steps",!1;if(this.tasks=ao(this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,this.config,!0,{step:this.step,checkpointer:this.checkpointer,isResuming:this.isResuming,manager:this.manager,store:this.store,stream:this.stream,triggerToNodes:this.triggerToNodes,updatedChannels:this.updatedChannels}),this.checkpointer&&this._emit(await Kn(ls(jM(this.checkpointConfig,this.channels,this.streamKeys,this.checkpointMetadata,Object.values(this.tasks),this.checkpointPendingWrites,this.prevCheckpointConfig,this.outputKeys),"checkpoints"))),Object.values(this.tasks).length===0)return this.status="done",!1;if(this.skipDoneTasks&&this.checkpointPendingWrites.length>0){for(let[i,s,o]of this.checkpointPendingWrites){if(s===Ot||s===Ee||s===Nt)continue;let a=Object.values(this.tasks).find(c=>c.id===i);a&&a.writes.push([s,o])}for(let i of Object.values(this.tasks))i.writes.length>0&&this._outputWrites(i.id,i.writes,!0)}if(Object.values(this.tasks).every(i=>i.writes.length>0))return this.tick({inputKeys:r});if(yd(this.checkpoint,this.interruptBefore,Object.values(this.tasks)))throw this.status="interrupt_before",new ji;let n=await Kn(ls(CS(Object.values(this.tasks)),"tasks"));return this._emit(n),!0}async finishAndHandleError(t){this.durability==="exit"&&(!this.isNested||typeof t<"u"||this.checkpointNamespace.every(n=>!n.includes(Ir)))&&(this._putCheckpoint(this.checkpointMetadata),this._flushPendingWrites());let r=this._suppressInterrupt(t);return(r||t===void 0)&&(this.output=Hn(this.channels,this.outputKeys)),r&&(this.tasks!==void 0&&this.checkpointPendingWrites.length>0&&Object.values(this.tasks).some(n=>n.writes.length>0)&&(this.updatedChannels=Sr(this.checkpoint,this.channels,Object.values(this.tasks),this.checkpointerGetNextVersion,this.triggerToNodes),this._emit(Ta(ls(jg(this.outputKeys,Object.values(this.tasks).flatMap(n=>n.writes),this.channels),"values")))),Di(t)&&!t.interrupts.length&&this._emit([["updates",{[Ee]:[]}],["values",{[Ee]:[]}]])),r}async acceptPush(t,r,n){if(this.interruptAfter?.length>0&&yd(this.checkpoint,this.interruptAfter,[t])){this.toInterrupt.push(t);return}let i=zg([nr,t.path??[],r,t.id,n],this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,t.config??{},!0,{step:this.step,checkpointer:this.checkpointer,manager:this.manager,store:this.store,stream:this.stream});if(!i)return;if(this.interruptBefore?.length>0&&yd(this.checkpoint,this.interruptBefore,[i])){this.toInterrupt.push(i);return}this._emit(Ta(ls(CS([i]),"tasks"))),this.debug&&Lg(this.step,[i]),this.tasks[i.id]=i,this.skipDoneTasks&&this._matchWrites({[i.id]:i});let s=await this._matchCachedWrites();for(let{task:o}of s)this._outputWrites(o.id,o.writes,!0);return i}_suppressInterrupt(t){return Di(t)&&!this.isNested}async _first(t){let{configurable:r}=this.config,n=r?.[Wr];if(n&&n.nullResume!==void 0&&this.putWrites(ir,[[Nt,n.nullResume]]),Pt(this.input)){let o=this.input.resume!=null;if(this.input.resume!=null&&typeof this.input.resume=="object"&&Object.keys(this.input.resume).every(Rg)&&(this.config.configurable??={},this.config.configurable[su]=this.input.resume),o&&this.checkpointer==null)throw new Error("Cannot use Command(resume=...) without checkpointer");let a={};for(let[c,u,l]of SM(this.input,this.checkpointPendingWrites))a[c]??=[],a[c].push([u,l]);if(Object.keys(a).length===0)throw new Yd("Received empty Command input");for(let[c,u]of Object.entries(a))this.putWrites(c,u)}let i=(this.checkpointPendingWrites??[]).filter(o=>o[0]===ir).map(o=>o.slice(1));i.length>0&&Sr(this.checkpoint,this.channels,[{name:Vn,writes:i,triggers:[]}],this.checkpointerGetNextVersion,this.triggerToNodes);let s=Pt(this.input)&&i.length>0;if(this.isResuming||s){for(let a in this.channels)if(Object.prototype.hasOwnProperty.call(this.channels,a)&&this.checkpoint.channel_versions[a]!==void 0){let c=this.checkpoint.channel_versions[a];this.checkpoint.versions_seen[Ee]={...this.checkpoint.versions_seen[Ee],[a]:c}}let o=await Kn(ls(jg(this.outputKeys,!0,this.channels),"values"));this._emit(o)}if(this.isResuming)this.input=jS;else if(s)await this._putCheckpoint({source:"input"}),this.input=Fg;else{let o=await Kn(Mg(t,this.input));if(o.length>0){let a=ao(this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,this.config,!0,{step:this.step});this.updatedChannels=Sr(this.checkpoint,this.channels,Object.values(a).concat([{name:Vn,writes:o,triggers:[]}]),this.checkpointerGetNextVersion,this.triggerToNodes),await this._putCheckpoint({source:"input"}),this.input=Fg}else if(wi in(this.config.configurable??{}))this.input=Fg;else throw new Yd(`Received no input writes for ${JSON.stringify(t,null,2)}`)}this.isNested||(this.config=zr(this.config,{[wi]:this.isResuming}))}_emit(t){for(let[r,n]of t)if(this.stream.modes.has(r)&&this.stream.push([this.checkpointNamespace,r,n]),(r==="checkpoints"||r==="tasks")&&this.stream.modes.has("debug")){let i=r==="checkpoints"?this.step-1:this.step,s=new Date().toISOString(),o=r==="checkpoints"?"checkpoint":typeof n=="object"&&n!=null&&"result"in n?"task_result":"task";this.stream.push([this.checkpointNamespace,"debug",{step:i,type:o,timestamp:s,payload:n}])}}_putCheckpoint(t){let r=this.checkpointMetadata===t,n=this.checkpointer!=null&&(this.durability!=="exit"||r),i=s=>{this.prevCheckpointConfig=this.checkpointConfig?.configurable?.checkpoint_id?this.checkpointConfig:void 0,this.checkpointConfig=zr(this.checkpointConfig,{[Jr]:this.config.configurable?.checkpoint_ns??""});let o={...this.checkpoint.channel_versions},a=lu(this.checkpointPreviousVersions,o);this.checkpointPreviousVersions=o,this._checkpointerPutAfterPrevious({config:{...this.checkpointConfig},checkpoint:Ln(s),metadata:{...this.checkpointMetadata},newVersions:a}),this.checkpointConfig={...this.checkpointConfig,configurable:{...this.checkpointConfig.configurable,checkpoint_id:this.checkpoint.id}}};r||(this.checkpointMetadata={...t,step:this.step,parents:this.config.configurable?.[xr]??{}}),this.checkpoint=Un(this.checkpoint,n?this.channels:void 0,this.step,r?{id:this.checkpoint.id}:void 0),n&&i(this.checkpoint),r||(this.step+=1)}_flushPendingWrites(){if(this.checkpointer==null||this.checkpointPendingWrites.length===0)return;let t=zr(this.checkpointConfig,{[Jr]:this.config.configurable?.checkpoint_ns??"",[Ig]:this.checkpoint.id}),r={};for(let[n,i,s]of this.checkpointPendingWrites)r[n]??=[],r[n].push([i,s]);for(let[n,i]of Object.entries(r))this.checkpointerPromises.push(this.checkpointer.putWrites(t,i,n))}_matchWrites(t){for(let[r,n,i]of this.checkpointPendingWrites){if(n===Ot||n===Ee||n===Nt)continue;let s=Object.values(t).find(o=>o.id===r);s&&s.writes.push([n,i])}for(let r of Object.values(t))r.writes.length>0&&this._outputWrites(r.id,r.writes,!0)}};function e5(e){return ot(e?.message)}var ZM=class extends Fi{name="StreamMessagesHandler";streamFn;metadatas={};seen={};emittedChatModelRunIds={};stableMessageIdMap={};lc_prefer_streaming=!0;constructor(e){super(),this.streamFn=e}_emit(e,t,r,n=!1){if(n&&t.id!==void 0&&this.seen[t.id]!==void 0)return;let i=t.id;r!=null&&(jo(t)?i??=`run-${r}-tool-${t.tool_call_id}`:((i==null||i===`run-${r}`)&&(i=this.stableMessageIdMap[r]??i??`run-${r}`),this.stableMessageIdMap[r]??=i)),i!==t.id&&(t.id=i,t.lc_kwargs.id=i),t.id!=null&&(this.seen[t.id]=t),this.streamFn([e[0],"messages",[t,e[1]]])}handleChatModelStart(e,t,r,n,i,s,o,a){o&&(!s||!s.includes(aM)&&!s.includes("nostream"))&&(this.metadatas[r]=[o.langgraph_checkpoint_ns.split("|"),{tags:s,name:a,...o}])}handleLLMNewToken(e,t,r,n,i,s){let o=s?.chunk;this.emittedChatModelRunIds[r]=!0,this.metadatas[r]!==void 0&&(e5(o)?this._emit(this.metadatas[r],o.message,r):this._emit(this.metadatas[r],new nt({content:e}),r))}handleLLMEnd(e,t){if(this.metadatas[t]!==void 0){if(!this.emittedChatModelRunIds[t]){let r=e.generations?.[0]?.[0];ot(r?.message)&&this._emit(this.metadatas[t],r?.message,t,!0),delete this.emittedChatModelRunIds[t]}delete this.metadatas[t],delete this.stableMessageIdMap[t]}}handleLLMError(e,t){delete this.metadatas[t]}handleChainStart(e,t,r,n,i,s,o,a){if(s!==void 0&&a===s.langgraph_node&&(i===void 0||!i.includes(Be))&&(this.metadatas[r]=[s.langgraph_checkpoint_ns.split("|"),{tags:i,name:a,...s}],typeof t=="object")){for(let c of Object.values(t))if((ot(c)||Ui(c))&&c.id!==void 0)this.seen[c.id]=c;else if(Array.isArray(c))for(let u of c)(ot(u)||Ui(u))&&u.id!==void 0&&(this.seen[u.id]=u)}}handleChainEnd(e,t){let r=this.metadatas[t];if(delete this.metadatas[t],r!==void 0){if(ot(e))this._emit(r,e,t,!0);else if(Array.isArray(e))for(let n of e)ot(n)&&this._emit(r,n,t,!0);else if(e!=null&&typeof e=="object"){for(let n of Object.values(e))if(ot(n))this._emit(r,n,t,!0);else if(Array.isArray(n))for(let i of n)ot(i)&&this._emit(r,i,t,!0)}}}handleChainError(e,t){delete this.metadatas[t]}};var t5=500,r5=2,n5=128e3,i5=3,s5=[400,401,402,403,404,405,406,407,409],o5=e=>{if(e.message.startsWith("Cancel")||e.message.startsWith("AbortError")||e.name==="AbortError"||e.name==="GraphValueError"||e?.code==="ECONNABORTED")return!1;let t=e?.response?.status??e?.status;return!(t&&s5.includes(+t)||e?.error?.code==="insufficient_quota")};async function DS(e,t,r,n){let i=e.retry_policy??t,s=i!==void 0?i.initialInterval??t5:0,o=0,a,c,{config:u}=e;for(r&&(u=zr(u,r)),u={...u,signal:n};!n?.aborted;){e.writes.splice(0,e.writes.length),a=void 0;try{c=await e.proc.invoke(e.input,u);break}catch(l){if(a=l,a.pregelTaskId=e.id,N_(a)){let d=u?.configurable?.checkpoint_ns,m=a.command;if(m.graph===d){for(let h of e.writers)await h.invoke(m,u);a=void 0;break}else if(m.graph===jr.PARENT){let h=lM(d);a.command=new jr({...a.command,graph:h})}}if(Po(a)||i===void 0||(o+=1,o>=(i.maxAttempts??i5))||!(i.retryOn??o5)(a))break;s=Math.min(i.maxInterval??n5,s*(i.backoffFactor??r5));let p=i.jitter?Math.floor(s+Math.random()*1e3):s;await new Promise(d=>setTimeout(d,p));let f=a.name??a.constructor.unminifiable_name??a.constructor.name;(i?.logWarning??!0)&&console.log(`Retrying task "${String(e.name)}" after ${s.toFixed(2)}ms (attempt ${o}) after ${f}: ${a}`),u=zr(u,{[wi]:!0})}}return{task:e,result:c,error:a,signalAborted:n?.aborted}}var zS=Symbol.for("promiseAdded");function a5(){let e={next:()=>{},wait:Promise.resolve(zS)};function t(r){e.next=()=>{e.wait=new Promise(t),r(zS)}}return e.wait=new Promise(t),e}var GM=class{nodeFinished;loop;constructor({loop:e,nodeFinished:t}){this.loop=e,this.nodeFinished=t}async tick(e={}){let{timeout:t,retryPolicy:r,onStepWrite:n,maxConcurrency:i}=e,s=new Set,o,a=new AbortController,c=a.signal,u=t?AbortSignal.timeout(t):void 0,l=Object.values(this.loop.tasks).filter(m=>m.writes.length===0),{signals:p,disposeCombinedSignal:f}=this._initializeAbortSignals({exceptionSignal:c,stepTimeoutSignal:u,signal:e.signal}),d=this._executeTasksWithRetry(l,{signals:p,retryPolicy:r,maxConcurrency:i});for await(let{task:m,error:h,signalAborted:b}of d)this._commit(m,h),Di(h)||Po(h)&&!Di(o)?o=h:h&&(s.size===0||!b)&&(a.abort(),s.add(h));if(f?.(),n?.(this.loop.step,Object.values(this.loop.tasks).map(m=>m.writes).flat()),s.size===1)throw Array.from(s)[0];if(s.size>1)throw new AggregateError(Array.from(s),`Multiple errors occurred during superstep ${this.loop.step}. See the "errors" field of this exception for more details.`);if(Di(o)||Po(o)&&this.loop.isNested)throw o}_initializeAbortSignals({exceptionSignal:e,stepTimeoutSignal:t,signal:r}){let n=this.loop.config.configurable?.[wS]??{},i=n.externalAbortSignal??r,s=t??n.timeoutAbortSignal,{signal:o,dispose:a}=pu(i,s,e),c={externalAbortSignal:i,timeoutAbortSignal:s,composedAbortSignal:o};return this.loop.config=zr(this.loop.config,{[wS]:c}),{signals:c,disposeCombinedSignal:a}}async*_executeTasksWithRetry(e,t){let{retryPolicy:r,maxConcurrency:n,signals:i}=t??{},s=a5(),o={},a={executingTasksMap:o,barrier:s,retryPolicy:r,scheduleTask:async(f,d,m)=>this.loop.acceptPush(f,d,m)};if(i?.composedAbortSignal?.aborted)throw new Error("Abort");let c=0,u,l=pu(i?.externalAbortSignal,i?.timeoutAbortSignal),p=l.signal?new Promise((f,d)=>{u=()=>d(new Error("Abort")),l.signal?.addEventListener("abort",u,{once:!0})}):void 0;for(;(c===0||Object.keys(o).length>0)&&e.length;){for(;Object.values(o).length<(n??e.length)&&c<e.length;c+=1){let d=e[c];o[d.id]=DS(d,r,{[ld]:KM?.bind(a,this,d)},i?.composedAbortSignal).catch(m=>({task:d,error:m,signalAborted:i?.composedAbortSignal?.aborted}))}let f=await Promise.race([...Object.values(o),...p?[p]:[],s.wait]);f!==zS&&(yield f,u!=null&&(l.signal?.removeEventListener("abort",u),l.dispose?.()),delete o[f.task.id])}}_commit(e,t){if(t!==void 0)if(Di(t)){if(t.interrupts.length){let r=t.interrupts.map(i=>[Ee,i]),n=e.writes.filter(i=>i[0]===Nt);n.length&&r.push(...n),this.loop.putWrites(e.id,r)}}else Po(t)&&e.writes.length?this.loop.putWrites(e.id,e.writes):this.loop.putWrites(e.id,[[Ot,{message:t.message,name:t.name}]]);else this.nodeFinished&&(e.config?.tags==null||!e.config.tags.includes(Be))&&this.nodeFinished(String(e.name)),e.writes.length===0&&e.writes.push([pd,null]),this.loop.putWrites(e.id,e.writes)}};async function KM(e,t,r,n,i,s={}){let o=t.config?.configurable?.[Wr];if(!o)throw new Error(`BUG: No scratchpad found on task ${t.name}__${t.id}`);let a=o.callCounter;o.callCounter+=1;let c=new TM({func:r,name:n,input:i,cache:s.cache,retry:s.retry,callbacks:s.callbacks}),u=await this.scheduleTask(t,a,c);if(!u)return;let l=this.executingTasksMap[u.id];if(l!==void 0)return l;if(u.writes.length>0){let p=u.writes.filter(([d])=>d===Gn),f=u.writes.filter(([d])=>d===Ot);if(p.length>0){if(p.length===1)return Promise.resolve(p[0][1]);throw new Error(`BUG: multiple returns found for task ${u.name}__${u.id}`)}if(f.length>0){if(f.length===1){let d=f[0][1],m=d instanceof Error?d:new Error(String(d));return Promise.reject(m)}throw new Error(`BUG: multiple errors found for task ${u.name}__${u.id}`)}return}else{let p=DS(u,s.retry,{[ld]:KM.bind(this,e,u)});return this.executingTasksMap[u.id]=p,this.barrier.next(),p.then(({result:f,error:d})=>d?Promise.reject(d):f)}}var fs=class extends Error{constructor(e){super(e),this.name="GraphValidationError"}};function qM({nodes:e,channels:t,inputChannels:r,outputChannels:n,streamChannels:i,interruptAfterNodes:s,interruptBeforeNodes:o}){if(!t)throw new fs("Channels not provided");let a=new Set,c=new Set;for(let[u,l]of Object.entries(e)){if(u===Ee)throw new fs(`"Node name ${Ee} is reserved"`);if(l.constructor===qn)l.triggers.forEach(p=>a.add(p));else throw new fs(`Invalid node type ${typeof l}, expected PregelNode`)}for(let u of a)if(!(u in t))throw new fs(`Subscribed channel '${String(u)}' not in channels`);if(Array.isArray(r)){if(r.every(u=>!a.has(u)))throw new fs(`None of the input channels ${r} are subscribed to by any node`)}else if(!a.has(r))throw new fs(`Input channel ${String(r)} is not subscribed to by any node`);Array.isArray(n)?n.forEach(u=>c.add(u)):c.add(n),i&&!Array.isArray(i)?c.add(i):Array.isArray(i)&&i.forEach(u=>c.add(u));for(let u of c)if(!(u in t))throw new fs(`Output channel '${String(u)}' not in channels`);if(s&&s!=="*"){for(let u of s)if(!(u in e))throw new fs(`Node ${String(u)} not in nodes`)}if(o&&o!=="*"){for(let u of o)if(!(u in e))throw new fs(`Node ${String(u)} not in nodes`)}}function LS(e,t){if(Array.isArray(e)){for(let r of e)if(!(r in t))throw new Error(`Key ${String(r)} not found in channels`)}else if(!(e in t))throw new Error(`Key ${String(e)} not found in channels`)}var US=class HM extends Lt{lc_graph_name="Topic";unique=!1;accumulate=!1;seen;values;constructor(t){super(),this.unique=t?.unique??this.unique,this.accumulate=t?.accumulate??this.accumulate,this.seen=new Set,this.values=[]}fromCheckpoint(t){let r=new HM({unique:this.unique,accumulate:this.accumulate});return typeof t<"u"&&(r.seen=new Set(t[0]),r.values=t[1]),r}update(t){let r=!1;this.accumulate||(r=this.values.length>0,this.values=[]);let n=t.flat();if(n.length>0)if(this.unique)for(let i of n)this.seen.has(i)||(r=!0,this.seen.add(i),this.values.push(i));else r=!0,this.values.push(...n);return r}get(){if(this.values.length===0)throw new Ve;return this.values}checkpoint(){return[[...this.seen],this.values]}isAvailable(){return this.values.length!==0}};function WM(e){let t=Ze.getRunnableConfig();if(!t)throw new Error("Called interrupt() outside the context of a graph.");let r=t.configurable;if(!r)throw new Error("No configurable found in config");if(!r[ft])throw new Co("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});let n=r[Wr];n.interruptCounter+=1;let i=n.interruptCounter;if(n.resume.length>0&&i<n.resume.length)return r[bn]?.([[Nt,n.resume]]),n.resume[i];if(n.nullResume!==void 0){if(n.resume.length!==i)throw new Error(`Resume length mismatch: ${n.resume.length} !== ${i}`);let o=n.consumeNullResume();return n.resume.push(o),r[bn]?.([[Nt,n.resume]]),o}let s=r[Jr]?.split(et);throw new ji([{id:s?ds(s.join(et)):void 0,value:e}])}var JM=class{static subscribeTo(e,t){let{key:r,tags:n}={key:void 0,tags:void 0,...t??{}};if(Array.isArray(e)&&r!==void 0)throw new Error("Can't specify a key when subscribing to multiple channels");let i;return typeof e=="string"?r?i={[r]:e}:i=[e]:i=Object.fromEntries(e.map(s=>[s,s])),new qn({channels:i,triggers:Array.isArray(e)?e:[e],tags:n})}static writeTo(e,t){let r=[];for(let n of e)r.push({channel:n,value:Dr,skipNone:!1});for(let[n,i]of Object.entries(t??{}))ce.isRunnable(i)||typeof i=="function"?r.push({channel:n,value:Dr,skipNone:!0,mapper:dt(i)}):r.push({channel:n,value:i,skipNone:!1});return new _t(r)}},c5=class extends ce{lc_namespace=["langgraph","pregel"];invoke(e,t){throw new Error("Not implemented")}withConfig(e){return super.withConfig(e)}stream(e,t){return super.stream(e,t)}},Bg=class extends c5{static lc_name(){return"LangGraph"}lc_namespace=["langgraph","pregel"];lg_is_pregel=!0;nodes;channels;inputChannels;outputChannels;autoValidate=!0;streamMode=["values"];streamChannels;interruptAfter;interruptBefore;stepTimeout;debug=!1;checkpointer;retryPolicy;config;store;cache;userInterrupt;triggerToNodes={};constructor(e){super(e);let{streamMode:t}=e;if(t!=null&&!Array.isArray(t)&&(t=[t]),this.nodes=e.nodes,this.channels=e.channels,Ut in this.channels&&"lc_graph_name"in this.channels[Ut]&&this.channels[Ut].lc_graph_name!=="Topic")throw new Error(`Channel '${Ut}' is reserved and cannot be used in the graph.`);this.channels[Ut]=new US({accumulate:!1}),this.autoValidate=e.autoValidate??this.autoValidate,this.streamMode=t??this.streamMode,this.inputChannels=e.inputChannels,this.outputChannels=e.outputChannels,this.streamChannels=e.streamChannels??this.streamChannels,this.interruptAfter=e.interruptAfter,this.interruptBefore=e.interruptBefore,this.stepTimeout=e.stepTimeout??this.stepTimeout,this.debug=e.debug??this.debug,this.checkpointer=e.checkpointer,this.retryPolicy=e.retryPolicy,this.config=e.config,this.store=e.store,this.cache=e.cache,this.name=e.name,this.triggerToNodes=e.triggerToNodes??this.triggerToNodes,this.userInterrupt=e.userInterrupt,this.autoValidate&&this.validate()}withConfig(e){let t=Dt(this.config,e);return new this.constructor({...this,config:t})}validate(){qM({nodes:this.nodes,channels:this.channels,outputChannels:this.outputChannels,inputChannels:this.inputChannels,streamChannels:this.streamChannels,interruptAfterNodes:this.interruptAfter,interruptBeforeNodes:this.interruptBefore});for(let[e,t]of Object.entries(this.nodes))for(let r of t.triggers)this.triggerToNodes[r]??=[],this.triggerToNodes[r].push(e);return this}get streamChannelsList(){return Array.isArray(this.streamChannels)?this.streamChannels:this.streamChannels?[this.streamChannels]:Object.keys(this.channels)}get streamChannelsAsIs(){return this.streamChannels?this.streamChannels:Object.keys(this.channels)}async getGraphAsync(e){return this.getGraph(e)}*getSubgraphs(e,t){for(let[r,n]of Object.entries(this.nodes)){if(e!==void 0&&!e.startsWith(r))continue;let i=n.subgraphs?.length?n.subgraphs:[n.bound];for(let s of i){let o=Tg(s);if(o!==void 0){if(r===e){yield[r,o];return}if(e===void 0&&(yield[r,o]),t){let a=e;e!==void 0&&(a=e.slice(r.length+1));for(let[c,u]of o.getSubgraphs(a,t))yield[`${r}${et}${c}`,u]}}}}}async*getSubgraphsAsync(e,t){yield*this.getSubgraphs(e,t)}async _prepareStateSnapshot({config:e,saved:t,subgraphCheckpointer:r,applyPendingWrites:n=!1}){if(t===void 0)return{values:{},next:[],config:e,tasks:[]};let i=io(this.channels,t.checkpoint);if(t.pendingWrites?.length){let p=t.pendingWrites.filter(([f,d])=>f===ir).map(([f,d,m])=>[String(d),m]);p.length>0&&Sr(t.checkpoint,i,[{name:Vn,writes:p,triggers:[]}],void 0,this.triggerToNodes)}let s=Object.values(ao(t.checkpoint,t.pendingWrites,this.nodes,i,t.config,!0,{step:(t.metadata?.step??-1)+1,store:this.store})),o=await Kn(this.getSubgraphsAsync()),a=t.config.configurable?.checkpoint_ns??"",c={};for(let p of s){let f=o.find(([m])=>m===p.name);if(!f)continue;let d=`${String(p.name)}${Ir}${p.id}`;if(a&&(d=`${a}${et}${d}`),r===void 0){let m={configurable:{thread_id:t.config.configurable?.thread_id,checkpoint_ns:d}};c[p.id]=m}else{let m={configurable:{[ft]:r,thread_id:t.config.configurable?.thread_id,checkpoint_ns:d}},h=f[1];c[p.id]=await h.getState(m,{subgraphs:!0})}}if(n&&t.pendingWrites?.length){let p=Object.fromEntries(s.map(d=>[d.id,d]));for(let[d,m,h]of t.pendingWrites)[Ot,Ee,Ro].includes(m)||d in p&&p[d].writes.push([String(m),h]);let f=s.filter(d=>d.writes.length>0);f.length>0&&Sr(t.checkpoint,i,f,void 0,this.triggerToNodes)}let u=t?.metadata;u&&t?.config?.configurable?.thread_id&&(u={...u,thread_id:t.config.configurable.thread_id});let l=s.filter(p=>p.writes.length===0).map(p=>p.name);return{values:Hn(i,this.streamChannelsAsIs),next:l,tasks:PS(s,t?.pendingWrites??[],c,this.streamChannelsAsIs),metadata:u,config:oo(t.config,t.metadata),createdAt:t.checkpoint.ts,parentConfig:t.parentConfig}}async getState(e,t){let r=e.configurable?.[ft]??this.checkpointer;if(!r)throw new Co("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});let n=e.configurable?.checkpoint_ns??"";if(n!==""&&e.configurable?.[ft]===void 0){let o=Eg(n);for await(let[a,c]of this.getSubgraphsAsync(o,!0))if(a===o)return await c.getState(Oa(e,{[ft]:r}),{subgraphs:t?.subgraphs});throw new Error(`Subgraph with namespace "${o}" not found.`)}let i=Dt(this.config,e),s=await r.getTuple(e);return await this._prepareStateSnapshot({config:i,saved:s,subgraphCheckpointer:t?.subgraphs?r:void 0,applyPendingWrites:!e.configurable?.checkpoint_id})}async*getStateHistory(e,t){let r=e.configurable?.[ft]??this.checkpointer;if(!r)throw new Co("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});let n=e.configurable?.checkpoint_ns??"";if(n!==""&&e.configurable?.[ft]===void 0){let s=Eg(n);for await(let[o,a]of this.getSubgraphsAsync(s,!0))if(o===s){yield*a.getStateHistory(Oa(e,{[ft]:r}),t);return}throw new Error(`Subgraph with namespace "${s}" not found.`)}let i=Dt(this.config,e,{configurable:{checkpoint_ns:n}});for await(let s of r.list(i,t))yield this._prepareStateSnapshot({config:s.config,saved:s})}async bulkUpdateState(e,t){let r=e.configurable?.[ft]??this.checkpointer;if(!r)throw new Co("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});if(t.length===0)throw new Error("No supersteps provided");if(t.some(o=>o.updates.length===0))throw new Error("No updates provided");let n=e.configurable?.checkpoint_ns??"";if(n!==""&&e.configurable?.[ft]===void 0){let o=Eg(n);for await(let[,a]of this.getSubgraphsAsync(o,!0))return await a.bulkUpdateState(Oa(e,{[ft]:r}),t);throw new Error(`Subgraph "${o}" not found`)}let i=async(o,a)=>{let c=this.config?Dt(this.config,o):o,u=await r.getTuple(c),l=u!==void 0?Ln(u.checkpoint):ru(),p={...u?.checkpoint.channel_versions},f=u?.metadata?.step??-1,d=Oa(c,{checkpoint_ns:c.configurable?.checkpoint_ns??""}),m=c.metadata??{};u?.config.configurable&&(d=Oa(c,u.config.configurable),m={...u.metadata,...m});let{values:h,asNode:b}=a[0];if(h==null&&b===void 0){if(a.length>1)throw new De("Cannot create empty checkpoint with multiple updates");return oo(await r.put(d,Un(l,void 0,f),{source:"update",step:f+1,parents:u?.metadata?.parents??{}},{}),u?u.metadata:void 0)}let _=io(this.channels,l);if(h===null&&b===we){if(a.length>1)throw new De("Cannot apply multiple updates when clearing state");if(u){let O=ao(l,u.pendingWrites||[],this.nodes,_,u.config,!0,{step:(u.metadata?.step??-1)+1,checkpointer:r,store:this.store}),w=(u.pendingWrites||[]).filter(F=>F[0]===ir).map(F=>F.slice(1));w.length>0&&Sr(l,_,[{name:Vn,writes:w,triggers:[]}],r.getNextVersion.bind(r),this.triggerToNodes);for(let[F,P,V]of u.pendingWrites||[])[Ot,Ee,Ro].includes(P)||F in O&&O[F].writes.push([P,V]);Sr(l,_,Object.values(O),r.getNextVersion.bind(r),this.triggerToNodes)}return oo(await r.put(d,Un(l,_,f),{...m,source:"update",step:f+1,parents:u?.metadata?.parents??{}},lu(p,l.channel_versions)),u?u.metadata:void 0)}if(b===sM){if(a.length>1)throw new De("Cannot copy checkpoint with multiple updates");if(u==null)throw new De("Cannot copy a non-existent checkpoint");let O=P=>!Array.isArray(P)||P.length===0?!1:P.every(V=>Array.isArray(V)&&V.length===2),w=Un(l,void 0,f),F=await r.put(u.parentConfig??Oa(u.config,{checkpoint_id:void 0}),w,{source:"fork",step:f+1,parents:u.metadata?.parents??{}},{});if(O(h)){let P=ao(w,u.pendingWrites,this.nodes,_,F,!1,{step:f+2}),V=Object.values(P).reduce((qe,{name:cr,id:Lr})=>(qe[cr]??=[],qe[cr].push({id:Lr}),qe),{}),Te=h.reduce((qe,cr)=>{let[Lr,Me]=cr;qe[Me]??=[];let To=qe[Me].length,Ni=V[Me]?.[To]?.id;return qe[Me].push({values:Lr,asNode:Me,taskId:Ni}),qe},{});return i(oo(F,u.metadata),Object.values(Te).flat())}return oo(F,u.metadata)}if(b===Vn){if(a.length>1)throw new De("Cannot apply multiple updates when updating as input");let O=await Kn(Mg(this.inputChannels,h));if(O.length===0)throw new De(`Received no input writes for ${JSON.stringify(this.inputChannels,null,2)}`);Sr(l,_,[{name:Vn,writes:O,triggers:[]}],r.getNextVersion.bind(this.checkpointer),this.triggerToNodes);let w=u?.metadata?.step!=null?u.metadata.step+1:-1,F=await r.put(d,Un(l,_,w),{source:"input",step:w,parents:u?.metadata?.parents??{}},lu(p,l.channel_versions));return await r.putWrites(F,O,zi(Vn,l.id)),oo(F,u?u.metadata:void 0)}if(c.configurable?.checkpoint_id===void 0&&u?.pendingWrites!==void 0&&u.pendingWrites.length>0){let O=ao(l,u.pendingWrites,this.nodes,_,u.config,!0,{store:this.store,checkpointer:this.checkpointer,step:(u.metadata?.step??-1)+1}),w=(u.pendingWrites??[]).filter(P=>P[0]===ir).map(P=>P.slice(1));w.length>0&&Sr(u.checkpoint,_,[{name:Vn,writes:w,triggers:[]}],void 0,this.triggerToNodes);for(let[P,V,Te]of u.pendingWrites)[Ot,Ee,Ro].includes(V)||O[P]===void 0||O[P].writes.push([V,Te]);let F=Object.values(O).filter(P=>P.writes.length>0);F.length>0&&Sr(l,_,F,void 0,this.triggerToNodes)}let y=Object.values(l.versions_seen).map(O=>Object.values(O)).flat().find(O=>!!O),x=[];if(a.length===1){let{values:O,asNode:w,taskId:F}=a[0];if(w===void 0&&Object.keys(this.nodes).length===1)[w]=Object.keys(this.nodes);else if(w===void 0&&y===void 0)typeof this.inputChannels=="string"&&this.nodes[this.inputChannels]!==void 0&&(w=this.inputChannels);else if(w===void 0){let P=Object.entries(l.versions_seen).map(([V,Te])=>Object.values(Te).map(qe=>[qe,V])).flat().filter(([V,Te])=>Te!==Ee).sort(([V],[Te])=>gg(V,Te));P&&(P.length===1?w=P[0][1]:P[P.length-1][0]!==P[P.length-2][0]&&(w=P[P.length-1][1]))}if(w===void 0)throw new De('Ambiguous update, specify "asNode"');x.push({values:O,asNode:w,taskId:F})}else for(let{asNode:O,values:w,taskId:F}of a){if(O==null)throw new De('"asNode" is required when applying multiple updates');x.push({values:w,asNode:O,taskId:F})}let I=[];for(let{asNode:O,values:w,taskId:F}of x){if(this.nodes[O]===void 0)throw new De(`Node "${O.toString()}" does not exist`);let P=this.nodes[O].getWriters();if(!P.length)throw new De(`No writers found for node "${O.toString()}"`);I.push({name:O,input:w,proc:P.length>1?br.from(P,{omitSequenceTags:!0}):P[0],writes:[],triggers:[Ee],id:F??zi(Ee,l.id),writers:[]})}for(let O of I)await O.proc.invoke(O.input,Ne({...c,store:c?.store??this.store},{runName:c.runName??`${this.getName()}UpdateState`,configurable:{[bn]:w=>O.writes.push(...w),[Zn]:(w,F=!1)=>_d(l,_,O,w,F)}}));for(let O of I){let w=O.writes.filter(F=>F[0]!==nr);u!==void 0&&w.length>0&&await r.putWrites(d,w,O.id)}Sr(l,_,I,r.getNextVersion.bind(this.checkpointer),this.triggerToNodes);let A=lu(p,l.channel_versions),j=await r.put(d,Un(l,_,f+1),{source:"update",step:f+1,parents:u?.metadata?.parents??{}},A);for(let O of I){let w=O.writes.filter(F=>F[0]===nr);w.length>0&&await r.putWrites(j,w,O.id)}return oo(j,u?u.metadata:void 0)},s=e;for(let{updates:o}of t)s=await i(s,o);return s}async updateState(e,t,r){return this.bulkUpdateState(e,[{updates:[{values:t,asNode:r}]}])}_defaults(e){let{debug:t,streamMode:r,inputKeys:n,outputKeys:i,interruptAfter:s,interruptBefore:o,...a}=e,c=!0,u=t!==void 0?t:this.debug,l=i;l===void 0?l=this.streamChannelsAsIs:LS(l,this.channels);let p=n;p===void 0?p=this.inputChannels:LS(p,this.channels);let f=o??this.interruptBefore??[],d=s??this.interruptAfter??[],m;r!==void 0?(m=Array.isArray(r)?r:[r],c=typeof r=="string"):(e.configurable?.[ka]!==void 0?m=["values"]:m=this.streamMode,c=!0);let h;if(this.checkpointer===!1)h=void 0;else if(e!==void 0&&e.configurable?.[ft]!==void 0)h=e.configurable[ft];else{if(this.checkpointer===!0)throw new Error("checkpointer: true cannot be used for root graphs.");h=this.checkpointer}let b=e.store??this.store,_=e.cache??this.cache;if(e.durability!=null&&e.checkpointDuring!=null)throw new Error("Cannot use both `durability` and `checkpointDuring` at the same time.");let y=(()=>{if(e.checkpointDuring!=null)return e.checkpointDuring===!1?"exit":"async"})(),x=e.durability??y??e?.configurable?.[bS]??"async";return[u,m,p,l,a,f,d,h,b,c,_,x]}async stream(e,t){let r=new AbortController,n={recursionLimit:this.config?.recursionLimit,...t,signal:pu(t?.signal,r.signal).signal},i=await super.stream(e,n);return new RS(t?.encoding==="text/event-stream"?FM(i):i,r)}streamEvents(e,t,r){let n=new AbortController,i={recursionLimit:this.config?.recursionLimit,...t,callbacks:AM(this.config?.callbacks,t?.callbacks),signal:pu(t?.signal,n.signal).signal};return new RS(super.streamEvents(e,i,r),n)}async _validateInput(e){return e}async _validateContext(e){return e}async*_streamIterator(e,t){let r="version"in(t??{})?void 0:t?.encoding??void 0,n=t?.subgraphs,i=md(this.config,t);if(i.recursionLimit===void 0||i.recursionLimit<1)throw new Error('Passed "recursionLimit" must be at least 1.');if(this.checkpointer!==void 0&&this.checkpointer!==!1&&i.configurable===void 0)throw new Error('Checkpointer requires one or more of the following "configurable" keys: "thread_id", "checkpoint_ns", "checkpoint_id"');let s=await this._validateInput(e),{runId:o,...a}=i,[c,u,,l,p,f,d,m,h,b,_,y]=this._defaults(a);typeof p.context<"u"?p.context=await this._validateContext(p.context):p.configurable=await this._validateContext(p.configurable);let x=new Ug({modes:new Set(u)});if(this.checkpointer===!0){p.configurable??={};let P=p.configurable[Jr]??"";p.configurable[Jr]=P.split(et).map(V=>V.split(Ir)[0]).join(et)}if(u.includes("messages")){let P=new ZM(Te=>x.push(Te)),{callbacks:V}=p;if(V===void 0)p.callbacks=[P];else if(Array.isArray(V))p.callbacks=V.concat(P);else{let Te=V.copy();Te.addHandler(P,!0),p.callbacks=Te}}p.writer??=P=>{if(!u.includes("custom"))return;let V=uM()?.configurable?.[Jr]?.split(et).slice(0,-1);x.push([V??[],"custom",P])},p.interrupt??=this.userInterrupt??WM;let I=await(await Et(p))?.handleChainStart(this.toJSON(),kM(e,"input"),o,void 0,void 0,void 0,p?.runName??this.getName()),A=cd(this.channels),j,O,F=(async()=>{try{j=await BM.initialize({input:s,config:p,checkpointer:m,nodes:this.nodes,channelSpecs:A,outputKeys:l,streamKeys:this.streamChannelsAsIs,store:h,cache:_,stream:x,interruptAfter:d,interruptBefore:f,manager:I,debug:this.debug,triggerToNodes:this.triggerToNodes,durability:y});let P=new GM({loop:j,nodeFinished:p.configurable?.[oM]});t?.subgraphs&&(j.config.configurable={...j.config.configurable,[iu]:j.stream}),await this._runLoop({loop:j,runner:P,debug:c,config:p}),y==="sync"&&await Promise.all(j?.checkpointerPromises??[])}catch(P){O=P}finally{try{j&&(await j.store?.stop(),await j.cache?.stop()),await Promise.all(j?.checkpointerPromises??[])}catch(P){O=O??P}O?x.error(O):x.close()}})();try{for await(let P of x){if(P===void 0)throw new Error("Data structure error.");let[V,Te,qe]=P;if(u.includes(Te)){if(r==="text/event-stream"){n?yield[V,Te,qe]:yield[null,Te,qe];continue}n&&!b?yield[V,Te,qe]:b?n?yield[V,qe]:yield qe:yield[Te,qe]}}}catch(P){throw await I?.handleChainError(O),P}finally{await F}await I?.handleChainEnd(j?.output??{},o,void 0,void 0,void 0)}async invoke(e,t){let r=t?.streamMode??"values",n={...t,outputKeys:t?.outputKeys??this.outputChannels,streamMode:r,encoding:void 0},i=[],s=await this.stream(e,n),o=[],a;for await(let c of s)r==="values"?fd(c)?o.push(c[Ee]):a=c:i.push(c);if(r==="values"){if(o.length>0){let c=o.flat(1);if(a==null)return{[Ee]:c};if(typeof a=="object")return{...a,[Ee]:c}}return a}return i}async _runLoop(e){let{loop:t,runner:r,debug:n,config:i}=e,s;try{for(;await t.tick({inputKeys:this.inputChannels});){for(let{task:o}of await t._matchCachedWrites())t._outputWrites(o.id,o.writes,!0);n&&DM(t.checkpointMetadata.step,t.channels,this.streamChannelsList),n&&Lg(t.step,Object.values(t.tasks)),await r.tick({timeout:this.stepTimeout,retryPolicy:this.retryPolicy,onStepWrite:(o,a)=>{n&&zM(o,a,this.streamChannelsList)},maxConcurrency:i.maxConcurrency,signal:i.signal})}if(t.status==="out_of_steps")throw new P_([`Recursion limit of ${i.recursionLimit} reached`,"without hitting a stop condition. You can increase the",'limit by setting the "recursionLimit" config key.'].join(" "),{lc_error_code:"GRAPH_RECURSION_LIMIT"})}catch(o){if(s=o,!await t.finishAndHandleError(s))throw o}finally{s===void 0&&await t.finishAndHandleError()}}async clearCache(){await this.cache?.clear([])}};var Wn=class XM extends Lt{lc_graph_name="EphemeralValue";guard;value=[];constructor(t=!0){super(),this.guard=t}fromCheckpoint(t){let r=new XM(this.guard);return typeof t<"u"&&(r.value=[t]),r}update(t){if(t.length===0){let r=this.value.length>0;return this.value=[],r}if(t.length!==1&&this.guard)throw new De("EphemeralValue can only receive one value per step.");return this.value=[t[t.length-1]],!0}get(){if(this.value.length===0)throw new Ve;return this.value[0]}checkpoint(){if(this.value.length===0)throw new Ve;return this.value[0]}isAvailable(){return this.value.length!==0}};var FS=class{path;ends;constructor(e){ce.isRunnable(e.path)?this.path=e.path:this.path=dt(e.path).withConfig({runName:"Branch"}),this.ends=Array.isArray(e.pathMap)?e.pathMap.reduce((t,r)=>(t[r]=r,t),{}):e.pathMap}run(e,t){return _t.registerWriter(new sr({name:"<branch_run>",trace:!1,func:async(r,n)=>{try{return await this._route(r,n,e,t)}catch(i){throw i.name===Jd.unminifiable_name&&console.warn(`[WARN]: 'NodeInterrupt' thrown in conditional edge. This is likely a bug in your graph implementation.
|
|
223
|
+
NodeInterrupt should only be thrown inside a node, not in edge conditions.`),i}}}))}async _route(e,t,r,n){let i=await this.path.invoke(n?n(t):e,t);Array.isArray(i)||(i=[i]);let s;if(this.ends?s=i.map(o=>$t(o)?o:this.ends[o]):s=i,s.some(o=>!o))throw new Error("Branch condition returned unknown or null destination");if(s.filter($t).some(o=>o.node===we))throw new De("Cannot send a packet to the END node");return await r(s,t)??e}},BS=class{nodes;edges;branches;entryPoint;compiled=!1;constructor(){this.nodes={},this.edges=new Set,this.branches={}}warnIfCompiled(e){this.compiled&&console.warn(e)}get allEdges(){return this.edges}addNode(...e){function t(n){return n.length>=1&&typeof n[0]!="string"}let r=t(e)?Array.isArray(e[0])?e[0]:Object.entries(e[0]):[[e[0],e[1],e[2]]];if(r.length===0)throw new Error("No nodes provided in `addNode`");for(let[n,i,s]of r){for(let a of[et,Ir])if(n.includes(a))throw new Error(`"${a}" is a reserved character and is not allowed in node names.`);if(this.warnIfCompiled("Adding a node to a graph that has already been compiled. This will not be reflected in the compiled graph."),n in this.nodes)throw new Error(`Node \`${n}\` already present.`);if(n===we)throw new Error(`Node \`${n}\` is reserved.`);let o=dt(i);this.nodes[n]={runnable:o,metadata:s?.metadata,subgraphs:gd(o)?[o]:s?.subgraphs,ends:s?.ends}}return this}addEdge(e,t){if(this.warnIfCompiled("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph."),e===we)throw new Error("END cannot be a start node");if(t===ke)throw new Error("START cannot be an end node");if(Array.from(this.edges).some(([r])=>r===e)&&!("channels"in this))throw new Error(`Already found path for ${e}. For multiple edges, use StateGraph.`);return this.edges.add([e,t]),this}addConditionalEdges(e,t,r){let n=typeof e=="object"?e:{source:e,path:t,pathMap:r};if(this.warnIfCompiled("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph."),!ce.isRunnable(n.path)){let s=Array.isArray(n.pathMap)?n.pathMap.join(","):Object.keys(n.pathMap??{}).join(",");n.path=dt(n.path).withConfig({runName:`Branch<${n.source}${s!==""?`,${s}`:""}>`.slice(0,63)})}let i=n.path.getName()==="RunnableLambda"?"condition":n.path.getName();if(this.branches[n.source]&&this.branches[n.source][i])throw new Error(`Condition \`${i}\` already present for node \`${e}\``);return this.branches[n.source]??={},this.branches[n.source][i]=new FS(n),this}setEntryPoint(e){return this.warnIfCompiled("Setting the entry point of a graph that has already been compiled. This will not be reflected in the compiled graph."),this.addEdge(ke,e)}setFinishPoint(e){return this.warnIfCompiled("Setting a finish point of a graph that has already been compiled. This will not be reflected in the compiled graph."),this.addEdge(e,we)}compile({checkpointer:e,interruptBefore:t,interruptAfter:r,name:n}={}){this.validate([...Array.isArray(t)?t:[],...Array.isArray(r)?r:[]]);let i=new VS({builder:this,checkpointer:e,interruptAfter:r,interruptBefore:t,autoValidate:!1,nodes:{},channels:{[ke]:new Wn,[we]:new Wn},inputChannels:ke,outputChannels:we,streamChannels:[],streamMode:"values",name:n});for(let[s,o]of Object.entries(this.nodes))i.attachNode(s,o);for(let[s,o]of this.edges)i.attachEdge(s,o);for(let[s,o]of Object.entries(this.branches))for(let[a,c]of Object.entries(o))i.attachBranch(s,a,c);return i.validate()}validate(e){let t=new Set([...this.allEdges].map(([n,i])=>n));for(let[n]of Object.entries(this.branches))t.add(n);for(let n of t)if(n!==ke&&!(n in this.nodes))throw new Error(`Found edge starting at unknown node \`${n}\``);let r=new Set([...this.allEdges].map(([n,i])=>i));for(let[n,i]of Object.entries(this.branches))for(let s of Object.values(i))if(s.ends!=null)for(let o of Object.values(s.ends))r.add(o);else{r.add(we);for(let o of Object.keys(this.nodes))o!==n&&r.add(o)}for(let n of Object.values(this.nodes))for(let i of n.ends??[])r.add(i);for(let n of Object.keys(this.nodes))if(!r.has(n))throw new R_([`Node \`${n}\` is not reachable.`,"","If you are returning Command objects from your node,",'make sure you are passing names of potential destination nodes as an "ends" array','into ".addNode(..., { ends: ["node1", "node2"] })".'].join(`
|
|
224
|
+
`),{lc_error_code:"UNREACHABLE_NODE"});for(let n of r)if(n!==we&&!(n in this.nodes))throw new Error(`Found edge ending at unknown node \`${n}\``);if(e){for(let n of e)if(!(n in this.nodes))throw new Error(`Interrupt node \`${n}\` is not present`)}this.compiled=!0}},VS=class extends Bg{builder;constructor({builder:e,...t}){super(t),this.builder=e}attachNode(e,t){this.channels[e]=new Wn,this.nodes[e]=new qn({channels:[],triggers:[],metadata:t.metadata,subgraphs:t.subgraphs,ends:t.ends}).pipe(t.runnable).pipe(new _t([{channel:e,value:Dr}],[Be])),this.streamChannels.push(e)}attachEdge(e,t){if(t===we){if(e===ke)throw new Error("Cannot have an edge from START to END");this.nodes[e].writers.push(new _t([{channel:we,value:Dr}],[Be]))}else this.nodes[t].triggers.push(e),this.nodes[t].channels.push(e)}attachBranch(e,t,r){e===ke&&!this.nodes[ke]&&(this.nodes[ke]=JM.subscribeTo(ke,{tags:[Be]})),this.nodes[e].pipe(r.run(i=>new _t(i.map(s=>$t(s)?s:{channel:s===we?we:`branch:${e}:${t}:${s}`,value:Dr}),[Be])));let n=r.ends?Object.values(r.ends):Object.keys(this.nodes);for(let i of n)if(i!==we){let s=`branch:${e}:${t}:${i}`;this.channels[s]=new Wn,this.nodes[i].triggers.push(s),this.nodes[i].channels.push(s)}}async getGraphAsync(e){let t=e?.xray,r=new ya,n={[ke]:r.addNode({schema:Z.any()},ke)},i={},s={};t&&(s=Object.fromEntries((await Kn(this.getSubgraphsAsync())).filter(c=>YM(c[1]))));function o(c,u,l,p=!1){if(u===we&&i[we]===void 0&&(i[we]=r.addNode({schema:Z.any()},we)),n[c]!==void 0){if(i[u]===void 0)throw new Error(`End node ${u} not found!`);return r.addEdge(n[c],i[u],l!==u?l:void 0,p)}}for(let[c,u]of Object.entries(this.builder.nodes)){let l=or(c),p=u.runnable,f=u.metadata??{};if(this.interruptBefore?.includes(c)&&this.interruptAfter?.includes(c)?f.__interrupt="before,after":this.interruptBefore?.includes(c)?f.__interrupt="before":this.interruptAfter?.includes(c)&&(f.__interrupt="after"),t){let d=typeof t=="number"?t-1:t,m=s[c]!==void 0?await s[c].getGraphAsync({...e,xray:d}):p.getGraph(e);if(m.trimFirstNode(),m.trimLastNode(),Object.keys(m.nodes).length>1){let _=function(x){return x?x.lc_runnable:!1},y=function(x,I){if(x!==void 0&&!kn(x))return x;if(_(I))try{let A=I.getName();return A=A.startsWith("Runnable")?A.slice(8):A,A}catch{return I.getName()}else return I.name??"UnknownSchema"},[h,b]=r.extend(m,l);if(h===void 0)throw new Error(`Could not extend subgraph "${c}" due to missing entrypoint.`);b!==void 0&&(n[l]={name:y(b.id,b.data),...b}),i[l]={name:y(h.id,h.data),...h}}else{let h=r.addNode(p,l,f);n[l]=h,i[l]=h}}else{let d=r.addNode(p,l,f);n[l]=d,i[l]=d}}let a=[...this.builder.allEdges].sort(([c],[u])=>c<u?-1:u>c?1:0);for(let[c,u]of a)o(or(c),or(u));for(let[c,u]of Object.entries(this.builder.branches)){let l={...Object.fromEntries(Object.keys(this.builder.nodes).filter(p=>p!==c).map(p=>[or(p),or(p)])),[we]:we};for(let p of Object.values(u)){let f;p.ends!==void 0?f=p.ends:f=l;for(let[d,m]of Object.entries(f))o(or(c),or(m),d,!0)}}for(let[c,u]of Object.entries(this.builder.nodes))if(u.ends!==void 0)for(let l of u.ends)o(or(c),or(l),void 0,!0);return r}getGraph(e){let t=e?.xray,r=new ya,n={[ke]:r.addNode({schema:Z.any()},ke)},i={},s={};t&&(s=Object.fromEntries(Ta(this.getSubgraphs()).filter(c=>YM(c[1]))));function o(c,u,l,p=!1){return u===we&&i[we]===void 0&&(i[we]=r.addNode({schema:Z.any()},we)),r.addEdge(n[c],i[u],l!==u?l:void 0,p)}for(let[c,u]of Object.entries(this.builder.nodes)){let l=or(c),p=u.runnable,f=u.metadata??{};if(this.interruptBefore?.includes(c)&&this.interruptAfter?.includes(c)?f.__interrupt="before,after":this.interruptBefore?.includes(c)?f.__interrupt="before":this.interruptAfter?.includes(c)&&(f.__interrupt="after"),t){let d=typeof t=="number"?t-1:t,m=s[c]!==void 0?s[c].getGraph({...e,xray:d}):p.getGraph(e);if(m.trimFirstNode(),m.trimLastNode(),Object.keys(m.nodes).length>1){let _=function(x){return x?x.lc_runnable:!1},y=function(x,I){if(x!==void 0&&!kn(x))return x;if(_(I))try{let A=I.getName();return A=A.startsWith("Runnable")?A.slice(8):A,A}catch{return I.getName()}else return I.name??"UnknownSchema"},[h,b]=r.extend(m,l);if(h===void 0)throw new Error(`Could not extend subgraph "${c}" due to missing entrypoint.`);b!==void 0&&(n[l]={name:y(b.id,b.data),...b}),i[l]={name:y(h.id,h.data),...h}}else{let h=r.addNode(p,l,f);n[l]=h,i[l]=h}}else{let d=r.addNode(p,l,f);n[l]=d,i[l]=d}}let a=[...this.builder.allEdges].sort(([c],[u])=>c<u?-1:u>c?1:0);for(let[c,u]of a)o(or(c),or(u));for(let[c,u]of Object.entries(this.builder.branches)){let l={...Object.fromEntries(Object.keys(this.builder.nodes).filter(p=>p!==c).map(p=>[or(p),or(p)])),[we]:we};for(let p of Object.values(u)){let f;p.ends!==void 0?f=p.ends:f=l;for(let[d,m]of Object.entries(f))o(or(c),or(m),d,!0)}}return r}};function YM(e){return typeof e.attachNode=="function"&&typeof e.attachEdge=="function"}function or(e){return e==="subgraph"?`"${e}"`:e}function co(e){return typeof e=="object"&&e!==null&&"~standard"in e&&typeof e["~standard"]=="object"&&e["~standard"]!==null&&"validate"in e["~standard"]}function QM(e){return typeof e=="object"&&e!==null&&"~standard"in e&&typeof e["~standard"]=="object"&&e["~standard"]!==null&&"jsonSchema"in e["~standard"]}function uo(e){if(QM(e))try{return e["~standard"].jsonSchema.input({target:"draft-07"})}catch{return}}function lo(e){if(e!=null&&co(e))try{let t=e["~standard"].validate(void 0);if(t&&typeof t=="object"&&!("then"in t&&typeof t.then=="function")){let r=t;if(!r.issues){let n=r.value;return()=>n}}}catch{}}var ZS=Symbol.for("langgraph.channel.missing"),Vg=class ej extends Lt{lc_graph_name="UntrackedValue";guard;_value=ZS;initialValueFactory;constructor(t){super(),this.guard=t?.guard??!0,this.initialValueFactory=t?.initialValueFactory,this.initialValueFactory&&(this._value=this.initialValueFactory())}fromCheckpoint(t){return new ej({guard:this.guard,initialValueFactory:this.initialValueFactory})}update(t){if(t.length===0)return!1;if(t.length!==1&&this.guard)throw new De("UntrackedValue(guard=true) can receive only one value per step. Use guard=false if you want to store any one of multiple values.",{lc_error_code:"INVALID_CONCURRENT_GRAPH_UPDATE"});return this._value=t[t.length-1],!0}get(){if(this._value===ZS)throw new Ve;return this._value}checkpoint(){}isAvailable(){return this._value!==ZS}};var po=(e,t)=>e.size===t.size&&[...e].every(r=>t.has(r)),GS=class tj extends Lt{lc_graph_name="NamedBarrierValue";names;seen;constructor(t){super(),this.names=t,this.seen=new Set}fromCheckpoint(t){let r=new tj(this.names);return typeof t<"u"&&(r.seen=new Set(t)),r}update(t){let r=!1;for(let n of t)if(this.names.has(n))this.seen.has(n)||(this.seen.add(n),r=!0);else throw new De(`Value ${JSON.stringify(n)} not in names ${JSON.stringify(this.names)}`);return r}get(){if(!po(this.names,this.seen))throw new Ve}checkpoint(){return[...this.seen]}consume(){return this.seen&&this.names&&po(this.seen,this.names)?(this.seen=new Set,!0):!1}isAvailable(){return!!this.names&&po(this.names,this.seen)}},KS=class rj extends Lt{lc_graph_name="NamedBarrierValueAfterFinish";names;seen;finished;constructor(t){super(),this.names=t,this.seen=new Set,this.finished=!1}fromCheckpoint(t){let r=new rj(this.names);if(typeof t<"u"){let[n,i]=t;r.seen=new Set(n),r.finished=i}return r}update(t){let r=!1;for(let n of t)if(this.names.has(n)&&!this.seen.has(n))this.seen.add(n),r=!0;else if(!this.names.has(n))throw new De(`Value ${JSON.stringify(n)} not in names ${JSON.stringify(this.names)}`);return r}get(){if(!this.finished||!po(this.names,this.seen))throw new Ve}checkpoint(){return[[...this.seen],this.finished]}consume(){return this.finished&&this.seen&&this.names&&po(this.seen,this.names)?(this.seen=new Set,this.finished=!1,!0):!1}finish(){return!this.finished&&this.names&&po(this.names,this.seen)?(this.finished=!0,!0):!1}isAvailable(){return this.finished&&!!this.names&&po(this.names,this.seen)}};var qS=Symbol.for("langgraph.state.reduced_value"),ms=class{[qS]=!0;valueSchema;inputSchema;reducer;jsonSchemaExtra;constructor(e,t){this.reducer=t.reducer,this.jsonSchemaExtra=t.jsonSchemaExtra,this.valueSchema=e,this.inputSchema="inputSchema"in t?t.inputSchema:e,this.jsonSchemaExtra=t.jsonSchemaExtra}static isInstance(e){return typeof e=="object"&&e!==null&&qS in e&&e[qS]===!0}};var nj=Symbol.for("langgraph.state.untracked_value"),Pa=class{[nj]=!0;schema;guard;constructor(e,t){this.schema=e,this.guard=t?.guard??!0}static isInstance(e){return typeof e=="object"&&e!==null&&nj in e}};var HS=Symbol.for("langgraph.state.state_schema"),Si=class{[HS]=!0;constructor(e){this.fields=e}getChannels(){let e={};for(let[t,r]of Object.entries(this.fields))if(ms.isInstance(r)){let n=lo(r.valueSchema);e[t]=new us(r.reducer,n)}else if(Pa.isInstance(r)){let n=r.schema?lo(r.schema):void 0;e[t]=new Vg({guard:r.guard,initialValueFactory:n})}else if(co(r))e[t]=new Fn(lo(r));else throw new Error(`Invalid state field "${t}": must be a schema, ReducedValue, UntrackedValue, or ManagedValue`);return e}getJsonSchema(){let e={},t=[];for(let[r,n]of Object.entries(this.fields)){let i;if(ms.isInstance(n)?(i=uo(n.valueSchema),i&&n.jsonSchemaExtra&&(i={...i,...n.jsonSchemaExtra})):Pa.isInstance(n)?i=n.schema?uo(n.schema):void 0:co(n)&&(i=uo(n)),i){e[r]=i;let s=!1;ms.isInstance(n)?s=lo(n.valueSchema)!==void 0:Pa.isInstance(n)?s=n.schema?lo(n.schema)!==void 0:!1:s=lo(n)!==void 0,s||t.push(r)}}return{type:"object",properties:e,required:t.length>0?t:void 0}}getInputJsonSchema(){let e={};for(let[t,r]of Object.entries(this.fields)){let n;ms.isInstance(r)?n=uo(r.inputSchema):Pa.isInstance(r)?n=r.schema?uo(r.schema):void 0:co(r)&&(n=uo(r)),n&&(e[t]=n)}return{type:"object",properties:e}}getChannelKeys(){return Object.entries(this.fields).map(([e])=>e)}getAllKeys(){return Object.keys(this.fields)}async validateInput(e){if(e==null||typeof e!="object")return e;let t={};for(let[r,n]of Object.entries(e)){let i=this.fields[r];if(i===void 0){t[r]=n;continue}let s;if(ms.isInstance(i)?s=i.inputSchema:Pa.isInstance(i)?s=i.schema:co(i)&&(s=i),s){let o=await s["~standard"].validate(n);if(o.issues)throw new Error(`Validation failed for field "${r}": ${JSON.stringify(o.issues)}`);t[r]=o.value}else t[r]=n}return t}static isInstance(e){return typeof e=="object"&&e!==null&&HS in e&&e[HS]===!0}};var ij="__remove_all__";function hs(e,t){let r=Array.isArray(e)?e:[e],n=Array.isArray(t)?t:[t],i=r.map(Qt),s=n.map(Qt);for(let l of i)(l.id===null||l.id===void 0)&&(l.id=Ar(),l.lc_kwargs.id=l.id);let o;for(let l=0;l<s.length;l+=1){let p=s[l];(p.id===null||p.id===void 0)&&(p.id=Ar(),p.lc_kwargs.id=p.id),On.isInstance(p)&&p.id===ij&&(o=l)}if(o!=null)return s.slice(o+1);let a=[...i],c=new Map(a.map((l,p)=>[l.id,p])),u=new Set;for(let l of s){let p=c.get(l.id);if(p!==void 0)On.isInstance(l)?u.add(l.id):(u.delete(l.id),a[p]=l);else{if(On.isInstance(l))throw new Error(`Attempting to delete a message with an ID that doesn't exist ('${l.id}')`);c.set(l.id,a.length),a.push(l)}}return a.filter(l=>!u.has(l.id))}var u5=Z.custom().default(()=>[]),l5=Z.custom(),p5=new ms(u5,{inputSchema:l5,reducer:hs,jsonSchemaExtra:{langgraph_type:"messages",description:"A list of chat messages"}});var d5="lg:",f5=class{_map=new WeakMap;_extensionCache=new Map;get(e){return this._map.get(e)}extend(e,t){let r=this.get(e);this._map.set(e,t(r))}remove(e){return this._map.delete(e),this}has(e){return this._map.has(e)}getChannelsForSchema(e){let t={},r=ta(e);for(let[n,i]of Object.entries(r)){let s=this.get(i);s?.reducer?t[n]=new us(s.reducer.fn,s.default):t[n]=new Fn(s?.default)}return t}getExtendedChannelSchemas(e,t){if(Object.keys(t).length===0)return e;let r=Object.entries(t).filter(([,s])=>s===!0).sort(([s],[o])=>s.localeCompare(o)).map(([s,o])=>`${s}:${o}`).join("|"),n=this._extensionCache.get(r)??new WeakMap;if(n.has(e))return n.get(e);let i=e;if(t.withReducerSchema||t.withJsonSchemaExtrasAsDescription){let s=Object.entries(ta(e)).map(([o,a])=>{let c=this.get(a),u=t.withReducerSchema?c?.reducer?.schema??a:a;if(t.withJsonSchemaExtrasAsDescription&&c?.jsonSchemaExtra){let l=$n(u)??$n(a),p=JSON.stringify({...c.jsonSchemaExtra,description:l});u=u.describe(`${d5}${p}`)}return[o,u]});i=sh(e,Object.fromEntries(s)),it(i)&&(i._def.unknownKeys="strip")}return t.asPartial&&(i=Pc(i)),n.set(e,i),this._extensionCache.set(r,n),i}},wd=new f5;function sj(e,t){if(t.reducer&&!t.default){let r=oh(e);r!=null&&(t.default=r)}if(t.reducer){let r=Object.assign(e,{lg_reducer_schema:t.reducer?.schema??e});return wd.extend(r,()=>t),r}else return wd.extend(e,()=>t),e}function Na(e){return e==null?!1:!!(Si.isInstance(e)||yr(e)||typeof e=="object"&&"lc_graph_name"in e&&e.lc_graph_name==="AnnotationRoot"||typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length>0&&Object.values(e).every(t=>typeof t=="function"||yS(t)))}function oj(e){if(typeof e!="object"||e==null)return!1;let t=e,r="state"in t&&Na(t.state),n="stateSchema"in t&&Na(t.stateSchema),i="input"in t&&Na(t.input);return!(!r&&!n&&!i||"input"in t&&t.input!=null&&!Na(t.input)||"output"in t&&t.output!=null&&!Na(t.output))}var gs="__root__",Zg=Symbol.for("langgraph.state.partial"),Gg=class extends BS{channels={};waitingEdges=new Set;_schemaDefinition;_schemaRuntimeDefinition;_inputDefinition;_inputRuntimeDefinition;_outputDefinition;_outputRuntimeDefinition;_schemaDefinitions=new Map;_metaRegistry=wd;_configSchema;_configRuntimeSchema;_interrupt;_writer;constructor(e,t){super();let r=this._normalizeToStateGraphInit(e,t),n=r.state??r.stateSchema??r.input;if(!n)throw new fl;let i=this._getChannelsFromSchema(n);this._schemaDefinition=i,Si.isInstance(n)?this._schemaRuntimeDefinition=n:yr(n)&&(this._schemaRuntimeDefinition=n),r.input?Si.isInstance(r.input)?this._inputRuntimeDefinition=r.input:yr(r.input)?this._inputRuntimeDefinition=r.input:this._inputRuntimeDefinition=Zg:this._inputRuntimeDefinition=Zg,r.output?Si.isInstance(r.output)?this._outputRuntimeDefinition=r.output:yr(r.output)?this._outputRuntimeDefinition=r.output:this._outputRuntimeDefinition=this._schemaRuntimeDefinition:this._outputRuntimeDefinition=this._schemaRuntimeDefinition;let s=r.input?this._getChannelsFromSchema(r.input):i,o=r.output?this._getChannelsFromSchema(r.output):i;this._inputDefinition=s,this._outputDefinition=o,this._addSchema(this._schemaDefinition),this._addSchema(this._inputDefinition),this._addSchema(this._outputDefinition),r.context&&yr(r.context)&&(this._configRuntimeSchema=r.context),this._interrupt=r.interrupt,this._writer=r.writer}_normalizeToStateGraphInit(e,t){if(oj(e)){if(yr(t)||bg.isInstance(t))return{...e,context:t};let r=t;return{...e,input:e.input??r?.input,output:e.output??r?.output,context:e.context??r?.context,interrupt:e.interrupt??r?.interrupt,writer:e.writer??r?.writer,nodes:e.nodes??r?.nodes}}if(Na(e)){if(yr(t)||bg.isInstance(t))return{state:e,context:t};let r=t;return{state:e,input:r?.input,output:r?.output,context:r?.context,interrupt:r?.interrupt,writer:r?.writer,nodes:r?.nodes}}if(h5(e))return{state:m5(e.channels)};throw new fl}_getChannelsFromSchema(e){if(Si.isInstance(e))return e.getChannels();if(yr(e))return this._metaRegistry.getChannelsForSchema(e);if(typeof e=="object"&&"lc_graph_name"in e&&e.lc_graph_name==="AnnotationRoot")return e.spec;if(typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length>0)return e;throw new fl("Invalid schema type. Expected StateSchema, Zod object, AnnotationRoot, or StateDefinition.")}get allEdges(){return new Set([...this.edges,...Array.from(this.waitingEdges).flatMap(([e,t])=>e.map(r=>[r,t]))])}_addSchema(e){if(!this._schemaDefinitions.has(e)){this._schemaDefinitions.set(e,e);for(let[t,r]of Object.entries(e)){let n;if(typeof r=="function"?n=r():n=r,this.channels[t]!==void 0){if(!this.channels[t].equals(n)&&n.lc_graph_name!=="LastValue")throw new Error(`Channel "${t}" already exists with a different type.`)}else this.channels[t]=n}}}addNode(...e){function t(n){return n.length>=1&&typeof n[0]!="string"}let r=t(e)?Array.isArray(e[0])?e[0]:Object.entries(e[0]).map(([n,i])=>[n,i]):[[e[0],e[1],e[2]]];if(r.length===0)throw new Error("No nodes provided in `addNode`");for(let[n,i,s]of r){if(n in this.channels)throw new Error(`${n} is already being used as a state attribute (a.k.a. a channel), cannot also be used as a node name.`);for(let l of[et,Ir])if(n.includes(l))throw new Error(`"${l}" is a reserved character and is not allowed in node names.`);if(this.warnIfCompiled("Adding a node to a graph that has already been compiled. This will not be reflected in the compiled graph."),n in this.nodes)throw new Error(`Node \`${n}\` already present.`);if(n===we||n===ke)throw new Error(`Node \`${n}\` is reserved.`);let o=this._schemaDefinition;s?.input!==void 0&&(o=this._getChannelsFromSchema(s.input)),this._addSchema(o);let a;ce.isRunnable(i)?a=i:typeof i=="function"?a=new sr({func:i,name:n,trace:!1}):a=dt(i);let c=s?.cachePolicy;typeof c=="boolean"&&(c=c?{}:void 0);let u={runnable:a,retryPolicy:s?.retryPolicy,cachePolicy:c,metadata:s?.metadata,input:o??this._schemaDefinition,subgraphs:gd(a)?[a]:s?.subgraphs,ends:s?.ends,defer:s?.defer};this.nodes[n]=u}return this}addEdge(e,t){if(typeof e=="string")return super.addEdge(e,t);this.compiled&&console.warn("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph.");for(let r of e){if(r===we)throw new Error("END cannot be a start node");if(!Object.keys(this.nodes).some(n=>n===r))throw new Error(`Need to add a node named "${r}" first`)}if(t===we)throw new Error("END cannot be an end node");if(!Object.keys(this.nodes).some(r=>r===t))throw new Error(`Need to add a node named "${t}" first`);return this.waitingEdges.add([e,t]),this}addSequence(e){let t=Array.isArray(e)?e:Object.entries(e);if(t.length===0)throw new Error("Sequence requires at least one node.");let r;for(let[n,i,s]of t){if(n in this.nodes)throw new Error(`Node names must be unique: node with the name "${n}" already exists.`);let o=n;this.addNode(o,i,s),r!=null&&this.addEdge(r,o),r=o}return this}compile({checkpointer:e,store:t,cache:r,interruptBefore:n,interruptAfter:i,name:s,description:o}={}){this.validate([...Array.isArray(n)?n:[],...Array.isArray(i)?i:[]]);let a=Object.keys(this._schemaDefinitions.get(this._outputDefinition)),c=a.length===1&&a[0]===gs?gs:a,u=Object.keys(this.channels),l=u.length===1&&u[0]===gs?gs:u,p=this._interrupt,f=new cj({builder:this,checkpointer:e,interruptAfter:i,interruptBefore:n,autoValidate:!1,nodes:{},channels:{...this.channels,[ke]:new Wn},inputChannels:ke,outputChannels:c,streamChannels:l,streamMode:"updates",store:t,cache:r,name:s,description:o,userInterrupt:p});f.attachNode(ke);for(let[d,m]of Object.entries(this.nodes))f.attachNode(d,m);f.attachBranch(ke,xS,aj(),{withReader:!1});for(let[d]of Object.entries(this.nodes))f.attachBranch(d,xS,aj(),{withReader:!1});for(let[d,m]of this.edges)f.attachEdge(d,m);for(let[d,m]of this.waitingEdges)f.attachEdge(d,m);for(let[d,m]of Object.entries(this.branches))for(let[h,b]of Object.entries(m))f.attachBranch(d,h,b);return f.validate()}};function m5(e){let t={};for(let[r,n]of Object.entries(e))r===gs?t[r]=wg(n):t[r]=wg(n);return t}var cj=class extends VS{description;_metaRegistry=wd;constructor({description:e,...t}){super(t),this.description=e}attachNode(e,t){let r;e===ke?r=Object.entries(this.builder._schemaDefinitions.get(this.builder._inputDefinition)).map(([a])=>a):r=Object.keys(this.builder.channels);function n(a){if(Pt(a))return a.graph===jr.PARENT?null:a._updateAsTuples();if(Array.isArray(a)&&a.length>0&&a.some(c=>Pt(c))){let c=[];for(let u of a)if(Pt(u)){if(u.graph===jr.PARENT)continue;c.push(...u._updateAsTuples())}else c.push([gs,u]);return c}else if(a!=null)return[[gs,a]];return null}let i=e;function s(a){if(a){if(Pt(a))return a.graph===jr.PARENT?null:a._updateAsTuples().filter(([c])=>r.includes(c));if(Array.isArray(a)&&a.length>0&&a.some(Pt)){let c=[];for(let u of a)if(Pt(u)){if(u.graph===jr.PARENT)continue;c.push(...u._updateAsTuples().filter(([l])=>r.includes(l)))}else{let l=s(u);l&&c.push(...l??[])}return c}else{if(typeof a=="object"&&!Array.isArray(a))return Object.entries(a).filter(([c])=>r.includes(c));{let c=Array.isArray(a)?"array":typeof a;throw new De(`Expected node "${i.toString()}" to return an object or an array containing at least one Command object, received ${c}`,{lc_error_code:"INVALID_GRAPH_NODE_RETURN_VALUE"})}}}else return null}let o=[{value:Dr,mapper:new sr({func:r.length&&r[0]===gs?n:s,trace:!1,recurse:!1})}];if(e===ke)this.nodes[e]=new qn({tags:[Be],triggers:[ke],channels:[ke],writers:[new _t(o,[Be])]});else{let a=t?.input??this.builder._schemaDefinition,c=Object.fromEntries(Object.keys(this.builder._schemaDefinitions.get(a)).map(p=>[p,p])),u=Object.keys(c).length===1&&gs in c,l=`branch:to:${e}`;this.channels[l]=t?.defer?new vS:new Wn(!1),this.nodes[e]=new qn({triggers:[l],channels:u?Object.keys(c):c,writers:[new _t(o,[Be])],mapper:u?void 0:p=>Object.fromEntries(Object.entries(p).filter(([f])=>f in c)),bound:t?.runnable,metadata:t?.metadata,retryPolicy:t?.retryPolicy,cachePolicy:t?.cachePolicy,subgraphs:t?.subgraphs,ends:t?.ends})}}attachEdge(e,t){if(t!==we){if(typeof e=="string")this.nodes[e].writers.push(new _t([{channel:`branch:to:${t}`,value:null}],[Be]));else if(Array.isArray(e)){let r=`join:${e.join("+")}:${t}`;this.channels[r]=this.builder.nodes[t].defer?new KS(new Set(e)):new GS(new Set(e)),this.nodes[t].triggers.push(r);for(let n of e)this.nodes[n].writers.push(new _t([{channel:r,value:n}],[Be]))}}}attachBranch(e,t,r,n={withReader:!0}){let i=async(s,o)=>{let a=s.filter(u=>u!==we);if(!a.length)return;let c=a.map(u=>$t(u)?u:{channel:u===we?u:`branch:to:${u}`,value:e});await _t.doWrite({...o,tags:(o.tags??[]).concat([Be])},c)};this.nodes[e].writers.push(r.run(i,n.withReader?s=>fM.doRead(s,this.streamChannels??this.outputChannels,!0):void 0))}async _validateInput(e){if(e==null)return e;let t=this.builder._inputRuntimeDefinition,r=this.builder._schemaRuntimeDefinition;if(Si.isInstance(t)){if(Pt(e)){let i=e;return e.update&&(i.update=await t.validateInput(Array.isArray(e.update)?Object.fromEntries(e.update):e.update)),i}return await t.validateInput(e)}if(t===Zg&&Si.isInstance(r)){if(Pt(e)){let i=e;return e.update&&(i.update=await r.validateInput(Array.isArray(e.update)?Object.fromEntries(e.update):e.update)),i}return await r.validateInput(e)}let n=(()=>{let i=s=>{if(s!=null)return this._metaRegistry.getExtendedChannelSchemas(s,{withReducerSchema:!0})};if(yr(t))return i(t);if(t===Zg)return yr(r)?Pc(i(r)):void 0})();if(Pt(e)){let i=e;return e.update&&n!=null&&(i.update=$c(n,e.update)),i}return n!=null?$c(n,e):e}isInterrupted(e){return fd(e)}async _validateContext(e){let t=this.builder._configRuntimeSchema;return yr(t)&&$c(t,e),e}};function h5(e){return typeof e=="object"&&e!==null&&e.channels!==void 0}function g5(e){if($t(e))return[e];let t=[];Pt(e)?t.push(e):Array.isArray(e)&&t.push(...e.filter(Pt));let r=[];for(let n of t){if(n.graph===jr.PARENT)throw new Xd(n);$t(n.goto)||typeof n.goto=="string"?r.push(n.goto):Array.isArray(n.goto)&&r.push(...n.goto)}return r}function aj(){return new FS({path:new sr({func:g5,tags:[Be],trace:!1,recurse:!1,name:"<control_branch>"})})}var uj=function(t,r){let{name:n,checkpointer:i,store:s,cache:o}=typeof t=="string"?{name:t,checkpointer:void 0,store:void 0}:t;if(pM(r)||dM(r))throw new Error("Generators are disallowed as entrypoints. For streaming responses, use config.write.");let a="updates",c=CM(n,r);function u(d){return typeof d=="object"&&d!==null&&"__lg_type"in d&&d.__lg_type==="__pregel_final"}let l=new sr({name:"pluckReturnValue",func:d=>u(d)?d.value:d}),p=new sr({name:"pluckSaveValue",func:d=>u(d)?d.save:d}),f=new qn({bound:c,triggers:[ke],channels:[ke],writers:[new _t([{channel:we,value:Dr,mapper:l},{channel:Aa,value:Dr,mapper:p}],[Be])]});return new Bg({name:n,checkpointer:i,nodes:{[n]:f},channels:{[ke]:new Wn,[we]:new Fn,[Aa]:new Fn},inputChannels:ke,outputChannels:we,streamChannels:we,streamMode:a,store:s,cache:o})};uj.final=function({value:t,save:r}){return{value:t,save:r,__lg_type:"__pregel_final"}};var _5=Bn.Root({messages:Bn({reducer:hs,default:()=>[]})}),lj={reducer:{fn:hs},jsonSchemaExtra:{langgraph_type:"messages"},default:()=>[]},y5=Ge.object({messages:sj(Ge.custom(),lj)});async function WS(e,t,r){if(r===void 0)throw new Error(["Unable to dispatch a custom event without a parent run id.",'"dispatchCustomEvent" can only be called from within an existing run (e.g.,',"inside a tool or a RunnableLambda).",`
|
|
225
|
+
|
|
226
|
+
If you continue to see this error, please import from "@langchain/core/callbacks/dispatch/web"`,"and explicitly pass in a config parameter.",`
|
|
227
|
+
|
|
228
|
+
Or, if you are calling this from a custom tool, ensure you're using the "tool" helper constructor as documented here:`,`
|
|
229
|
+
|`,`
|
|
230
|
+
\u2514-> https://js.langchain.com/docs/how_to/custom_tools#tool-function`,`
|
|
231
|
+
`].join(" "));let n=await Et(r),i=n?.getParentRunId();n!==void 0&&i!==void 0&&await n.handleCustomEvent?.(e,t,i)}var wn=Ge;function xd(e,t){return e.lc_error_code=t,e.message=`${e.message}
|
|
232
|
+
|
|
233
|
+
Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${t}/
|
|
234
|
+
`,e}function se(e,t,r,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?e!==t||!i:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(e,r):i?i.value=r:t.set(e,r),r}function k(e,t,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(e):n?n.value:t.get(e)}var JS=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return JS=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),r=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^r()&15>>+n/4).toString(16))};function Id(e){return typeof e=="object"&&e!==null&&("name"in e&&e.name==="AbortError"||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}var Sd=e=>{if(e instanceof Error)return e;if(typeof e=="object"&&e!==null){try{if(Object.prototype.toString.call(e)==="[object Error]"){let t=new Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return new Error(JSON.stringify(e))}catch{}}return new Error(e)};var q=class extends Error{},Rt=class e extends q{constructor(t,r,n,i){super(`${e.makeMessage(t,r,n)}`),this.status=t,this.headers=i,this.requestID=i?.get("x-request-id"),this.error=r;let s=r;this.code=s?.code,this.param=s?.param,this.type=s?.type}static makeMessage(t,r,n){let i=r?.message?typeof r.message=="string"?r.message:JSON.stringify(r.message):r?JSON.stringify(r):n;return t&&i?`${t} ${i}`:t?`${t} status code (no body)`:i||"(no status code or body)"}static generate(t,r,n,i){if(!t||!i)return new fo({message:n,cause:Sd(r)});let s=r?.error;return t===400?new du(t,s,n,i):t===401?new fu(t,s,n,i):t===403?new mu(t,s,n,i):t===404?new hu(t,s,n,i):t===409?new gu(t,s,n,i):t===422?new _u(t,s,n,i):t===429?new yu(t,s,n,i):t>=500?new vu(t,s,n,i):new e(t,s,n,i)}},yt=class extends Rt{constructor({message:t}={}){super(void 0,void 0,t||"Request was aborted.",void 0)}},fo=class extends Rt{constructor({message:t,cause:r}){super(void 0,void 0,t||"Connection error.",void 0),r&&(this.cause=r)}},Ei=class extends fo{constructor({message:t}={}){super({message:t??"Request timed out."})}},du=class extends Rt{},fu=class extends Rt{},mu=class extends Rt{},hu=class extends Rt{},gu=class extends Rt{},_u=class extends Rt{},yu=class extends Rt{},vu=class extends Rt{},bu=class extends q{constructor(){super("Could not parse response content as the length limit was reached")}},wu=class extends q{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},ki=class extends Error{constructor(t){super(t)}};var b5=/^[a-z][a-z0-9+.-]*:/i,pj=e=>b5.test(e),ar=e=>(ar=Array.isArray,ar(e)),XS=ar;function YS(e){return typeof e!="object"?{}:e??{}}function dj(e){if(!e)return!0;for(let t in e)return!1;return!0}function fj(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function xu(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}var mj=(e,t)=>{if(typeof t!="number"||!Number.isInteger(t))throw new q(`${e} must be an integer`);if(t<0)throw new q(`${e} must be a positive integer`);return t};var hj=e=>{try{return JSON.parse(e)}catch{return}};var Ai=e=>new Promise(t=>setTimeout(t,e));var mo="6.16.0";var vj=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function w5(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}var x5=()=>{let e=w5();if(e==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":mo,"X-Stainless-OS":_j(Deno.build.os),"X-Stainless-Arch":gj(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":mo,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(e==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":mo,"X-Stainless-OS":_j(globalThis.process.platform??"unknown"),"X-Stainless-Arch":gj(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let t=I5();return t?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":mo,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":mo,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function I5(){if(typeof navigator>"u"||!navigator)return null;let e=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:t,pattern:r}of e){let n=r.exec(navigator.userAgent);if(n){let i=n[1]||0,s=n[2]||0,o=n[3]||0;return{browser:t,version:`${i}.${s}.${o}`}}}return null}var gj=e=>e==="x32"?"x32":e==="x86_64"||e==="x64"?"x64":e==="arm"?"arm":e==="aarch64"||e==="arm64"?"arm64":e?`other:${e}`:"unknown",_j=e=>(e=e.toLowerCase(),e.includes("ios")?"iOS":e==="android"?"Android":e==="darwin"?"MacOS":e==="win32"?"Windows":e==="freebsd"?"FreeBSD":e==="openbsd"?"OpenBSD":e==="linux"?"Linux":e?`Other:${e}`:"Unknown"),yj,bj=()=>yj??(yj=x5());function wj(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function QS(...e){let t=globalThis.ReadableStream;if(typeof t>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function Kg(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return QS({start(){},async pull(r){let{done:n,value:i}=await t.next();n?r.close():r.enqueue(i)},async cancel(){await t.return?.()}})}function eE(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let r=await t.read();return r?.done&&t.releaseLock(),r}catch(r){throw t.releaseLock(),r}},async return(){let r=t.cancel();return t.releaseLock(),await r,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function xj(e){if(e===null||typeof e!="object")return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}let t=e.getReader(),r=t.cancel();t.releaseLock(),await r}var Ij=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)});var qg="RFC3986",tE=e=>String(e),Hg={RFC1738:e=>String(e).replace(/%20/g,"+"),RFC3986:tE},rE="RFC1738";var Wg=(e,t)=>(Wg=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Wg(e,t)),Ti=(()=>{let e=[];for(let t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e})();var nE=1024,Sj=(e,t,r,n,i)=>{if(e.length===0)return e;let s=e;if(typeof e=="symbol"?s=Symbol.prototype.toString.call(e):typeof e!="string"&&(s=String(e)),r==="iso-8859-1")return escape(s).replace(/%u[0-9a-f]{4}/gi,function(a){return"%26%23"+parseInt(a.slice(2),16)+"%3B"});let o="";for(let a=0;a<s.length;a+=nE){let c=s.length>=nE?s.slice(a,a+nE):s,u=[];for(let l=0;l<c.length;++l){let p=c.charCodeAt(l);if(p===45||p===46||p===95||p===126||p>=48&&p<=57||p>=65&&p<=90||p>=97&&p<=122||i===rE&&(p===40||p===41)){u[u.length]=c.charAt(l);continue}if(p<128){u[u.length]=Ti[p];continue}if(p<2048){u[u.length]=Ti[192|p>>6]+Ti[128|p&63];continue}if(p<55296||p>=57344){u[u.length]=Ti[224|p>>12]+Ti[128|p>>6&63]+Ti[128|p&63];continue}l+=1,p=65536+((p&1023)<<10|c.charCodeAt(l)&1023),u[u.length]=Ti[240|p>>18]+Ti[128|p>>12&63]+Ti[128|p>>6&63]+Ti[128|p&63]}o+=u.join("")}return o};function Ej(e){return!e||typeof e!="object"?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function iE(e,t){if(ar(e)){let r=[];for(let n=0;n<e.length;n+=1)r.push(t(e[n]));return r}return t(e)}var Aj={brackets(e){return String(e)+"[]"},comma:"comma",indices(e,t){return String(e)+"["+t+"]"},repeat(e){return String(e)}},Tj=function(e,t){Array.prototype.push.apply(e,ar(t)?t:[t])},kj,Mt={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Sj,encodeValuesOnly:!1,format:qg,formatter:tE,indices:!1,serializeDate(e){return(kj??(kj=Function.prototype.call.bind(Date.prototype.toISOString)))(e)},skipNulls:!1,strictNullHandling:!1};function k5(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"||typeof e=="symbol"||typeof e=="bigint"}var sE={};function Oj(e,t,r,n,i,s,o,a,c,u,l,p,f,d,m,h,b,_){let y=e,x=_,I=0,A=!1;for(;(x=x.get(sE))!==void 0&&!A;){let P=x.get(e);if(I+=1,typeof P<"u"){if(P===I)throw new RangeError("Cyclic object value");A=!0}typeof x.get(sE)>"u"&&(I=0)}if(typeof u=="function"?y=u(t,y):y instanceof Date?y=f?.(y):r==="comma"&&ar(y)&&(y=iE(y,function(P){return P instanceof Date?f?.(P):P})),y===null){if(s)return c&&!h?c(t,Mt.encoder,b,"key",d):t;y=""}if(k5(y)||Ej(y)){if(c){let P=h?t:c(t,Mt.encoder,b,"key",d);return[m?.(P)+"="+m?.(c(y,Mt.encoder,b,"value",d))]}return[m?.(t)+"="+m?.(String(y))]}let j=[];if(typeof y>"u")return j;let O;if(r==="comma"&&ar(y))h&&c&&(y=iE(y,c)),O=[{value:y.length>0?y.join(",")||null:void 0}];else if(ar(u))O=u;else{let P=Object.keys(y);O=l?P.sort(l):P}let w=a?String(t).replace(/\./g,"%2E"):String(t),F=n&&ar(y)&&y.length===1?w+"[]":w;if(i&&ar(y)&&y.length===0)return F+"[]";for(let P=0;P<O.length;++P){let V=O[P],Te=typeof V=="object"&&typeof V.value<"u"?V.value:y[V];if(o&&Te===null)continue;let qe=p&&a?V.replace(/\./g,"%2E"):V,cr=ar(y)?typeof r=="function"?r(F,qe):F:F+(p?"."+qe:"["+qe+"]");_.set(e,I);let Lr=new WeakMap;Lr.set(sE,_),Tj(j,Oj(Te,cr,r,n,i,s,o,a,r==="comma"&&h&&ar(y)?null:c,u,l,p,f,d,m,h,b,Lr))}return j}function A5(e=Mt){if(typeof e.allowEmptyArrays<"u"&&typeof e.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof e.encodeDotInKeys<"u"&&typeof e.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(e.encoder!==null&&typeof e.encoder<"u"&&typeof e.encoder!="function")throw new TypeError("Encoder has to be a function.");let t=e.charset||Mt.charset;if(typeof e.charset<"u"&&e.charset!=="utf-8"&&e.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let r=qg;if(typeof e.format<"u"){if(!Wg(Hg,e.format))throw new TypeError("Unknown format option provided.");r=e.format}let n=Hg[r],i=Mt.filter;(typeof e.filter=="function"||ar(e.filter))&&(i=e.filter);let s;if(e.arrayFormat&&e.arrayFormat in Aj?s=e.arrayFormat:"indices"in e?s=e.indices?"indices":"repeat":s=Mt.arrayFormat,"commaRoundTrip"in e&&typeof e.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let o=typeof e.allowDots>"u"?e.encodeDotInKeys?!0:Mt.allowDots:!!e.allowDots;return{addQueryPrefix:typeof e.addQueryPrefix=="boolean"?e.addQueryPrefix:Mt.addQueryPrefix,allowDots:o,allowEmptyArrays:typeof e.allowEmptyArrays=="boolean"?!!e.allowEmptyArrays:Mt.allowEmptyArrays,arrayFormat:s,charset:t,charsetSentinel:typeof e.charsetSentinel=="boolean"?e.charsetSentinel:Mt.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:typeof e.delimiter>"u"?Mt.delimiter:e.delimiter,encode:typeof e.encode=="boolean"?e.encode:Mt.encode,encodeDotInKeys:typeof e.encodeDotInKeys=="boolean"?e.encodeDotInKeys:Mt.encodeDotInKeys,encoder:typeof e.encoder=="function"?e.encoder:Mt.encoder,encodeValuesOnly:typeof e.encodeValuesOnly=="boolean"?e.encodeValuesOnly:Mt.encodeValuesOnly,filter:i,format:r,formatter:n,serializeDate:typeof e.serializeDate=="function"?e.serializeDate:Mt.serializeDate,skipNulls:typeof e.skipNulls=="boolean"?e.skipNulls:Mt.skipNulls,sort:typeof e.sort=="function"?e.sort:null,strictNullHandling:typeof e.strictNullHandling=="boolean"?e.strictNullHandling:Mt.strictNullHandling}}function oE(e,t={}){let r=e,n=A5(t),i,s;typeof n.filter=="function"?(s=n.filter,r=s("",r)):ar(n.filter)&&(s=n.filter,i=s);let o=[];if(typeof r!="object"||r===null)return"";let a=Aj[n.arrayFormat],c=a==="comma"&&n.commaRoundTrip;i||(i=Object.keys(r)),n.sort&&i.sort(n.sort);let u=new WeakMap;for(let f=0;f<i.length;++f){let d=i[f];n.skipNulls&&r[d]===null||Tj(o,Oj(r[d],d,a,c,n.allowEmptyArrays,n.strictNullHandling,n.skipNulls,n.encodeDotInKeys,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.format,n.formatter,n.encodeValuesOnly,n.charset,u))}let l=o.join(n.delimiter),p=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?p+="utf8=%26%2310003%3B&":p+="utf8=%E2%9C%93&"),l.length>0?p+l:""}function Pj(e){let t=0;for(let i of e)t+=i.length;let r=new Uint8Array(t),n=0;for(let i of e)r.set(i,n),n+=i.length;return r}var $j;function Iu(e){let t;return($j??(t=new globalThis.TextEncoder,$j=t.encode.bind(t)))(e)}var Cj;function aE(e){let t;return(Cj??(t=new globalThis.TextDecoder,Cj=t.decode.bind(t)))(e)}var Xr,Yr,Ra=class{constructor(){Xr.set(this,void 0),Yr.set(this,void 0),se(this,Xr,new Uint8Array,"f"),se(this,Yr,null,"f")}decode(t){if(t==null)return[];let r=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?Iu(t):t;se(this,Xr,Pj([k(this,Xr,"f"),r]),"f");let n=[],i;for(;(i=O5(k(this,Xr,"f"),k(this,Yr,"f")))!=null;){if(i.carriage&&k(this,Yr,"f")==null){se(this,Yr,i.index,"f");continue}if(k(this,Yr,"f")!=null&&(i.index!==k(this,Yr,"f")+1||i.carriage)){n.push(aE(k(this,Xr,"f").subarray(0,k(this,Yr,"f")-1))),se(this,Xr,k(this,Xr,"f").subarray(k(this,Yr,"f")),"f"),se(this,Yr,null,"f");continue}let s=k(this,Yr,"f")!==null?i.preceding-1:i.preceding,o=aE(k(this,Xr,"f").subarray(0,s));n.push(o),se(this,Xr,k(this,Xr,"f").subarray(i.index),"f"),se(this,Yr,null,"f")}return n}flush(){return k(this,Xr,"f").length?this.decode(`
|
|
235
|
+
`):[]}};Xr=new WeakMap,Yr=new WeakMap;Ra.NEWLINE_CHARS=new Set([`
|
|
236
|
+
`,"\r"]);Ra.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function O5(e,t){for(let i=t??0;i<e.length;i++){if(e[i]===10)return{preceding:i,index:i+1,carriage:!1};if(e[i]===13)return{preceding:i,index:i+1,carriage:!0}}return null}function Nj(e){for(let n=0;n<e.length-1;n++){if(e[n]===10&&e[n+1]===10||e[n]===13&&e[n+1]===13)return n+2;if(e[n]===13&&e[n+1]===10&&n+3<e.length&&e[n+2]===13&&e[n+3]===10)return n+4}return-1}var Xg={off:0,error:200,warn:300,info:400,debug:500},cE=(e,t,r)=>{if(e){if(fj(Xg,e))return e;It(r).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(Xg))}`)}};function Ed(){}function Jg(e,t,r){return!t||Xg[e]>Xg[r]?Ed:t[e].bind(t)}var $5={error:Ed,warn:Ed,info:Ed,debug:Ed},Rj=new WeakMap;function It(e){let t=e.logger,r=e.logLevel??"off";if(!t)return $5;let n=Rj.get(t);if(n&&n[0]===r)return n[1];let i={error:Jg("error",t,r),warn:Jg("warn",t,r),info:Jg("info",t,r),debug:Jg("debug",t,r)};return Rj.set(t,[r,i]),i}var _s=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&(e.headers=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([t,r])=>[t,t.toLowerCase()==="authorization"||t.toLowerCase()==="cookie"||t.toLowerCase()==="set-cookie"?"***":r]))),"retryOfRequestLogID"in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e);var kd,Oi=class e{constructor(t,r,n){this.iterator=t,kd.set(this,void 0),this.controller=r,se(this,kd,n,"f")}static fromSSEResponse(t,r,n){let i=!1,s=n?It(n):console;async function*o(){if(i)throw new q("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let a=!1;try{for await(let c of C5(t,r))if(!a){if(c.data.startsWith("[DONE]")){a=!0;continue}if(c.event===null||!c.event.startsWith("thread.")){let u;try{u=JSON.parse(c.data)}catch(l){throw s.error("Could not parse message into JSON:",c.data),s.error("From chunk:",c.raw),l}if(u&&u.error)throw new Rt(void 0,u.error,void 0,t.headers);yield u}else{let u;try{u=JSON.parse(c.data)}catch(l){throw console.error("Could not parse message into JSON:",c.data),console.error("From chunk:",c.raw),l}if(c.event=="error")throw new Rt(void 0,u.error,u.message,void 0);yield{event:c.event,data:u}}}a=!0}catch(c){if(Id(c))return;throw c}finally{a||r.abort()}}return new e(o,r,n)}static fromReadableStream(t,r,n){let i=!1;async function*s(){let a=new Ra,c=eE(t);for await(let u of c)for(let l of a.decode(u))yield l;for(let u of a.flush())yield u}async function*o(){if(i)throw new q("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let a=!1;try{for await(let c of s())a||c&&(yield JSON.parse(c));a=!0}catch(c){if(Id(c))return;throw c}finally{a||r.abort()}}return new e(o,r,n)}[(kd=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let t=[],r=[],n=this.iterator(),i=s=>({next:()=>{if(s.length===0){let o=n.next();t.push(o),r.push(o)}return s.shift()}});return[new e(()=>i(t),this.controller,k(this,kd,"f")),new e(()=>i(r),this.controller,k(this,kd,"f"))]}toReadableStream(){let t=this,r;return QS({async start(){r=t[Symbol.asyncIterator]()},async pull(n){try{let{value:i,done:s}=await r.next();if(s)return n.close();let o=Iu(JSON.stringify(i)+`
|
|
237
|
+
`);n.enqueue(o)}catch(i){n.error(i)}},async cancel(){await r.return?.()}})}};async function*C5(e,t){if(!e.body)throw t.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new q("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new q("Attempted to iterate over a response with no body");let r=new uE,n=new Ra,i=eE(e.body);for await(let s of P5(i))for(let o of n.decode(s)){let a=r.decode(o);a&&(yield a)}for(let s of n.flush()){let o=r.decode(s);o&&(yield o)}}async function*P5(e){let t=new Uint8Array;for await(let r of e){if(r==null)continue;let n=r instanceof ArrayBuffer?new Uint8Array(r):typeof r=="string"?Iu(r):r,i=new Uint8Array(t.length+n.length);i.set(t),i.set(n,t.length),t=i;let s;for(;(s=Nj(t))!==-1;)yield t.slice(0,s),t=t.slice(s)}t.length>0&&(yield t)}var uE=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(t){if(t.endsWith("\r")&&(t=t.substring(0,t.length-1)),!t){if(!this.event&&!this.data.length)return null;let s={event:this.event,data:this.data.join(`
|
|
238
|
+
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],s}if(this.chunks.push(t),t.startsWith(":"))return null;let[r,n,i]=N5(t,":");return i.startsWith(" ")&&(i=i.substring(1)),r==="event"?this.event=i:r==="data"&&this.data.push(i),null}};function N5(e,t){let r=e.indexOf(t);return r!==-1?[e.substring(0,r),t,e.substring(r+t.length)]:[e,"",""]}async function Yg(e,t){let{response:r,requestLogID:n,retryOfRequestLogID:i,startTime:s}=t,o=await(async()=>{if(t.options.stream)return It(e).debug("response",r.status,r.url,r.headers,r.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(r,t.controller,e):Oi.fromSSEResponse(r,t.controller,e);if(r.status===204)return null;if(t.options.__binaryResponse)return r;let c=r.headers.get("content-type")?.split(";")[0]?.trim();if(c?.includes("application/json")||c?.endsWith("+json")){let p=await r.json();return lE(p,r)}return await r.text()})();return It(e).debug(`[${n}] response parsed`,_s({retryOfRequestLogID:i,url:r.url,status:r.status,body:o,durationMs:Date.now()-s})),o}function lE(e,t){return!e||typeof e!="object"||Array.isArray(e)?e:Object.defineProperty(e,"_request_id",{value:t.headers.get("x-request-id"),enumerable:!1})}var Ad,Ma=class e extends Promise{constructor(t,r,n=Yg){super(i=>{i(null)}),this.responsePromise=r,this.parseResponse=n,Ad.set(this,void 0),se(this,Ad,t,"f")}_thenUnwrap(t){return new e(k(this,Ad,"f"),this.responsePromise,async(r,n)=>lE(t(await this.parseResponse(r,n),n),n.response))}asResponse(){return this.responsePromise.then(t=>t.response)}async withResponse(){let[t,r]=await Promise.all([this.parse(),this.asResponse()]);return{data:t,response:r,request_id:r.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(t=>this.parseResponse(k(this,Ad,"f"),t))),this.parsedPromise}then(t,r){return this.parse().then(t,r)}catch(t){return this.parse().catch(t)}finally(t){return this.parse().finally(t)}};Ad=new WeakMap;var Qg,Td=class{constructor(t,r,n,i){Qg.set(this,void 0),se(this,Qg,t,"f"),this.options=i,this.response=r,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let t=this.nextPageRequestOptions();if(!t)throw new q("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await k(this,Qg,"f").requestAPIList(this.constructor,t)}async*iterPages(){let t=this;for(yield t;t.hasNextPage();)t=await t.getNextPage(),yield t}async*[(Qg=new WeakMap,Symbol.asyncIterator)](){for await(let t of this.iterPages())for(let r of t.getPaginatedItems())yield r}},Od=class extends Ma{constructor(t,r,n){super(t,r,async(i,s)=>new n(i,s.response,await Yg(i,s),s.options))}async*[Symbol.asyncIterator](){let t=await this;for await(let r of t)yield r}},$i=class extends Td{constructor(t,r,n,i){super(t,r,n,i),this.data=n.data||[],this.object=n.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},Ie=class extends Td{constructor(t,r,n,i){super(t,r,n,i),this.data=n.data||[],this.has_more=n.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let t=this.getPaginatedItems(),r=t[t.length-1]?.id;return r?{...this.options,query:{...YS(this.options.query),after:r}}:null}},ys=class extends Td{constructor(t,r,n,i){super(t,r,n,i),this.data=n.data||[],this.has_more=n.has_more||!1,this.last_id=n.last_id||""}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let t=this.last_id;return t?{...this.options,query:{...YS(this.options.query),after:t}}:null}};var fE=()=>{if(typeof File>"u"){let{process:e}=globalThis,t=typeof e?.versions?.node=="string"&&parseInt(e.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function Su(e,t,r){return fE(),new File(e,t??"unknown_file",r)}function $d(e){return(typeof e=="object"&&e!==null&&("name"in e&&e.name&&String(e.name)||"url"in e&&e.url&&String(e.url)||"filename"in e&&e.filename&&String(e.filename)||"path"in e&&e.path&&String(e.path))||"").split(/[\\/]/).pop()||void 0}var e_=e=>e!=null&&typeof e=="object"&&typeof e[Symbol.asyncIterator]=="function",mE=async(e,t)=>pE(e.body)?{...e,body:await jj(e.body,t)}:e,Qr=async(e,t)=>({...e,body:await jj(e.body,t)}),Mj=new WeakMap;function M5(e){let t=typeof e=="function"?e:e.fetch,r=Mj.get(t);if(r)return r;let n=(async()=>{try{let i="Response"in t?t.Response:(await t("data:,")).constructor,s=new FormData;return s.toString()!==await new i(s).text()}catch{return!0}})();return Mj.set(t,n),n}var jj=async(e,t)=>{if(!await M5(t))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let r=new FormData;return await Promise.all(Object.entries(e||{}).map(([n,i])=>dE(r,n,i))),r},Dj=e=>e instanceof Blob&&"name"in e,j5=e=>typeof e=="object"&&e!==null&&(e instanceof Response||e_(e)||Dj(e)),pE=e=>{if(j5(e))return!0;if(Array.isArray(e))return e.some(pE);if(e&&typeof e=="object"){for(let t in e)if(pE(e[t]))return!0}return!1},dE=async(e,t,r)=>{if(r!==void 0){if(r==null)throw new TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")e.append(t,String(r));else if(r instanceof Response)e.append(t,Su([await r.blob()],$d(r)));else if(e_(r))e.append(t,Su([await new Response(Kg(r)).blob()],$d(r)));else if(Dj(r))e.append(t,r,$d(r));else if(Array.isArray(r))await Promise.all(r.map(n=>dE(e,t+"[]",n)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([n,i])=>dE(e,`${t}[${n}]`,i)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${r} instead`)}};var zj=e=>e!=null&&typeof e=="object"&&typeof e.size=="number"&&typeof e.type=="string"&&typeof e.text=="function"&&typeof e.slice=="function"&&typeof e.arrayBuffer=="function",D5=e=>e!=null&&typeof e=="object"&&typeof e.name=="string"&&typeof e.lastModified=="number"&&zj(e),z5=e=>e!=null&&typeof e=="object"&&typeof e.url=="string"&&typeof e.blob=="function";async function Cd(e,t,r){if(fE(),e=await e,D5(e))return e instanceof File?e:Su([await e.arrayBuffer()],e.name);if(z5(e)){let i=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()),Su(await hE(i),t,r)}let n=await hE(e);if(t||(t=$d(e)),!r?.type){let i=n.find(s=>typeof s=="object"&&"type"in s&&s.type);typeof i=="string"&&(r={...r,type:i})}return Su(n,t,r)}async function hE(e){let t=[];if(typeof e=="string"||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(zj(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(e_(e))for await(let r of e)t.push(...await hE(r));else{let r=e?.constructor?.name;throw new Error(`Unexpected data type: ${typeof e}${r?`; constructor: ${r}`:""}${L5(e)}`)}return t}function L5(e){return typeof e!="object"||e===null?"":`; props: [${Object.getOwnPropertyNames(e).map(r=>`"${r}"`).join(", ")}]`}var N=class{constructor(t){this._client=t}};function Uj(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var Lj=Object.freeze(Object.create(null)),F5=(e=Uj)=>function(r,...n){if(r.length===1)return r[0];let i=!1,s=[],o=r.reduce((l,p,f)=>{/[?#]/.test(p)&&(i=!0);let d=n[f],m=(i?encodeURIComponent:e)(""+d);return f!==n.length&&(d==null||typeof d=="object"&&d.toString===Object.getPrototypeOf(Object.getPrototypeOf(d.hasOwnProperty??Lj)??Lj)?.toString)&&(m=d+"",s.push({start:l.length+p.length,length:m.length,error:`Value of type ${Object.prototype.toString.call(d).slice(8,-1)} is not a valid path parameter`})),l+p+(f===n.length?"":m)},""),a=o.split(/[?#]/,1)[0],c=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,u;for(;(u=c.exec(a))!==null;)s.push({start:u.index,length:u[0].length,error:`Value "${u[0]}" can't be safely passed as a path parameter`});if(s.sort((l,p)=>l.start-p.start),s.length>0){let l=0,p=s.reduce((f,d)=>{let m=" ".repeat(d.start-l),h="^".repeat(d.length);return l=d.start+d.length,f+m+h},"");throw new q(`Path parameters result in path with invalid segments:
|
|
239
|
+
${s.map(f=>f.error).join(`
|
|
240
|
+
`)}
|
|
241
|
+
${o}
|
|
242
|
+
${p}`)}return o},$=F5(Uj);var ja=class extends N{list(t,r={},n){return this._client.getAPIList($`/chat/completions/${t}/messages`,Ie,{query:r,...n})}};function Pd(e){return e!==void 0&&"function"in e&&e.function!==void 0}function Fj(e,t){let r={...e};return Object.defineProperties(r,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:t,enumerable:!1}}),r}function Nd(e){return e?.$brand==="auto-parseable-response-format"}function Da(e){return e?.$brand==="auto-parseable-tool"}function Bj(e,t){return!t||!gE(t)?{...e,choices:e.choices.map(r=>(Zj(r.message.tool_calls),{...r,message:{...r.message,parsed:null,...r.message.tool_calls?{tool_calls:r.message.tool_calls}:void 0}}))}:Rd(e,t)}function Rd(e,t){let r=e.choices.map(n=>{if(n.finish_reason==="length")throw new bu;if(n.finish_reason==="content_filter")throw new wu;return Zj(n.message.tool_calls),{...n,message:{...n.message,...n.message.tool_calls?{tool_calls:n.message.tool_calls?.map(i=>G5(t,i))??void 0}:void 0,parsed:n.message.content&&!n.message.refusal?Z5(t,n.message.content):null}}});return{...e,choices:r}}function Z5(e,t){return e.response_format?.type!=="json_schema"?null:e.response_format?.type==="json_schema"?"$parseRaw"in e.response_format?e.response_format.$parseRaw(t):JSON.parse(t):null}function G5(e,t){let r=e.tools?.find(n=>Pd(n)&&n.function?.name===t.function.name);return{...t,function:{...t.function,parsed_arguments:Da(r)?r.$parseRaw(t.function.arguments):r?.function.strict?JSON.parse(t.function.arguments):null}}}function Vj(e,t){if(!e||!("tools"in e)||!e.tools)return!1;let r=e.tools?.find(n=>Pd(n)&&n.function?.name===t.function.name);return Pd(r)&&(Da(r)||r?.function.strict||!1)}function gE(e){return Nd(e.response_format)?!0:e.tools?.some(t=>Da(t)||t.type==="function"&&t.function.strict===!0)??!1}function Zj(e){for(let t of e||[])if(t.type!=="function")throw new q(`Currently only \`function\` tool calls are supported; Received \`${t.type}\``)}function Gj(e){for(let t of e??[]){if(t.type!=="function")throw new q(`Currently only \`function\` tool types support auto-parsing; Received \`${t.type}\``);if(t.function.strict!==!0)throw new q(`The \`${t.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var Eu=e=>e?.role==="assistant",_E=e=>e?.role==="tool";var yE,t_,r_,Md,jd,n_,Dd,vs,zd,i_,s_,ku,Kj,ho=class{constructor(){yE.add(this),this.controller=new AbortController,t_.set(this,void 0),r_.set(this,()=>{}),Md.set(this,()=>{}),jd.set(this,void 0),n_.set(this,()=>{}),Dd.set(this,()=>{}),vs.set(this,{}),zd.set(this,!1),i_.set(this,!1),s_.set(this,!1),ku.set(this,!1),se(this,t_,new Promise((t,r)=>{se(this,r_,t,"f"),se(this,Md,r,"f")}),"f"),se(this,jd,new Promise((t,r)=>{se(this,n_,t,"f"),se(this,Dd,r,"f")}),"f"),k(this,t_,"f").catch(()=>{}),k(this,jd,"f").catch(()=>{})}_run(t){setTimeout(()=>{t().then(()=>{this._emitFinal(),this._emit("end")},k(this,yE,"m",Kj).bind(this))},0)}_connected(){this.ended||(k(this,r_,"f").call(this),this._emit("connect"))}get ended(){return k(this,zd,"f")}get errored(){return k(this,i_,"f")}get aborted(){return k(this,s_,"f")}abort(){this.controller.abort()}on(t,r){return(k(this,vs,"f")[t]||(k(this,vs,"f")[t]=[])).push({listener:r}),this}off(t,r){let n=k(this,vs,"f")[t];if(!n)return this;let i=n.findIndex(s=>s.listener===r);return i>=0&&n.splice(i,1),this}once(t,r){return(k(this,vs,"f")[t]||(k(this,vs,"f")[t]=[])).push({listener:r,once:!0}),this}emitted(t){return new Promise((r,n)=>{se(this,ku,!0,"f"),t!=="error"&&this.once("error",n),this.once(t,r)})}async done(){se(this,ku,!0,"f"),await k(this,jd,"f")}_emit(t,...r){if(k(this,zd,"f"))return;t==="end"&&(se(this,zd,!0,"f"),k(this,n_,"f").call(this));let n=k(this,vs,"f")[t];if(n&&(k(this,vs,"f")[t]=n.filter(i=>!i.once),n.forEach(({listener:i})=>i(...r))),t==="abort"){let i=r[0];!k(this,ku,"f")&&!n?.length&&Promise.reject(i),k(this,Md,"f").call(this,i),k(this,Dd,"f").call(this,i),this._emit("end");return}if(t==="error"){let i=r[0];!k(this,ku,"f")&&!n?.length&&Promise.reject(i),k(this,Md,"f").call(this,i),k(this,Dd,"f").call(this,i),this._emit("end")}}_emitFinal(){}};t_=new WeakMap,r_=new WeakMap,Md=new WeakMap,jd=new WeakMap,n_=new WeakMap,Dd=new WeakMap,vs=new WeakMap,zd=new WeakMap,i_=new WeakMap,s_=new WeakMap,ku=new WeakMap,yE=new WeakSet,Kj=function(t){if(se(this,i_,!0,"f"),t instanceof Error&&t.name==="AbortError"&&(t=new yt),t instanceof yt)return se(this,s_,!0,"f"),this._emit("abort",t);if(t instanceof q)return this._emit("error",t);if(t instanceof Error){let r=new q(t.message);return r.cause=t,this._emit("error",r)}return this._emit("error",new q(String(t)))};function qj(e){return typeof e.parse=="function"}var Er,vE,o_,bE,wE,xE,Hj,Wj,K5=10,Au=class extends ho{constructor(){super(...arguments),Er.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(t){this._chatCompletions.push(t),this._emit("chatCompletion",t);let r=t.choices[0]?.message;return r&&this._addMessage(r),t}_addMessage(t,r=!0){if("content"in t||(t.content=null),this.messages.push(t),r){if(this._emit("message",t),_E(t)&&t.content)this._emit("functionToolCallResult",t.content);else if(Eu(t)&&t.tool_calls)for(let n of t.tool_calls)n.type==="function"&&this._emit("functionToolCall",n.function)}}async finalChatCompletion(){await this.done();let t=this._chatCompletions[this._chatCompletions.length-1];if(!t)throw new q("stream ended without producing a ChatCompletion");return t}async finalContent(){return await this.done(),k(this,Er,"m",vE).call(this)}async finalMessage(){return await this.done(),k(this,Er,"m",o_).call(this)}async finalFunctionToolCall(){return await this.done(),k(this,Er,"m",bE).call(this)}async finalFunctionToolCallResult(){return await this.done(),k(this,Er,"m",wE).call(this)}async totalUsage(){return await this.done(),k(this,Er,"m",xE).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let t=this._chatCompletions[this._chatCompletions.length-1];t&&this._emit("finalChatCompletion",t);let r=k(this,Er,"m",o_).call(this);r&&this._emit("finalMessage",r);let n=k(this,Er,"m",vE).call(this);n&&this._emit("finalContent",n);let i=k(this,Er,"m",bE).call(this);i&&this._emit("finalFunctionToolCall",i);let s=k(this,Er,"m",wE).call(this);s!=null&&this._emit("finalFunctionToolCallResult",s),this._chatCompletions.some(o=>o.usage)&&this._emit("totalUsage",k(this,Er,"m",xE).call(this))}async _createChatCompletion(t,r,n){let i=n?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort())),k(this,Er,"m",Hj).call(this,r);let s=await t.chat.completions.create({...r,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(Rd(s,r))}async _runChatCompletion(t,r,n){for(let i of r.messages)this._addMessage(i,!1);return await this._createChatCompletion(t,r,n)}async _runTools(t,r,n){let i="tool",{tool_choice:s="auto",stream:o,...a}=r,c=typeof s!="string"&&s.type==="function"&&s?.function?.name,{maxChatCompletions:u=K5}=n||{},l=r.tools.map(d=>{if(Da(d)){if(!d.$callback)throw new q("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:d.$callback,name:d.function.name,description:d.function.description||"",parameters:d.function.parameters,parse:d.$parseRaw,strict:!0}}}return d}),p={};for(let d of l)d.type==="function"&&(p[d.function.name||d.function.function.name]=d.function);let f="tools"in r?l.map(d=>d.type==="function"?{type:"function",function:{name:d.function.name||d.function.function.name,parameters:d.function.parameters,description:d.function.description,strict:d.function.strict}}:d):void 0;for(let d of r.messages)this._addMessage(d,!1);for(let d=0;d<u;++d){let h=(await this._createChatCompletion(t,{...a,tool_choice:s,tools:f,messages:[...this.messages]},n)).choices[0]?.message;if(!h)throw new q("missing message in ChatCompletion response");if(!h.tool_calls?.length)return;for(let b of h.tool_calls){if(b.type!=="function")continue;let _=b.id,{name:y,arguments:x}=b.function,I=p[y];if(I){if(c&&c!==y){let w=`Invalid tool_call: ${JSON.stringify(y)}. ${JSON.stringify(c)} requested. Please try again`;this._addMessage({role:i,tool_call_id:_,content:w});continue}}else{let w=`Invalid tool_call: ${JSON.stringify(y)}. Available options are: ${Object.keys(p).map(F=>JSON.stringify(F)).join(", ")}. Please try again`;this._addMessage({role:i,tool_call_id:_,content:w});continue}let A;try{A=qj(I)?await I.parse(x):x}catch(w){let F=w instanceof Error?w.message:String(w);this._addMessage({role:i,tool_call_id:_,content:F});continue}let j=await I.function(A,this),O=k(this,Er,"m",Wj).call(this,j);if(this._addMessage({role:i,tool_call_id:_,content:O}),c)return}}}};Er=new WeakSet,vE=function(){return k(this,Er,"m",o_).call(this).content??null},o_=function(){let t=this.messages.length;for(;t-- >0;){let r=this.messages[t];if(Eu(r))return{...r,content:r.content??null,refusal:r.refusal??null}}throw new q("stream ended without producing a ChatCompletionMessage with role=assistant")},bE=function(){for(let t=this.messages.length-1;t>=0;t--){let r=this.messages[t];if(Eu(r)&&r?.tool_calls?.length)return r.tool_calls.filter(n=>n.type==="function").at(-1)?.function}},wE=function(){for(let t=this.messages.length-1;t>=0;t--){let r=this.messages[t];if(_E(r)&&r.content!=null&&typeof r.content=="string"&&this.messages.some(n=>n.role==="assistant"&&n.tool_calls?.some(i=>i.type==="function"&&i.id===r.tool_call_id)))return r.content}},xE=function(){let t={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:r}of this._chatCompletions)r&&(t.completion_tokens+=r.completion_tokens,t.prompt_tokens+=r.prompt_tokens,t.total_tokens+=r.total_tokens);return t},Hj=function(t){if(t.n!=null&&t.n>1)throw new q("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},Wj=function(t){return typeof t=="string"?t:t===void 0?"undefined":JSON.stringify(t)};var Ld=class e extends Au{static runTools(t,r,n){let i=new e,s={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runTools"}};return i._run(()=>i._runTools(t,r,s)),i}_addMessage(t,r=!0){super._addMessage(t,r),Eu(t)&&t.content&&this._emit("content",t.content)}};var Ft={STR:1,NUM:2,ARR:4,OBJ:8,NULL:16,BOOL:32,NAN:64,INFINITY:128,MINUS_INFINITY:256,INF:384,SPECIAL:496,ATOM:499,COLLECTION:12,ALL:511},IE=class extends Error{},SE=class extends Error{};function q5(e,t=Ft.ALL){if(typeof e!="string")throw new TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw new Error(`${e} is empty`);return H5(e.trim(),t)}var H5=(e,t)=>{let r=e.length,n=0,i=f=>{throw new IE(`${f} at position ${n}`)},s=f=>{throw new SE(`${f} at position ${n}`)},o=()=>(p(),n>=r&&i("Unexpected end of input"),e[n]==='"'?a():e[n]==="{"?c():e[n]==="["?u():e.substring(n,n+4)==="null"||Ft.NULL&t&&r-n<4&&"null".startsWith(e.substring(n))?(n+=4,null):e.substring(n,n+4)==="true"||Ft.BOOL&t&&r-n<4&&"true".startsWith(e.substring(n))?(n+=4,!0):e.substring(n,n+5)==="false"||Ft.BOOL&t&&r-n<5&&"false".startsWith(e.substring(n))?(n+=5,!1):e.substring(n,n+8)==="Infinity"||Ft.INFINITY&t&&r-n<8&&"Infinity".startsWith(e.substring(n))?(n+=8,1/0):e.substring(n,n+9)==="-Infinity"||Ft.MINUS_INFINITY&t&&1<r-n&&r-n<9&&"-Infinity".startsWith(e.substring(n))?(n+=9,-1/0):e.substring(n,n+3)==="NaN"||Ft.NAN&t&&r-n<3&&"NaN".startsWith(e.substring(n))?(n+=3,NaN):l()),a=()=>{let f=n,d=!1;for(n++;n<r&&(e[n]!=='"'||d&&e[n-1]==="\\");)d=e[n]==="\\"?!d:!1,n++;if(e.charAt(n)=='"')try{return JSON.parse(e.substring(f,++n-Number(d)))}catch(m){s(String(m))}else if(Ft.STR&t)try{return JSON.parse(e.substring(f,n-Number(d))+'"')}catch{return JSON.parse(e.substring(f,e.lastIndexOf("\\"))+'"')}i("Unterminated string literal")},c=()=>{n++,p();let f={};try{for(;e[n]!=="}";){if(p(),n>=r&&Ft.OBJ&t)return f;let d=a();p(),n++;try{let m=o();Object.defineProperty(f,d,{value:m,writable:!0,enumerable:!0,configurable:!0})}catch(m){if(Ft.OBJ&t)return f;throw m}p(),e[n]===","&&n++}}catch{if(Ft.OBJ&t)return f;i("Expected '}' at end of object")}return n++,f},u=()=>{n++;let f=[];try{for(;e[n]!=="]";)f.push(o()),p(),e[n]===","&&n++}catch{if(Ft.ARR&t)return f;i("Expected ']' at end of array")}return n++,f},l=()=>{if(n===0){e==="-"&&Ft.NUM&t&&i("Not sure what '-' is");try{return JSON.parse(e)}catch(d){if(Ft.NUM&t)try{return e[e.length-1]==="."?JSON.parse(e.substring(0,e.lastIndexOf("."))):JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch{}s(String(d))}}let f=n;for(e[n]==="-"&&n++;e[n]&&!",]}".includes(e[n]);)n++;n==r&&!(Ft.NUM&t)&&i("Unterminated number literal");try{return JSON.parse(e.substring(f,n))}catch{e.substring(f,n)==="-"&&Ft.NUM&t&&i("Not sure what '-' is");try{return JSON.parse(e.substring(f,e.lastIndexOf("e")))}catch(m){s(String(m))}}},p=()=>{for(;n<r&&`
|
|
243
|
+
\r `.includes(e[n]);)n++};return o()},EE=e=>q5(e,Ft.ALL^Ft.NUM);var jt,bs,Tu,go,kE,a_,AE,TE,OE,c_,$E,Jj,za=class e extends Au{constructor(t){super(),jt.add(this),bs.set(this,void 0),Tu.set(this,void 0),go.set(this,void 0),se(this,bs,t,"f"),se(this,Tu,[],"f")}get currentChatCompletionSnapshot(){return k(this,go,"f")}static fromReadableStream(t){let r=new e(null);return r._run(()=>r._fromReadableStream(t)),r}static createChatCompletion(t,r,n){let i=new e(r);return i._run(()=>i._runChatCompletion(t,{...r,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),i}async _createChatCompletion(t,r,n){super._createChatCompletion;let i=n?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort())),k(this,jt,"m",kE).call(this);let s=await t.chat.completions.create({...r,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(let o of s)k(this,jt,"m",AE).call(this,o);if(s.controller.signal?.aborted)throw new yt;return this._addChatCompletion(k(this,jt,"m",c_).call(this))}async _fromReadableStream(t,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),k(this,jt,"m",kE).call(this),this._connected();let i=Oi.fromReadableStream(t,this.controller),s;for await(let o of i)s&&s!==o.id&&this._addChatCompletion(k(this,jt,"m",c_).call(this)),k(this,jt,"m",AE).call(this,o),s=o.id;if(i.controller.signal?.aborted)throw new yt;return this._addChatCompletion(k(this,jt,"m",c_).call(this))}[(bs=new WeakMap,Tu=new WeakMap,go=new WeakMap,jt=new WeakSet,kE=function(){this.ended||se(this,go,void 0,"f")},a_=function(r){let n=k(this,Tu,"f")[r.index];return n||(n={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},k(this,Tu,"f")[r.index]=n,n)},AE=function(r){if(this.ended)return;let n=k(this,jt,"m",Jj).call(this,r);this._emit("chunk",r,n);for(let i of r.choices){let s=n.choices[i.index];i.delta.content!=null&&s.message?.role==="assistant"&&s.message?.content&&(this._emit("content",i.delta.content,s.message.content),this._emit("content.delta",{delta:i.delta.content,snapshot:s.message.content,parsed:s.message.parsed})),i.delta.refusal!=null&&s.message?.role==="assistant"&&s.message?.refusal&&this._emit("refusal.delta",{delta:i.delta.refusal,snapshot:s.message.refusal}),i.logprobs?.content!=null&&s.message?.role==="assistant"&&this._emit("logprobs.content.delta",{content:i.logprobs?.content,snapshot:s.logprobs?.content??[]}),i.logprobs?.refusal!=null&&s.message?.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:i.logprobs?.refusal,snapshot:s.logprobs?.refusal??[]});let o=k(this,jt,"m",a_).call(this,s);s.finish_reason&&(k(this,jt,"m",OE).call(this,s),o.current_tool_call_index!=null&&k(this,jt,"m",TE).call(this,s,o.current_tool_call_index));for(let a of i.delta.tool_calls??[])o.current_tool_call_index!==a.index&&(k(this,jt,"m",OE).call(this,s),o.current_tool_call_index!=null&&k(this,jt,"m",TE).call(this,s,o.current_tool_call_index)),o.current_tool_call_index=a.index;for(let a of i.delta.tool_calls??[]){let c=s.message.tool_calls?.[a.index];c?.type&&(c?.type==="function"?this._emit("tool_calls.function.arguments.delta",{name:c.function?.name,index:a.index,arguments:c.function.arguments,parsed_arguments:c.function.parsed_arguments,arguments_delta:a.function?.arguments??""}):(c?.type,void 0))}}},TE=function(r,n){if(k(this,jt,"m",a_).call(this,r).done_tool_calls.has(n))return;let s=r.message.tool_calls?.[n];if(!s)throw new Error("no tool call snapshot");if(!s.type)throw new Error("tool call snapshot missing `type`");if(s.type==="function"){let o=k(this,bs,"f")?.tools?.find(a=>Pd(a)&&a.function.name===s.function.name);this._emit("tool_calls.function.arguments.done",{name:s.function.name,index:n,arguments:s.function.arguments,parsed_arguments:Da(o)?o.$parseRaw(s.function.arguments):o?.function.strict?JSON.parse(s.function.arguments):null})}else s.type},OE=function(r){let n=k(this,jt,"m",a_).call(this,r);if(r.message.content&&!n.content_done){n.content_done=!0;let i=k(this,jt,"m",$E).call(this);this._emit("content.done",{content:r.message.content,parsed:i?i.$parseRaw(r.message.content):null})}r.message.refusal&&!n.refusal_done&&(n.refusal_done=!0,this._emit("refusal.done",{refusal:r.message.refusal})),r.logprobs?.content&&!n.logprobs_content_done&&(n.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:r.logprobs.content})),r.logprobs?.refusal&&!n.logprobs_refusal_done&&(n.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:r.logprobs.refusal}))},c_=function(){if(this.ended)throw new q("stream has ended, this shouldn't happen");let r=k(this,go,"f");if(!r)throw new q("request ended without sending any chunks");return se(this,go,void 0,"f"),se(this,Tu,[],"f"),W5(r,k(this,bs,"f"))},$E=function(){let r=k(this,bs,"f")?.response_format;return Nd(r)?r:null},Jj=function(r){var n,i,s,o;let a=k(this,go,"f"),{choices:c,...u}=r;a?Object.assign(a,u):a=se(this,go,{...u,choices:[]},"f");for(let{delta:l,finish_reason:p,index:f,logprobs:d=null,...m}of r.choices){let h=a.choices[f];if(h||(h=a.choices[f]={finish_reason:p,index:f,message:{},logprobs:d,...m}),d)if(!h.logprobs)h.logprobs=Object.assign({},d);else{let{content:j,refusal:O,...w}=d;Object.assign(h.logprobs,w),j&&((n=h.logprobs).content??(n.content=[]),h.logprobs.content.push(...j)),O&&((i=h.logprobs).refusal??(i.refusal=[]),h.logprobs.refusal.push(...O))}if(p&&(h.finish_reason=p,k(this,bs,"f")&&gE(k(this,bs,"f")))){if(p==="length")throw new bu;if(p==="content_filter")throw new wu}if(Object.assign(h,m),!l)continue;let{content:b,refusal:_,function_call:y,role:x,tool_calls:I,...A}=l;if(Object.assign(h.message,A),_&&(h.message.refusal=(h.message.refusal||"")+_),x&&(h.message.role=x),y&&(h.message.function_call?(y.name&&(h.message.function_call.name=y.name),y.arguments&&((s=h.message.function_call).arguments??(s.arguments=""),h.message.function_call.arguments+=y.arguments)):h.message.function_call=y),b&&(h.message.content=(h.message.content||"")+b,!h.message.refusal&&k(this,jt,"m",$E).call(this)&&(h.message.parsed=EE(h.message.content))),I){h.message.tool_calls||(h.message.tool_calls=[]);for(let{index:j,id:O,type:w,function:F,...P}of I){let V=(o=h.message.tool_calls)[j]??(o[j]={});Object.assign(V,P),O&&(V.id=O),w&&(V.type=w),F&&(V.function??(V.function={name:F.name??"",arguments:""})),F?.name&&(V.function.name=F.name),F?.arguments&&(V.function.arguments+=F.arguments,Vj(k(this,bs,"f"),V)&&(V.function.parsed_arguments=EE(V.function.arguments)))}}}return a},Symbol.asyncIterator)](){let t=[],r=[],n=!1;return this.on("chunk",i=>{let s=r.shift();s?s.resolve(i):t.push(i)}),this.on("end",()=>{n=!0;for(let i of r)i.resolve(void 0);r.length=0}),this.on("abort",i=>{n=!0;for(let s of r)s.reject(i);r.length=0}),this.on("error",i=>{n=!0;for(let s of r)s.reject(i);r.length=0}),{next:async()=>t.length?{value:t.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((s,o)=>r.push({resolve:s,reject:o})).then(s=>s?{value:s,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new Oi(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function W5(e,t){let{id:r,choices:n,created:i,model:s,system_fingerprint:o,...a}=e,c={...a,id:r,choices:n.map(({message:u,finish_reason:l,index:p,logprobs:f,...d})=>{if(!l)throw new q(`missing finish_reason for choice ${p}`);let{content:m=null,function_call:h,tool_calls:b,..._}=u,y=u.role;if(!y)throw new q(`missing role for choice ${p}`);if(h){let{arguments:x,name:I}=h;if(x==null)throw new q(`missing function_call.arguments for choice ${p}`);if(!I)throw new q(`missing function_call.name for choice ${p}`);return{...d,message:{content:m,function_call:{arguments:x,name:I},role:y,refusal:u.refusal??null},finish_reason:l,index:p,logprobs:f}}return b?{...d,index:p,finish_reason:l,logprobs:f,message:{..._,role:y,content:m,refusal:u.refusal??null,tool_calls:b.map((x,I)=>{let{function:A,type:j,id:O,...w}=x,{arguments:F,name:P,...V}=A||{};if(O==null)throw new q(`missing choices[${p}].tool_calls[${I}].id
|
|
244
|
+
${u_(e)}`);if(j==null)throw new q(`missing choices[${p}].tool_calls[${I}].type
|
|
245
|
+
${u_(e)}`);if(P==null)throw new q(`missing choices[${p}].tool_calls[${I}].function.name
|
|
246
|
+
${u_(e)}`);if(F==null)throw new q(`missing choices[${p}].tool_calls[${I}].function.arguments
|
|
247
|
+
${u_(e)}`);return{...w,id:O,type:j,function:{...V,name:P,arguments:F}}})}}:{...d,message:{..._,content:m,role:y,refusal:u.refusal??null},finish_reason:l,index:p,logprobs:f}}),created:i,model:s,object:"chat.completion",...o?{system_fingerprint:o}:{}};return Bj(c,t)}function u_(e){return JSON.stringify(e)}var Ud=class e extends za{static fromReadableStream(t){let r=new e(null);return r._run(()=>r._fromReadableStream(t)),r}static runTools(t,r,n){let i=new e(r),s={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runTools"}};return i._run(()=>i._runTools(t,r,s)),i}};var ws=class extends N{constructor(){super(...arguments),this.messages=new ja(this._client)}create(t,r){return this._client.post("/chat/completions",{body:t,...r,stream:t.stream??!1})}retrieve(t,r){return this._client.get($`/chat/completions/${t}`,r)}update(t,r,n){return this._client.post($`/chat/completions/${t}`,{body:r,...n})}list(t={},r){return this._client.getAPIList("/chat/completions",Ie,{query:t,...r})}delete(t,r){return this._client.delete($`/chat/completions/${t}`,r)}parse(t,r){return Gj(t.tools),this._client.chat.completions.create(t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(n=>Rd(n,t))}runTools(t,r){return t.stream?Ud.runTools(this._client,t,r):Ld.runTools(this._client,t,r)}stream(t,r){return za.createChatCompletion(this._client,t,r)}};ws.Messages=ja;var _o=class extends N{constructor(){super(...arguments),this.completions=new ws(this._client)}};_o.Completions=ws;var Xj=Symbol("brand.privateNullableHeaders");function*X5(e){if(!e)return;if(Xj in e){let{values:n,nulls:i}=e;yield*n.entries();for(let s of i)yield[s,null];return}let t=!1,r;e instanceof Headers?r=e.entries():XS(e)?r=e:(t=!0,r=Object.entries(e??{}));for(let n of r){let i=n[0];if(typeof i!="string")throw new TypeError("expected header name to be a string");let s=XS(n[1])?n[1]:[n[1]],o=!1;for(let a of s)a!==void 0&&(t&&!o&&(o=!0,yield[i,null]),yield[i,a])}}var U=e=>{let t=new Headers,r=new Set;for(let n of e){let i=new Set;for(let[s,o]of X5(n)){let a=s.toLowerCase();i.has(a)||(t.delete(s),i.add(a)),o===null?(t.delete(s),r.add(a)):(t.append(s,o),r.delete(a))}}return{[Xj]:!0,values:t,nulls:r}};var Ou=class extends N{create(t,r){return this._client.post("/audio/speech",{body:t,...r,headers:U([{Accept:"application/octet-stream"},r?.headers]),__binaryResponse:!0})}};var $u=class extends N{create(t,r){return this._client.post("/audio/transcriptions",Qr({body:t,...r,stream:t.stream??!1,__metadata:{model:t.model}},this._client))}};var Cu=class extends N{create(t,r){return this._client.post("/audio/translations",Qr({body:t,...r,__metadata:{model:t.model}},this._client))}};var Ci=class extends N{constructor(){super(...arguments),this.transcriptions=new $u(this._client),this.translations=new Cu(this._client),this.speech=new Ou(this._client)}};Ci.Transcriptions=$u;Ci.Translations=Cu;Ci.Speech=Ou;var La=class extends N{create(t,r){return this._client.post("/batches",{body:t,...r})}retrieve(t,r){return this._client.get($`/batches/${t}`,r)}list(t={},r){return this._client.getAPIList("/batches",Ie,{query:t,...r})}cancel(t,r){return this._client.post($`/batches/${t}/cancel`,r)}};var Pu=class extends N{create(t,r){return this._client.post("/assistants",{body:t,...r,headers:U([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(t,r){return this._client.get($`/assistants/${t}`,{...r,headers:U([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(t,r,n){return this._client.post($`/assistants/${t}`,{body:r,...n,headers:U([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(t={},r){return this._client.getAPIList("/assistants",Ie,{query:t,...r,headers:U([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(t,r){return this._client.delete($`/assistants/${t}`,{...r,headers:U([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}};var Nu=class extends N{create(t,r){return this._client.post("/realtime/sessions",{body:t,...r,headers:U([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}};var Ru=class extends N{create(t,r){return this._client.post("/realtime/transcription_sessions",{body:t,...r,headers:U([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}};var yo=class extends N{constructor(){super(...arguments),this.sessions=new Nu(this._client),this.transcriptionSessions=new Ru(this._client)}};yo.Sessions=Nu;yo.TranscriptionSessions=Ru;var Mu=class extends N{create(t,r){return this._client.post("/chatkit/sessions",{body:t,...r,headers:U([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers])})}cancel(t,r){return this._client.post($`/chatkit/sessions/${t}/cancel`,{...r,headers:U([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers])})}};var ju=class extends N{retrieve(t,r){return this._client.get($`/chatkit/threads/${t}`,{...r,headers:U([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers])})}list(t={},r){return this._client.getAPIList("/chatkit/threads",ys,{query:t,...r,headers:U([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers])})}delete(t,r){return this._client.delete($`/chatkit/threads/${t}`,{...r,headers:U([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers])})}listItems(t,r={},n){return this._client.getAPIList($`/chatkit/threads/${t}/items`,ys,{query:r,...n,headers:U([{"OpenAI-Beta":"chatkit_beta=v1"},n?.headers])})}};var vo=class extends N{constructor(){super(...arguments),this.sessions=new Mu(this._client),this.threads=new ju(this._client)}};vo.Sessions=Mu;vo.Threads=ju;var Du=class extends N{create(t,r,n){return this._client.post($`/threads/${t}/messages`,{body:r,...n,headers:U([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}retrieve(t,r,n){let{thread_id:i}=r;return this._client.get($`/threads/${i}/messages/${t}`,{...n,headers:U([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}update(t,r,n){let{thread_id:i,...s}=r;return this._client.post($`/threads/${i}/messages/${t}`,{body:s,...n,headers:U([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(t,r={},n){return this._client.getAPIList($`/threads/${t}/messages`,Ie,{query:r,...n,headers:U([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}delete(t,r,n){let{thread_id:i}=r;return this._client.delete($`/threads/${i}/messages/${t}`,{...n,headers:U([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}};var zu=class extends N{retrieve(t,r,n){let{thread_id:i,run_id:s,...o}=r;return this._client.get($`/threads/${i}/runs/${s}/steps/${t}`,{query:o,...n,headers:U([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(t,r,n){let{thread_id:i,...s}=r;return this._client.getAPIList($`/threads/${i}/runs/${t}/steps`,Ie,{query:s,...n,headers:U([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}};var Yj=e=>{if(typeof Buffer<"u"){let t=Buffer.from(e,"base64");return Array.from(new Float32Array(t.buffer,t.byteOffset,t.length/Float32Array.BYTES_PER_ELEMENT))}else{let t=atob(e),r=t.length,n=new Uint8Array(r);for(let i=0;i<r;i++)n[i]=t.charCodeAt(i);return Array.from(new Float32Array(n.buffer))}};var Jn=e=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[e]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(e)?.trim()};var Kt,Fa,CE,Pi,l_,Xn,Ba,Lu,Ua,f_,en,p_,d_,Vd,Fd,Bd,Qj,eD,tD,rD,nD,iD,sD,xs=class extends ho{constructor(){super(...arguments),Kt.add(this),CE.set(this,[]),Pi.set(this,{}),l_.set(this,{}),Xn.set(this,void 0),Ba.set(this,void 0),Lu.set(this,void 0),Ua.set(this,void 0),f_.set(this,void 0),en.set(this,void 0),p_.set(this,void 0),d_.set(this,void 0),Vd.set(this,void 0)}[(CE=new WeakMap,Pi=new WeakMap,l_=new WeakMap,Xn=new WeakMap,Ba=new WeakMap,Lu=new WeakMap,Ua=new WeakMap,f_=new WeakMap,en=new WeakMap,p_=new WeakMap,d_=new WeakMap,Vd=new WeakMap,Kt=new WeakSet,Symbol.asyncIterator)](){let t=[],r=[],n=!1;return this.on("event",i=>{let s=r.shift();s?s.resolve(i):t.push(i)}),this.on("end",()=>{n=!0;for(let i of r)i.resolve(void 0);r.length=0}),this.on("abort",i=>{n=!0;for(let s of r)s.reject(i);r.length=0}),this.on("error",i=>{n=!0;for(let s of r)s.reject(i);r.length=0}),{next:async()=>t.length?{value:t.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((s,o)=>r.push({resolve:s,reject:o})).then(s=>s?{value:s,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(t){let r=new Fa;return r._run(()=>r._fromReadableStream(t)),r}async _fromReadableStream(t,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),this._connected();let i=Oi.fromReadableStream(t,this.controller);for await(let s of i)k(this,Kt,"m",Fd).call(this,s);if(i.controller.signal?.aborted)throw new yt;return this._addRun(k(this,Kt,"m",Bd).call(this))}toReadableStream(){return new Oi(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(t,r,n,i){let s=new Fa;return s._run(()=>s._runToolAssistantStream(t,r,n,{...i,headers:{...i?.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createToolAssistantStream(t,r,n,i){let s=i?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort()));let o={...n,stream:!0},a=await t.submitToolOutputs(r,o,{...i,signal:this.controller.signal});this._connected();for await(let c of a)k(this,Kt,"m",Fd).call(this,c);if(a.controller.signal?.aborted)throw new yt;return this._addRun(k(this,Kt,"m",Bd).call(this))}static createThreadAssistantStream(t,r,n){let i=new Fa;return i._run(()=>i._threadAssistantStream(t,r,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),i}static createAssistantStream(t,r,n,i){let s=new Fa;return s._run(()=>s._runAssistantStream(t,r,n,{...i,headers:{...i?.headers,"X-Stainless-Helper-Method":"stream"}})),s}currentEvent(){return k(this,p_,"f")}currentRun(){return k(this,d_,"f")}currentMessageSnapshot(){return k(this,Xn,"f")}currentRunStepSnapshot(){return k(this,Vd,"f")}async finalRunSteps(){return await this.done(),Object.values(k(this,Pi,"f"))}async finalMessages(){return await this.done(),Object.values(k(this,l_,"f"))}async finalRun(){if(await this.done(),!k(this,Ba,"f"))throw Error("Final run was not received.");return k(this,Ba,"f")}async _createThreadAssistantStream(t,r,n){let i=n?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort()));let s={...r,stream:!0},o=await t.createAndRun(s,{...n,signal:this.controller.signal});this._connected();for await(let a of o)k(this,Kt,"m",Fd).call(this,a);if(o.controller.signal?.aborted)throw new yt;return this._addRun(k(this,Kt,"m",Bd).call(this))}async _createAssistantStream(t,r,n,i){let s=i?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort()));let o={...n,stream:!0},a=await t.create(r,o,{...i,signal:this.controller.signal});this._connected();for await(let c of a)k(this,Kt,"m",Fd).call(this,c);if(a.controller.signal?.aborted)throw new yt;return this._addRun(k(this,Kt,"m",Bd).call(this))}static accumulateDelta(t,r){for(let[n,i]of Object.entries(r)){if(!t.hasOwnProperty(n)){t[n]=i;continue}let s=t[n];if(s==null){t[n]=i;continue}if(n==="index"||n==="type"){t[n]=i;continue}if(typeof s=="string"&&typeof i=="string")s+=i;else if(typeof s=="number"&&typeof i=="number")s+=i;else if(xu(s)&&xu(i))s=this.accumulateDelta(s,i);else if(Array.isArray(s)&&Array.isArray(i)){if(s.every(o=>typeof o=="string"||typeof o=="number")){s.push(...i);continue}for(let o of i){if(!xu(o))throw new Error(`Expected array delta entry to be an object but got: ${o}`);let a=o.index;if(a==null)throw console.error(o),new Error("Expected array delta entry to have an `index` property");if(typeof a!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${a}`);let c=s[a];c==null?s.push(o):s[a]=this.accumulateDelta(c,o)}continue}else throw Error(`Unhandled record type: ${n}, deltaValue: ${i}, accValue: ${s}`);t[n]=s}return t}_addRun(t){return t}async _threadAssistantStream(t,r,n){return await this._createThreadAssistantStream(r,t,n)}async _runAssistantStream(t,r,n,i){return await this._createAssistantStream(r,t,n,i)}async _runToolAssistantStream(t,r,n,i){return await this._createToolAssistantStream(r,t,n,i)}};Fa=xs,Fd=function(t){if(!this.ended)switch(se(this,p_,t,"f"),k(this,Kt,"m",tD).call(this,t),t.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":k(this,Kt,"m",sD).call(this,t);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":k(this,Kt,"m",eD).call(this,t);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":k(this,Kt,"m",Qj).call(this,t);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:}},Bd=function(){if(this.ended)throw new q("stream has ended, this shouldn't happen");if(!k(this,Ba,"f"))throw Error("Final run has not been received");return k(this,Ba,"f")},Qj=function(t){let[r,n]=k(this,Kt,"m",nD).call(this,t,k(this,Xn,"f"));se(this,Xn,r,"f"),k(this,l_,"f")[r.id]=r;for(let i of n){let s=r.content[i.index];s?.type=="text"&&this._emit("textCreated",s.text)}switch(t.event){case"thread.message.created":this._emit("messageCreated",t.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",t.data.delta,r),t.data.delta.content)for(let i of t.data.delta.content){if(i.type=="text"&&i.text){let s=i.text,o=r.content[i.index];if(o&&o.type=="text")this._emit("textDelta",s,o.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(i.index!=k(this,Lu,"f")){if(k(this,Ua,"f"))switch(k(this,Ua,"f").type){case"text":this._emit("textDone",k(this,Ua,"f").text,k(this,Xn,"f"));break;case"image_file":this._emit("imageFileDone",k(this,Ua,"f").image_file,k(this,Xn,"f"));break}se(this,Lu,i.index,"f")}se(this,Ua,r.content[i.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(k(this,Lu,"f")!==void 0){let i=t.data.content[k(this,Lu,"f")];if(i)switch(i.type){case"image_file":this._emit("imageFileDone",i.image_file,k(this,Xn,"f"));break;case"text":this._emit("textDone",i.text,k(this,Xn,"f"));break}}k(this,Xn,"f")&&this._emit("messageDone",t.data),se(this,Xn,void 0,"f")}},eD=function(t){let r=k(this,Kt,"m",rD).call(this,t);switch(se(this,Vd,r,"f"),t.event){case"thread.run.step.created":this._emit("runStepCreated",t.data);break;case"thread.run.step.delta":let n=t.data.delta;if(n.step_details&&n.step_details.type=="tool_calls"&&n.step_details.tool_calls&&r.step_details.type=="tool_calls")for(let s of n.step_details.tool_calls)s.index==k(this,f_,"f")?this._emit("toolCallDelta",s,r.step_details.tool_calls[s.index]):(k(this,en,"f")&&this._emit("toolCallDone",k(this,en,"f")),se(this,f_,s.index,"f"),se(this,en,r.step_details.tool_calls[s.index],"f"),k(this,en,"f")&&this._emit("toolCallCreated",k(this,en,"f")));this._emit("runStepDelta",t.data.delta,r);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":se(this,Vd,void 0,"f"),t.data.step_details.type=="tool_calls"&&k(this,en,"f")&&(this._emit("toolCallDone",k(this,en,"f")),se(this,en,void 0,"f")),this._emit("runStepDone",t.data,r);break;case"thread.run.step.in_progress":break}},tD=function(t){k(this,CE,"f").push(t),this._emit("event",t)},rD=function(t){switch(t.event){case"thread.run.step.created":return k(this,Pi,"f")[t.data.id]=t.data,t.data;case"thread.run.step.delta":let r=k(this,Pi,"f")[t.data.id];if(!r)throw Error("Received a RunStepDelta before creation of a snapshot");let n=t.data;if(n.delta){let i=Fa.accumulateDelta(r,n.delta);k(this,Pi,"f")[t.data.id]=i}return k(this,Pi,"f")[t.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":k(this,Pi,"f")[t.data.id]=t.data;break}if(k(this,Pi,"f")[t.data.id])return k(this,Pi,"f")[t.data.id];throw new Error("No snapshot available")},nD=function(t,r){let n=[];switch(t.event){case"thread.message.created":return[t.data,n];case"thread.message.delta":if(!r)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let i=t.data;if(i.delta.content)for(let s of i.delta.content)if(s.index in r.content){let o=r.content[s.index];r.content[s.index]=k(this,Kt,"m",iD).call(this,s,o)}else r.content[s.index]=s,n.push(s);return[r,n];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(r)return[r,n];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},iD=function(t,r){return Fa.accumulateDelta(r,t)},sD=function(t){switch(se(this,d_,t.data,"f"),t.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":se(this,Ba,t.data,"f"),k(this,en,"f")&&(this._emit("toolCallDone",k(this,en,"f")),se(this,en,void 0,"f"));break;case"thread.run.cancelling":break}};var Va=class extends N{constructor(){super(...arguments),this.steps=new zu(this._client)}create(t,r,n){let{include:i,...s}=r;return this._client.post($`/threads/${t}/runs`,{query:{include:i},body:s,...n,headers:U([{"OpenAI-Beta":"assistants=v2"},n?.headers]),stream:r.stream??!1})}retrieve(t,r,n){let{thread_id:i}=r;return this._client.get($`/threads/${i}/runs/${t}`,{...n,headers:U([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}update(t,r,n){let{thread_id:i,...s}=r;return this._client.post($`/threads/${i}/runs/${t}`,{body:s,...n,headers:U([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(t,r={},n){return this._client.getAPIList($`/threads/${t}/runs`,Ie,{query:r,...n,headers:U([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}cancel(t,r,n){let{thread_id:i}=r;return this._client.post($`/threads/${i}/runs/${t}/cancel`,{...n,headers:U([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}async createAndPoll(t,r,n){let i=await this.create(t,r,n);return await this.poll(i.id,{thread_id:t},n)}createAndStream(t,r,n){return xs.createAssistantStream(t,this._client.beta.threads.runs,r,n)}async poll(t,r,n){let i=U([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:s,response:o}=await this.retrieve(t,r,{...n,headers:{...n?.headers,...i}}).withResponse();switch(s.status){case"queued":case"in_progress":case"cancelling":let a=5e3;if(n?.pollIntervalMs)a=n.pollIntervalMs;else{let c=o.headers.get("openai-poll-after-ms");if(c){let u=parseInt(c);isNaN(u)||(a=u)}}await Ai(a);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return s}}}stream(t,r,n){return xs.createAssistantStream(t,this._client.beta.threads.runs,r,n)}submitToolOutputs(t,r,n){let{thread_id:i,...s}=r;return this._client.post($`/threads/${i}/runs/${t}/submit_tool_outputs`,{body:s,...n,headers:U([{"OpenAI-Beta":"assistants=v2"},n?.headers]),stream:r.stream??!1})}async submitToolOutputsAndPoll(t,r,n){let i=await this.submitToolOutputs(t,r,n);return await this.poll(i.id,r,n)}submitToolOutputsStream(t,r,n){return xs.createToolAssistantStream(t,this._client.beta.threads.runs,r,n)}};Va.Steps=zu;var bo=class extends N{constructor(){super(...arguments),this.runs=new Va(this._client),this.messages=new Du(this._client)}create(t={},r){return this._client.post("/threads",{body:t,...r,headers:U([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(t,r){return this._client.get($`/threads/${t}`,{...r,headers:U([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(t,r,n){return this._client.post($`/threads/${t}`,{body:r,...n,headers:U([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}delete(t,r){return this._client.delete($`/threads/${t}`,{...r,headers:U([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}createAndRun(t,r){return this._client.post("/threads/runs",{body:t,...r,headers:U([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:t.stream??!1})}async createAndRunPoll(t,r){let n=await this.createAndRun(t,r);return await this.runs.poll(n.id,{thread_id:n.thread_id},r)}createAndRunStream(t,r){return xs.createThreadAssistantStream(t,this._client.beta.threads,r)}};bo.Runs=Va;bo.Messages=Du;var Yn=class extends N{constructor(){super(...arguments),this.realtime=new yo(this._client),this.chatkit=new vo(this._client),this.assistants=new Pu(this._client),this.threads=new bo(this._client)}};Yn.Realtime=yo;Yn.ChatKit=vo;Yn.Assistants=Pu;Yn.Threads=bo;var Za=class extends N{create(t,r){return this._client.post("/completions",{body:t,...r,stream:t.stream??!1})}};var Uu=class extends N{retrieve(t,r,n){let{container_id:i}=r;return this._client.get($`/containers/${i}/files/${t}/content`,{...n,headers:U([{Accept:"application/binary"},n?.headers]),__binaryResponse:!0})}};var Ga=class extends N{constructor(){super(...arguments),this.content=new Uu(this._client)}create(t,r,n){return this._client.post($`/containers/${t}/files`,Qr({body:r,...n},this._client))}retrieve(t,r,n){let{container_id:i}=r;return this._client.get($`/containers/${i}/files/${t}`,n)}list(t,r={},n){return this._client.getAPIList($`/containers/${t}/files`,Ie,{query:r,...n})}delete(t,r,n){let{container_id:i}=r;return this._client.delete($`/containers/${i}/files/${t}`,{...n,headers:U([{Accept:"*/*"},n?.headers])})}};Ga.Content=Uu;var wo=class extends N{constructor(){super(...arguments),this.files=new Ga(this._client)}create(t,r){return this._client.post("/containers",{body:t,...r})}retrieve(t,r){return this._client.get($`/containers/${t}`,r)}list(t={},r){return this._client.getAPIList("/containers",Ie,{query:t,...r})}delete(t,r){return this._client.delete($`/containers/${t}`,{...r,headers:U([{Accept:"*/*"},r?.headers])})}};wo.Files=Ga;var Fu=class extends N{create(t,r,n){let{include:i,...s}=r;return this._client.post($`/conversations/${t}/items`,{query:{include:i},body:s,...n})}retrieve(t,r,n){let{conversation_id:i,...s}=r;return this._client.get($`/conversations/${i}/items/${t}`,{query:s,...n})}list(t,r={},n){return this._client.getAPIList($`/conversations/${t}/items`,ys,{query:r,...n})}delete(t,r,n){let{conversation_id:i}=r;return this._client.delete($`/conversations/${i}/items/${t}`,n)}};var xo=class extends N{constructor(){super(...arguments),this.items=new Fu(this._client)}create(t={},r){return this._client.post("/conversations",{body:t,...r})}retrieve(t,r){return this._client.get($`/conversations/${t}`,r)}update(t,r,n){return this._client.post($`/conversations/${t}`,{body:r,...n})}delete(t,r){return this._client.delete($`/conversations/${t}`,r)}};xo.Items=Fu;var Ka=class extends N{create(t,r){let n=!!t.encoding_format,i=n?t.encoding_format:"base64";n&&It(this._client).debug("embeddings/user defined encoding_format:",t.encoding_format);let s=this._client.post("/embeddings",{body:{...t,encoding_format:i},...r});return n?s:(It(this._client).debug("embeddings/decoding base64 embeddings from base64"),s._thenUnwrap(o=>(o&&o.data&&o.data.forEach(a=>{let c=a.embedding;a.embedding=Yj(c)}),o)))}};var Bu=class extends N{retrieve(t,r,n){let{eval_id:i,run_id:s}=r;return this._client.get($`/evals/${i}/runs/${s}/output_items/${t}`,n)}list(t,r,n){let{eval_id:i,...s}=r;return this._client.getAPIList($`/evals/${i}/runs/${t}/output_items`,Ie,{query:s,...n})}};var qa=class extends N{constructor(){super(...arguments),this.outputItems=new Bu(this._client)}create(t,r,n){return this._client.post($`/evals/${t}/runs`,{body:r,...n})}retrieve(t,r,n){let{eval_id:i}=r;return this._client.get($`/evals/${i}/runs/${t}`,n)}list(t,r={},n){return this._client.getAPIList($`/evals/${t}/runs`,Ie,{query:r,...n})}delete(t,r,n){let{eval_id:i}=r;return this._client.delete($`/evals/${i}/runs/${t}`,n)}cancel(t,r,n){let{eval_id:i}=r;return this._client.post($`/evals/${i}/runs/${t}`,n)}};qa.OutputItems=Bu;var Io=class extends N{constructor(){super(...arguments),this.runs=new qa(this._client)}create(t,r){return this._client.post("/evals",{body:t,...r})}retrieve(t,r){return this._client.get($`/evals/${t}`,r)}update(t,r,n){return this._client.post($`/evals/${t}`,{body:r,...n})}list(t={},r){return this._client.getAPIList("/evals",Ie,{query:t,...r})}delete(t,r){return this._client.delete($`/evals/${t}`,r)}};Io.Runs=qa;var Ha=class extends N{create(t,r){return this._client.post("/files",Qr({body:t,...r},this._client))}retrieve(t,r){return this._client.get($`/files/${t}`,r)}list(t={},r){return this._client.getAPIList("/files",Ie,{query:t,...r})}delete(t,r){return this._client.delete($`/files/${t}`,r)}content(t,r){return this._client.get($`/files/${t}/content`,{...r,headers:U([{Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}async waitForProcessing(t,{pollInterval:r=5e3,maxWait:n=1800*1e3}={}){let i=new Set(["processed","error","deleted"]),s=Date.now(),o=await this.retrieve(t);for(;!o.status||!i.has(o.status);)if(await Ai(r),o=await this.retrieve(t),Date.now()-s>n)throw new Ei({message:`Giving up on waiting for file ${t} to finish processing after ${n} milliseconds.`});return o}};var Vu=class extends N{};var Zu=class extends N{run(t,r){return this._client.post("/fine_tuning/alpha/graders/run",{body:t,...r})}validate(t,r){return this._client.post("/fine_tuning/alpha/graders/validate",{body:t,...r})}};var Wa=class extends N{constructor(){super(...arguments),this.graders=new Zu(this._client)}};Wa.Graders=Zu;var Gu=class extends N{create(t,r,n){return this._client.getAPIList($`/fine_tuning/checkpoints/${t}/permissions`,$i,{body:r,method:"post",...n})}retrieve(t,r={},n){return this._client.get($`/fine_tuning/checkpoints/${t}/permissions`,{query:r,...n})}delete(t,r,n){let{fine_tuned_model_checkpoint:i}=r;return this._client.delete($`/fine_tuning/checkpoints/${i}/permissions/${t}`,n)}};var Ja=class extends N{constructor(){super(...arguments),this.permissions=new Gu(this._client)}};Ja.Permissions=Gu;var Ku=class extends N{list(t,r={},n){return this._client.getAPIList($`/fine_tuning/jobs/${t}/checkpoints`,Ie,{query:r,...n})}};var Xa=class extends N{constructor(){super(...arguments),this.checkpoints=new Ku(this._client)}create(t,r){return this._client.post("/fine_tuning/jobs",{body:t,...r})}retrieve(t,r){return this._client.get($`/fine_tuning/jobs/${t}`,r)}list(t={},r){return this._client.getAPIList("/fine_tuning/jobs",Ie,{query:t,...r})}cancel(t,r){return this._client.post($`/fine_tuning/jobs/${t}/cancel`,r)}listEvents(t,r={},n){return this._client.getAPIList($`/fine_tuning/jobs/${t}/events`,Ie,{query:r,...n})}pause(t,r){return this._client.post($`/fine_tuning/jobs/${t}/pause`,r)}resume(t,r){return this._client.post($`/fine_tuning/jobs/${t}/resume`,r)}};Xa.Checkpoints=Ku;var Qn=class extends N{constructor(){super(...arguments),this.methods=new Vu(this._client),this.jobs=new Xa(this._client),this.checkpoints=new Ja(this._client),this.alpha=new Wa(this._client)}};Qn.Methods=Vu;Qn.Jobs=Xa;Qn.Checkpoints=Ja;Qn.Alpha=Wa;var qu=class extends N{};var So=class extends N{constructor(){super(...arguments),this.graderModels=new qu(this._client)}};So.GraderModels=qu;var Ya=class extends N{createVariation(t,r){return this._client.post("/images/variations",Qr({body:t,...r},this._client))}edit(t,r){return this._client.post("/images/edits",Qr({body:t,...r,stream:t.stream??!1},this._client))}generate(t,r){return this._client.post("/images/generations",{body:t,...r,stream:t.stream??!1})}};var Qa=class extends N{retrieve(t,r){return this._client.get($`/models/${t}`,r)}list(t){return this._client.getAPIList("/models",$i,t)}delete(t,r){return this._client.delete($`/models/${t}`,r)}};var ec=class extends N{create(t,r){return this._client.post("/moderations",{body:t,...r})}};var Hu=class extends N{accept(t,r,n){return this._client.post($`/realtime/calls/${t}/accept`,{body:r,...n,headers:U([{Accept:"*/*"},n?.headers])})}hangup(t,r){return this._client.post($`/realtime/calls/${t}/hangup`,{...r,headers:U([{Accept:"*/*"},r?.headers])})}refer(t,r,n){return this._client.post($`/realtime/calls/${t}/refer`,{body:r,...n,headers:U([{Accept:"*/*"},n?.headers])})}reject(t,r={},n){return this._client.post($`/realtime/calls/${t}/reject`,{body:r,...n,headers:U([{Accept:"*/*"},n?.headers])})}};var Wu=class extends N{create(t,r){return this._client.post("/realtime/client_secrets",{body:t,...r})}};var Is=class extends N{constructor(){super(...arguments),this.clientSecrets=new Wu(this._client),this.calls=new Hu(this._client)}};Is.ClientSecrets=Wu;Is.Calls=Hu;function oD(e,t){return!t||!TK(t)?{...e,output_parsed:null,output:e.output.map(r=>r.type==="function_call"?{...r,parsed_arguments:null}:r.type==="message"?{...r,content:r.content.map(n=>({...n,parsed:null}))}:r)}:PE(e,t)}function PE(e,t){let r=e.output.map(i=>{if(i.type==="function_call")return{...i,parsed_arguments:CK(t,i)};if(i.type==="message"){let s=i.content.map(o=>o.type==="output_text"?{...o,parsed:AK(t,o.text)}:o);return{...i,content:s}}return i}),n=Object.assign({},e,{output:r});return Object.getOwnPropertyDescriptor(e,"output_text")||m_(n),Object.defineProperty(n,"output_parsed",{enumerable:!0,get(){for(let i of n.output)if(i.type==="message"){for(let s of i.content)if(s.type==="output_text"&&s.parsed!==null)return s.parsed}return null}}),n}function AK(e,t){return e.text?.format?.type!=="json_schema"?null:"$parseRaw"in e.text?.format?(e.text?.format).$parseRaw(t):JSON.parse(t)}function TK(e){return!!Nd(e.text?.format)}function OK(e){return e?.$brand==="auto-parseable-tool"}function $K(e,t){return e.find(r=>r.type==="function"&&r.name===t)}function CK(e,t){let r=$K(e.tools??[],t.name);return{...t,...t,parsed_arguments:OK(r)?r.$parseRaw(t.arguments):r?.strict?JSON.parse(t.arguments):null}}function m_(e){let t=[];for(let r of e.output)if(r.type==="message")for(let n of r.content)n.type==="output_text"&&t.push(n.text);e.output_text=t.join("")}var Ju,h_,Eo,g_,aD,cD,uD,lD,__=class e extends ho{constructor(t){super(),Ju.add(this),h_.set(this,void 0),Eo.set(this,void 0),g_.set(this,void 0),se(this,h_,t,"f")}static createResponse(t,r,n){let i=new e(r);return i._run(()=>i._createOrRetrieveResponse(t,r,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),i}async _createOrRetrieveResponse(t,r,n){let i=n?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort())),k(this,Ju,"m",aD).call(this);let s,o=null;"response_id"in r?(s=await t.responses.retrieve(r.response_id,{stream:!0},{...n,signal:this.controller.signal,stream:!0}),o=r.starting_after??null):s=await t.responses.create({...r,stream:!0},{...n,signal:this.controller.signal}),this._connected();for await(let a of s)k(this,Ju,"m",cD).call(this,a,o);if(s.controller.signal?.aborted)throw new yt;return k(this,Ju,"m",uD).call(this)}[(h_=new WeakMap,Eo=new WeakMap,g_=new WeakMap,Ju=new WeakSet,aD=function(){this.ended||se(this,Eo,void 0,"f")},cD=function(r,n){if(this.ended)return;let i=(o,a)=>{(n==null||a.sequence_number>n)&&this._emit(o,a)},s=k(this,Ju,"m",lD).call(this,r);switch(i("event",r),r.type){case"response.output_text.delta":{let o=s.output[r.output_index];if(!o)throw new q(`missing output at index ${r.output_index}`);if(o.type==="message"){let a=o.content[r.content_index];if(!a)throw new q(`missing content at index ${r.content_index}`);if(a.type!=="output_text")throw new q(`expected content to be 'output_text', got ${a.type}`);i("response.output_text.delta",{...r,snapshot:a.text})}break}case"response.function_call_arguments.delta":{let o=s.output[r.output_index];if(!o)throw new q(`missing output at index ${r.output_index}`);o.type==="function_call"&&i("response.function_call_arguments.delta",{...r,snapshot:o.arguments});break}default:i(r.type,r);break}},uD=function(){if(this.ended)throw new q("stream has ended, this shouldn't happen");let r=k(this,Eo,"f");if(!r)throw new q("request ended without sending any events");se(this,Eo,void 0,"f");let n=PK(r,k(this,h_,"f"));return se(this,g_,n,"f"),n},lD=function(r){let n=k(this,Eo,"f");if(!n){if(r.type!=="response.created")throw new q(`When snapshot hasn't been set yet, expected 'response.created' event, got ${r.type}`);return n=se(this,Eo,r.response,"f"),n}switch(r.type){case"response.output_item.added":{n.output.push(r.item);break}case"response.content_part.added":{let i=n.output[r.output_index];if(!i)throw new q(`missing output at index ${r.output_index}`);let s=i.type,o=r.part;s==="message"&&o.type!=="reasoning_text"?i.content.push(o):s==="reasoning"&&o.type==="reasoning_text"&&(i.content||(i.content=[]),i.content.push(o));break}case"response.output_text.delta":{let i=n.output[r.output_index];if(!i)throw new q(`missing output at index ${r.output_index}`);if(i.type==="message"){let s=i.content[r.content_index];if(!s)throw new q(`missing content at index ${r.content_index}`);if(s.type!=="output_text")throw new q(`expected content to be 'output_text', got ${s.type}`);s.text+=r.delta}break}case"response.function_call_arguments.delta":{let i=n.output[r.output_index];if(!i)throw new q(`missing output at index ${r.output_index}`);i.type==="function_call"&&(i.arguments+=r.delta);break}case"response.reasoning_text.delta":{let i=n.output[r.output_index];if(!i)throw new q(`missing output at index ${r.output_index}`);if(i.type==="reasoning"){let s=i.content?.[r.content_index];if(!s)throw new q(`missing content at index ${r.content_index}`);if(s.type!=="reasoning_text")throw new q(`expected content to be 'reasoning_text', got ${s.type}`);s.text+=r.delta}break}case"response.completed":{se(this,Eo,r.response,"f");break}}return n},Symbol.asyncIterator)](){let t=[],r=[],n=!1;return this.on("event",i=>{let s=r.shift();s?s.resolve(i):t.push(i)}),this.on("end",()=>{n=!0;for(let i of r)i.resolve(void 0);r.length=0}),this.on("abort",i=>{n=!0;for(let s of r)s.reject(i);r.length=0}),this.on("error",i=>{n=!0;for(let s of r)s.reject(i);r.length=0}),{next:async()=>t.length?{value:t.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((s,o)=>r.push({resolve:s,reject:o})).then(s=>s?{value:s,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();let t=k(this,g_,"f");if(!t)throw new q("stream ended without producing a ChatCompletion");return t}};function PK(e,t){return oD(e,t)}var Xu=class extends N{list(t,r={},n){return this._client.getAPIList($`/responses/${t}/input_items`,Ie,{query:r,...n})}};var Yu=class extends N{count(t={},r){return this._client.post("/responses/input_tokens",{body:t,...r})}};var Ss=class extends N{constructor(){super(...arguments),this.inputItems=new Xu(this._client),this.inputTokens=new Yu(this._client)}create(t,r){return this._client.post("/responses",{body:t,...r,stream:t.stream??!1})._thenUnwrap(n=>("object"in n&&n.object==="response"&&m_(n),n))}retrieve(t,r={},n){return this._client.get($`/responses/${t}`,{query:r,...n,stream:r?.stream??!1})._thenUnwrap(i=>("object"in i&&i.object==="response"&&m_(i),i))}delete(t,r){return this._client.delete($`/responses/${t}`,{...r,headers:U([{Accept:"*/*"},r?.headers])})}parse(t,r){return this._client.responses.create(t,r)._thenUnwrap(n=>PE(n,t))}stream(t,r){return __.createResponse(this._client,t,r)}cancel(t,r){return this._client.post($`/responses/${t}/cancel`,r)}compact(t,r){return this._client.post("/responses/compact",{body:t,...r})}};Ss.InputItems=Xu;Ss.InputTokens=Yu;var Qu=class extends N{create(t,r,n){return this._client.post($`/uploads/${t}/parts`,Qr({body:r,...n},this._client))}};var ko=class extends N{constructor(){super(...arguments),this.parts=new Qu(this._client)}create(t,r){return this._client.post("/uploads",{body:t,...r})}cancel(t,r){return this._client.post($`/uploads/${t}/cancel`,r)}complete(t,r,n){return this._client.post($`/uploads/${t}/complete`,{body:r,...n})}};ko.Parts=Qu;var pD=async e=>{let t=await Promise.allSettled(e),r=t.filter(i=>i.status==="rejected");if(r.length){for(let i of r)console.error(i.reason);throw new Error(`${r.length} promise(s) failed - see the above errors`)}let n=[];for(let i of t)i.status==="fulfilled"&&n.push(i.value);return n};var el=class extends N{create(t,r,n){return this._client.post($`/vector_stores/${t}/file_batches`,{body:r,...n,headers:U([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}retrieve(t,r,n){let{vector_store_id:i}=r;return this._client.get($`/vector_stores/${i}/file_batches/${t}`,{...n,headers:U([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}cancel(t,r,n){let{vector_store_id:i}=r;return this._client.post($`/vector_stores/${i}/file_batches/${t}/cancel`,{...n,headers:U([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}async createAndPoll(t,r,n){let i=await this.create(t,r);return await this.poll(t,i.id,n)}listFiles(t,r,n){let{vector_store_id:i,...s}=r;return this._client.getAPIList($`/vector_stores/${i}/file_batches/${t}/files`,Ie,{query:s,...n,headers:U([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}async poll(t,r,n){let i=U([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:s,response:o}=await this.retrieve(r,{vector_store_id:t},{...n,headers:i}).withResponse();switch(s.status){case"in_progress":let a=5e3;if(n?.pollIntervalMs)a=n.pollIntervalMs;else{let c=o.headers.get("openai-poll-after-ms");if(c){let u=parseInt(c);isNaN(u)||(a=u)}}await Ai(a);break;case"failed":case"cancelled":case"completed":return s}}}async uploadAndPoll(t,{files:r,fileIds:n=[]},i){if(r==null||r.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let s=i?.maxConcurrency??5,o=Math.min(s,r.length),a=this._client,c=r.values(),u=[...n];async function l(f){for(let d of f){let m=await a.files.create({file:d,purpose:"assistants"},i);u.push(m.id)}}let p=Array(o).fill(c).map(l);return await pD(p),await this.createAndPoll(t,{file_ids:u})}};var tl=class extends N{create(t,r,n){return this._client.post($`/vector_stores/${t}/files`,{body:r,...n,headers:U([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}retrieve(t,r,n){let{vector_store_id:i}=r;return this._client.get($`/vector_stores/${i}/files/${t}`,{...n,headers:U([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}update(t,r,n){let{vector_store_id:i,...s}=r;return this._client.post($`/vector_stores/${i}/files/${t}`,{body:s,...n,headers:U([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(t,r={},n){return this._client.getAPIList($`/vector_stores/${t}/files`,Ie,{query:r,...n,headers:U([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}delete(t,r,n){let{vector_store_id:i}=r;return this._client.delete($`/vector_stores/${i}/files/${t}`,{...n,headers:U([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}async createAndPoll(t,r,n){let i=await this.create(t,r,n);return await this.poll(t,i.id,n)}async poll(t,r,n){let i=U([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let s=await this.retrieve(r,{vector_store_id:t},{...n,headers:i}).withResponse(),o=s.data;switch(o.status){case"in_progress":let a=5e3;if(n?.pollIntervalMs)a=n.pollIntervalMs;else{let c=s.response.headers.get("openai-poll-after-ms");if(c){let u=parseInt(c);isNaN(u)||(a=u)}}await Ai(a);break;case"failed":case"completed":return o}}}async upload(t,r,n){let i=await this._client.files.create({file:r,purpose:"assistants"},n);return this.create(t,{file_id:i.id},n)}async uploadAndPoll(t,r,n){let i=await this.upload(t,r,n);return await this.poll(t,i.id,n)}content(t,r,n){let{vector_store_id:i}=r;return this._client.getAPIList($`/vector_stores/${i}/files/${t}/content`,$i,{...n,headers:U([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}};var Es=class extends N{constructor(){super(...arguments),this.files=new tl(this._client),this.fileBatches=new el(this._client)}create(t,r){return this._client.post("/vector_stores",{body:t,...r,headers:U([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(t,r){return this._client.get($`/vector_stores/${t}`,{...r,headers:U([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(t,r,n){return this._client.post($`/vector_stores/${t}`,{body:r,...n,headers:U([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(t={},r){return this._client.getAPIList("/vector_stores",Ie,{query:t,...r,headers:U([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(t,r){return this._client.delete($`/vector_stores/${t}`,{...r,headers:U([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}search(t,r,n){return this._client.getAPIList($`/vector_stores/${t}/search`,$i,{body:r,method:"post",...n,headers:U([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}};Es.Files=tl;Es.FileBatches=el;var tc=class extends N{create(t,r){return this._client.post("/videos",mE({body:t,...r},this._client))}retrieve(t,r){return this._client.get($`/videos/${t}`,r)}list(t={},r){return this._client.getAPIList("/videos",ys,{query:t,...r})}delete(t,r){return this._client.delete($`/videos/${t}`,r)}downloadContent(t,r={},n){return this._client.get($`/videos/${t}/content`,{query:r,...n,headers:U([{Accept:"application/binary"},n?.headers]),__binaryResponse:!0})}remix(t,r,n){return this._client.post($`/videos/${t}/remix`,mE({body:r,...n},this._client))}};var rl,dD,y_,rc=class extends N{constructor(){super(...arguments),rl.add(this)}async unwrap(t,r,n=this._client.webhookSecret,i=300){return await this.verifySignature(t,r,n,i),JSON.parse(t)}async verifySignature(t,r,n=this._client.webhookSecret,i=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!="function"||typeof crypto.subtle.verify!="function")throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");k(this,rl,"m",dD).call(this,n);let s=U([r]).values,o=k(this,rl,"m",y_).call(this,s,"webhook-signature"),a=k(this,rl,"m",y_).call(this,s,"webhook-timestamp"),c=k(this,rl,"m",y_).call(this,s,"webhook-id"),u=parseInt(a,10);if(isNaN(u))throw new ki("Invalid webhook timestamp format");let l=Math.floor(Date.now()/1e3);if(l-u>i)throw new ki("Webhook timestamp is too old");if(u>l+i)throw new ki("Webhook timestamp is too new");let p=o.split(" ").map(h=>h.startsWith("v1,")?h.substring(3):h),f=n.startsWith("whsec_")?Buffer.from(n.replace("whsec_",""),"base64"):Buffer.from(n,"utf-8"),d=c?`${c}.${a}.${t}`:`${a}.${t}`,m=await crypto.subtle.importKey("raw",f,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let h of p)try{let b=Buffer.from(h,"base64");if(await crypto.subtle.verify("HMAC",m,b,new TextEncoder().encode(d)))return}catch{continue}throw new ki("The given webhook signature does not match the expected signature")}};rl=new WeakSet,dD=function(t){if(typeof t!="string"||t.length===0)throw new Error("The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function")},y_=function(t,r){if(!t)throw new Error("Headers are required");let n=t.get(r);if(n==null)throw new Error(`Missing required header: ${r}`);return n};var NE,RE,v_,fD,le=class{constructor({baseURL:t=Jn("OPENAI_BASE_URL"),apiKey:r=Jn("OPENAI_API_KEY"),organization:n=Jn("OPENAI_ORG_ID")??null,project:i=Jn("OPENAI_PROJECT_ID")??null,webhookSecret:s=Jn("OPENAI_WEBHOOK_SECRET")??null,...o}={}){if(NE.add(this),v_.set(this,void 0),this.completions=new Za(this),this.chat=new _o(this),this.embeddings=new Ka(this),this.files=new Ha(this),this.images=new Ya(this),this.audio=new Ci(this),this.moderations=new ec(this),this.models=new Qa(this),this.fineTuning=new Qn(this),this.graders=new So(this),this.vectorStores=new Es(this),this.webhooks=new rc(this),this.beta=new Yn(this),this.batches=new La(this),this.uploads=new ko(this),this.responses=new Ss(this),this.realtime=new Is(this),this.conversations=new xo(this),this.evals=new Io(this),this.containers=new wo(this),this.videos=new tc(this),r===void 0)throw new q("Missing credentials. Please pass an `apiKey`, or set the `OPENAI_API_KEY` environment variable.");let a={apiKey:r,organization:n,project:i,webhookSecret:s,...o,baseURL:t||"https://api.openai.com/v1"};if(!a.dangerouslyAllowBrowser&&vj())throw new q(`It looks like you're running in a browser-like environment.
|
|
248
|
+
|
|
249
|
+
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
250
|
+
If you understand the risks and have appropriate mitigations in place,
|
|
251
|
+
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
252
|
+
|
|
253
|
+
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
|
|
254
|
+
|
|
255
|
+
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
|
256
|
+
`);this.baseURL=a.baseURL,this.timeout=a.timeout??RE.DEFAULT_TIMEOUT,this.logger=a.logger??console;let c="warn";this.logLevel=c,this.logLevel=cE(a.logLevel,"ClientOptions.logLevel",this)??cE(Jn("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??c,this.fetchOptions=a.fetchOptions,this.maxRetries=a.maxRetries??2,this.fetch=a.fetch??wj(),se(this,v_,Ij,"f"),this._options=a,this.apiKey=typeof r=="string"?r:"Missing Key",this.organization=n,this.project=i,this.webhookSecret=s}withOptions(t){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...t})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:t,nulls:r}){}async authHeaders(t){return U([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(t){return oE(t,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${mo}`}defaultIdempotencyKey(){return`stainless-node-retry-${JS()}`}makeStatusError(t,r,n,i){return Rt.generate(t,r,n,i)}async _callApiKey(){let t=this._options.apiKey;if(typeof t!="function")return!1;let r;try{r=await t()}catch(n){throw n instanceof q?n:new q(`Failed to get token from 'apiKey' function: ${n.message}`,{cause:n})}if(typeof r!="string"||!r)throw new q(`Expected 'apiKey' function argument to return a string but it returned ${r}`);return this.apiKey=r,!0}buildURL(t,r,n){let i=!k(this,NE,"m",fD).call(this)&&n||this.baseURL,s=pj(t)?new URL(t):new URL(i+(i.endsWith("/")&&t.startsWith("/")?t.slice(1):t)),o=this.defaultQuery();return dj(o)||(r={...o,...r}),typeof r=="object"&&r&&!Array.isArray(r)&&(s.search=this.stringifyQuery(r)),s.toString()}async prepareOptions(t){await this._callApiKey()}async prepareRequest(t,{url:r,options:n}){}get(t,r){return this.methodRequest("get",t,r)}post(t,r){return this.methodRequest("post",t,r)}patch(t,r){return this.methodRequest("patch",t,r)}put(t,r){return this.methodRequest("put",t,r)}delete(t,r){return this.methodRequest("delete",t,r)}methodRequest(t,r,n){return this.request(Promise.resolve(n).then(i=>({method:t,path:r,...i})))}request(t,r=null){return new Ma(this,this.makeRequest(t,r,void 0))}async makeRequest(t,r,n){let i=await t,s=i.maxRetries??this.maxRetries;r==null&&(r=s),await this.prepareOptions(i);let{req:o,url:a,timeout:c}=await this.buildRequest(i,{retryCount:s-r});await this.prepareRequest(o,{url:a,options:i});let u="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),l=n===void 0?"":`, retryOf: ${n}`,p=Date.now();if(It(this).debug(`[${u}] sending request`,_s({retryOfRequestLogID:n,method:i.method,url:a,options:i,headers:o.headers})),i.signal?.aborted)throw new yt;let f=new AbortController,d=await this.fetchWithTimeout(a,o,c,f).catch(Sd),m=Date.now();if(d instanceof globalThis.Error){let _=`retrying, ${r} attempts remaining`;if(i.signal?.aborted)throw new yt;let y=Id(d)||/timed? ?out/i.test(String(d)+("cause"in d?String(d.cause):""));if(r)return It(this).info(`[${u}] connection ${y?"timed out":"failed"} - ${_}`),It(this).debug(`[${u}] connection ${y?"timed out":"failed"} (${_})`,_s({retryOfRequestLogID:n,url:a,durationMs:m-p,message:d.message})),this.retryRequest(i,r,n??u);throw It(this).info(`[${u}] connection ${y?"timed out":"failed"} - error; no more retries left`),It(this).debug(`[${u}] connection ${y?"timed out":"failed"} (error; no more retries left)`,_s({retryOfRequestLogID:n,url:a,durationMs:m-p,message:d.message})),y?new Ei:new fo({cause:d})}let h=[...d.headers.entries()].filter(([_])=>_==="x-request-id").map(([_,y])=>", "+_+": "+JSON.stringify(y)).join(""),b=`[${u}${l}${h}] ${o.method} ${a} ${d.ok?"succeeded":"failed"} with status ${d.status} in ${m-p}ms`;if(!d.ok){let _=await this.shouldRetry(d);if(r&&_){let O=`retrying, ${r} attempts remaining`;return await xj(d.body),It(this).info(`${b} - ${O}`),It(this).debug(`[${u}] response error (${O})`,_s({retryOfRequestLogID:n,url:d.url,status:d.status,headers:d.headers,durationMs:m-p})),this.retryRequest(i,r,n??u,d.headers)}let y=_?"error; no more retries left":"error; not retryable";It(this).info(`${b} - ${y}`);let x=await d.text().catch(O=>Sd(O).message),I=hj(x),A=I?void 0:x;throw It(this).debug(`[${u}] response error (${y})`,_s({retryOfRequestLogID:n,url:d.url,status:d.status,headers:d.headers,message:A,durationMs:Date.now()-p})),this.makeStatusError(d.status,I,A,d.headers)}return It(this).info(b),It(this).debug(`[${u}] response start`,_s({retryOfRequestLogID:n,url:d.url,status:d.status,headers:d.headers,durationMs:m-p})),{response:d,options:i,controller:f,requestLogID:u,retryOfRequestLogID:n,startTime:p}}getAPIList(t,r,n){return this.requestAPIList(r,{method:"get",path:t,...n})}requestAPIList(t,r){let n=this.makeRequest(r,null,void 0);return new Od(this,n,t)}async fetchWithTimeout(t,r,n,i){let{signal:s,method:o,...a}=r||{};s&&s.addEventListener("abort",()=>i.abort());let c=setTimeout(()=>i.abort(),n),u=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||typeof a.body=="object"&&a.body!==null&&Symbol.asyncIterator in a.body,l={signal:i.signal,...u?{duplex:"half"}:{},method:"GET",...a};o&&(l.method=o.toUpperCase());try{return await this.fetch.call(void 0,t,l)}finally{clearTimeout(c)}}async shouldRetry(t){let r=t.headers.get("x-should-retry");return r==="true"?!0:r==="false"?!1:t.status===408||t.status===409||t.status===429||t.status>=500}async retryRequest(t,r,n,i){let s,o=i?.get("retry-after-ms");if(o){let c=parseFloat(o);Number.isNaN(c)||(s=c)}let a=i?.get("retry-after");if(a&&!s){let c=parseFloat(a);Number.isNaN(c)?s=Date.parse(a)-Date.now():s=c*1e3}if(!(s&&0<=s&&s<60*1e3)){let c=t.maxRetries??this.maxRetries;s=this.calculateDefaultRetryTimeoutMillis(r,c)}return await Ai(s),this.makeRequest(t,r-1,n)}calculateDefaultRetryTimeoutMillis(t,r){let s=r-t,o=Math.min(.5*Math.pow(2,s),8),a=1-Math.random()*.25;return o*a*1e3}async buildRequest(t,{retryCount:r=0}={}){let n={...t},{method:i,path:s,query:o,defaultBaseURL:a}=n,c=this.buildURL(s,o,a);"timeout"in n&&mj("timeout",n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:u,body:l}=this.buildBody({options:n}),p=await this.buildHeaders({options:t,method:i,bodyHeaders:u,retryCount:r});return{req:{method:i,headers:p,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&l instanceof globalThis.ReadableStream&&{duplex:"half"},...l&&{body:l},...this.fetchOptions??{},...n.fetchOptions??{}},url:c,timeout:n.timeout}}async buildHeaders({options:t,method:r,bodyHeaders:n,retryCount:i}){let s={};this.idempotencyHeader&&r!=="get"&&(t.idempotencyKey||(t.idempotencyKey=this.defaultIdempotencyKey()),s[this.idempotencyHeader]=t.idempotencyKey);let o=U([s,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(i),...t.timeout?{"X-Stainless-Timeout":String(Math.trunc(t.timeout/1e3))}:{},...bj(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(t),this._options.defaultHeaders,n,t.headers]);return this.validateHeaders(o),o.values}buildBody({options:{body:t,headers:r}}){if(!t)return{bodyHeaders:void 0,body:void 0};let n=U([r]);return ArrayBuffer.isView(t)||t instanceof ArrayBuffer||t instanceof DataView||typeof t=="string"&&n.values.has("content-type")||globalThis.Blob&&t instanceof globalThis.Blob||t instanceof FormData||t instanceof URLSearchParams||globalThis.ReadableStream&&t instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:t}:typeof t=="object"&&(Symbol.asyncIterator in t||Symbol.iterator in t&&"next"in t&&typeof t.next=="function")?{bodyHeaders:void 0,body:Kg(t)}:k(this,v_,"f").call(this,{body:t,headers:n})}};RE=le,v_=new WeakMap,NE=new WeakSet,fD=function(){return this.baseURL!=="https://api.openai.com/v1"};le.OpenAI=RE;le.DEFAULT_TIMEOUT=6e5;le.OpenAIError=q;le.APIError=Rt;le.APIConnectionError=fo;le.APIConnectionTimeoutError=Ei;le.APIUserAbortError=yt;le.NotFoundError=hu;le.ConflictError=gu;le.RateLimitError=yu;le.BadRequestError=du;le.AuthenticationError=fu;le.InternalServerError=vu;le.PermissionDeniedError=mu;le.UnprocessableEntityError=_u;le.InvalidWebhookSignatureError=ki;le.toFile=Cd;le.Completions=Za;le.Chat=_o;le.Embeddings=Ka;le.Files=Ha;le.Images=Ya;le.Audio=Ci;le.Moderations=ec;le.Models=Qa;le.FineTuning=Qn;le.Graders=So;le.VectorStores=Es;le.Webhooks=rc;le.Beta=Yn;le.Batches=La;le.Uploads=ko;le.Responses=Ss;le.Realtime=Is;le.Conversations=xo;le.Evals=Io;le.Containers=wo;le.Videos=tc;var Ao=class extends le{constructor({baseURL:t=Jn("OPENAI_BASE_URL"),apiKey:r=Jn("AZURE_OPENAI_API_KEY"),apiVersion:n=Jn("OPENAI_API_VERSION"),endpoint:i,deployment:s,azureADTokenProvider:o,dangerouslyAllowBrowser:a,...c}={}){if(!n)throw new q("The OPENAI_API_VERSION environment variable is missing or empty; either provide it, or instantiate the AzureOpenAI client with an apiVersion option, like new AzureOpenAI({ apiVersion: 'My API Version' }).");if(typeof o=="function"&&(a=!0),!o&&!r)throw new q("Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.");if(o&&r)throw new q("The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.");if(c.defaultQuery={...c.defaultQuery,"api-version":n},t){if(i)throw new q("baseURL and endpoint are mutually exclusive")}else{if(i||(i=process.env.AZURE_OPENAI_ENDPOINT),!i)throw new q("Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable");t=`${i}/openai`}super({apiKey:o??r,baseURL:t,...c,...a!==void 0?{dangerouslyAllowBrowser:a}:{}}),this.apiVersion="",this.apiVersion=n,this.deploymentName=s}async buildRequest(t,r={}){if(LK.has(t.path)&&t.method==="post"&&t.body!==void 0){if(!xu(t.body))throw new Error("Expected request body to be an object");let n=this.deploymentName||t.body.model||t.__metadata?.model;n!==void 0&&!this.baseURL.includes("/deployments")&&(t.path=`/deployments/${n}${t.path}`)}return super.buildRequest(t,r)}async authHeaders(t){return typeof this._options.apiKey=="string"?U([{"api-key":this.apiKey}]):super.authHeaders(t)}},LK=new Set(["/completions","/chat/completions","/embeddings","/audio/transcriptions","/audio/translations","/audio/speech","/images/generations","/batches","/images/edits"]);function xn(e){if(!e||typeof e!="object")return e;let t;return e.constructor.name===Ei.name&&"message"in e&&typeof e.message=="string"?(t=new Error(e.message),t.name="TimeoutError"):e.constructor.name===yt.name&&"message"in e&&typeof e.message=="string"?(t=new Error(e.message),t.name="AbortError"):"status"in e&&e.status===400&&"message"in e&&typeof e.message=="string"&&e.message.includes("tool_calls")?t=xd(e,"INVALID_TOOL_RESULTS"):"status"in e&&e.status===401?t=xd(e,"MODEL_AUTHENTICATION"):"status"in e&&e.status===429?t=xd(e,"MODEL_RATE_LIMIT"):"status"in e&&e.status===404?t=xd(e,"MODEL_NOT_FOUND"):t=e,t}var ks=e=>e();function As(e){return e?!!(/^o\d/.test(e??"")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-chat")):!1}function UK(e){return e.role!=="system"&&e.role!=="developer"&&e.role!=="assistant"&&e.role!=="user"&&e.role!=="function"&&e.role!=="tool"&&console.warn(`Unknown message role: ${e.role}`),e.role}function nl(e){let t=e.metadata?.filename??e.metadata?.name??e.metadata?.title;if(!t)throw new Error("a filename or name or title is needed via meta-data for OpenAI when working with multimodal blocks");return t}function Ts(e){let t=e._getType();switch(t){case"system":return"system";case"ai":return"assistant";case"human":return"user";case"function":return"function";case"tool":return"tool";case"generic":if(!mr.isInstance(e))throw new Error("Invalid generic chat message");return UK(e);default:throw new Error(`Unknown message type: ${t}`)}}function mD(e){return e.includes("gpt-5.2-pro")}function ei(e){let{azureOpenAIApiDeploymentName:t,azureOpenAIApiInstanceName:r,azureOpenAIApiKey:n,azureOpenAIBasePath:i,baseURL:s,azureADTokenProvider:o,azureOpenAIEndpoint:a}=e;if((n||o)&&i&&t)return`${i}/${t}`;if((n||o)&&a&&t)return`${a}/openai/deployments/${t}`;if(n||o){if(!r)throw new Error("azureOpenAIApiInstanceName is required when using azureOpenAIApiKey");if(!t)throw new Error("azureOpenAIApiDeploymentName is a required parameter when using azureOpenAIApiKey");return`https://${r}.openai.azure.com/openai/deployments/${t}`}return s}function ME(e){return typeof Headers<"u"&&e!==null&&typeof e=="object"&&Object.prototype.toString.call(e)==="[object Headers]"}function hD(e){let t=ks(()=>{if(ME(e))return e;if(Array.isArray(e))return new Headers(e);if(typeof e=="object"&&e!==null&&"values"in e&&ME(e.values))return e.values;if(typeof e=="object"&&e!==null){let r=Object.entries(e).filter(([,n])=>typeof n=="string").map(([n,i])=>[n,i]);return new Headers(r)}return new Headers});return Object.fromEntries(t.entries())}function gD(){let e=pf();return(e==="node"||e==="deno")&&(e=`(${e}/${process.version}; ${process.platform}; ${process.arch})`),e}function ti(e,t=!1,r="1.0.0"){let n=hD(e),i=gD(),s=`langchainjs${t?"-azure":""}-openai`;return{...n,"User-Agent":n["User-Agent"]?`${s}/${r} (${i})${n["User-Agent"]}`:`${s}/${r} (${i})`}}function _D(e,t){let r;return Sa(e)?r=aS(e):r=e,t?.strict!==void 0&&(r.function.strict=t.strict),r}function FK(e){return e.anyOf!==void 0&&Array.isArray(e.anyOf)}function yD(e){let t=["namespace functions {",""];for(let r of e)r.description&&t.push(`// ${r.description}`),Object.keys(r.parameters.properties??{}).length>0?(t.push(`type ${r.name} = (_: {`),t.push(vD(r.parameters,0)),t.push("}) => any;")):t.push(`type ${r.name} = () => any;`),t.push("");return t.push("} // namespace functions"),t.join(`
|
|
257
|
+
`)}function vD(e,t){let r=[];for(let[n,i]of Object.entries(e.properties??{}))i.description&&t<2&&r.push(`// ${i.description}`),e.required?.includes(n)?r.push(`${n}: ${b_(i,t)},`):r.push(`${n}?: ${b_(i,t)},`);return r.map(n=>" ".repeat(t)+n).join(`
|
|
258
|
+
`)}function b_(e,t){if(FK(e))return e.anyOf.map(r=>b_(r,t)).join(" | ");switch(e.type){case"string":return e.enum?e.enum.map(r=>`"${r}"`).join(" | "):"string";case"number":return e.enum?e.enum.map(r=>`${r}`).join(" | "):"number";case"integer":return e.enum?e.enum.map(r=>`${r}`).join(" | "):"number";case"boolean":return"boolean";case"null":return"null";case"object":return["{",vD(e,t+2),"}"].join(`
|
|
259
|
+
`);case"array":return e.items?`${b_(e.items,t)}[]`:"any[]";default:return""}}function w_(e){if(e)return e==="any"||e==="required"?"required":e==="auto"?"auto":e==="none"?"none":typeof e=="string"?{type:"function",function:{name:e}}:e}function il(e){return"type"in e&&e.type!=="function"}function bD(e){return typeof e=="object"&&e!==null&&"extras"in e&&typeof e.extras=="object"&&e.extras!==null&&"providerToolDefinition"in e.extras&&typeof e.extras.providerToolDefinition=="object"&&e.extras.providerToolDefinition!==null}function wD(e){return e!=null&&typeof e=="object"&&"type"in e&&e.type!=="function"}function nc(e){return typeof e=="object"&&e!==null&&"metadata"in e&&typeof e.metadata=="object"&&e.metadata!==null&&"customTool"in e.metadata&&typeof e.metadata.customTool=="object"&&e.metadata.customTool!==null}function x_(e){return"type"in e&&e.type==="custom"&&"custom"in e&&typeof e.custom=="object"&&e.custom!==null}function xD(e){if(e.type==="custom_tool_call")return{...e,type:"tool_call",call_id:e.id,id:e.call_id,name:e.name,isCustomTool:!0,args:{input:e.input}}}function ID(e){if(e.type==="computer_call")return{...e,type:"tool_call",call_id:e.id,id:e.call_id,name:"computer_use",isComputerTool:!0,args:{action:e.action}}}function SD(e){return typeof e=="object"&&e!==null&&"type"in e&&e.type==="tool_call"&&"isComputerTool"in e&&e.isComputerTool===!0}function ED(e){return typeof e=="object"&&e!==null&&"type"in e&&e.type==="tool_call"&&"isCustomTool"in e&&e.isCustomTool===!0}function kD(e){let t=()=>{if(e.custom.format){if(e.custom.format.type==="grammar")return{type:"grammar",definition:e.custom.format.grammar.definition,syntax:e.custom.format.grammar.syntax};if(e.custom.format.type==="text")return{type:"text"}}};return{type:"custom",name:e.custom.name,description:e.custom.description,format:t()}}function AD(e){let t=()=>{if(e.format){if(e.format.type==="grammar")return{type:"grammar",grammar:{definition:e.format.definition,syntax:e.format.syntax}};if(e.format.type==="text")return{type:"text"}}};return{type:"custom",custom:{name:e.name,description:e.description,format:t()}}}var OD=Symbol("Let zodToJsonSchema decide on which parser to use"),TD={name:void 0,$refStrategy:"root",effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",nullableStrategy:"from-target",removeAdditionalStrategy:"passthrough",definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},$D=e=>typeof e=="string"?{...TD,basePath:["#"],definitions:{},name:e}:{...TD,basePath:["#"],definitions:{},...e};var Zd=e=>"_def"in e?e._def:e;function CD(e){if(!e)return!0;for(let t in e)return!1;return!0}var PD=e=>{let t=$D(e),r=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,currentPath:r,propertyPath:void 0,seenRefs:new Set,seen:new Map(Object.entries(t.definitions).map(([n,i])=>[Zd(i),{def:Zd(i),path:[...t.basePath,t.definitionPath,n],jsonSchema:void 0}]))}};function jE(e,t,r,n){n?.errorMessages&&r&&(e.errorMessage={...e.errorMessage,[t]:r})}function Ue(e,t,r,n,i){e[t]=r,jE(e,t,n,i)}function ND(){return{}}function RD(e,t){let r={type:"array"};return e.type?._def?.typeName!==T.ZodAny&&(r.items=de(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&Ue(r,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&Ue(r,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(Ue(r,"minItems",e.exactLength.value,e.exactLength.message,t),Ue(r,"maxItems",e.exactLength.value,e.exactLength.message,t)),r}function MD(e,t){let r={type:"integer",format:"int64"};if(!e.checks)return r;for(let n of e.checks)switch(n.kind){case"min":t.target==="jsonSchema7"?n.inclusive?Ue(r,"minimum",n.value,n.message,t):Ue(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),Ue(r,"minimum",n.value,n.message,t));break;case"max":t.target==="jsonSchema7"?n.inclusive?Ue(r,"maximum",n.value,n.message,t):Ue(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),Ue(r,"maximum",n.value,n.message,t));break;case"multipleOf":Ue(r,"multipleOf",n.value,n.message,t);break}return r}function jD(){return{type:"boolean"}}function DD(e,t){return de(e.type._def,t)}var zD=(e,t)=>de(e.innerType._def,t);function DE(e,t,r){let n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((i,s)=>DE(e,t,i))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return BK(e,t)}}var BK=(e,t)=>{let r={type:"integer",format:"unix-time"};if(t.target==="openApi3")return r;for(let n of e.checks)switch(n.kind){case"min":Ue(r,"minimum",n.value,n.message,t);break;case"max":Ue(r,"maximum",n.value,n.message,t);break}return r};function LD(e,t){return{...de(e.innerType._def,t),default:e.defaultValue()}}function UD(e,t,r){return t.effectStrategy==="input"?de(e.schema._def,t,r):{}}function FD(e){return{type:"string",enum:[...e.values]}}var VK=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function BD(e,t){let r=[de(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),de(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(s=>!!s),n=t.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,i=[];return r.forEach(s=>{if(VK(s))i.push(...s.allOf),s.unevaluatedProperties===void 0&&(n=void 0);else{let o=s;if("additionalProperties"in s&&s.additionalProperties===!1){let{additionalProperties:a,...c}=s;o=c}else n=void 0;i.push(o)}}),i.length?{allOf:i,...n}:void 0}function VD(e,t){let r=typeof e.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(e.value)?"array":"object"}:t.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[e.value]}:{type:r==="bigint"?"integer":r,const:e.value}}var zE,ic={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(zE===void 0&&(zE=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),zE),uuid:/^[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}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/};function I_(e,t){let r={type:"string"};function n(i){return t.patternStrategy==="escape"?ZK(i):i}if(e.checks)for(let i of e.checks)switch(i.kind){case"min":Ue(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,i.value):i.value,i.message,t);break;case"max":Ue(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,i.value):i.value,i.message,t);break;case"email":switch(t.emailStrategy){case"format:email":ri(r,"email",i.message,t);break;case"format:idn-email":ri(r,"idn-email",i.message,t);break;case"pattern:zod":ni(r,ic.email,i.message,t);break}break;case"url":ri(r,"uri",i.message,t);break;case"uuid":ri(r,"uuid",i.message,t);break;case"regex":ni(r,i.regex,i.message,t);break;case"cuid":ni(r,ic.cuid,i.message,t);break;case"cuid2":ni(r,ic.cuid2,i.message,t);break;case"startsWith":ni(r,RegExp(`^${n(i.value)}`),i.message,t);break;case"endsWith":ni(r,RegExp(`${n(i.value)}$`),i.message,t);break;case"datetime":ri(r,"date-time",i.message,t);break;case"date":ri(r,"date",i.message,t);break;case"time":ri(r,"time",i.message,t);break;case"duration":ri(r,"duration",i.message,t);break;case"length":Ue(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,i.value):i.value,i.message,t),Ue(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,i.value):i.value,i.message,t);break;case"includes":{ni(r,RegExp(n(i.value)),i.message,t);break}case"ip":{i.version!=="v6"&&ri(r,"ipv4",i.message,t),i.version!=="v4"&&ri(r,"ipv6",i.message,t);break}case"emoji":ni(r,ic.emoji,i.message,t);break;case"ulid":{ni(r,ic.ulid,i.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{ri(r,"binary",i.message,t);break}case"contentEncoding:base64":{Ue(r,"contentEncoding","base64",i.message,t);break}case"pattern:zod":{ni(r,ic.base64,i.message,t);break}}break}case"nanoid":ni(r,ic.nanoid,i.message,t);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}var ZK=e=>Array.from(e).map(t=>/[a-zA-Z0-9]/.test(t)?t:`\\${t}`).join(""),ri=(e,t,r,n)=>{e.format||e.anyOf?.some(i=>i.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&n.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...r&&n.errorMessages&&{errorMessage:{format:r}}})):Ue(e,"format",t,r,n)},ni=(e,t,r,n)=>{e.pattern||e.allOf?.some(i=>i.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&n.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:ZD(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):Ue(e,"pattern",ZD(t,n),r,n)},ZD=(e,t)=>{let r=typeof e=="function"?e():e;if(!t.applyRegexFlags||!r.flags)return r.source;let n={i:r.flags.includes("i"),m:r.flags.includes("m"),s:r.flags.includes("s")},i=n.i?r.source.toLowerCase():r.source,s="",o=!1,a=!1,c=!1;for(let u=0;u<i.length;u++){if(o){s+=i[u],o=!1;continue}if(n.i){if(a){if(i[u].match(/[a-z]/)){c?(s+=i[u],s+=`${i[u-2]}-${i[u]}`.toUpperCase(),c=!1):i[u+1]==="-"&&i[u+2]?.match(/[a-z]/)?(s+=i[u],c=!0):s+=`${i[u]}${i[u].toUpperCase()}`;continue}}else if(i[u].match(/[a-z]/)){s+=`[${i[u]}${i[u].toUpperCase()}]`;continue}}if(n.m){if(i[u]==="^"){s+=`(^|(?<=[\r
|
|
260
|
+
]))`;continue}else if(i[u]==="$"){s+=`($|(?=[\r
|
|
261
|
+
]))`;continue}}if(n.s&&i[u]==="."){s+=a?`${i[u]}\r
|
|
262
|
+
`:`[${i[u]}\r
|
|
263
|
+
]`;continue}s+=i[u],i[u]==="\\"?o=!0:a&&i[u]==="]"?a=!1:!a&&i[u]==="["&&(a=!0)}try{let u=new RegExp(s)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),r.source}return s};function S_(e,t){if(t.target==="openApi3"&&e.keyType?._def.typeName===T.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,i)=>({...n,[i]:de(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",i]})??{}}),{}),additionalProperties:!1};let r={type:"object",additionalProperties:de(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??{}};if(t.target==="openApi3")return r;if(e.keyType?._def.typeName===T.ZodString&&e.keyType._def.checks?.length){let n=Object.entries(I_(e.keyType._def,t)).reduce((i,[s,o])=>s==="type"?i:{...i,[s]:o},{});return{...r,propertyNames:n}}else if(e.keyType?._def.typeName===T.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};return r}function GD(e,t){if(t.mapStrategy==="record")return S_(e,t);let r=de(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||{},n=de(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function KD(e){let t=e.values,n=Object.keys(e.values).filter(s=>typeof t[t[s]]!="number").map(s=>t[s]),i=Array.from(new Set(n.map(s=>typeof s)));return{type:i.length===1?i[0]==="string"?"string":"number":["string","number"],enum:n}}function qD(){return{not:{}}}function HD(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Gd={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function JD(e,t){if(t.target==="openApi3")return WD(e,t);let r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(n=>n._def.typeName in Gd&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((i,s)=>{let o=Gd[s._def.typeName];return o&&!i.includes(o)?[...i,o]:i},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((i,s)=>{let o=typeof s._def.value;switch(o){case"string":case"number":case"boolean":return[...i,o];case"bigint":return[...i,"integer"];case"object":if(s._def.value===null)return[...i,"null"];case"symbol":case"undefined":case"function":default:return i}},[]);if(n.length===r.length){let i=n.filter((s,o,a)=>a.indexOf(s)===o);return{type:i.length>1?i:i[0],enum:r.reduce((s,o)=>s.includes(o._def.value)?s:[...s,o._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,i)=>[...n,...i._def.values.filter(s=>!n.includes(s))],[])};return WD(e,t)}var WD=(e,t)=>{let r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((n,i)=>de(n._def,{...t,currentPath:[...t.currentPath,"anyOf",`${i}`]})).filter(n=>!!n&&(!t.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function XD(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target==="openApi3"||t.nullableStrategy==="property"?{type:Gd[e.innerType._def.typeName],nullable:!0}:{type:[Gd[e.innerType._def.typeName],"null"]};if(t.target==="openApi3"){let n=de(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=de(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function YD(e,t){let r={type:"number"};if(!e.checks)return r;for(let n of e.checks)switch(n.kind){case"int":r.type="integer",jE(r,"type",n.message,t);break;case"min":t.target==="jsonSchema7"?n.inclusive?Ue(r,"minimum",n.value,n.message,t):Ue(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),Ue(r,"minimum",n.value,n.message,t));break;case"max":t.target==="jsonSchema7"?n.inclusive?Ue(r,"maximum",n.value,n.message,t):Ue(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),Ue(r,"maximum",n.value,n.message,t));break;case"multipleOf":Ue(r,"multipleOf",n.value,n.message,t);break}return r}function GK(e,t){return t.removeAdditionalStrategy==="strict"?e.catchall._def.typeName==="ZodNever"?e.unknownKeys!=="strict":de(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??!0:e.catchall._def.typeName==="ZodNever"?e.unknownKeys==="passthrough":de(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??!0}function QD(e,t){let r={type:"object",...Object.entries(e.shape()).reduce((n,[i,s])=>{if(s===void 0||s._def===void 0)return n;let o=[...t.currentPath,"properties",i],a=de(s._def,{...t,currentPath:o,propertyPath:o});if(a===void 0)return n;if(t.openaiStrictMode&&s.isOptional()&&!s.isNullable()&&typeof s._def?.defaultValue>"u")throw new Error(`Zod field at \`${o.join("/")}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);return{properties:{...n.properties,[i]:a},required:s.isOptional()&&!t.openaiStrictMode?n.required:[...n.required,i]}},{properties:{},required:[]}),additionalProperties:GK(e,t)};return r.required.length||delete r.required,r}var ez=(e,t)=>{if(t.propertyPath&&t.currentPath.slice(0,t.propertyPath.length).toString()===t.propertyPath.toString())return de(e.innerType._def,{...t,currentPath:t.currentPath});let r=de(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:{}},r]}:{}};var tz=(e,t)=>{if(t.pipeStrategy==="input")return de(e.in._def,t);if(t.pipeStrategy==="output")return de(e.out._def,t);let r=de(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),n=de(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(i=>i!==void 0)}};function rz(e,t){return de(e.type._def,t)}function nz(e,t){let n={type:"array",uniqueItems:!0,items:de(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&Ue(n,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&Ue(n,"maxItems",e.maxSize.value,e.maxSize.message,t),n}function iz(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((r,n)=>de(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:de(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,n)=>de(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function sz(){return{not:{}}}function oz(){return{}}var az=(e,t)=>de(e.innerType._def,t);function de(e,t,r=!1){let n=t.seen.get(e);if(t.override){let o=t.override?.(e,t,n,r);if(o!==OD)return o}if(n&&!r){let o=KK(n,t);if(o!==void 0)return"$ref"in o&&t.seenRefs.add(o.$ref),o}let i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);let s=HK(e,e.typeName,t,r);return s&&WK(e,t,s),i.jsonSchema=s,s}var KK=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"extract-to-root":let r=e.path.slice(t.basePath.length+1).join("_");return r!==t.name&&t.nameStrategy==="duplicate-ref"&&(t.definitions[r]=e.def),{$ref:[...t.basePath,t.definitionPath,r].join("/")};case"relative":return{$ref:qK(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((n,i)=>t.currentPath[i]===n)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),{}):t.$refStrategy==="seen"?{}:void 0}},qK=(e,t)=>{let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];r++);return[(e.length-r).toString(),...t.slice(r)].join("/")},HK=(e,t,r,n)=>{switch(t){case T.ZodString:return I_(e,r);case T.ZodNumber:return YD(e,r);case T.ZodObject:return QD(e,r);case T.ZodBigInt:return MD(e,r);case T.ZodBoolean:return jD();case T.ZodDate:return DE(e,r);case T.ZodUndefined:return sz();case T.ZodNull:return HD(r);case T.ZodArray:return RD(e,r);case T.ZodUnion:case T.ZodDiscriminatedUnion:return JD(e,r);case T.ZodIntersection:return BD(e,r);case T.ZodTuple:return iz(e,r);case T.ZodRecord:return S_(e,r);case T.ZodLiteral:return VD(e,r);case T.ZodEnum:return FD(e);case T.ZodNativeEnum:return KD(e);case T.ZodNullable:return XD(e,r);case T.ZodOptional:return ez(e,r);case T.ZodMap:return GD(e,r);case T.ZodSet:return nz(e,r);case T.ZodLazy:return de(e.getter()._def,r);case T.ZodPromise:return rz(e,r);case T.ZodNaN:case T.ZodNever:return qD();case T.ZodEffects:return UD(e,r,n);case T.ZodAny:return ND();case T.ZodUnknown:return oz();case T.ZodDefault:return LD(e,r);case T.ZodBranded:return DD(e,r);case T.ZodReadonly:return az(e,r);case T.ZodCatch:return zD(e,r);case T.ZodPipeline:return tz(e,r);case T.ZodFunction:case T.ZodVoid:case T.ZodSymbol:return;default:return(i=>{})(t)}},WK=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r);var LE=(e,t)=>{let r=PD(t),n=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,i=de(e._def,n===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,n]},!1)??{},s=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;s!==void 0&&(i.title=s);let o=(()=>{if(CD(r.definitions))return;let c={},u=new Set;for(let l=0;l<500;l++){let p=Object.entries(r.definitions).filter(([f])=>!u.has(f));if(p.length===0)break;for(let[f,d]of p)c[f]=de(Zd(d),{...r,currentPath:[...r.basePath,r.definitionPath,f]},!0)??{},u.add(f)}return c})(),a=n===void 0?o?{...i,[r.definitionPath]:o}:i:r.nameStrategy==="duplicate-ref"?{...i,...o||r.seenRefs.size?{[r.definitionPath]:{...o,...r.seenRefs.size?{[n]:i}:void 0}}:void 0}:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,n].join("/"),[r.definitionPath]:{...o,[n]:i}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":r.target==="jsonSchema2019-09"&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),a};function cz(e){if(e.type!=="object")throw new Error(`Root schema must have type: 'object' but got type: ${e.type?`'${e.type}'`:"undefined"}`);let t=structuredClone(e);return Os(t,[],t)}function UE(e){if(typeof e=="boolean")return!1;if(e.type==="null")return!0;for(let t of e.oneOf??[])if(UE(t))return!0;for(let t of e.anyOf??[])if(UE(t))return!0;return!1}function Os(e,t,r){if(typeof e=="boolean")throw new TypeError(`Expected object schema but got boolean; path=${t.join("/")}`);if(!sc(e))throw new TypeError(`Expected ${JSON.stringify(e)} to be an object; path=${t.join("/")}`);let n=e.$defs;if(sc(n))for(let[f,d]of Object.entries(n))Os(d,[...t,"$defs",f],r);let i=e.definitions;if(sc(i))for(let[f,d]of Object.entries(i))Os(d,[...t,"definitions",f],r);e.type==="object"&&!("additionalProperties"in e)&&(e.additionalProperties=!1);let o=e.required??[],a=e.properties;if(sc(a)){for(let[f,d]of Object.entries(a))if(!UE(d)&&!o.includes(f))throw new Error(`Zod field at \`${[...t,"properties",f].join("/")}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);e.required=Object.keys(a),e.properties=Object.fromEntries(Object.entries(a).map(([f,d])=>[f,Os(d,[...t,"properties",f],r)]))}let c=e.items;sc(c)&&(e.items=Os(c,[...t,"items"],r));let u=e.anyOf;Array.isArray(u)&&(e.anyOf=u.map((f,d)=>Os(f,[...t,"anyOf",String(d)],r)));let l=e.allOf;if(Array.isArray(l))if(l.length===1){let f=Os(l[0],[...t,"allOf","0"],r);Object.assign(e,f),delete e.allOf}else e.allOf=l.map((f,d)=>Os(f,[...t,"allOf",String(d)],r));e.default===null&&delete e.default;let p=e.$ref;if(p&&XK(e,1)){if(typeof p!="string")throw new TypeError(`Received non-string $ref - ${p}; path=${t.join("/")}`);let f=JK(r,p);if(typeof f=="boolean")throw new Error(`Expected \`$ref: ${p}\` to resolve to an object schema but got boolean`);if(!sc(f))throw new Error(`Expected \`$ref: ${p}\` to resolve to an object but got ${JSON.stringify(f)}`);return Object.assign(e,{...f,...e}),delete e.$ref,Os(e,t,r)}return e}function JK(e,t){if(!t.startsWith("#/"))throw new Error(`Unexpected $ref format ${JSON.stringify(t)}; Does not start with #/`);let r=t.slice(2).split("/"),n=e;for(let i of r){if(!sc(n))throw new Error(`encountered non-object entry while resolving ${t} - ${JSON.stringify(n)}`);let s=n[i];if(s===void 0)throw new Error(`Key ${i} not found while resolving ${t}`);n=s}return n}function sc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function XK(e,t){let r=0;for(let n in e)if(r++,r>t)return!0;return!1}function YK(e,t){return LE(e,{openaiStrictMode:!0,name:t.name,nameStrategy:"duplicate-ref",$refStrategy:"extract-to-root",nullableStrategy:"property"})}function QK(e){return cz(Hs(e,{target:"draft-7"}))}function eq(e){return"_zod"in e}function uz(e,t,r){return Fj({type:"json_schema",json_schema:{...r,name:t,strict:!0,schema:eq(e)?QK(e):YK(e,{name:t})}},n=>e.parse(JSON.parse(n)))}var lz=["jsonSchema","functionCalling","jsonMode"];function pz(e,t){if(typeof t<"u"&&!lz.includes(t))throw new Error(`Invalid method: ${t}. Supported methods are: ${lz.join(", ")}`);let r=!e.startsWith("gpt-3")&&!e.startsWith("gpt-4-")&&e!=="gpt-4";if(r&&!t)return"jsonSchema";if(!r&&t==="jsonSchema")throw new Error(`JSON Schema is not supported for model "${e}". Please use a different method, e.g. "functionCalling" or "jsonMode".`);return t??"functionCalling"}function tq(e,t){let r={...e};return Object.defineProperties(r,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:t,enumerable:!1}}),r}function dz(e,t,r){if(it(e))return uz(e,t,r);if(Je(e))return tq({type:"json_schema",json_schema:{...r,name:t,strict:!0,schema:Ye(e,{cycles:"ref",reused:"ref",override(n){n.jsonSchema.title=t}})}},n=>di(e,JSON.parse(n)));throw new Error("Unsupported schema response format")}function fz(e,t){if(t&&typeof t=="object"&&"images"in t&&Array.isArray(t.images)){let r=t.images.filter(n=>typeof n?.image_url?.url=="string").map(n=>({type:"image",url:n.image_url.url}));return[{type:"text",text:e},...r]}return e}var rq={"gpt-4.1-nano":{maxInputTokens:1047576,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"text-embedding-3-small":{maxInputTokens:8191,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1536,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4":{maxInputTokens:8192,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-pro":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-2024-05-13":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-2024-08-06":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4.1-mini":{maxInputTokens:1047576,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-deep-research":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-3.5-turbo":{maxInputTokens:16385,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!1,imageUrlInputs:!1,pdfToolMessage:!1,imageToolMessage:!1,toolChoice:!0},"text-embedding-3-large":{maxInputTokens:8191,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:3072,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4-turbo":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-preview":{maxInputTokens:128e3,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-mini":{maxInputTokens:2e5,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"codex-mini-latest":{maxInputTokens:2e5,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-nano":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4.1":{maxInputTokens:1047576,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o4-mini":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},o1:{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-mini":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-mini":{maxInputTokens:128e3,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"text-embedding-ada-002":{maxInputTokens:8192,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1536,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-pro":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-2024-11-20":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},o3:{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o4-mini-deep-research":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-chat-latest":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-mini":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-pro":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:272e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0}},mz=rq;var oc=class extends to{temperature;topP;frequencyPenalty;presencePenalty;n;logitBias;model="gpt-3.5-turbo";modelKwargs;stop;stopSequences;user;timeout;streaming=!1;streamUsage=!0;maxTokens;logprobs;topLogprobs;apiKey;organization;__includeRawResponse;client;clientConfig;supportsStrictToolCalling;audio;modalities;reasoning;zdrEnabled;service_tier;promptCacheKey;promptCacheRetention;verbosity;defaultOptions;_llmType(){return"openai"}static lc_name(){return"ChatOpenAI"}get callKeys(){return[...super.callKeys,"options","function_call","functions","tools","tool_choice","promptIndex","response_format","seed","reasoning","service_tier"]}lc_serializable=!0;get lc_secrets(){return{apiKey:"OPENAI_API_KEY",organization:"OPENAI_ORGANIZATION"}}get lc_aliases(){return{apiKey:"openai_api_key",modelName:"model"}}get lc_serializable_keys(){return["configuration","logprobs","topLogprobs","prefixMessages","supportsStrictToolCalling","modalities","audio","temperature","maxTokens","topP","frequencyPenalty","presencePenalty","n","logitBias","user","streaming","streamUsage","model","modelName","modelKwargs","stop","stopSequences","timeout","apiKey","cache","maxConcurrency","maxRetries","verbose","callbacks","tags","metadata","disableStreaming","zdrEnabled","reasoning","promptCacheKey","promptCacheRetention","verbosity"]}getLsParams(e){let t=this.invocationParams(e);return{ls_provider:"openai",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:t.temperature??void 0,ls_max_tokens:t.max_tokens??void 0,ls_stop:e.stop}}_identifyingParams(){return{model_name:this.model,...this.invocationParams(),...this.clientConfig}}identifyingParams(){return this._identifyingParams()}constructor(e){super(e??{});let t=typeof e?.configuration?.apiKey=="string"||typeof e?.configuration?.apiKey=="function"?e?.configuration?.apiKey:void 0;this.apiKey=e?.apiKey??t??Pe("OPENAI_API_KEY"),this.organization=e?.configuration?.organization??Pe("OPENAI_ORGANIZATION"),this.model=e?.model??e?.modelName??this.model,this.modelKwargs=e?.modelKwargs??{},this.timeout=e?.timeout,this.temperature=e?.temperature??this.temperature,this.topP=e?.topP??this.topP,this.frequencyPenalty=e?.frequencyPenalty??this.frequencyPenalty,this.presencePenalty=e?.presencePenalty??this.presencePenalty,this.logprobs=e?.logprobs,this.topLogprobs=e?.topLogprobs,this.n=e?.n??this.n,this.logitBias=e?.logitBias,this.stop=e?.stopSequences??e?.stop,this.stopSequences=this.stop,this.user=e?.user,this.__includeRawResponse=e?.__includeRawResponse,this.audio=e?.audio,this.modalities=e?.modalities,this.reasoning=e?.reasoning,this.maxTokens=e?.maxCompletionTokens??e?.maxTokens,this.promptCacheKey=e?.promptCacheKey??this.promptCacheKey,this.promptCacheRetention=e?.promptCacheRetention??this.promptCacheRetention,this.verbosity=e?.verbosity??this.verbosity,this.disableStreaming=e?.disableStreaming===!0,this.streaming=e?.streaming===!0,this.disableStreaming&&(this.streaming=!1),e?.streaming===!1&&(this.disableStreaming=!0),this.streamUsage=e?.streamUsage??this.streamUsage,this.disableStreaming&&(this.streamUsage=!1),this.clientConfig={apiKey:this.apiKey,organization:this.organization,dangerouslyAllowBrowser:!0,...e?.configuration},e?.supportsStrictToolCalling!==void 0&&(this.supportsStrictToolCalling=e.supportsStrictToolCalling),e?.service_tier!==void 0&&(this.service_tier=e.service_tier),this.zdrEnabled=e?.zdrEnabled??!1}_getReasoningParams(e){if(!As(this.model))return;let t;return this.reasoning!==void 0&&(t={...t,...this.reasoning}),e?.reasoning!==void 0&&(t={...t,...e.reasoning}),t}_getResponseFormat(e){return e&&e.type==="json_schema"&&e.json_schema.schema&&_r(e.json_schema.schema)?dz(e.json_schema.schema,e.json_schema.name,{description:e.json_schema.description}):e}_combineCallOptions(e){return{...this.defaultOptions,...e??{}}}_getClientOptions(e){if(!this.client){let r={baseURL:this.clientConfig.baseURL},n=ei(r),i={...this.clientConfig,baseURL:n,timeout:this.timeout,maxRetries:0};i.baseURL||delete i.baseURL,i.defaultHeaders=ti(i.defaultHeaders),this.client=new le(i)}return{...this.clientConfig,...e}}_convertChatOpenAIToolToCompletionsTool(e,t){return nc(e)?AD(e.metadata.customTool):Rp(e)?t?.strict!==void 0?{...e,function:{...e.function,strict:t.strict}}:e:_D(e,t)}bindTools(e,t){let r;return t?.strict!==void 0?r=t.strict:this.supportsStrictToolCalling!==void 0&&(r=this.supportsStrictToolCalling),this.withConfig({tools:e.map(n=>il(n)||nc(n)?n:bD(n)?n.extras.providerToolDefinition:this._convertChatOpenAIToolToCompletionsTool(n,{strict:r})),...t})}async stream(e,t){return super.stream(e,this._combineCallOptions(t))}async invoke(e,t){return super.invoke(e,this._combineCallOptions(t))}_combineLLMOutput(...e){return e.reduce((t,r)=>(r&&r.tokenUsage&&(t.tokenUsage.completionTokens+=r.tokenUsage.completionTokens??0,t.tokenUsage.promptTokens+=r.tokenUsage.promptTokens??0,t.tokenUsage.totalTokens+=r.tokenUsage.totalTokens??0),t),{tokenUsage:{completionTokens:0,promptTokens:0,totalTokens:0}})}async getNumTokensFromMessages(e){let t=0,r=0,n=0;this.model==="gpt-3.5-turbo-0301"?(r=4,n=-1):(r=3,n=1);let i=await Promise.all(e.map(async s=>{let[o,a]=await Promise.all([this.getNumTokens(s.content),this.getNumTokens(Ts(s))]),c=s.name!==void 0?n+await this.getNumTokens(s.name):0,u=o+r+a+c,l=s;if(l._getType()==="function"&&(u-=2),l.additional_kwargs?.function_call&&(u+=3),l?.additional_kwargs.function_call?.name&&(u+=await this.getNumTokens(l.additional_kwargs.function_call?.name)),l.additional_kwargs.function_call?.arguments)try{u+=await this.getNumTokens(JSON.stringify(JSON.parse(l.additional_kwargs.function_call?.arguments)))}catch(p){console.error("Error parsing function arguments",p,JSON.stringify(l.additional_kwargs.function_call)),u+=await this.getNumTokens(l.additional_kwargs.function_call?.arguments)}return t+=u,u}));return t+=3,{totalCount:t,countPerMessage:i}}async _getNumTokensFromGenerations(e){return(await Promise.all(e.map(async r=>r.message.additional_kwargs?.function_call?(await this.getNumTokensFromMessages([r.message])).countPerMessage[0]:await this.getNumTokens(r.message.content)))).reduce((r,n)=>r+n,0)}async _getEstimatedTokenCountFromPrompt(e,t,r){let n=(await this.getNumTokensFromMessages(e)).totalCount;if(t&&r!=="auto"){let i=yD(t);n+=await this.getNumTokens(i),n+=9}return t&&e.find(i=>i._getType()==="system")&&(n-=4),r==="none"?n+=1:typeof r=="object"&&(n+=await this.getNumTokens(r.name)+4),n}async moderateContent(e,t){let r=this._getClientOptions(t?.options),n=t?.model??"omni-moderation-latest",i={input:e,model:n};return this.caller.call(async()=>{try{return await this.client.moderations.create(i,r)}catch(s){throw xn(s)}})}get profile(){return mz[this.model]??{}}_getStructuredOutputMethod(e){let t={...e};if(!this.model.startsWith("gpt-3")&&!this.model.startsWith("gpt-4-")&&this.model!=="gpt-4"){if(t?.method===void 0)return"jsonSchema"}else t.method==="jsonSchema"&&console.warn(`[WARNING]: JSON Schema is not supported for model "${this.model}". Falling back to tool calling.`);return t.method}withStructuredOutput(e,t){let r,n,{schema:i,name:s,includeRaw:o}={...t,schema:e};if(t?.strict!==void 0&&t.method==="jsonMode")throw new Error("Argument `strict` is only supported for `method` = 'function_calling'");let a=pz(this.model,t?.method);if(a==="jsonMode"){_r(i)?n=qc.fromZodSchema(i):n=new Dp;let p=Ye(i);r=this.withConfig({outputVersion:"v0",response_format:{type:"json_object"},ls_structured_output_format:{kwargs:{method:"json_mode"},schema:{title:s??"extract",...p}}})}else if(a==="jsonSchema"){let p={name:s??"extract",description:$n(i),schema:i,strict:t?.strict},f=Ye(p.schema);if(r=this.withConfig({outputVersion:"v0",response_format:{type:"json_schema",json_schema:p},ls_structured_output_format:{kwargs:{method:"json_schema"},schema:{title:p.name,description:p.description,...f}}}),_r(i)){let d=qc.fromZodSchema(i);n=tr.from(m=>"parsed"in m.additional_kwargs?m.additional_kwargs.parsed:d)}else n=new Dp}else{let p=s??"extract";if(_r(i)){let f=Ye(i);r=this.withConfig({outputVersion:"v0",tools:[{type:"function",function:{name:p,description:f.description,parameters:f}}],tool_choice:{type:"function",function:{name:p}},ls_structured_output_format:{kwargs:{method:"function_calling"},schema:{title:p,...f}},...t?.strict!==void 0?{strict:t.strict}:{}}),n=new zp({returnSingle:!0,keyName:p,zodSchema:i})}else{let f;typeof i.name=="string"&&typeof i.parameters=="object"&&i.parameters!=null?(f=i,p=i.name):(p=i.title??p,f={name:p,description:i.description??"",parameters:i});let d=Ye(i);r=this.withConfig({outputVersion:"v0",tools:[{type:"function",function:f}],tool_choice:{type:"function",function:{name:p}},ls_structured_output_format:{kwargs:{method:"function_calling"},schema:{title:p,...d}},...t?.strict!==void 0?{strict:t.strict}:{}}),n=new zp({returnSingle:!0,keyName:p})}}if(!o)return r.pipe(n);let c=yn.assign({parsed:(p,f)=>n.invoke(p.raw,f)}),u=yn.assign({parsed:()=>null}),l=c.withFallbacks({fallbacks:[u]});return br.from([{raw:r},l])}};var E_={providerName:"ChatOpenAI",fromStandardTextBlock(e){return{type:"text",text:e.text}},fromStandardImageBlock(e){if(e.source_type==="url")return{type:"image_url",image_url:{url:e.url,...e.metadata?.detail?{detail:e.metadata.detail}:{}}};if(e.source_type==="base64")return{type:"image_url",image_url:{url:`data:${e.mime_type??""};base64,${e.data}`,...e.metadata?.detail?{detail:e.metadata.detail}:{}}};throw new Error(`Image content blocks with source_type ${e.source_type} are not supported for ChatOpenAI`)},fromStandardAudioBlock(e){if(e.source_type==="url"){let t=Ns({dataUrl:e.url});if(!t)throw new Error(`URL audio blocks with source_type ${e.source_type} must be formatted as a data URL for ChatOpenAI`);let r=t.mime_type||e.mime_type||"",n;try{n=gl(r)}catch{throw new Error(`Audio blocks with source_type ${e.source_type} must have mime type of audio/wav or audio/mp3`)}if(n.type!=="audio"||n.subtype!=="wav"&&n.subtype!=="mp3")throw new Error(`Audio blocks with source_type ${e.source_type} must have mime type of audio/wav or audio/mp3`);return{type:"input_audio",input_audio:{format:n.subtype,data:t.data}}}if(e.source_type==="base64"){let t;try{t=gl(e.mime_type??"")}catch{throw new Error(`Audio blocks with source_type ${e.source_type} must have mime type of audio/wav or audio/mp3`)}if(t.type!=="audio"||t.subtype!=="wav"&&t.subtype!=="mp3")throw new Error(`Audio blocks with source_type ${e.source_type} must have mime type of audio/wav or audio/mp3`);return{type:"input_audio",input_audio:{format:t.subtype,data:e.data}}}throw new Error(`Audio content blocks with source_type ${e.source_type} are not supported for ChatOpenAI`)},fromStandardFileBlock(e){if(e.source_type==="url"){let t=Ns({dataUrl:e.url}),r=nl(e);if(!t)throw new Error(`URL file blocks with source_type ${e.source_type} must be formatted as a data URL for ChatOpenAI`);return{type:"file",file:{file_data:e.url,...e.metadata?.filename||e.metadata?.name?{filename:r}:{}}}}if(e.source_type==="base64"){let t=nl(e);return{type:"file",file:{file_data:`data:${e.mime_type??""};base64,${e.data}`,...e.metadata?.filename||e.metadata?.name||e.metadata?.title?{filename:t}:{}}}}if(e.source_type==="id")return{type:"file",file:{file_id:e.id}};throw new Error(`File content blocks with source_type ${e.source_type} are not supported for ChatOpenAI`)}},FE=({message:e,rawResponse:t,includeRawResponse:r})=>{let n=e.tool_calls;switch(e.role){case"assistant":{let i=[],s=[];for(let u of n??[])try{i.push(wa(u,{returnId:!0}))}catch(l){s.push(ro(u,l.message))}let o={function_call:e.function_call,tool_calls:n};r!==void 0&&(o.__raw_response=t);let a={model_provider:"openai",model_name:t.model,...t.system_fingerprint?{usage:{...t.usage},system_fingerprint:t.system_fingerprint}:{}};e.audio&&(o.audio=e.audio);let c=fz(e.content||"",t.choices?.[0]?.message);return new Oe({content:c,tool_calls:i,invalid_tool_calls:s,additional_kwargs:o,response_metadata:a,id:t.id})}default:return new mr(e.content||"",e.role??"unknown")}},BE=({delta:e,rawResponse:t,includeRawResponse:r,defaultRole:n})=>{let i=e.role??n,s=e.content??"",o;e.function_call?o={function_call:e.function_call}:e.tool_calls?o={tool_calls:e.tool_calls}:o={},r&&(o.__raw_response=t),e.audio&&(o.audio={...e.audio,index:t.choices[0].index});let a={model_provider:"openai",usage:{...t.usage}};if(i==="user")return new Ki({content:s,response_metadata:a});if(i==="assistant"){let c=[];if(Array.isArray(e.tool_calls))for(let u of e.tool_calls)c.push({name:u.function?.name,args:u.function?.arguments,id:u.id,index:u.index,type:"tool_call_chunk"});return new nt({content:s,tool_call_chunks:c,additional_kwargs:o,id:t.id,response_metadata:a})}else return i==="system"?new un({content:s,response_metadata:a}):i==="developer"?new un({content:s,response_metadata:a,additional_kwargs:{__openai_role__:"developer"}}):i==="function"?new Gi({content:s,additional_kwargs:o,name:e.name,response_metadata:a}):i==="tool"?new Rs({content:s,additional_kwargs:o,tool_call_id:e.tool_call_id,response_metadata:a}):new Zi({content:s,role:i,response_metadata:a})},hz=e=>{if(e.type==="image"){if(e.url)return{type:"image_url",image_url:{url:e.url}};if(e.data)return{type:"image_url",image_url:{url:`data:${e.mimeType};base64,${e.data}`}}}if(e.type==="audio"&&e.data){let t=em(()=>{let[,r]=e.mimeType.split("/");return r==="wav"||r==="mp3"?r:"wav"});return{type:"input_audio",input_audio:{data:e.data.toString(),format:t}}}if(e.type==="file"){if(e.data){let t=nl(e);return{type:"file",file:{file_data:`data:${e.mimeType};base64,${e.data}`,filename:t}}}if(e.fileId)return{type:"file",file:{file_id:e.fileId}}}},gz=({message:e,model:t})=>{let r=Ts(e);if(r==="system"&&As(t)&&(r="developer"),r==="developer")return{role:"developer",content:e.contentBlocks.filter(i=>i.type==="text")};if(r==="system")return{role:"system",content:e.contentBlocks.filter(i=>i.type==="text")};if(r==="assistant")return{role:"assistant",content:e.contentBlocks.filter(i=>i.type==="text")};if(r==="tool"&&Wt.isInstance(e))return{role:"tool",tool_call_id:e.tool_call_id,content:e.contentBlocks.filter(i=>i.type==="text")};if(r==="function")return{role:"function",name:e.name??"",content:e.contentBlocks.filter(i=>i.type==="text").join("")};function*n(i){for(let s of i){s.type==="text"&&(yield{type:"text",text:s.text});let o=hz(s);o&&(yield o)}}return{role:"user",content:Array.from(n(e.contentBlocks))}},Kd=({messages:e,model:t})=>e.flatMap(r=>{if("output_version"in r.response_metadata&&r.response_metadata?.output_version==="v1")return gz({message:r});let n=Ts(r);n==="system"&&As(t)&&(n="developer");let i=typeof r.content=="string"?r.content:r.content.map(o=>Tr(o)?dc(o,E_):o),s={role:n,content:i};if(r.name!=null&&(s.name=r.name),r.additional_kwargs.function_call!=null&&(s.function_call=r.additional_kwargs.function_call),Oe.isInstance(r)&&r.tool_calls?.length?s.tool_calls=r.tool_calls.map(Uh):(r.additional_kwargs.tool_calls!=null&&(s.tool_calls=r.additional_kwargs.tool_calls),Wt.isInstance(r)&&r.tool_call_id!=null&&(s.tool_call_id=r.tool_call_id)),r.additional_kwargs.audio&&typeof r.additional_kwargs.audio=="object"&&"id"in r.additional_kwargs.audio){let o={role:"assistant",audio:{id:r.additional_kwargs.audio.id}};return[s,o]}return s});var qd=class extends oc{invocationParams(e,t){let r;e?.strict!==void 0?r=e.strict:this.supportsStrictToolCalling!==void 0&&(r=this.supportsStrictToolCalling);let n={};e?.stream_options!==void 0?n={stream_options:e.stream_options}:this.streamUsage&&(this.streaming||t?.streaming)&&(n={stream_options:{include_usage:!0}});let i={model:this.model,temperature:this.temperature,top_p:this.topP,frequency_penalty:this.frequencyPenalty,presence_penalty:this.presencePenalty,logprobs:this.logprobs,top_logprobs:this.topLogprobs,n:this.n,logit_bias:this.logitBias,stop:e?.stop??this.stopSequences,user:this.user,stream:this.streaming,functions:e?.functions,function_call:e?.function_call,tools:e?.tools?.length?e.tools.map(o=>this._convertChatOpenAIToolToCompletionsTool(o,{strict:r})):void 0,tool_choice:w_(e?.tool_choice),response_format:this._getResponseFormat(e?.response_format),seed:e?.seed,...n,parallel_tool_calls:e?.parallel_tool_calls,...this.audio||e?.audio?{audio:this.audio||e?.audio}:{},...this.modalities||e?.modalities?{modalities:this.modalities||e?.modalities}:{},...this.modelKwargs,prompt_cache_key:e?.promptCacheKey??this.promptCacheKey,prompt_cache_retention:e?.promptCacheRetention??this.promptCacheRetention,verbosity:e?.verbosity??this.verbosity};e?.prediction!==void 0&&(i.prediction=e.prediction),this.service_tier!==void 0&&(i.service_tier=this.service_tier),e?.service_tier!==void 0&&(i.service_tier=e.service_tier);let s=this._getReasoningParams(e);return s!==void 0&&s.effort!==void 0&&(i.reasoning_effort=s.effort),As(i.model)?i.max_completion_tokens=this.maxTokens===-1?void 0:this.maxTokens:i.max_tokens=this.maxTokens===-1?void 0:this.maxTokens,i}async _generate(e,t,r){let n={},i=this.invocationParams(t),s=Kd({messages:e,model:this.model});if(i.stream){let o=this._streamResponseChunks(e,t,r),a={};for await(let d of o){d.message.response_metadata={...d.generationInfo,...d.message.response_metadata};let m=d.generationInfo?.completion??0;a[m]===void 0?a[m]=d:a[m]=a[m].concat(d)}let c=Object.entries(a).sort(([d],[m])=>parseInt(d,10)-parseInt(m,10)).map(([d,m])=>m),{functions:u,function_call:l}=this.invocationParams(t),p=await this._getEstimatedTokenCountFromPrompt(e,u,l),f=await this._getNumTokensFromGenerations(c);return n.input_tokens=p,n.output_tokens=f,n.total_tokens=p+f,{generations:c,llmOutput:{estimatedTokenUsage:{promptTokens:n.input_tokens,completionTokens:n.output_tokens,totalTokens:n.total_tokens}}}}else{let o=await this.completionWithRetry({...i,stream:!1,messages:s},{signal:t?.signal,...t?.options}),{completion_tokens:a,prompt_tokens:c,total_tokens:u,prompt_tokens_details:l,completion_tokens_details:p}=o?.usage??{};a&&(n.output_tokens=(n.output_tokens??0)+a),c&&(n.input_tokens=(n.input_tokens??0)+c),u&&(n.total_tokens=(n.total_tokens??0)+u),(l?.audio_tokens!==null||l?.cached_tokens!==null)&&(n.input_token_details={...l?.audio_tokens!==null&&{audio:l?.audio_tokens},...l?.cached_tokens!==null&&{cache_read:l?.cached_tokens}}),(p?.audio_tokens!==null||p?.reasoning_tokens!==null)&&(n.output_token_details={...p?.audio_tokens!==null&&{audio:p?.audio_tokens},...p?.reasoning_tokens!==null&&{reasoning:p?.reasoning_tokens}});let f=[];for(let d of o?.choices??[]){let h={text:d.message?.content??"",message:this._convertCompletionsMessageToBaseMessage(d.message??{role:"assistant"},o)};h.generationInfo={...d.finish_reason?{finish_reason:d.finish_reason}:{},...d.logprobs?{logprobs:d.logprobs}:{}},ci(h.message)&&(h.message.usage_metadata=n),h.message=new Oe(Object.fromEntries(Object.entries(h.message).filter(([b])=>!b.startsWith("lc_")))),f.push(h)}return{generations:f,llmOutput:{tokenUsage:{promptTokens:n.input_tokens,completionTokens:n.output_tokens,totalTokens:n.total_tokens}}}}}async*_streamResponseChunks(e,t,r){let n=Kd({messages:e,model:this.model}),i={...this.invocationParams(t,{streaming:!0}),messages:n,stream:!0},s,o=await this.completionWithRetry(i,t),a;for await(let c of o){let u=c?.choices?.[0];if(c.usage&&(a=c.usage),!u)continue;let{delta:l}=u;if(!l)continue;let p=this._convertCompletionsDeltaToBaseMessageChunk(l,c,s);s=l.role??s;let f={prompt:t.promptIndex??0,completion:u.index??0};if(typeof p.content!="string"){console.log("[WARNING]: Received non-string content from OpenAI. This is currently not supported.");continue}let d={...f};u.finish_reason!=null&&(d.finish_reason=u.finish_reason,d.system_fingerprint=c.system_fingerprint,d.model_name=c.model,d.service_tier=c.service_tier),this.logprobs&&(d.logprobs=u.logprobs);let m=new Zr({message:p,text:p.content,generationInfo:d});yield m,await r?.handleLLMNewToken(m.text??"",f,void 0,void 0,void 0,{chunk:m})}if(a){let c={...a.prompt_tokens_details?.audio_tokens!==null&&{audio:a.prompt_tokens_details?.audio_tokens},...a.prompt_tokens_details?.cached_tokens!==null&&{cache_read:a.prompt_tokens_details?.cached_tokens}},u={...a.completion_tokens_details?.audio_tokens!==null&&{audio:a.completion_tokens_details?.audio_tokens},...a.completion_tokens_details?.reasoning_tokens!==null&&{reasoning:a.completion_tokens_details?.reasoning_tokens}};yield new Zr({message:new nt({content:"",response_metadata:{usage:{...a}},usage_metadata:{input_tokens:a.prompt_tokens,output_tokens:a.completion_tokens,total_tokens:a.total_tokens,...Object.keys(c).length>0&&{input_token_details:c},...Object.keys(u).length>0&&{output_token_details:u}}}),text:""})}if(t.signal?.aborted)throw new Error("AbortError")}async completionWithRetry(e,t){let r=this._getClientOptions(t),n=e.response_format&&e.response_format.type==="json_schema";return this.caller.call(async()=>{try{return n&&!e.stream?await this.client.chat.completions.parse(e,r):await this.client.chat.completions.create(e,r)}catch(i){throw xn(i)}})}_convertCompletionsDeltaToBaseMessageChunk(e,t,r){return BE({delta:e,rawResponse:t,includeRawResponse:this.__includeRawResponse,defaultRole:r})}_convertCompletionsMessageToBaseMessage(e,t){return FE({message:e,rawResponse:t,includeRawResponse:this.__includeRawResponse})}};var sl={openAIApiKey:"openai_api_key",openAIApiVersion:"openai_api_version",openAIBasePath:"openai_api_base",deploymentName:"deployment_name",azureOpenAIEndpoint:"azure_endpoint",azureOpenAIApiVersion:"openai_api_version",azureOpenAIBasePath:"openai_api_base",azureOpenAIApiDeploymentName:"deployment_name"},ol={azureOpenAIApiKey:"AZURE_OPENAI_API_KEY"},al=["azureOpenAIApiKey","azureOpenAIApiVersion","azureOpenAIBasePath","azureOpenAIEndpoint","azureOpenAIApiInstanceName","azureOpenAIApiDeploymentName","deploymentName","openAIApiKey","openAIApiVersion"];function cl(e){if(this.azureOpenAIApiKey=e?.azureOpenAIApiKey??(typeof e?.openAIApiKey=="string"?e?.openAIApiKey:void 0)??(typeof e?.apiKey=="string"?e?.apiKey:void 0)??Pe("AZURE_OPENAI_API_KEY"),this.azureOpenAIApiInstanceName=e?.azureOpenAIApiInstanceName??Pe("AZURE_OPENAI_API_INSTANCE_NAME"),this.azureOpenAIApiDeploymentName=e?.azureOpenAIApiDeploymentName??e?.deploymentName??Pe("AZURE_OPENAI_API_DEPLOYMENT_NAME"),this.azureOpenAIApiVersion=e?.azureOpenAIApiVersion??e?.openAIApiVersion??Pe("AZURE_OPENAI_API_VERSION"),this.azureOpenAIBasePath=e?.azureOpenAIBasePath??Pe("AZURE_OPENAI_BASE_PATH"),this.azureOpenAIEndpoint=e?.azureOpenAIEndpoint??Pe("AZURE_OPENAI_ENDPOINT"),this.azureADTokenProvider=e?.azureADTokenProvider,!this.azureOpenAIApiKey&&!this.apiKey&&!this.azureADTokenProvider)throw new Error("Azure OpenAI API key or Token Provider not found")}function k_(e){if(!this.client){let r={azureOpenAIApiDeploymentName:this.azureOpenAIApiDeploymentName,azureOpenAIApiInstanceName:this.azureOpenAIApiInstanceName,azureOpenAIApiKey:this.azureOpenAIApiKey,azureOpenAIBasePath:this.azureOpenAIBasePath,azureADTokenProvider:this.azureADTokenProvider,baseURL:this.clientConfig.baseURL,azureOpenAIEndpoint:this.azureOpenAIEndpoint},n=ei(r),{apiKey:i,...s}=this.clientConfig,o={...s,baseURL:n,timeout:this.timeout,maxRetries:0};this.azureADTokenProvider||(o.apiKey=r.azureOpenAIApiKey),o.baseURL||delete o.baseURL,o.defaultHeaders=ti(o.defaultHeaders,!0,"2.0.0"),this.client=new Ao({apiVersion:this.azureOpenAIApiVersion,azureADTokenProvider:this.azureADTokenProvider,deployment:this.azureOpenAIApiDeploymentName,...o})}let t={...this.clientConfig,...e};return this.azureOpenAIApiKey&&(t.headers={"api-key":this.azureOpenAIApiKey,...t.headers},t.query={"api-version":this.azureOpenAIApiVersion,...t.query}),t}function ul(e){let t=e;function r(n){return typeof n=="object"&&n!=null}if(r(t)&&r(t.kwargs)){if(delete t.kwargs.azure_openai_base_path,delete t.kwargs.azure_openai_api_deployment_name,delete t.kwargs.azure_openai_api_key,delete t.kwargs.azure_openai_api_version,delete t.kwargs.azure_open_ai_base_path,!t.kwargs.azure_endpoint&&this.azureOpenAIEndpoint&&(t.kwargs.azure_endpoint=this.azureOpenAIEndpoint),!t.kwargs.azure_endpoint&&this.azureOpenAIBasePath){let n=this.azureOpenAIBasePath.split("/openai/deployments/");if(n.length===2&&n[0].startsWith("http")){let[i]=n;t.kwargs.azure_endpoint=i}}if(!t.kwargs.azure_endpoint&&this.azureOpenAIApiInstanceName&&(t.kwargs.azure_endpoint=`https://${this.azureOpenAIApiInstanceName}.openai.azure.com/`),!t.kwargs.deployment_name&&this.azureOpenAIApiDeploymentName&&(t.kwargs.deployment_name=this.azureOpenAIApiDeploymentName),!t.kwargs.deployment_name&&this.azureOpenAIBasePath){let n=this.azureOpenAIBasePath.split("/openai/deployments/");if(n.length===2){let[,i]=n;t.kwargs.deployment_name=i}}t.kwargs.azure_endpoint&&t.kwargs.deployment_name&&t.kwargs.openai_api_base&&delete t.kwargs.openai_api_base,t.kwargs.azure_openai_api_instance_name&&t.kwargs.azure_endpoint&&delete t.kwargs.azure_openai_api_instance_name}return t}var VE=class extends qd{azureOpenAIApiVersion;azureOpenAIApiKey;azureADTokenProvider;azureOpenAIApiInstanceName;azureOpenAIApiDeploymentName;azureOpenAIBasePath;azureOpenAIEndpoint;_llmType(){return"azure_openai"}get lc_aliases(){return{...super.lc_aliases,...sl}}get lc_secrets(){return{...super.lc_secrets,...ol}}get lc_serializable_keys(){return[...super.lc_serializable_keys,...al]}getLsParams(e){let t=super.getLsParams(e);return t.ls_provider="azure",t}constructor(e){super(e),cl.call(this,e)}_getClientOptions(e){return k_.call(this,e)}toJSON(){return ul.call(this,super.toJSON())}};var A_="__openai_function_call_ids__";function _z(e){return e.type==="url_citation"?{type:"citation",source:"url_citation",url:e.url,title:e.title,startIndex:e.start_index,endIndex:e.end_index}:e.type==="file_citation"?{type:"citation",source:"file_citation",title:e.filename,startIndex:e.index,file_id:e.file_id}:e.type==="container_file_citation"?{type:"citation",source:"container_file_citation",title:e.filename,startIndex:e.start_index,endIndex:e.end_index,file_id:e.file_id,container_id:e.container_id}:e.type==="file_path"?{type:"citation",source:"file_path",startIndex:e.index,file_id:e.file_id}:{type:"non_standard",value:e}}var ZE=e=>{let t={...e?.input_tokens_details?.cached_tokens!=null&&{cache_read:e?.input_tokens_details?.cached_tokens}},r={...e?.output_tokens_details?.reasoning_tokens!=null&&{reasoning:e?.output_tokens_details?.reasoning_tokens}};return{input_tokens:e?.input_tokens??0,output_tokens:e?.output_tokens??0,total_tokens:e?.total_tokens??0,input_token_details:t,output_token_details:r}},T_=e=>{if(e.error){let a=new Error(e.error.message);throw a.name=e.error.code,a}let t,r=[],n=[],i=[],s={model_provider:"openai",model:e.model,created_at:e.created_at,id:e.id,incomplete_details:e.incomplete_details,metadata:e.metadata,object:e.object,status:e.status,user:e.user,service_tier:e.service_tier,model_name:e.model},o={};for(let a of e.output)if(a.type==="message")t=a.id,r.push(...a.content.flatMap(c=>c.type==="output_text"?("parsed"in c&&c.parsed!=null&&(o.parsed=c.parsed),{type:"text",text:c.text,annotations:c.annotations.map(_z)}):c.type==="refusal"?(o.refusal=c.refusal,[]):c));else if(a.type==="function_call"){let c={function:{name:a.name,arguments:a.arguments},id:a.call_id};try{n.push(wa(c,{returnId:!0}))}catch(u){let l;typeof u=="object"&&u!=null&&"message"in u&&typeof u.message=="string"&&(l=u.message),i.push(ro(c,l))}o[A_]??={},a.id&&(o[A_][a.call_id]=a.id)}else if(a.type==="reasoning"){o.reasoning=a;let c=a.summary?.map(u=>u.text).filter(Boolean).join("");c&&r.push({type:"reasoning",reasoning:c})}else if(a.type==="custom_tool_call"){let c=xD(a);c?n.push(c):i.push(ro(a,"Malformed custom tool call"))}else if(a.type==="computer_call"){let c=ID(a);c?n.push(c):i.push(ro(a,"Malformed computer call"))}else a.type==="image_generation_call"?(a.result&&r.push({type:"image",mimeType:"image/png",data:a.result,id:a.id,metadata:{status:a.status}}),o.tool_outputs??=[],o.tool_outputs.push(a)):(o.tool_outputs??=[],o.tool_outputs.push(a));return new Oe({id:t,content:r,tool_calls:n,invalid_tool_calls:i,usage_metadata:ZE(e.usage),additional_kwargs:o,response_metadata:s})},yz=e=>{let t=(e.summary.length>1?e.summary.reduce((r,n)=>{let i=r[r.length-1];return i.index===n.index?i.text+=n.text:r.push(n),r},[{...e.summary[0]}]):e.summary).map(r=>Object.fromEntries(Object.entries(r).filter(([n])=>n!=="index")));return{...e,summary:t}},GE=e=>{let t=[],r={},n,i=[],s={model_provider:"openai"},o={},a;if(e.type==="response.output_text.delta")t.push({type:"text",text:e.delta,index:e.content_index});else if(e.type==="response.output_text.annotation.added")t.push({type:"text",text:"",annotations:[_z(e.annotation)],index:e.content_index});else if(e.type==="response.output_item.added"&&e.item.type==="message")a=e.item.id;else if(e.type==="response.output_item.added"&&e.item.type==="function_call")i.push({type:"tool_call_chunk",name:e.item.name,args:e.item.arguments,id:e.item.call_id,index:e.output_index}),o[A_]={[e.item.call_id]:e.item.id};else if(e.type==="response.output_item.done"&&e.item.type==="computer_call")i.push({type:"tool_call_chunk",name:"computer_use",args:JSON.stringify({action:e.item.action}),id:e.item.call_id,index:e.output_index}),o.tool_outputs=[e.item];else if(e.type==="response.output_item.done"&&e.item.type==="image_generation_call")e.item.result&&t.push({type:"image",mimeType:"image/png",data:e.item.result,id:e.item.id,metadata:{status:e.item.status}}),o.tool_outputs=[e.item];else if(e.type==="response.output_item.done"&&["web_search_call","file_search_call","code_interpreter_call","mcp_call","mcp_list_tools","mcp_approval_request","custom_tool_call"].includes(e.item.type))o.tool_outputs=[e.item];else if(e.type==="response.created")s.id=e.response.id,s.model_name=e.response.model,s.model=e.response.model;else if(e.type==="response.completed"){let c=T_(e.response);n=ZE(e.response.usage),e.response.text?.format?.type==="json_schema"&&(o.parsed??=JSON.parse(c.text));for(let[u,l]of Object.entries(e.response))u!=="id"&&(s[u]=l)}else if(e.type==="response.function_call_arguments.delta"||e.type==="response.custom_tool_call_input.delta")i.push({type:"tool_call_chunk",args:e.delta,index:e.output_index});else if(e.type==="response.web_search_call.completed"||e.type==="response.file_search_call.completed")r={tool_outputs:{id:e.item_id,type:e.type.replace("response.","").replace(".completed",""),status:"completed"}};else if(e.type==="response.refusal.done")o.refusal=e.refusal;else if(e.type==="response.output_item.added"&&"item"in e&&e.item.type==="reasoning"){let c=e.item.summary?e.item.summary.map((l,p)=>({...l,index:p})):void 0;o.reasoning={id:e.item.id,type:e.item.type,...c?{summary:c}:{}};let u=e.item.summary?.map(l=>l.text).filter(Boolean).join("");u&&t.push({type:"reasoning",reasoning:u})}else if(e.type==="response.reasoning_summary_part.added")o.reasoning={type:"reasoning",summary:[{...e.part,index:e.summary_index}]},e.part.text&&t.push({type:"reasoning",reasoning:e.part.text});else if(e.type==="response.reasoning_summary_text.delta")o.reasoning={type:"reasoning",summary:[{text:e.delta,type:"summary_text",index:e.summary_index}]},e.delta&&t.push({type:"reasoning",reasoning:e.delta});else return e.type==="response.image_generation_call.partial_image",null;return new Zr({text:t.map(c=>c.text).join(""),message:new nt({id:a,content:t,tool_call_chunks:i,usage_metadata:n,additional_kwargs:o,response_metadata:s}),generationInfo:r})},vz=e=>{let t=Oe.isInstance(e)&&e.response_metadata?.model_provider==="openai";function*r(){let n=ks(()=>{try{let _=Ts(e);return _==="system"||_==="developer"||_==="assistant"||_==="user"?_:"assistant"}catch{return"assistant"}}),i,s=new Set,o=new Set,a=new Map,c=new Map;function*u(){if(!i)return;let _=i.content;(typeof _=="string"&&_.length>0||Array.isArray(_)&&_.length>0)&&(yield i),i=void 0}let l=_=>{i||(i={type:"message",role:n,content:[]}),typeof i.content=="string"?i.content=i.content.length>0?[{type:"input_text",text:i.content},..._]:[..._]:i.content.push(..._)},p=_=>{if(typeof _=="string")return _;try{return JSON.stringify(_??{})}catch{return"{}"}},f=_=>{let y=ks(()=>{let x=_.metadata?.detail;return x==="low"||x==="high"||x==="auto"?x:"auto"});if(_.fileId)return{type:"input_image",detail:y,file_id:_.fileId};if(_.url)return{type:"input_image",detail:y,image_url:_.url};if(_.data){let x=typeof _.data=="string"?_.data:Buffer.from(_.data).toString("base64"),I=_.mimeType??"image/png";return{type:"input_image",detail:y,image_url:`data:${I};base64,${x}`}}},d=_=>{let y=nl(_);if(_.fileId&&typeof y=="string")return{type:"input_file",file_id:_.fileId,...y?{filename:y}:{}};if(_.url&&typeof y=="string")return{type:"input_file",file_url:_.url,...y?{filename:y}:{}};if(_.data&&typeof y=="string"){let x=typeof _.data=="string"?_.data:Buffer.from(_.data).toString("base64");return{type:"input_file",file_data:`data:${_.mimeType??"application/octet-stream"};base64,${x}`,...y?{filename:y}:{}}}},m=_=>{let y=ks(()=>{if(Array.isArray(_.summary)){let j=_.summary?.map(O=>O?.text).filter(O=>typeof O=="string")??[];if(j.length>0)return j}return _.reasoning?[_.reasoning]:[]}),x=y.length>0?y.map(A=>({type:"summary_text",text:A})):[{type:"summary_text",text:""}],I={type:"reasoning",id:_.id??"",summary:x};return _.reasoning&&(I.content=[{type:"reasoning_text",text:_.reasoning}]),I},h=_=>({type:"function_call",name:_.name??"",call_id:_.id??"",arguments:p(_.args)}),b=_=>{let y=p(_.output),x=_.status==="success"?"completed":_.status==="error"?"incomplete":void 0;return{type:"function_call_output",call_id:_.toolCallId??"",output:y,...x?{status:x}:{}}};for(let _ of e.contentBlocks)if(_.type==="text")l([{type:"input_text",text:_.text}]);else if(_.type!=="invalid_tool_call"){if(_.type==="reasoning")yield*u(),yield m(_);else if(_.type==="tool_call"){yield*u();let y=_.id??"";y&&(s.add(y),a.delete(y)),yield h(_)}else if(_.type==="tool_call_chunk"){if(_.id){let y=a.get(_.id)??{name:_.name,args:[]};_.name&&(y.name=_.name),_.args&&y.args.push(_.args),a.set(_.id,y)}}else if(_.type==="server_tool_call"){yield*u();let y=_.id??"";y&&(o.add(y),c.delete(y)),yield h(_)}else if(_.type==="server_tool_call_chunk"){if(_.id){let y=c.get(_.id)??{name:_.name,args:[]};_.name&&(y.name=_.name),_.args&&y.args.push(_.args),c.set(_.id,y)}}else if(_.type==="server_tool_call_result")yield*u(),yield b(_);else if(_.type!=="audio")if(_.type==="file"){let y=d(_);y&&l([y])}else if(_.type==="image"){let y=f(_);y&&l([y])}else if(_.type==="video"){let y=d(_);y&&l([y])}else _.type==="text-plain"?_.text&&l([{type:"input_text",text:_.text}]):_.type==="non_standard"&&t&&(yield*u(),yield _.value)}yield*u();for(let[_,y]of a){if(!_||s.has(_))continue;let x=y.args.join("");!y.name&&!x||(yield{type:"function_call",call_id:_,name:y.name??"",arguments:x})}for(let[_,y]of c){if(!_||o.has(_))continue;let x=y.args.join("");!y.name&&!x||(yield{type:"function_call",call_id:_,name:y.name??"",arguments:x})}}return Array.from(r())},O_=({messages:e,zdrEnabled:t,model:r})=>e.flatMap(n=>{let i=n.response_metadata;if(i?.output_version==="v1")return vz(n);let s=n.additional_kwargs,o=Ts(n);if(o==="system"&&As(r)&&(o="developer"),o==="function")throw new Error("Function messages are not supported in Responses API");if(o==="tool"){let a=n;if(s?.type==="computer_call_output")return{type:"computer_call_output",output:(()=>{if(typeof a.content=="string")return{type:"input_image",image_url:a.content};if(Array.isArray(a.content)){let l=a.content.find(d=>d.type==="input_image");if(l)return l;let p=a.content.find(d=>d.type==="computer_screenshot");if(p)return p;let f=a.content.find(d=>d.type==="image_url");if(f)return{type:"input_image",image_url:typeof f.image_url=="string"?f.image_url:f.image_url.url}}throw new Error("Invalid computer call output")})(),call_id:a.tool_call_id};if(a.additional_kwargs?.customTool)return{type:"custom_tool_call_output",call_id:a.tool_call_id,output:a.content};let c=Array.isArray(a.content)&&a.content.every(u=>typeof u=="object"&&u!==null&&"type"in u&&(u.type==="input_file"||u.type==="input_image"||u.type==="input_text"));return{type:"function_call_output",call_id:a.tool_call_id,id:a.id?.startsWith("fc_")?a.id:void 0,output:c?a.content:typeof a.content!="string"?JSON.stringify(a.content):a.content}}if(o==="assistant"){if(!t&&i?.output!=null&&Array.isArray(i?.output)&&i?.output.length>0&&i?.output.every(f=>"type"in f))return i?.output;let a=[];if(s?.reasoning&&!t){let f=yz(s.reasoning);a.push(f)}let{content:c}=n;s?.refusal&&(typeof c=="string"&&(c=[{type:"output_text",text:c,annotations:[]}]),c=[...c,{type:"refusal",refusal:s.refusal}]),(typeof c=="string"||c.length>0)&&a.push({type:"message",role:"assistant",...n.id&&!t&&n.id.startsWith("msg_")?{id:n.id}:{},content:ks(()=>typeof c=="string"?c:c.flatMap(f=>f.type==="text"?{type:"output_text",text:f.text,annotations:f.annotations??[]}:f.type==="output_text"||f.type==="refusal"?f:[]))});let u=s?.[A_];Oe.isInstance(n)&&n.tool_calls?.length?a.push(...n.tool_calls.map(f=>ED(f)?{type:"custom_tool_call",id:f.call_id,call_id:f.id??"",input:f.args.input,name:f.name}:SD(f)?{type:"computer_call",id:f.call_id,call_id:f.id??"",action:f.args.action}:{type:"function_call",name:f.name,arguments:JSON.stringify(f.args),call_id:f.id,...t?{}:{id:u?.[f.id]}})):s?.tool_calls&&a.push(...s.tool_calls.map(f=>({type:"function_call",name:f.function.name,call_id:f.id,arguments:f.function.arguments,...t?{}:{id:u?.[f.id]}})));let l=i?.output?.length?i?.output:s.tool_outputs,p=["computer_call","mcp_call","code_interpreter_call","image_generation_call"];if(l!=null){let d=l?.filter(m=>p.includes(m.type));d.length>0&&a.push(...d)}return a}if(o==="user"||o==="system"||o==="developer"){if(typeof n.content=="string")return{type:"message",role:o,content:n.content};let a=[],c=n.content.flatMap(u=>{if(u.type==="mcp_approval_response"&&a.push({type:"mcp_approval_response",approval_request_id:u.approval_request_id,approve:u.approve}),Tr(u))return dc(u,E_);if(u.type==="text")return{type:"input_text",text:u.text};if(u.type==="image_url"){let l=ks(()=>{if(typeof u.image_url=="string")return u.image_url;if(typeof u.image_url=="object"&&u.image_url!==null&&"url"in u.image_url)return u.image_url.url}),p=ks(()=>{if(typeof u.image_url=="string")return"auto";if(typeof u.image_url=="object"&&u.image_url!==null&&"detail"in u.image_url)return u.image_url.detail});return{type:"input_image",image_url:l,detail:p}}return u.type==="input_text"||u.type==="input_image"||u.type==="input_file"?u:[]});return c.length>0&&a.push({type:"message",role:o,content:c}),a}return console.warn(`Unsupported role found when converting to OpenAI Responses API: ${o}`),[]});var Hd=class extends oc{invocationParams(e){let t;e?.strict!==void 0&&(t=e.strict),t===void 0&&this.supportsStrictToolCalling!==void 0&&(t=this.supportsStrictToolCalling);let r={model:this.model,temperature:this.temperature,top_p:this.topP,user:this.user,stream:this.streaming,previous_response_id:e?.previous_response_id,truncation:e?.truncation,include:e?.include,tools:e?.tools?.length?this._reduceChatOpenAITools(e.tools,{stream:this.streaming,strict:t}):void 0,tool_choice:wD(e?.tool_choice)?e?.tool_choice:(()=>{let i=w_(e?.tool_choice);if(typeof i=="object"&&"type"in i){if(i.type==="function")return{type:"function",name:i.function.name};if(i.type==="allowed_tools")return{type:"allowed_tools",mode:i.allowed_tools.mode,tools:i.allowed_tools.tools};if(i.type==="custom")return{type:"custom",name:i.custom.name}}})(),text:(()=>{if(e?.text)return e.text;let i=this._getResponseFormat(e?.response_format);return i?.type==="json_schema"?i.json_schema.schema!=null?{format:{type:"json_schema",schema:i.json_schema.schema,description:i.json_schema.description,name:i.json_schema.name,strict:i.json_schema.strict},verbosity:e?.verbosity}:void 0:{format:i,verbosity:e?.verbosity}})(),parallel_tool_calls:e?.parallel_tool_calls,max_output_tokens:this.maxTokens===-1?void 0:this.maxTokens,prompt_cache_key:e?.promptCacheKey??this.promptCacheKey,prompt_cache_retention:e?.promptCacheRetention??this.promptCacheRetention,...this.zdrEnabled?{store:!1}:{},...this.modelKwargs},n=this._getReasoningParams(e);return n!==void 0&&(r.reasoning=n),r}async _generate(e,t,r){let n=this.invocationParams(t);if(n.stream){let i=this._streamResponseChunks(e,t,r),s;for await(let o of i)o.message.response_metadata={...o.generationInfo,...o.message.response_metadata},s=s?.concat(o)??o;return{generations:s?[s]:[],llmOutput:{estimatedTokenUsage:s?.message?.usage_metadata}}}else{let i=await this.completionWithRetry({input:O_({messages:e,zdrEnabled:this.zdrEnabled??!1,model:this.model}),...n,stream:!1},{signal:t?.signal,...t?.options});return{generations:[{text:i.output_text,message:T_(i)}],llmOutput:{id:i.id,estimatedTokenUsage:i.usage?{promptTokens:i.usage.input_tokens,completionTokens:i.usage.output_tokens,totalTokens:i.usage.total_tokens}:void 0}}}}async*_streamResponseChunks(e,t,r){let n=await this.completionWithRetry({...this.invocationParams(t),input:O_({messages:e,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},t);for await(let i of n){let s=GE(i);s!=null&&(yield s,await r?.handleLLMNewToken(s.text||"",{prompt:t.promptIndex??0,completion:0},void 0,void 0,void 0,{chunk:s}))}}async completionWithRetry(e,t){return this.caller.call(async()=>{let r=this._getClientOptions(t);try{return e.text?.format?.type==="json_schema"&&!e.stream?await this.client.responses.parse(e,r):await this.client.responses.create(e,r)}catch(n){throw xn(n)}})}_reduceChatOpenAITools(e,t){let r=[];for(let n of e)if(il(n))n.type==="image_generation"&&t?.stream&&(n.partial_images=1),r.push(n);else if(nc(n)){let i=n.metadata.customTool;r.push({type:"custom",name:i.name,description:i.description,format:i.format})}else Rp(n)?r.push({type:"function",name:n.function.name,parameters:n.function.parameters,description:n.function.description,strict:t?.strict??null}):x_(n)&&r.push(kD(n));return r}};var KE=class extends Hd{azureOpenAIApiVersion;azureOpenAIApiKey;azureADTokenProvider;azureOpenAIApiInstanceName;azureOpenAIApiDeploymentName;azureOpenAIBasePath;azureOpenAIEndpoint;_llmType(){return"azure_openai"}get lc_aliases(){return{...super.lc_aliases,...sl}}get lc_secrets(){return{...super.lc_secrets,...ol}}get lc_serializable_keys(){return[...super.lc_serializable_keys,...al]}getLsParams(e){let t=super.getLsParams(e);return t.ls_provider="azure",t}constructor(e){super(e),cl.call(this,e)}_getClientOptions(e){return k_.call(this,e)}toJSON(){return ul.call(this,super.toJSON())}};var qE=class bz extends oc{useResponsesApi=!1;responses;completions;get lc_serializable_keys(){return[...super.lc_serializable_keys,"useResponsesApi"]}get callKeys(){return[...super.callKeys,"useResponsesApi"]}constructor(t){super(t),this.fields=t,this.useResponsesApi=t?.useResponsesApi??!1,this.responses=t?.responses??new Hd(t),this.completions=t?.completions??new qd(t)}_useResponsesApi(t){let r=t?.tools?.some(il),n=t?.previous_response_id!=null||t?.text!=null||t?.truncation!=null||t?.include!=null||t?.reasoning?.summary!=null||this.reasoning?.summary!=null,i=t?.tools?.some(x_)||t?.tools?.some(nc);return this.useResponsesApi||r||n||i||mD(this.model)}getLsParams(t){let r=this._combineCallOptions(t);return this._useResponsesApi(t)?this.responses.getLsParams(r):this.completions.getLsParams(r)}invocationParams(t){let r=this._combineCallOptions(t);return this._useResponsesApi(t)?this.responses.invocationParams(r):this.completions.invocationParams(r)}async _generate(t,r,n){return this._useResponsesApi(r)?this.responses._generate(t,r):this.completions._generate(t,r,n)}async*_streamResponseChunks(t,r,n){if(this._useResponsesApi(r)){yield*this.responses._streamResponseChunks(t,this._combineCallOptions(r),n);return}yield*this.completions._streamResponseChunks(t,this._combineCallOptions(r),n)}withConfig(t){let r=new bz(this.fields);return r.defaultOptions={...this.defaultOptions,...t},r}};var HE=class extends qE{azureOpenAIApiVersion;azureOpenAIApiKey;azureADTokenProvider;azureOpenAIApiInstanceName;azureOpenAIApiDeploymentName;azureOpenAIBasePath;azureOpenAIEndpoint;_llmType(){return"azure_openai"}get lc_aliases(){return{...super.lc_aliases,...sl}}get lc_secrets(){return{...super.lc_secrets,...ol}}get lc_serializable_keys(){return[...super.lc_serializable_keys,...al]}getLsParams(e){let t=super.getLsParams(e);return t.ls_provider="azure",t}constructor(e){super({...e,completions:new VE(e),responses:new KE(e)}),cl.call(this,e)}_getStructuredOutputMethod(e){let t={...e};return this.model.startsWith("gpt-4o")&&t?.method===void 0?"functionCalling":super._getStructuredOutputMethod(t)}toJSON(){return ul.call(this,super.toJSON())}};var WE=class extends Bc{model="text-embedding-ada-002";modelName;batchSize=512;stripNewLines=!0;dimensions;timeout;organization;encodingFormat;client;clientConfig;apiKey;constructor(e){let t={maxConcurrency:2,...e};super(t);let r=t?.apiKey??t?.openAIApiKey??Pe("OPENAI_API_KEY");this.organization=t?.configuration?.organization??Pe("OPENAI_ORGANIZATION"),this.model=t?.model??t?.modelName??this.model,this.modelName=this.model,this.batchSize=t?.batchSize??this.batchSize,this.stripNewLines=t?.stripNewLines??this.stripNewLines,this.timeout=t?.timeout,this.dimensions=t?.dimensions,this.encodingFormat=t?.encodingFormat,this.clientConfig={apiKey:r,organization:this.organization,dangerouslyAllowBrowser:!0,...e?.configuration}}async embedDocuments(e){let t=lg(this.stripNewLines?e.map(s=>s.replace(/\n/g," ")):e,this.batchSize),r=t.map(s=>{let o={model:this.model,input:s};return this.dimensions&&(o.dimensions=this.dimensions),this.encodingFormat&&(o.encoding_format=this.encodingFormat),this.embeddingWithRetry(o)}),n=await Promise.all(r),i=[];for(let s=0;s<n.length;s+=1){let o=t[s],{data:a}=n[s];for(let c=0;c<o.length;c+=1)i.push(a[c].embedding)}return i}async embedQuery(e){let t={model:this.model,input:this.stripNewLines?e.replace(/\n/g," "):e};this.dimensions&&(t.dimensions=this.dimensions),this.encodingFormat&&(t.encoding_format=this.encodingFormat);let{data:r}=await this.embeddingWithRetry(t);return r[0].embedding}async embeddingWithRetry(e){if(!this.client){let r={baseURL:this.clientConfig.baseURL},n=ei(r),i={...this.clientConfig,baseURL:n,timeout:this.timeout,maxRetries:0};i.baseURL||delete i.baseURL,i.defaultHeaders=ti(i.defaultHeaders),this.client=new le(i)}let t={};return this.caller.call(async()=>{try{return await this.client.embeddings.create(e,t)}catch(r){throw xn(r)}})}};var JE=class extends WE{azureOpenAIApiVersion;azureOpenAIApiKey;azureADTokenProvider;azureOpenAIApiInstanceName;azureOpenAIApiDeploymentName;azureOpenAIBasePath;constructor(e){super(e),this.batchSize=e?.batchSize??1,this.azureOpenAIApiKey=e?.azureOpenAIApiKey??(typeof e?.apiKey=="string"?e?.apiKey:void 0)??Pe("AZURE_OPENAI_API_KEY"),this.azureOpenAIApiVersion=e?.azureOpenAIApiVersion??e?.openAIApiVersion??Pe("AZURE_OPENAI_API_VERSION"),this.azureOpenAIBasePath=e?.azureOpenAIBasePath??Pe("AZURE_OPENAI_BASE_PATH"),this.azureOpenAIApiInstanceName=e?.azureOpenAIApiInstanceName??Pe("AZURE_OPENAI_API_INSTANCE_NAME"),this.azureOpenAIApiDeploymentName=(e?.azureOpenAIApiEmbeddingsDeploymentName||e?.azureOpenAIApiDeploymentName)??(Pe("AZURE_OPENAI_API_EMBEDDINGS_DEPLOYMENT_NAME")||Pe("AZURE_OPENAI_API_DEPLOYMENT_NAME")),this.azureADTokenProvider=e?.azureADTokenProvider}async embeddingWithRetry(e){if(!this.client){let r={azureOpenAIApiDeploymentName:this.azureOpenAIApiDeploymentName,azureOpenAIApiInstanceName:this.azureOpenAIApiInstanceName,azureOpenAIApiKey:this.azureOpenAIApiKey,azureOpenAIBasePath:this.azureOpenAIBasePath,azureADTokenProvider:this.azureADTokenProvider,baseURL:this.clientConfig.baseURL},n=ei(r),{apiKey:i,...s}=this.clientConfig,o={...s,baseURL:n,timeout:this.timeout,maxRetries:0};this.azureADTokenProvider||(o.apiKey=r.azureOpenAIApiKey),o.baseURL||delete o.baseURL,o.defaultHeaders=ti(o.defaultHeaders,!0,"2.0.0"),this.client=new Ao({apiVersion:this.azureOpenAIApiVersion,azureADTokenProvider:this.azureADTokenProvider,deployment:this.azureOpenAIApiDeploymentName,...o})}let t={};return this.azureOpenAIApiKey&&(t.headers={"api-key":this.azureOpenAIApiKey,...t.headers},t.query={"api-version":this.azureOpenAIApiVersion,...t.query}),this.caller.call(async()=>{try{return await this.client.embeddings.create(e,t)}catch(r){throw xn(r)}})}};var iq=Z.object({type:Z.literal("screenshot")}),sq=Z.object({type:Z.literal("click"),x:Z.number(),y:Z.number(),button:Z.enum(["left","right","wheel","back","forward"]).default("left")}),oq=Z.object({type:Z.literal("double_click"),x:Z.number(),y:Z.number(),button:Z.enum(["left","right","wheel","back","forward"]).default("left")}),aq=Z.object({type:Z.literal("drag"),path:Z.array(Z.object({x:Z.number(),y:Z.number()}))}),cq=Z.object({type:Z.literal("keypress"),keys:Z.array(Z.string())}),uq=Z.object({type:Z.literal("move"),x:Z.number(),y:Z.number()}),lq=Z.object({type:Z.literal("scroll"),x:Z.number(),y:Z.number(),scroll_x:Z.number(),scroll_y:Z.number()}),pq=Z.object({type:Z.literal("type"),text:Z.string()}),dq=Z.object({type:Z.literal("wait"),duration:Z.number().optional()}),fq=Z.discriminatedUnion("type",[iq,sq,oq,aq,cq,uq,lq,pq,dq]),YMe=Z.object({action:fq});var mq=Z.object({type:Z.literal("exec"),command:Z.array(Z.string()),env:Z.record(Z.string(),Z.string()).optional(),working_directory:Z.string().optional(),timeout_ms:Z.number().optional(),user:Z.string().optional()}),rje=Z.discriminatedUnion("type",[mq]);var oje=Z.object({commands:Z.array(Z.string()).describe("Array of shell commands to execute"),timeout_ms:Z.number().optional().describe("Optional timeout in milliseconds for the commands"),max_output_length:Z.number().optional().describe("Optional maximum number of characters to return from each command")});var hq=Z.object({type:Z.literal("create_file"),path:Z.string(),diff:Z.string()}),gq=Z.object({type:Z.literal("update_file"),path:Z.string(),diff:Z.string()}),_q=Z.object({type:Z.literal("delete_file"),path:Z.string()}),lje=Z.discriminatedUnion("type",[hq,gq,_q]);var ek={"gpt-4.1":{deploymentName:"gpt-4.1",apiVersion:"2024-10-21",pathSegment:"models/gpt-4.1/openai/deployments/gpt-4.1/chat/completions"},"gpt-4.1-mini":{deploymentName:"gpt-4.1-mini",apiVersion:"2024-10-21",pathSegment:"models/gpt-4.1-mini/openai/deployments/gpt-4.1-mini/chat/completions"},"text-embedding-ada-002":{deploymentName:"text-embedding-ada-002",apiVersion:"2024-10-21",pathSegment:"models/text-embedding-ada-002/openai/deployments/text-embedding-ada-002/embeddings"}},Ez={default:"gpt-4.1",fast:"gpt-4.1-mini"},kz={default:"text-embedding-ada-002"},Az=(e,t)=>{let r=ek[t];return`${e}/${r.pathSegment}?api-version=${r.apiVersion}`};function Tz(){let e=$_.getDefault().helperServices;if(!e?.aiUtilityServices?.url)throw new Error("AI Utility Service URL is not defined in the portal's helper services.");return e.aiUtilityServices.url}function vq(e="default"){return Az(Tz(),Ez[e])}function Oz(e="default"){return Az(Tz(),kz[e])}var bq=async e=>{let t=await wq(),r=Oz("default"),n=$_.getDefault(),i=(await QE.getCredential(`${n.url}/sharing`)).token,s={type:"generateEmbeddings",layersAndFieldsRegistry:e,auth:{apiUrl:r,token:i}};return t.postMessage(s),await new Promise((o,a)=>{let c=l=>{l.data==="completed"&&(t.removeEventListener("message",c),o())},u=l=>{t.removeEventListener("message",c),a(l instanceof Error?l:new Error("Embeddings worker error"))};t.addEventListener("message",c),t.addEventListener("error",u,{once:!0})}),t},wq=async()=>{let e=(await import("./HNKWDK3D.js")).default;return new e},wz=(e,t)=>t,xq=Bn.Root({userInput:Bn(),messages:Bn({reducer:hs,default:()=>[]}),pendingIntents:Bn({default:()=>[],reducer:wz}),currentIntent:Bn({default:()=>"none",reducer:wz})}),$s=async(e,t)=>{await WS("trace_message",e,t)},jDe=async(e,t)=>{await WS("graph_ux_suggestion",e,t)},Iq=e=>{e.currentIntent="none",e.pendingIntents=[]},Sq=async(e,t)=>{if(e.userInput){let n=new at(e.userInput.trim());e.messages=[...e.messages,n],Iq(e)}let r=t?.configurable?.services.agentRegistry.list().map(n=>n.agent.id)??[];return await $s({text:`Available agents: ${[...r].join(", ")}`},t),await $s({text:"Analyzing user input"},t),e},Eq=async(e,t)=>(await $s({text:"Exiting..."},t),e),kq=e=>{if(e.pendingIntents.length===0)return{...e,currentIntent:"none"};let[t,...r]=e.pendingIntents;return{...e,currentIntent:t,pendingIntents:r}},xz=4e3,Aq=async(e,t)=>{let r=t?.configurable,{agentRegistry:n}=r.services,i=n?.get(e.currentIntent);if(!i)return console.warn(`No agent found for intent: ${e.currentIntent}`),e;await $s({text:`Executing registered agent: ${i.agent.name}`},t);let s={...t??{},configurable:{...r??{},agentId:i.agent.id,context:i.getContext?await i.getContext():void 0}},o=await i.agent.createGraph().compile().invoke({messages:[...e.messages]},s);await $s({text:`Finished executing registered agent: ${i.agent.name}`},t);let a=typeof o?.outputMessage=="string"?o.outputMessage.trim():"";if(!a)return e;let c=a.length>xz?`${a.slice(0,xz-14)}
|
|
264
|
+
[truncated]`:a;return{...e,messages:[...e.messages,new Oe(c)]}},Tq=(e,t,r)=>{let n=e[t];return n?typeof n=="function"?n():Promise.resolve(n):new Promise((i,s)=>{(typeof queueMicrotask=="function"?queueMicrotask:setTimeout)(s.bind(null,new Error("Unknown variable dynamic import: "+t+(t.split("/").length!==r?". Note that variables only represent file names one level deep.":""))))})},tk=async e=>(await Tq(Object.assign({"./field_descriptions_prompt.md":()=>import("./EFU7HGPY.js"),"./intent_prompt.md":()=>import("./IZ4NSOIH.js"),"./layer_descriptions_prompt.md":()=>import("./EU7GHH2Y.js")}),`./${e}.md`,2)).default,Oq=(e,t=3)=>e.filter(r=>r instanceof at).slice(-t),$q=e=>{let t=-1;for(let r=e.length-1;r>=0;r--)if(e[r]instanceof at){t=r;break}return t===-1?"":e.slice(t+1).filter(r=>r instanceof Oe).map(r=>r.content).join(`
|
|
265
|
+
`)},Cq=["x-stainless-package-version","x-stainless-timeout","x-stainless-retry-count","x-stainless-lang","x-stainless-os","x-stainless-arch","x-stainless-runtime","x-stainless-runtime-version","x-stainless-helper-method","api-key"],$z=e=>async(t,r)=>{let n=new Headers(r?.headers);return Cq.forEach(i=>n.delete(i)),e&&e.length>0&&n.set("X-Esri-Authorization",`Bearer ${e}`),await fetch(t,{...r,headers:n})},rk=async(e="default",t=0)=>{let r=$_.getDefault(),n=await QE.getCredential(`${r.url}/sharing`),i=Ez[e],s=vq(e),o=ek[i];return new HE({temperature:t,azureOpenAIApiKey:"x",azureOpenAIBasePath:s,azureOpenAIApiDeploymentName:o.deploymentName,azureOpenAIApiVersion:o.apiVersion,model:i,configuration:{fetch:$z(n.token)}})},Pq=e=>{let t=new Set;for(let r of e)if(ci(r)){let n=r;n.tool_calls&&n.tool_calls.length>0&&n.tool_calls.forEach(i=>{i.id&&t.add(i.id)})}return e.filter(r=>{if(jo(r)){let n=r;return t.has(n.tool_call_id)}return!0})},nk=(e,t)=>{let r=Kp.fromTemplate(e);return no.fromMessages([r,...t])},Nq=async e=>{let{promptText:t,modelTier:r,temperature:n,messages:i}=e,s=nk(t,i??[]),o=await rk(r,n);return s.pipe(o)},DDe=async e=>{let{promptText:t,modelTier:r="default",temperature:n=0,messages:i,inputVariables:s}=e,o=await(await Nq({promptText:t,modelTier:r,temperature:n,messages:i})).invoke(s??{});if(typeof o=="string")return o;let a=o.content;return typeof a=="string"?a:JSON.stringify(a)},ik=async e=>{let{promptText:t,modelTier:r="default",temperature:n=0,messages:i,inputVariables:s,schema:o}=e,a=nk(t,i??[]),c=(await rk(r,n)).withStructuredOutput(o);return await a.pipe(c).invoke(s??{})},zDe=async e=>{let{promptText:t,modelTier:r="default",temperature:n=0,messages:i,inputVariables:s,tools:o}=e,a=o.length>0?Pq(i??[]):i??[],c=nk(t,a),u=await rk(r,n);return await c.pipe(u.bindTools(o)).invoke(s??{})},Rq=Ge.object({id:Ge.string().min(1),name:Ge.string().min(1),description:Ge.string().min(1)});Ge.array(Rq);var Mq=e=>{let t=e.map(n=>n.id),r=Ge.enum(t);return Ge.object({intents:Ge.array(r)})},jq=async(e,t)=>{try{await $s({text:"Asking LLM to detect intents"},t);let r=await tk("intent_prompt"),n=(t?.configurable?.services.agentRegistry?.list()??[]).map(({agent:d})=>({id:d.id,name:d.name,description:d.description}));if(!n.length)return await $s({text:"No agents registered; skipping intent detection"},t),{...e,currentIntent:"none",pendingIntents:[]};let i=n.map(d=>JSON.stringify(d)).join(`
|
|
266
|
+
`),s=n.length,o=Mq(n),a={maxIntents:s,registeredAgents:i},c=await ik({promptText:r,modelTier:"fast",schema:o,messages:Oq(e.messages),inputVariables:a}),u=new Set,l=(c.intents??[]).filter(d=>u.has(d)?!1:(u.add(d),!0)).slice(0,s),p=l[0]??"none",f={...e,currentIntent:p,pendingIntents:l};return await $s({text:`Intents came back as: ${l.join(", ")||"none"}`},t),f}catch(r){throw await $s({text:"Error during intent detection"},t),new Error(`Error during intent detection: ${r instanceof Error?r.message:String(r)}`)}},Dq=()=>new Gg(xq).addNode("ingestInput",Sq).addNode("intentLLM",jq).addNode("intentDispatcher",kq).addNode("executeRegisteredAgent",Aq).addNode("exit",Eq).addEdge(ke,"ingestInput").addEdge("ingestInput","intentLLM").addEdge("intentLLM","intentDispatcher").addConditionalEdges("intentDispatcher",e=>e.currentIntent==="none"?"exit":"executeRegisteredAgent").addEdge("executeRegisteredAgent","intentDispatcher").addEdge("exit",we),XE=class{constructor(){this.agentRegistry=new Map}register(t){let{agent:r}=t;if(this.agentRegistry.has(r.id))throw new Error(`Duplicate agent id: ${r.id}`);this.agentRegistry.set(r.id,t)}get(t){return this.agentRegistry.get(t)}list(){return[...this.agentRegistry.values()]}},YE=class{constructor(t,r){this.graph=t,this.config={...r}}async waitForUser(){return await new Promise((t,r)=>{this.resolveWait=t,this.rejectWait=r})}handle(t,r){try{let n={agentId:t.agentId,id:t.id,payload:r},i=this.graph.streamEvents(null,{...this.config,configurable:{...this.config.configurable,hitlResponse:n},subgraphs:!0,version:"v2"});this.resolveWait?.(i)}catch(n){this.rejectWait?.(n)}finally{this.resolveWait=void 0,this.rejectWait=void 0}}cancel(){this.rejectWait&&(this.rejectWait(new Error("User cancelled HITL")),this.resolveWait=void 0,this.rejectWait=void 0)}},zq=wn.object({name:wn.string(),description:wn.string(),valueType:wn.string(),alias:wn.string()}),Lq=wn.object({fields:wn.array(zq)});function Iz(e,t){let r=new Map;for(let n of e.fields){let i=t.fields.find(o=>o.name===n.name),s={name:n.name,type:n.type,alias:i?.alias??n.alias??"",description:i?.description??n.description??"",valueType:i?.valueType??n.valueType??""};r.set(n.name,s)}return r}var Uq=async e=>{let t=await tk("field_descriptions_prompt"),r=e.fields.filter(s=>!(s.alias&&s.description)).map(s=>{let{name:o,type:a,alias:c,description:u}=s;return[`Name: ${o}`,`Type: ${a}`,`Alias: ${c}`,`Description: ${u??"N/A"}`].join(", ")}).join(`
|
|
267
|
+
`);if(r.length===0)return Iz(e,{fields:[]});let n={existingItemTitle:e.portalItem?.title,existingItemDescription:e.portalItem?.description,existingLayerTitle:e.title,existingLayerDescription:e.portalItem?.description,fieldInformation:r},i=await ik({promptText:t,modelTier:"fast",schema:Lq,inputVariables:n});return Iz(e,i)},Fq=wn.object({title:wn.string(),description:wn.string(),name:wn.string().nullable()}),Bq=async(e,t)=>{let r=await tk("layer_descriptions_prompt"),n=Array.from(t.values()),i={fieldInformation:JSON.stringify(n,null,2),existingLayerTitle:e.title,existingLayerDescription:e.portalItem?.description,existingLayerSnippet:e.portalItem?.snippet,layerGeometryType:e.geometryType};return{...await ik({promptText:r,modelTier:"fast",schema:Fq,inputVariables:i}),name:e.title??null}},Vq=async e=>{let t=e.allLayers.toArray(),r=[],n=new Map;for(let i of t)if(i instanceof yq){let s=(async()=>{let o=await Uq(i),a=await Bq(i,o);n.set(i.id,{layerItem:a,fieldRegistry:o})})();r.push(s)}return await Promise.all(r),n},Zq=async e=>{let t=kz.default,r=ek[t],n=Oz("default"),i=$_.getDefault(),s=(await QE.getCredential(`${i.url}/sharing`)).token;return await new JE({azureOpenAIApiKey:"x",azureOpenAIBasePath:n,azureOpenAIApiDeploymentName:r.deploymentName,azureOpenAIApiVersion:r.apiVersion,model:t,configuration:{fetch:$z(s)}}).embedQuery(e)},Cz=async(e,t)=>{let r=t.get(e);if(r)return r;let n=await Zq(e);return t.set(e,n),n};async function Gq(e,t,r,n){let i=`req-${Date.now()}`,s={type:"layerSearch",precomputedEmbedding:n?await Cz(e,n):void 0,requestId:i};return await new Promise(o=>{let a=c=>{if(c.data.requestId!==i)return;let u=c.data.results.filter(([,l])=>l>=r).map(([l,p])=>({id:l.id??"",score:p}));o(u)};t.addEventListener("message",a,{once:!0}),t.postMessage(s)})}function Kq(e){let{worker:t}=e;return{async searchLayers({text:r,minScore:n,embeddingCache:i}){return await Gq(r,t,n,i)}}}var qq=async({combinedQuery:e,layerIds:t,embeddingsWorker:r,minScore:n,topResults:i,embeddingCache:s})=>{let o=`req-${Date.now()}`,a=s?await Cz(e,s):void 0,c={type:"fieldSearch",layerIdForFieldsSearch:t,precomputedEmbedding:a,requestId:o};return await new Promise(u=>{let l=p=>{if(p.data.requestId!==o)return;let f=p.data.results.map(({layerId:d,results:m})=>{let h=m.filter(([,b])=>b>=n).map(([b,_])=>({name:b.id??"",score:_})).sort((b,_)=>_.score-b.score).slice(0,i);return{layerId:d,results:h}});u(f)};r.addEventListener("message",l,{once:!0}),r.postMessage(c)})};function Hq(e){let{worker:t}=e;return{async searchFields({text:r,layerIds:n,minScore:i,topResults:s,embeddingCache:o}){return await qq({combinedQuery:r,layerIds:n,embeddingsWorker:t,minScore:i,topResults:s,embeddingCache:o})}}}var Sz=class e{constructor(t){this.deps=t,this.orchestratorReady=!1,this.chatHistory=[],this.threadId="",this.agentRegistry=new XE,this.streamEpoch=0}static async init(t){let r=new e(t);if(t.view?.map){let n=await Vq(t.view.map);r.layersAndFieldsRegistry=n,r.embeddingsWorker=await bq(n)}return t.agents?.forEach(n=>{r.agentRegistry.register(n)}),r.orchestratorReady=!0,r}async*ask(t){if(!this.orchestratorReady)throw new Error("Orchestrator is not ready yet.");if(!this.agentRegistry.list().length)throw new Error("Orchestrator has no registered agents.");if(++this.streamEpoch,!t.trim())return;this.threadId=String(Date.now()),this.graph||(this.graph=Dq().compile({checkpointer:new _g}));let r=this.embeddingsWorker?Kq({worker:this.embeddingsWorker}):void 0,n=this.embeddingsWorker?Hq({worker:this.embeddingsWorker}):void 0,i=new Map,s={version:"v2",streamMode:"custom",configurable:{thread_id:this.threadId,hitlResponse:null,services:{layerSearch:r,fieldSearch:n,layersAndFieldsRegistry:this.layersAndFieldsRegistry,agentRegistry:this.agentRegistry,portal:this.deps.portal,embeddingCache:i}},subgraphs:!0},o=this.graph?.streamEvents({userInput:t,messages:this.chatHistory},s),a=++this.streamEpoch;for(yield*this.pipeStream(o,a);;){let u=(await this.graph.getState(s,{subgraphs:!0})).tasks.find(l=>l.interrupts.length>0)?.interrupts[0]?.value;if(!u)break;this.currentInterrupt=u,this.interruptHandler=new YE(this.graph,s),yield{runId:this.threadId,timestamp:Date.now(),type:"interrupt",interrupt:u};try{let l=await this.interruptHandler.waitForUser(),p=++this.streamEpoch;yield*this.pipeStream(l,p)}catch(l){if(l){yield{runId:this.threadId,timestamp:Date.now(),type:"error",error:{message:l?.message}};return}yield{runId:this.threadId,timestamp:Date.now(),type:"cancelled"};return}}let c=(await this.graph.getState(s,{subgraphs:!0})).values;this.chatHistory=c.messages.length?c.messages:this.chatHistory,yield{runId:this.threadId,timestamp:Date.now(),type:"completed",result:{content:$q(c.messages)}}}newConversation(){this.chatHistory=[]}resumeInterrupt(t){if(!this.currentInterrupt||!this.interruptHandler)throw new Error("No pending interrupt to resume.");this.interruptHandler.handle(this.currentInterrupt,t)}cancelInterrupt(){this.interruptHandler&&this.interruptHandler.cancel()}async*pipeStream(t,r){for await(let n of t){if(r!==this.streamEpoch){console.log("Stale stream detected, aborting.");break}n.event==="on_custom_event"&&n.name==="trace_message"?yield{runId:this.threadId,timestamp:Date.now(),type:"trace",data:n.data}:n.name==="graph_ux_suggestion"&&(yield{runId:this.threadId,timestamp:Date.now(),type:"ux-suggestion",suggestion:n.data})}}dispose(){this.embeddingsWorker&&(this.embeddingsWorker.terminate(),this.embeddingsWorker=void 0),this.orchestratorReady=!1}};return{a:Jd,b:Di,c:ot,d:Wt,e:at,f:Oe,g:ci,h:Ge,i:nd,j:Bn,k:ke,l:we,m:$t,n:jr,o:Pt,p:sr,q:hs,r:Gg,s:wn,t:$s,u:jDe,v:DDe,w:ik,x:zDe,y:Sz}},"identity/IdentityManager","portal/Portal","layers/FeatureLayer")
|