@arcgis/ai-components 5.0.0-next.133

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (126) hide show
  1. package/LICENSE.md +17 -0
  2. package/README.md +11 -0
  3. package/dist/cdn/2KGO3SIH.js +4 -0
  4. package/dist/cdn/2OKOKVH3.js +4 -0
  5. package/dist/cdn/46CNQJRX.js +4 -0
  6. package/dist/cdn/7QPPUNQ3.js +4 -0
  7. package/dist/cdn/A3UHOE4Q.js +30 -0
  8. package/dist/cdn/A7BGJLHS.js +204 -0
  9. package/dist/cdn/AB32PU6M.js +4 -0
  10. package/dist/cdn/AD7WB3RO.js +4 -0
  11. package/dist/cdn/ASKBAWPQ.js +27 -0
  12. package/dist/cdn/BCCDWQP4.js +4 -0
  13. package/dist/cdn/CF42OIDB.js +4 -0
  14. package/dist/cdn/CGGGHCIN.js +4 -0
  15. package/dist/cdn/EJW7PCMD.js +4 -0
  16. package/dist/cdn/FORRN75L.js +4 -0
  17. package/dist/cdn/FYKWTA6C.js +58 -0
  18. package/dist/cdn/G7XEFTIR.js +4 -0
  19. package/dist/cdn/GRXZ64LO.js +20 -0
  20. package/dist/cdn/GZUY3255.js +61 -0
  21. package/dist/cdn/HPGCDT6I.js +4 -0
  22. package/dist/cdn/ID5STKZH.js +90 -0
  23. package/dist/cdn/J62NTCLN.js +4 -0
  24. package/dist/cdn/KMV7W5OL.js +4 -0
  25. package/dist/cdn/LILVLE37.js +87 -0
  26. package/dist/cdn/MXHQFIP3.js +19 -0
  27. package/dist/cdn/N4CYINOF.js +6 -0
  28. package/dist/cdn/NR6PK4OK.js +4 -0
  29. package/dist/cdn/PA2KCYKL.js +71 -0
  30. package/dist/cdn/PEFKT7JJ.js +4 -0
  31. package/dist/cdn/Q34AELDL.js +4 -0
  32. package/dist/cdn/Q3MKHRXI.js +4 -0
  33. package/dist/cdn/QIU4T2DV.js +4 -0
  34. package/dist/cdn/TCNLHL43.js +79 -0
  35. package/dist/cdn/UC4HPCM3.js +19 -0
  36. package/dist/cdn/UIUJKONY.js +4 -0
  37. package/dist/cdn/USJ5YVZN.js +16 -0
  38. package/dist/cdn/W4LEGPD2.js +111 -0
  39. package/dist/cdn/WOP5ENGJ.js +134 -0
  40. package/dist/cdn/YXLN5DSL.js +6 -0
  41. package/dist/cdn/ZQEX3TGK.js +17 -0
  42. package/dist/cdn/assets/assistant/t9n/messages.en.json +1 -0
  43. package/dist/cdn/assets/assistant-chat-card/t9n/messages.en.json +1 -0
  44. package/dist/cdn/assets/assistant-chat-entry/t9n/messages.en.json +1 -0
  45. package/dist/cdn/assets/assistant-interrupt/t9n/messages.en.json +1 -0
  46. package/dist/cdn/assets/assistant-shell/t9n/messages.en.json +1 -0
  47. package/dist/cdn/index.js +4 -0
  48. package/dist/cdn/main.css +1 -0
  49. package/dist/chunks/runtime.js +17 -0
  50. package/dist/chunks/useT9n.js +9 -0
  51. package/dist/chunks/utils.js +35 -0
  52. package/dist/chunks/utils2.js +9 -0
  53. package/dist/components/arcgis-assistant/customElement.d.ts +14 -0
  54. package/dist/components/arcgis-assistant/customElement.js +250 -0
  55. package/dist/components/arcgis-assistant/index.d.ts +5 -0
  56. package/dist/components/arcgis-assistant/index.js +5 -0
  57. package/dist/components/arcgis-assistant/support/OrchestratorController.d.ts +33 -0
  58. package/dist/components/arcgis-assistant/support/utils.d.ts +1 -0
  59. package/dist/components/arcgis-assistant-agent/customElement.d.ts +10 -0
  60. package/dist/components/arcgis-assistant-agent/customElement.js +21 -0
  61. package/dist/components/arcgis-assistant-agent/index.d.ts +1 -0
  62. package/dist/components/arcgis-assistant-agent/index.js +1 -0
  63. package/dist/components/arcgis-assistant-chat/customElement.d.ts +17 -0
  64. package/dist/components/arcgis-assistant-chat/customElement.js +47 -0
  65. package/dist/components/arcgis-assistant-chat/index.d.ts +2 -0
  66. package/dist/components/arcgis-assistant-chat/index.js +2 -0
  67. package/dist/components/arcgis-assistant-chat-card/customElement.d.ts +18 -0
  68. package/dist/components/arcgis-assistant-chat-card/customElement.js +55 -0
  69. package/dist/components/arcgis-assistant-chat-card/index.d.ts +6 -0
  70. package/dist/components/arcgis-assistant-chat-card/index.js +6 -0
  71. package/dist/components/arcgis-assistant-chat-card-content/customElement.d.ts +11 -0
  72. package/dist/components/arcgis-assistant-chat-card-content/customElement.js +42 -0
  73. package/dist/components/arcgis-assistant-chat-card-content/index.d.ts +2 -0
  74. package/dist/components/arcgis-assistant-chat-card-content/index.js +2 -0
  75. package/dist/components/arcgis-assistant-chat-entry/customElement.d.ts +19 -0
  76. package/dist/components/arcgis-assistant-chat-entry/customElement.js +46 -0
  77. package/dist/components/arcgis-assistant-chat-entry/index.d.ts +4 -0
  78. package/dist/components/arcgis-assistant-chat-entry/index.js +4 -0
  79. package/dist/components/arcgis-assistant-data-exploration-agent/customElement.d.ts +7 -0
  80. package/dist/components/arcgis-assistant-data-exploration-agent/customElement.js +28 -0
  81. package/dist/components/arcgis-assistant-data-exploration-agent/index.d.ts +1 -0
  82. package/dist/components/arcgis-assistant-data-exploration-agent/index.js +1 -0
  83. package/dist/components/arcgis-assistant-interrupt/customElement.d.ts +14 -0
  84. package/dist/components/arcgis-assistant-interrupt/customElement.js +39 -0
  85. package/dist/components/arcgis-assistant-interrupt/index.d.ts +6 -0
  86. package/dist/components/arcgis-assistant-interrupt/index.js +6 -0
  87. package/dist/components/arcgis-assistant-layer-filter-agent/customElement.d.ts +7 -0
  88. package/dist/components/arcgis-assistant-layer-filter-agent/customElement.js +28 -0
  89. package/dist/components/arcgis-assistant-layer-filter-agent/index.d.ts +1 -0
  90. package/dist/components/arcgis-assistant-layer-filter-agent/index.js +1 -0
  91. package/dist/components/arcgis-assistant-layer-query-agent/customElement.d.ts +7 -0
  92. package/dist/components/arcgis-assistant-layer-query-agent/customElement.js +28 -0
  93. package/dist/components/arcgis-assistant-layer-query-agent/index.d.ts +1 -0
  94. package/dist/components/arcgis-assistant-layer-query-agent/index.js +1 -0
  95. package/dist/components/arcgis-assistant-layer-styling-agent/customElement.d.ts +7 -0
  96. package/dist/components/arcgis-assistant-layer-styling-agent/customElement.js +28 -0
  97. package/dist/components/arcgis-assistant-layer-styling-agent/index.d.ts +1 -0
  98. package/dist/components/arcgis-assistant-layer-styling-agent/index.js +1 -0
  99. package/dist/components/arcgis-assistant-navigation-agent/customElement.d.ts +7 -0
  100. package/dist/components/arcgis-assistant-navigation-agent/customElement.js +28 -0
  101. package/dist/components/arcgis-assistant-navigation-agent/index.d.ts +1 -0
  102. package/dist/components/arcgis-assistant-navigation-agent/index.js +1 -0
  103. package/dist/components/arcgis-assistant-shell/customElement.d.ts +25 -0
  104. package/dist/components/arcgis-assistant-shell/customElement.js +29 -0
  105. package/dist/components/arcgis-assistant-shell/index.d.ts +6 -0
  106. package/dist/components/arcgis-assistant-shell/index.js +6 -0
  107. package/dist/components/assistant/assistant-agents/support/utils.d.ts +14 -0
  108. package/dist/controllers/useT9n.d.ts +1 -0
  109. package/dist/customAgents/AddAgent/AddAgent.d.ts +2 -0
  110. package/dist/docs/api.json +2239 -0
  111. package/dist/docs/docs.json +2011 -0
  112. package/dist/docs/vscode.css-custom-data.json +6 -0
  113. package/dist/docs/vscode.html-custom-data.json +306 -0
  114. package/dist/docs/web-types.json +693 -0
  115. package/dist/index.d.ts +99 -0
  116. package/dist/index.js +8 -0
  117. package/dist/loader.d.ts +2 -0
  118. package/dist/loader.js +23 -0
  119. package/dist/oauth-callback.html +31 -0
  120. package/dist/runtime.d.ts +6 -0
  121. package/dist/types/components.d.ts +2 -0
  122. package/dist/types/lumina.d.ts +80 -0
  123. package/dist/types/preact.d.ts +98 -0
  124. package/dist/types/react.d.ts +119 -0
  125. package/dist/types/stencil.d.ts +87 -0
  126. package/package.json +47 -0
@@ -0,0 +1,87 @@
1
+ /*! All material copyright Esri, All Rights Reserved, unless otherwise specified.
2
+ See https://js.arcgis.com/5.0/esri/copyright.txt for details.
3
+ v5.0.0-next.133 */
4
+ import{a as P,b as le,c as ot}from"./46CNQJRX.js";var Ko=P((Iv,Jo)=>{"use strict";Jo.exports=function(r,e){if(typeof r!="string")throw new TypeError("Expected a string");return e=typeof e>"u"?"_":e,r.replace(/([a-z\d])([A-Z])/g,"$1"+e+"$2").replace(/([A-Z]+)([A-Z][a-z\d]+)/g,"$1"+e+"$2").toLowerCase()}});var ru=P((Av,zs)=>{"use strict";var Ip=/[\p{Lu}]/u,Ap=/[\p{Ll}]/u,Wo=/^[\p{Lu}](?![\p{Lu}])/gu,Qo=/([\p{Alpha}\p{N}_]|$)/u,eu=/[_.\- ]+/,kp=new RegExp("^"+eu.source),Yo=new RegExp(eu.source+Qo.source,"gu"),Xo=new RegExp("\\d+"+Qo.source,"gu"),Pp=(r,e,t)=>{let n=!1,i=!1,s=!1;for(let a=0;a<r.length;a++){let o=r[a];n&&Ip.test(o)?(r=r.slice(0,a)+"-"+r.slice(a),n=!1,s=i,i=!0,a++):i&&s&&Ap.test(o)?(r=r.slice(0,a-1)+"-"+r.slice(a-1),s=i,i=!1,n=!0):(n=e(o)===o&&t(o)!==o,s=i,i=t(o)===o&&e(o)!==o)}return r},Rp=(r,e)=>(Wo.lastIndex=0,r.replace(Wo,t=>e(t))),Np=(r,e)=>(Yo.lastIndex=0,Xo.lastIndex=0,r.replace(Yo,(t,n)=>e(n)).replace(Xo,t=>e(t))),tu=(r,e)=>{if(!(typeof r=="string"||Array.isArray(r)))throw new TypeError("Expected the input to be `string | string[]`");if(e={pascalCase:!1,preserveConsecutiveUppercase:!1,...e},Array.isArray(r)?r=r.map(s=>s.trim()).filter(s=>s.length).join("-"):r=r.trim(),r.length===0)return"";let t=e.locale===!1?s=>s.toLowerCase():s=>s.toLocaleLowerCase(e.locale),n=e.locale===!1?s=>s.toUpperCase():s=>s.toLocaleUpperCase(e.locale);return r.length===1?e.pascalCase?n(r):t(r):(r!==t(r)&&(r=Pp(r,t,n)),r=r.replace(kp,""),e.preserveConsecutiveUppercase?r=Rp(r,t):r=t(r),e.pascalCase&&(r=n(r.charAt(0))+r.slice(1)),Np(r,n))};zs.exports=tu;zs.exports.default=tu});var Ou=P((bE,Tu)=>{function He(r,e){typeof e=="boolean"&&(e={forever:e}),this._originalTimeouts=JSON.parse(JSON.stringify(r)),this._timeouts=r,this._options=e||{},this._maxRetryTime=e&&e.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}Tu.exports=He;He.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};He.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};He.prototype.retry=function(r){if(this._timeout&&clearTimeout(this._timeout),!r)return!1;var e=new Date().getTime();if(r&&e-this._operationStart>=this._maxRetryTime)return this._errors.push(r),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(r);var t=this._timeouts.shift();if(t===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),t=this._cachedTimeouts.slice(-1);else return!1;var n=this;return this._timer=setTimeout(function(){n._attempts++,n._operationTimeoutCb&&(n._timeout=setTimeout(function(){n._operationTimeoutCb(n._attempts)},n._operationTimeout),n._options.unref&&n._timeout.unref()),n._fn(n._attempts)},t),this._options.unref&&this._timer.unref(),!0};He.prototype.attempt=function(r,e){this._fn=r,e&&(e.timeout&&(this._operationTimeout=e.timeout),e.cb&&(this._operationTimeoutCb=e.cb));var t=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){t._operationTimeoutCb()},t._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};He.prototype.try=function(r){console.log("Using RetryOperation.try() is deprecated"),this.attempt(r)};He.prototype.start=function(r){console.log("Using RetryOperation.start() is deprecated"),this.attempt(r)};He.prototype.start=He.prototype.try;He.prototype.errors=function(){return this._errors};He.prototype.attempts=function(){return this._attempts};He.prototype.mainError=function(){if(this._errors.length===0)return null;for(var r={},e=null,t=0,n=0;n<this._errors.length;n++){var i=this._errors[n],s=i.message,a=(r[s]||0)+1;r[s]=a,a>=t&&(e=i,t=a)}return e}});var $u=P(ur=>{var rm=Ou();ur.operation=function(r){var e=ur.timeouts(r);return new rm(e,{forever:r&&(r.forever||r.retries===1/0),unref:r&&r.unref,maxRetryTime:r&&r.maxRetryTime})};ur.timeouts=function(r){if(r instanceof Array)return[].concat(r);var e={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var t in r)e[t]=r[t];if(e.minTimeout>e.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var n=[],i=0;i<e.retries;i++)n.push(this.createTimeout(i,e));return r&&r.forever&&!n.length&&n.push(this.createTimeout(i,e)),n.sort(function(s,a){return s-a}),n};ur.createTimeout=function(r,e){var t=e.randomize?Math.random()+1:1,n=Math.round(t*Math.max(e.minTimeout,1)*Math.pow(e.factor,r));return n=Math.min(n,e.maxTimeout),n};ur.wrap=function(r,e,t){if(e instanceof Array&&(t=e,e=null),!t){t=[];for(var n in r)typeof r[n]=="function"&&t.push(n)}for(var i=0;i<t.length;i++){var s=t[i],a=r[s];r[s]=function(u){var c=ur.operation(e),l=Array.prototype.slice.call(arguments,1),d=l.pop();l.push(function(f){c.retry(f)||(f&&(arguments[0]=c.mainError()),d.apply(this,arguments))}),c.attempt(function(){u.apply(r,l)})}.bind(r,a),r[s].options=e}}});var Au=P((vE,Iu)=>{Iu.exports=$u()});var ri=P((xE,ti)=>{"use strict";var nm=Au(),im=["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed"],ei=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}},sm=(r,e,t)=>{let n=t.retries-(e-1);return r.attemptNumber=e,r.retriesLeft=n,r},am=r=>im.includes(r),ku=(r,e)=>new Promise((t,n)=>{e={onFailedAttempt:()=>{},retries:10,...e};let i=nm.operation(e);i.attempt(async s=>{try{t(await r(s))}catch(a){if(!(a instanceof Error)){n(new TypeError(`Non-error was thrown: "${a}". You should only throw errors.`));return}if(a instanceof ei)i.stop(),n(a.originalError);else if(a instanceof TypeError&&!am(a.message))i.stop(),n(a);else{sm(a,s,e);try{await e.onFailedAttempt(a)}catch(o){n(o);return}i.retry(a)||n(i.mainError())}}})});ti.exports=ku;ti.exports.default=ku;ti.exports.AbortError=ei});var Sc=P((C0,ya)=>{"use strict";var Fm=Object.prototype.hasOwnProperty,xe="~";function on(){}Object.create&&(on.prototype=Object.create(null),new on().__proto__||(xe=!1));function Zm(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function Ec(r,e,t,n,i){if(typeof t!="function")throw new TypeError("The listener must be a function");var s=new Zm(t,n||r,i),a=xe?xe+e:e;return r._events[a]?r._events[a].fn?r._events[a]=[r._events[a],s]:r._events[a].push(s):(r._events[a]=s,r._eventsCount++),r}function vi(r,e){--r._eventsCount===0?r._events=new on:delete r._events[e]}function be(){this._events=new on,this._eventsCount=0}be.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)Fm.call(t,n)&&e.push(xe?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};be.prototype.listeners=function(e){var t=xe?xe+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,s=n.length,a=new Array(s);i<s;i++)a[i]=n[i].fn;return a};be.prototype.listenerCount=function(e){var t=xe?xe+e:e,n=this._events[t];return n?n.fn?1:n.length:0};be.prototype.emit=function(e,t,n,i,s,a){var o=xe?xe+e:e;if(!this._events[o])return!1;var u=this._events[o],c=arguments.length,l,d;if(u.fn){switch(u.once&&this.removeListener(e,u.fn,void 0,!0),c){case 1:return u.fn.call(u.context),!0;case 2:return u.fn.call(u.context,t),!0;case 3:return u.fn.call(u.context,t,n),!0;case 4:return u.fn.call(u.context,t,n,i),!0;case 5:return u.fn.call(u.context,t,n,i,s),!0;case 6:return u.fn.call(u.context,t,n,i,s,a),!0}for(d=1,l=new Array(c-1);d<c;d++)l[d-1]=arguments[d];u.fn.apply(u.context,l)}else{var f=u.length,p;for(d=0;d<f;d++)switch(u[d].once&&this.removeListener(e,u[d].fn,void 0,!0),c){case 1:u[d].fn.call(u[d].context);break;case 2:u[d].fn.call(u[d].context,t);break;case 3:u[d].fn.call(u[d].context,t,n);break;case 4:u[d].fn.call(u[d].context,t,n,i);break;default:if(!l)for(p=1,l=new Array(c-1);p<c;p++)l[p-1]=arguments[p];u[d].fn.apply(u[d].context,l)}}return!0};be.prototype.on=function(e,t,n){return Ec(this,e,t,n,!1)};be.prototype.once=function(e,t,n){return Ec(this,e,t,n,!0)};be.prototype.removeListener=function(e,t,n,i){var s=xe?xe+e:e;if(!this._events[s])return this;if(!t)return vi(this,s),this;var a=this._events[s];if(a.fn)a.fn===t&&(!i||a.once)&&(!n||a.context===n)&&vi(this,s);else{for(var o=0,u=[],c=a.length;o<c;o++)(a[o].fn!==t||i&&!a[o].once||n&&a[o].context!==n)&&u.push(a[o]);u.length?this._events[s]=u.length===1?u[0]:u:vi(this,s)}return this};be.prototype.removeAllListeners=function(e){var t;return e?(t=xe?xe+e:e,this._events[t]&&vi(this,t)):(this._events=new on,this._eventsCount=0),this};be.prototype.off=be.prototype.removeListener;be.prototype.addListener=be.prototype.on;be.prefixed=xe;be.EventEmitter=be;typeof ya<"u"&&(ya.exports=be)});var Oc=P((j0,Tc)=>{"use strict";Tc.exports=(r,e)=>(e=e||(()=>{}),r.then(t=>new Promise(n=>{n(e())}).then(()=>t),t=>new Promise(n=>{n(e())}).then(()=>{throw t})))});var Ic=P((L0,Ei)=>{"use strict";var Bm=Oc(),xi=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},$c=(r,e,t)=>new Promise((n,i)=>{if(typeof e!="number"||e<0)throw new TypeError("Expected `milliseconds` to be a positive number");if(e===1/0){n(r);return}let s=setTimeout(()=>{if(typeof t=="function"){try{n(t())}catch(u){i(u)}return}let a=typeof t=="string"?t:`Promise timed out after ${e} milliseconds`,o=t instanceof Error?t:new xi(a);typeof r.cancel=="function"&&r.cancel(),i(o)},e);Bm(r.then(n,i),()=>{clearTimeout(s)})});Ei.exports=$c;Ei.exports.default=$c;Ei.exports.TimeoutError=xi});var Ac=P(ba=>{"use strict";Object.defineProperty(ba,"__esModule",{value:!0});function Gm(r,e,t){let n=0,i=r.length;for(;i>0;){let s=i/2|0,a=n+s;t(r[a],e)<=0?(n=++a,i-=s+1):i=s}return n}ba.default=Gm});var kc=P(va=>{"use strict";Object.defineProperty(va,"__esModule",{value:!0});var qm=Ac(),wa=class{constructor(){this._queue=[]}enqueue(e,t){t=Object.assign({priority:0},t);let n={priority:t.priority,run:e};if(this.size&&this._queue[this.size-1].priority>=t.priority){this._queue.push(n);return}let i=qm.default(this._queue,n,(s,a)=>a.priority-s.priority);this._queue.splice(i,0,n)}dequeue(){let e=this._queue.shift();return e?.run}filter(e){return this._queue.filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return this._queue.length}};va.default=wa});var Ti=P(Ea=>{"use strict";Object.defineProperty(Ea,"__esModule",{value:!0});var Vm=Sc(),Pc=Ic(),Hm=kc(),Si=()=>{},Jm=new Pc.TimeoutError,xa=class extends Vm{constructor(e){var t,n,i,s;if(super(),this._intervalCount=0,this._intervalEnd=0,this._pendingCount=0,this._resolveEmpty=Si,this._resolveIdle=Si,e=Object.assign({carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:Hm.default},e),!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(n=(t=e.intervalCap)===null||t===void 0?void 0:t.toString())!==null&&n!==void 0?n:""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(s=(i=e.interval)===null||i===void 0?void 0:i.toString())!==null&&s!==void 0?s:""}\` (${typeof e.interval})`);this._carryoverConcurrencyCount=e.carryoverConcurrencyCount,this._isIntervalIgnored=e.intervalCap===1/0||e.interval===0,this._intervalCap=e.intervalCap,this._interval=e.interval,this._queue=new e.queueClass,this._queueClass=e.queueClass,this.concurrency=e.concurrency,this._timeout=e.timeout,this._throwOnTimeout=e.throwOnTimeout===!0,this._isPaused=e.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=Si,this._pendingCount===0&&(this._resolveIdle(),this._resolveIdle=Si,this.emit("idle"))}_onResumeInterval(){this._onInterval(),this._initializeIntervalIfNeeded(),this._timeoutId=void 0}_isIntervalPaused(){let e=Date.now();if(this._intervalId===void 0){let t=this._intervalEnd-e;if(t<0)this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0;else return this._timeoutId===void 0&&(this._timeoutId=setTimeout(()=>{this._onResumeInterval()},t)),!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 e=!this._isIntervalPaused();if(this._doesIntervalAllowAnother&&this._doesConcurrentAllowAnother){let t=this._queue.dequeue();return t?(this.emit("active"),t(),e&&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(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this._concurrency=e,this._processQueue()}async add(e,t={}){return new Promise((n,i)=>{let s=async()=>{this._pendingCount++,this._intervalCount++;try{let a=this._timeout===void 0&&t.timeout===void 0?e():Pc.default(Promise.resolve(e()),t.timeout===void 0?this._timeout:t.timeout,()=>{(t.throwOnTimeout===void 0?this._throwOnTimeout:t.throwOnTimeout)&&i(Jm)});n(await a)}catch(a){i(a)}this._next()};this._queue.enqueue(s,t),this._tryToStartAnother(),this.emit("add")})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}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(e=>{let t=this._resolveEmpty;this._resolveEmpty=()=>{t(),e()}})}async onIdle(){if(!(this._pendingCount===0&&this._queue.size===0))return new Promise(e=>{let t=this._resolveIdle;this._resolveIdle=()=>{t(),e()}})}get size(){return this._queue.size}sizeBy(e){return this._queue.filter(e).length}get pending(){return this._pendingCount}get isPaused(){return this._isPaused}get timeout(){return this._timeout}set timeout(e){this._timeout=e}};Ea.default=xa});var ln=P((G0,Cc)=>{"use strict";var Ym="2.0.0",Xm=Number.MAX_SAFE_INTEGER||9007199254740991,Qm=16,eg=250,tg=["major","premajor","minor","preminor","patch","prepatch","prerelease"];Cc.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:Qm,MAX_SAFE_BUILD_LENGTH:eg,MAX_SAFE_INTEGER:Xm,RELEASE_TYPES:tg,SEMVER_SPEC_VERSION:Ym,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var dn=P((q0,jc)=>{"use strict";var rg=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...r)=>console.error("SEMVER",...r):()=>{};jc.exports=rg});var jr=P((pt,Lc)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:Oa,MAX_SAFE_BUILD_LENGTH:ng,MAX_LENGTH:ig}=ln(),sg=dn();pt=Lc.exports={};var ag=pt.re=[],og=pt.safeRe=[],T=pt.src=[],ug=pt.safeSrc=[],O=pt.t={},cg=0,$a="[a-zA-Z0-9-]",lg=[["\\s",1],["\\d",ig],[$a,ng]],dg=r=>{for(let[e,t]of lg)r=r.split(`${e}*`).join(`${e}{0,${t}}`).split(`${e}+`).join(`${e}{1,${t}}`);return r},Z=(r,e,t)=>{let n=dg(e),i=cg++;sg(r,i,e),O[r]=i,T[i]=e,ug[i]=n,ag[i]=new RegExp(e,t?"g":void 0),og[i]=new RegExp(n,t?"g":void 0)};Z("NUMERICIDENTIFIER","0|[1-9]\\d*");Z("NUMERICIDENTIFIERLOOSE","\\d+");Z("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${$a}*`);Z("MAINVERSION",`(${T[O.NUMERICIDENTIFIER]})\\.(${T[O.NUMERICIDENTIFIER]})\\.(${T[O.NUMERICIDENTIFIER]})`);Z("MAINVERSIONLOOSE",`(${T[O.NUMERICIDENTIFIERLOOSE]})\\.(${T[O.NUMERICIDENTIFIERLOOSE]})\\.(${T[O.NUMERICIDENTIFIERLOOSE]})`);Z("PRERELEASEIDENTIFIER",`(?:${T[O.NONNUMERICIDENTIFIER]}|${T[O.NUMERICIDENTIFIER]})`);Z("PRERELEASEIDENTIFIERLOOSE",`(?:${T[O.NONNUMERICIDENTIFIER]}|${T[O.NUMERICIDENTIFIERLOOSE]})`);Z("PRERELEASE",`(?:-(${T[O.PRERELEASEIDENTIFIER]}(?:\\.${T[O.PRERELEASEIDENTIFIER]})*))`);Z("PRERELEASELOOSE",`(?:-?(${T[O.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${T[O.PRERELEASEIDENTIFIERLOOSE]})*))`);Z("BUILDIDENTIFIER",`${$a}+`);Z("BUILD",`(?:\\+(${T[O.BUILDIDENTIFIER]}(?:\\.${T[O.BUILDIDENTIFIER]})*))`);Z("FULLPLAIN",`v?${T[O.MAINVERSION]}${T[O.PRERELEASE]}?${T[O.BUILD]}?`);Z("FULL",`^${T[O.FULLPLAIN]}$`);Z("LOOSEPLAIN",`[v=\\s]*${T[O.MAINVERSIONLOOSE]}${T[O.PRERELEASELOOSE]}?${T[O.BUILD]}?`);Z("LOOSE",`^${T[O.LOOSEPLAIN]}$`);Z("GTLT","((?:<|>)?=?)");Z("XRANGEIDENTIFIERLOOSE",`${T[O.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);Z("XRANGEIDENTIFIER",`${T[O.NUMERICIDENTIFIER]}|x|X|\\*`);Z("XRANGEPLAIN",`[v=\\s]*(${T[O.XRANGEIDENTIFIER]})(?:\\.(${T[O.XRANGEIDENTIFIER]})(?:\\.(${T[O.XRANGEIDENTIFIER]})(?:${T[O.PRERELEASE]})?${T[O.BUILD]}?)?)?`);Z("XRANGEPLAINLOOSE",`[v=\\s]*(${T[O.XRANGEIDENTIFIERLOOSE]})(?:\\.(${T[O.XRANGEIDENTIFIERLOOSE]})(?:\\.(${T[O.XRANGEIDENTIFIERLOOSE]})(?:${T[O.PRERELEASELOOSE]})?${T[O.BUILD]}?)?)?`);Z("XRANGE",`^${T[O.GTLT]}\\s*${T[O.XRANGEPLAIN]}$`);Z("XRANGELOOSE",`^${T[O.GTLT]}\\s*${T[O.XRANGEPLAINLOOSE]}$`);Z("COERCEPLAIN",`(^|[^\\d])(\\d{1,${Oa}})(?:\\.(\\d{1,${Oa}}))?(?:\\.(\\d{1,${Oa}}))?`);Z("COERCE",`${T[O.COERCEPLAIN]}(?:$|[^\\d])`);Z("COERCEFULL",T[O.COERCEPLAIN]+`(?:${T[O.PRERELEASE]})?(?:${T[O.BUILD]})?(?:$|[^\\d])`);Z("COERCERTL",T[O.COERCE],!0);Z("COERCERTLFULL",T[O.COERCEFULL],!0);Z("LONETILDE","(?:~>?)");Z("TILDETRIM",`(\\s*)${T[O.LONETILDE]}\\s+`,!0);pt.tildeTrimReplace="$1~";Z("TILDE",`^${T[O.LONETILDE]}${T[O.XRANGEPLAIN]}$`);Z("TILDELOOSE",`^${T[O.LONETILDE]}${T[O.XRANGEPLAINLOOSE]}$`);Z("LONECARET","(?:\\^)");Z("CARETTRIM",`(\\s*)${T[O.LONECARET]}\\s+`,!0);pt.caretTrimReplace="$1^";Z("CARET",`^${T[O.LONECARET]}${T[O.XRANGEPLAIN]}$`);Z("CARETLOOSE",`^${T[O.LONECARET]}${T[O.XRANGEPLAINLOOSE]}$`);Z("COMPARATORLOOSE",`^${T[O.GTLT]}\\s*(${T[O.LOOSEPLAIN]})$|^$`);Z("COMPARATOR",`^${T[O.GTLT]}\\s*(${T[O.FULLPLAIN]})$|^$`);Z("COMPARATORTRIM",`(\\s*)${T[O.GTLT]}\\s*(${T[O.LOOSEPLAIN]}|${T[O.XRANGEPLAIN]})`,!0);pt.comparatorTrimReplace="$1$2$3";Z("HYPHENRANGE",`^\\s*(${T[O.XRANGEPLAIN]})\\s+-\\s+(${T[O.XRANGEPLAIN]})\\s*$`);Z("HYPHENRANGELOOSE",`^\\s*(${T[O.XRANGEPLAINLOOSE]})\\s+-\\s+(${T[O.XRANGEPLAINLOOSE]})\\s*$`);Z("STAR","(<|>)?=?\\s*\\*");Z("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");Z("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var $i=P((V0,zc)=>{"use strict";var fg=Object.freeze({loose:!0}),pg=Object.freeze({}),hg=r=>r?typeof r!="object"?fg:r:pg;zc.exports=hg});var Ia=P((H0,Uc)=>{"use strict";var Mc=/^[0-9]+$/,Dc=(r,e)=>{if(typeof r=="number"&&typeof e=="number")return r===e?0:r<e?-1:1;let t=Mc.test(r),n=Mc.test(e);return t&&n&&(r=+r,e=+e),r===e?0:t&&!n?-1:n&&!t?1:r<e?-1:1},mg=(r,e)=>Dc(e,r);Uc.exports={compareIdentifiers:Dc,rcompareIdentifiers:mg}});var we=P((J0,Zc)=>{"use strict";var Ii=dn(),{MAX_LENGTH:Fc,MAX_SAFE_INTEGER:Ai}=ln(),{safeRe:ki,t:Pi}=jr(),gg=$i(),{compareIdentifiers:Aa}=Ia(),ka=class r{constructor(e,t){if(t=gg(t),e instanceof r){if(e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease)return e;e=e.version}else if(typeof e!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof e}".`);if(e.length>Fc)throw new TypeError(`version is longer than ${Fc} characters`);Ii("SemVer",e,t),this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease;let n=e.trim().match(t.loose?ki[Pi.LOOSE]:ki[Pi.FULL]);if(!n)throw new TypeError(`Invalid Version: ${e}`);if(this.raw=e,this.major=+n[1],this.minor=+n[2],this.patch=+n[3],this.major>Ai||this.major<0)throw new TypeError("Invalid major version");if(this.minor>Ai||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>Ai||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<Ai)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(e){if(Ii("SemVer.compare",this.version,this.options,e),!(e instanceof r)){if(typeof e=="string"&&e===this.version)return 0;e=new r(e,this.options)}return e.version===this.version?0:this.compareMain(e)||this.comparePre(e)}compareMain(e){return e instanceof r||(e=new r(e,this.options)),this.major<e.major?-1:this.major>e.major?1:this.minor<e.minor?-1:this.minor>e.minor?1:this.patch<e.patch?-1:this.patch>e.patch?1:0}comparePre(e){if(e instanceof r||(e=new r(e,this.options)),this.prerelease.length&&!e.prerelease.length)return-1;if(!this.prerelease.length&&e.prerelease.length)return 1;if(!this.prerelease.length&&!e.prerelease.length)return 0;let t=0;do{let n=this.prerelease[t],i=e.prerelease[t];if(Ii("prerelease compare",t,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 Aa(n,i)}while(++t)}compareBuild(e){e instanceof r||(e=new r(e,this.options));let t=0;do{let n=this.build[t],i=e.build[t];if(Ii("build compare",t,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 Aa(n,i)}while(++t)}inc(e,t,n){if(e.startsWith("pre")){if(!t&&n===!1)throw new Error("invalid increment argument: identifier is empty");if(t){let i=`-${t}`.match(this.options.loose?ki[Pi.PRERELEASELOOSE]:ki[Pi.PRERELEASE]);if(!i||i[1]!==t)throw new Error(`invalid identifier: ${t}`)}}switch(e){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",t,n);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",t,n);break;case"prepatch":this.prerelease.length=0,this.inc("patch",t,n),this.inc("pre",t,n);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",t,n),this.inc("pre",t,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(t===this.prerelease.join(".")&&n===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(i)}}if(t){let s=[t,i];n===!1&&(s=[t]),Aa(this.prerelease[0],t)===0?isNaN(this.prerelease[1])&&(this.prerelease=s):this.prerelease=s}break}default:throw new Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};Zc.exports=ka});var pr=P((K0,Gc)=>{"use strict";var Bc=we(),_g=(r,e,t=!1)=>{if(r instanceof Bc)return r;try{return new Bc(r,e)}catch(n){if(!t)return null;throw n}};Gc.exports=_g});var Vc=P((W0,qc)=>{"use strict";var yg=pr(),bg=(r,e)=>{let t=yg(r,e);return t?t.version:null};qc.exports=bg});var Jc=P((Y0,Hc)=>{"use strict";var wg=pr(),vg=(r,e)=>{let t=wg(r.trim().replace(/^[=v]+/,""),e);return t?t.version:null};Hc.exports=vg});var Yc=P((X0,Wc)=>{"use strict";var Kc=we(),xg=(r,e,t,n,i)=>{typeof t=="string"&&(i=n,n=t,t=void 0);try{return new Kc(r instanceof Kc?r.version:r,t).inc(e,n,i).version}catch{return null}};Wc.exports=xg});var el=P((Q0,Qc)=>{"use strict";var Xc=pr(),Eg=(r,e)=>{let t=Xc(r,null,!0),n=Xc(e,null,!0),i=t.compare(n);if(i===0)return null;let s=i>0,a=s?t:n,o=s?n:t,u=!!a.prerelease.length;if(!!o.prerelease.length&&!u){if(!o.patch&&!o.minor)return"major";if(o.compareMain(a)===0)return o.minor&&!o.patch?"minor":"patch"}let l=u?"pre":"";return t.major!==n.major?l+"major":t.minor!==n.minor?l+"minor":t.patch!==n.patch?l+"patch":"prerelease"};Qc.exports=Eg});var rl=P((eS,tl)=>{"use strict";var Sg=we(),Tg=(r,e)=>new Sg(r,e).major;tl.exports=Tg});var il=P((tS,nl)=>{"use strict";var Og=we(),$g=(r,e)=>new Og(r,e).minor;nl.exports=$g});var al=P((rS,sl)=>{"use strict";var Ig=we(),Ag=(r,e)=>new Ig(r,e).patch;sl.exports=Ag});var ul=P((nS,ol)=>{"use strict";var kg=pr(),Pg=(r,e)=>{let t=kg(r,e);return t&&t.prerelease.length?t.prerelease:null};ol.exports=Pg});var Je=P((iS,ll)=>{"use strict";var cl=we(),Rg=(r,e,t)=>new cl(r,t).compare(new cl(e,t));ll.exports=Rg});var fl=P((sS,dl)=>{"use strict";var Ng=Je(),Cg=(r,e,t)=>Ng(e,r,t);dl.exports=Cg});var hl=P((aS,pl)=>{"use strict";var jg=Je(),Lg=(r,e)=>jg(r,e,!0);pl.exports=Lg});var Ri=P((oS,gl)=>{"use strict";var ml=we(),zg=(r,e,t)=>{let n=new ml(r,t),i=new ml(e,t);return n.compare(i)||n.compareBuild(i)};gl.exports=zg});var yl=P((uS,_l)=>{"use strict";var Mg=Ri(),Dg=(r,e)=>r.sort((t,n)=>Mg(t,n,e));_l.exports=Dg});var wl=P((cS,bl)=>{"use strict";var Ug=Ri(),Fg=(r,e)=>r.sort((t,n)=>Ug(n,t,e));bl.exports=Fg});var fn=P((lS,vl)=>{"use strict";var Zg=Je(),Bg=(r,e,t)=>Zg(r,e,t)>0;vl.exports=Bg});var Ni=P((dS,xl)=>{"use strict";var Gg=Je(),qg=(r,e,t)=>Gg(r,e,t)<0;xl.exports=qg});var Pa=P((fS,El)=>{"use strict";var Vg=Je(),Hg=(r,e,t)=>Vg(r,e,t)===0;El.exports=Hg});var Ra=P((pS,Sl)=>{"use strict";var Jg=Je(),Kg=(r,e,t)=>Jg(r,e,t)!==0;Sl.exports=Kg});var Ci=P((hS,Tl)=>{"use strict";var Wg=Je(),Yg=(r,e,t)=>Wg(r,e,t)>=0;Tl.exports=Yg});var ji=P((mS,Ol)=>{"use strict";var Xg=Je(),Qg=(r,e,t)=>Xg(r,e,t)<=0;Ol.exports=Qg});var Na=P((gS,$l)=>{"use strict";var e_=Pa(),t_=Ra(),r_=fn(),n_=Ci(),i_=Ni(),s_=ji(),a_=(r,e,t,n)=>{switch(e){case"===":return typeof r=="object"&&(r=r.version),typeof t=="object"&&(t=t.version),r===t;case"!==":return typeof r=="object"&&(r=r.version),typeof t=="object"&&(t=t.version),r!==t;case"":case"=":case"==":return e_(r,t,n);case"!=":return t_(r,t,n);case">":return r_(r,t,n);case">=":return n_(r,t,n);case"<":return i_(r,t,n);case"<=":return s_(r,t,n);default:throw new TypeError(`Invalid operator: ${e}`)}};$l.exports=a_});var Al=P((_S,Il)=>{"use strict";var o_=we(),u_=pr(),{safeRe:Li,t:zi}=jr(),c_=(r,e)=>{if(r instanceof o_)return r;if(typeof r=="number"&&(r=String(r)),typeof r!="string")return null;e=e||{};let t=null;if(!e.rtl)t=r.match(e.includePrerelease?Li[zi.COERCEFULL]:Li[zi.COERCE]);else{let u=e.includePrerelease?Li[zi.COERCERTLFULL]:Li[zi.COERCERTL],c;for(;(c=u.exec(r))&&(!t||t.index+t[0].length!==r.length);)(!t||c.index+c[0].length!==t.index+t[0].length)&&(t=c),u.lastIndex=c.index+c[1].length+c[2].length;u.lastIndex=-1}if(t===null)return null;let n=t[2],i=t[3]||"0",s=t[4]||"0",a=e.includePrerelease&&t[5]?`-${t[5]}`:"",o=e.includePrerelease&&t[6]?`+${t[6]}`:"";return u_(`${n}.${i}.${s}${a}${o}`,e)};Il.exports=c_});var Pl=P((yS,kl)=>{"use strict";var Ca=class{constructor(){this.max=1e3,this.map=new Map}get(e){let t=this.map.get(e);if(t!==void 0)return this.map.delete(e),this.map.set(e,t),t}delete(e){return this.map.delete(e)}set(e,t){if(!this.delete(e)&&t!==void 0){if(this.map.size>=this.max){let i=this.map.keys().next().value;this.delete(i)}this.map.set(e,t)}return this}};kl.exports=Ca});var Ke=P((bS,jl)=>{"use strict";var l_=/\s+/g,ja=class r{constructor(e,t){if(t=f_(t),e instanceof r)return e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease?e:new r(e.raw,t);if(e instanceof La)return this.raw=e.value,this.set=[[e]],this.formatted=void 0,this;if(this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease,this.raw=e.trim().replace(l_," "),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=>!Nl(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&&b_(i[0])){this.set=[i];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let e=0;e<this.set.length;e++){e>0&&(this.formatted+="||");let t=this.set[e];for(let n=0;n<t.length;n++)n>0&&(this.formatted+=" "),this.formatted+=t[n].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(e){let n=((this.options.includePrerelease&&__)|(this.options.loose&&y_))+":"+e,i=Rl.get(n);if(i)return i;let s=this.options.loose,a=s?Ee[ve.HYPHENRANGELOOSE]:Ee[ve.HYPHENRANGE];e=e.replace(a,A_(this.options.includePrerelease)),Y("hyphen replace",e),e=e.replace(Ee[ve.COMPARATORTRIM],h_),Y("comparator trim",e),e=e.replace(Ee[ve.TILDETRIM],m_),Y("tilde trim",e),e=e.replace(Ee[ve.CARETTRIM],g_),Y("caret trim",e);let o=e.split(" ").map(d=>w_(d,this.options)).join(" ").split(/\s+/).map(d=>I_(d,this.options));s&&(o=o.filter(d=>(Y("loose invalid filter",d,this.options),!!d.match(Ee[ve.COMPARATORLOOSE])))),Y("range list",o);let u=new Map,c=o.map(d=>new La(d,this.options));for(let d of c){if(Nl(d))return[d];u.set(d.value,d)}u.size>1&&u.has("")&&u.delete("");let l=[...u.values()];return Rl.set(n,l),l}intersects(e,t){if(!(e instanceof r))throw new TypeError("a Range is required");return this.set.some(n=>Cl(n,t)&&e.set.some(i=>Cl(i,t)&&n.every(s=>i.every(a=>s.intersects(a,t)))))}test(e){if(!e)return!1;if(typeof e=="string")try{e=new p_(e,this.options)}catch{return!1}for(let t=0;t<this.set.length;t++)if(k_(this.set[t],e,this.options))return!0;return!1}};jl.exports=ja;var d_=Pl(),Rl=new d_,f_=$i(),La=pn(),Y=dn(),p_=we(),{safeRe:Ee,t:ve,comparatorTrimReplace:h_,tildeTrimReplace:m_,caretTrimReplace:g_}=jr(),{FLAG_INCLUDE_PRERELEASE:__,FLAG_LOOSE:y_}=ln(),Nl=r=>r.value==="<0.0.0-0",b_=r=>r.value==="",Cl=(r,e)=>{let t=!0,n=r.slice(),i=n.pop();for(;t&&n.length;)t=n.every(s=>i.intersects(s,e)),i=n.pop();return t},w_=(r,e)=>(r=r.replace(Ee[ve.BUILD],""),Y("comp",r,e),r=E_(r,e),Y("caret",r),r=v_(r,e),Y("tildes",r),r=T_(r,e),Y("xrange",r),r=$_(r,e),Y("stars",r),r),Se=r=>!r||r.toLowerCase()==="x"||r==="*",v_=(r,e)=>r.trim().split(/\s+/).map(t=>x_(t,e)).join(" "),x_=(r,e)=>{let t=e.loose?Ee[ve.TILDELOOSE]:Ee[ve.TILDE];return r.replace(t,(n,i,s,a,o)=>{Y("tilde",r,n,i,s,a,o);let u;return Se(i)?u="":Se(s)?u=`>=${i}.0.0 <${+i+1}.0.0-0`:Se(a)?u=`>=${i}.${s}.0 <${i}.${+s+1}.0-0`:o?(Y("replaceTilde pr",o),u=`>=${i}.${s}.${a}-${o} <${i}.${+s+1}.0-0`):u=`>=${i}.${s}.${a} <${i}.${+s+1}.0-0`,Y("tilde return",u),u})},E_=(r,e)=>r.trim().split(/\s+/).map(t=>S_(t,e)).join(" "),S_=(r,e)=>{Y("caret",r,e);let t=e.loose?Ee[ve.CARETLOOSE]:Ee[ve.CARET],n=e.includePrerelease?"-0":"";return r.replace(t,(i,s,a,o,u)=>{Y("caret",r,i,s,a,o,u);let c;return Se(s)?c="":Se(a)?c=`>=${s}.0.0${n} <${+s+1}.0.0-0`:Se(o)?s==="0"?c=`>=${s}.${a}.0${n} <${s}.${+a+1}.0-0`:c=`>=${s}.${a}.0${n} <${+s+1}.0.0-0`:u?(Y("replaceCaret pr",u),s==="0"?a==="0"?c=`>=${s}.${a}.${o}-${u} <${s}.${a}.${+o+1}-0`:c=`>=${s}.${a}.${o}-${u} <${s}.${+a+1}.0-0`:c=`>=${s}.${a}.${o}-${u} <${+s+1}.0.0-0`):(Y("no pr"),s==="0"?a==="0"?c=`>=${s}.${a}.${o}${n} <${s}.${a}.${+o+1}-0`:c=`>=${s}.${a}.${o}${n} <${s}.${+a+1}.0-0`:c=`>=${s}.${a}.${o} <${+s+1}.0.0-0`),Y("caret return",c),c})},T_=(r,e)=>(Y("replaceXRanges",r,e),r.split(/\s+/).map(t=>O_(t,e)).join(" ")),O_=(r,e)=>{r=r.trim();let t=e.loose?Ee[ve.XRANGELOOSE]:Ee[ve.XRANGE];return r.replace(t,(n,i,s,a,o,u)=>{Y("xRange",r,n,i,s,a,o,u);let c=Se(s),l=c||Se(a),d=l||Se(o),f=d;return i==="="&&f&&(i=""),u=e.includePrerelease?"-0":"",c?i===">"||i==="<"?n="<0.0.0-0":n="*":i&&f?(l&&(a=0),o=0,i===">"?(i=">=",l?(s=+s+1,a=0,o=0):(a=+a+1,o=0)):i==="<="&&(i="<",l?s=+s+1:a=+a+1),i==="<"&&(u="-0"),n=`${i+s}.${a}.${o}${u}`):l?n=`>=${s}.0.0${u} <${+s+1}.0.0-0`:d&&(n=`>=${s}.${a}.0${u} <${s}.${+a+1}.0-0`),Y("xRange return",n),n})},$_=(r,e)=>(Y("replaceStars",r,e),r.trim().replace(Ee[ve.STAR],"")),I_=(r,e)=>(Y("replaceGTE0",r,e),r.trim().replace(Ee[e.includePrerelease?ve.GTE0PRE:ve.GTE0],"")),A_=r=>(e,t,n,i,s,a,o,u,c,l,d,f)=>(Se(n)?t="":Se(i)?t=`>=${n}.0.0${r?"-0":""}`:Se(s)?t=`>=${n}.${i}.0${r?"-0":""}`:a?t=`>=${t}`:t=`>=${t}${r?"-0":""}`,Se(c)?u="":Se(l)?u=`<${+c+1}.0.0-0`:Se(d)?u=`<${c}.${+l+1}.0-0`:f?u=`<=${c}.${l}.${d}-${f}`:r?u=`<${c}.${l}.${+d+1}-0`:u=`<=${u}`,`${t} ${u}`.trim()),k_=(r,e,t)=>{for(let n=0;n<r.length;n++)if(!r[n].test(e))return!1;if(e.prerelease.length&&!t.includePrerelease){for(let n=0;n<r.length;n++)if(Y(r[n].semver),r[n].semver!==La.ANY&&r[n].semver.prerelease.length>0){let i=r[n].semver;if(i.major===e.major&&i.minor===e.minor&&i.patch===e.patch)return!0}return!1}return!0}});var pn=P((wS,Fl)=>{"use strict";var hn=Symbol("SemVer ANY"),Da=class r{static get ANY(){return hn}constructor(e,t){if(t=Ll(t),e instanceof r){if(e.loose===!!t.loose)return e;e=e.value}e=e.trim().split(/\s+/).join(" "),Ma("comparator",e,t),this.options=t,this.loose=!!t.loose,this.parse(e),this.semver===hn?this.value="":this.value=this.operator+this.semver.version,Ma("comp",this)}parse(e){let t=this.options.loose?zl[Ml.COMPARATORLOOSE]:zl[Ml.COMPARATOR],n=e.match(t);if(!n)throw new TypeError(`Invalid comparator: ${e}`);this.operator=n[1]!==void 0?n[1]:"",this.operator==="="&&(this.operator=""),n[2]?this.semver=new Dl(n[2],this.options.loose):this.semver=hn}toString(){return this.value}test(e){if(Ma("Comparator.test",e,this.options.loose),this.semver===hn||e===hn)return!0;if(typeof e=="string")try{e=new Dl(e,this.options)}catch{return!1}return za(e,this.operator,this.semver,this.options)}intersects(e,t){if(!(e instanceof r))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new Ul(e.value,t).test(this.value):e.operator===""?e.value===""?!0:new Ul(this.value,t).test(e.semver):(t=Ll(t),t.includePrerelease&&(this.value==="<0.0.0-0"||e.value==="<0.0.0-0")||!t.includePrerelease&&(this.value.startsWith("<0.0.0")||e.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&e.operator.startsWith(">")||this.operator.startsWith("<")&&e.operator.startsWith("<")||this.semver.version===e.semver.version&&this.operator.includes("=")&&e.operator.includes("=")||za(this.semver,"<",e.semver,t)&&this.operator.startsWith(">")&&e.operator.startsWith("<")||za(this.semver,">",e.semver,t)&&this.operator.startsWith("<")&&e.operator.startsWith(">")))}};Fl.exports=Da;var Ll=$i(),{safeRe:zl,t:Ml}=jr(),za=Na(),Ma=dn(),Dl=we(),Ul=Ke()});var mn=P((vS,Zl)=>{"use strict";var P_=Ke(),R_=(r,e,t)=>{try{e=new P_(e,t)}catch{return!1}return e.test(r)};Zl.exports=R_});var Gl=P((xS,Bl)=>{"use strict";var N_=Ke(),C_=(r,e)=>new N_(r,e).set.map(t=>t.map(n=>n.value).join(" ").trim().split(" "));Bl.exports=C_});var Vl=P((ES,ql)=>{"use strict";var j_=we(),L_=Ke(),z_=(r,e,t)=>{let n=null,i=null,s=null;try{s=new L_(e,t)}catch{return null}return r.forEach(a=>{s.test(a)&&(!n||i.compare(a)===-1)&&(n=a,i=new j_(n,t))}),n};ql.exports=z_});var Jl=P((SS,Hl)=>{"use strict";var M_=we(),D_=Ke(),U_=(r,e,t)=>{let n=null,i=null,s=null;try{s=new D_(e,t)}catch{return null}return r.forEach(a=>{s.test(a)&&(!n||i.compare(a)===1)&&(n=a,i=new M_(n,t))}),n};Hl.exports=U_});var Yl=P((TS,Wl)=>{"use strict";var Ua=we(),F_=Ke(),Kl=fn(),Z_=(r,e)=>{r=new F_(r,e);let t=new Ua("0.0.0");if(r.test(t)||(t=new Ua("0.0.0-0"),r.test(t)))return t;t=null;for(let n=0;n<r.set.length;++n){let i=r.set[n],s=null;i.forEach(a=>{let o=new Ua(a.semver.version);switch(a.operator){case">":o.prerelease.length===0?o.patch++:o.prerelease.push(0),o.raw=o.format();case"":case">=":(!s||Kl(o,s))&&(s=o);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${a.operator}`)}}),s&&(!t||Kl(t,s))&&(t=s)}return t&&r.test(t)?t:null};Wl.exports=Z_});var Ql=P((OS,Xl)=>{"use strict";var B_=Ke(),G_=(r,e)=>{try{return new B_(r,e).range||"*"}catch{return null}};Xl.exports=G_});var Mi=P(($S,nd)=>{"use strict";var q_=we(),rd=pn(),{ANY:V_}=rd,H_=Ke(),J_=mn(),ed=fn(),td=Ni(),K_=ji(),W_=Ci(),Y_=(r,e,t,n)=>{r=new q_(r,n),e=new H_(e,n);let i,s,a,o,u;switch(t){case">":i=ed,s=K_,a=td,o=">",u=">=";break;case"<":i=td,s=W_,a=ed,o="<",u="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(J_(r,e,n))return!1;for(let c=0;c<e.set.length;++c){let l=e.set[c],d=null,f=null;if(l.forEach(p=>{p.semver===V_&&(p=new rd(">=0.0.0")),d=d||p,f=f||p,i(p.semver,d.semver,n)?d=p:a(p.semver,f.semver,n)&&(f=p)}),d.operator===o||d.operator===u||(!f.operator||f.operator===o)&&s(r,f.semver))return!1;if(f.operator===u&&a(r,f.semver))return!1}return!0};nd.exports=Y_});var sd=P((IS,id)=>{"use strict";var X_=Mi(),Q_=(r,e,t)=>X_(r,e,">",t);id.exports=Q_});var od=P((AS,ad)=>{"use strict";var ey=Mi(),ty=(r,e,t)=>ey(r,e,"<",t);ad.exports=ty});var ld=P((kS,cd)=>{"use strict";var ud=Ke(),ry=(r,e,t)=>(r=new ud(r,t),e=new ud(e,t),r.intersects(e,t));cd.exports=ry});var fd=P((PS,dd)=>{"use strict";var ny=mn(),iy=Je();dd.exports=(r,e,t)=>{let n=[],i=null,s=null,a=r.sort((l,d)=>iy(l,d,t));for(let l of a)ny(l,e,t)?(s=l,i||(i=l)):(s&&n.push([i,s]),s=null,i=null);i&&n.push([i,null]);let o=[];for(let[l,d]of n)l===d?o.push(l):!d&&l===a[0]?o.push("*"):d?l===a[0]?o.push(`<=${d}`):o.push(`${l} - ${d}`):o.push(`>=${l}`);let u=o.join(" || "),c=typeof e.raw=="string"?e.raw:String(e);return u.length<c.length?u:e}});var yd=P((RS,_d)=>{"use strict";var pd=Ke(),Za=pn(),{ANY:Fa}=Za,gn=mn(),Ba=Je(),sy=(r,e,t={})=>{if(r===e)return!0;r=new pd(r,t),e=new pd(e,t);let n=!1;e:for(let i of r.set){for(let s of e.set){let a=oy(i,s,t);if(n=n||a!==null,a)continue e}if(n)return!1}return!0},ay=[new Za(">=0.0.0-0")],hd=[new Za(">=0.0.0")],oy=(r,e,t)=>{if(r===e)return!0;if(r.length===1&&r[0].semver===Fa){if(e.length===1&&e[0].semver===Fa)return!0;t.includePrerelease?r=ay:r=hd}if(e.length===1&&e[0].semver===Fa){if(t.includePrerelease)return!0;e=hd}let n=new Set,i,s;for(let p of r)p.operator===">"||p.operator===">="?i=md(i,p,t):p.operator==="<"||p.operator==="<="?s=gd(s,p,t):n.add(p.semver);if(n.size>1)return null;let a;if(i&&s){if(a=Ba(i.semver,s.semver,t),a>0)return null;if(a===0&&(i.operator!==">="||s.operator!=="<="))return null}for(let p of n){if(i&&!gn(p,String(i),t)||s&&!gn(p,String(s),t))return null;for(let h of e)if(!gn(p,String(h),t))return!1;return!0}let o,u,c,l,d=s&&!t.includePrerelease&&s.semver.prerelease.length?s.semver:!1,f=i&&!t.includePrerelease&&i.semver.prerelease.length?i.semver:!1;d&&d.prerelease.length===1&&s.operator==="<"&&d.prerelease[0]===0&&(d=!1);for(let p of e){if(l=l||p.operator===">"||p.operator===">=",c=c||p.operator==="<"||p.operator==="<=",i){if(f&&p.semver.prerelease&&p.semver.prerelease.length&&p.semver.major===f.major&&p.semver.minor===f.minor&&p.semver.patch===f.patch&&(f=!1),p.operator===">"||p.operator===">="){if(o=md(i,p,t),o===p&&o!==i)return!1}else if(i.operator===">="&&!gn(i.semver,String(p),t))return!1}if(s){if(d&&p.semver.prerelease&&p.semver.prerelease.length&&p.semver.major===d.major&&p.semver.minor===d.minor&&p.semver.patch===d.patch&&(d=!1),p.operator==="<"||p.operator==="<="){if(u=gd(s,p,t),u===p&&u!==s)return!1}else if(s.operator==="<="&&!gn(s.semver,String(p),t))return!1}if(!p.operator&&(s||i)&&a!==0)return!1}return!(i&&c&&!s&&a!==0||s&&l&&!i&&a!==0||f||d)},md=(r,e,t)=>{if(!r)return e;let n=Ba(r.semver,e.semver,t);return n>0?r:n<0||e.operator===">"&&r.operator===">="?e:r},gd=(r,e,t)=>{if(!r)return e;let n=Ba(r.semver,e.semver,t);return n<0?r:n>0||e.operator==="<"&&r.operator==="<="?e:r};_d.exports=sy});var xd=P((NS,vd)=>{"use strict";var Ga=jr(),bd=ln(),uy=we(),wd=Ia(),cy=pr(),ly=Vc(),dy=Jc(),fy=Yc(),py=el(),hy=rl(),my=il(),gy=al(),_y=ul(),yy=Je(),by=fl(),wy=hl(),vy=Ri(),xy=yl(),Ey=wl(),Sy=fn(),Ty=Ni(),Oy=Pa(),$y=Ra(),Iy=Ci(),Ay=ji(),ky=Na(),Py=Al(),Ry=pn(),Ny=Ke(),Cy=mn(),jy=Gl(),Ly=Vl(),zy=Jl(),My=Yl(),Dy=Ql(),Uy=Mi(),Fy=sd(),Zy=od(),By=ld(),Gy=fd(),qy=yd();vd.exports={parse:cy,valid:ly,clean:dy,inc:fy,diff:py,major:hy,minor:my,patch:gy,prerelease:_y,compare:yy,rcompare:by,compareLoose:wy,compareBuild:vy,sort:xy,rsort:Ey,gt:Sy,lt:Ty,eq:Oy,neq:$y,gte:Iy,lte:Ay,cmp:ky,coerce:Py,Comparator:Ry,Range:Ny,satisfies:Cy,toComparators:jy,maxSatisfying:Ly,minSatisfying:zy,minVersion:My,validRange:Dy,outside:Uy,gtr:Fy,ltr:Zy,intersects:By,simplifyRange:Gy,subset:qy,SemVer:uy,re:Ga.re,src:Ga.src,tokens:Ga.t,SEMVER_SPEC_VERSION:bd.SEMVER_SPEC_VERSION,RELEASE_TYPES:bd.RELEASE_TYPES,compareIdentifiers:wd.compareIdentifiers,rcompareIdentifiers:wd.rcompareIdentifiers}});var Bd=P((gT,Zd)=>{"use strict";var Ud=(r=0)=>e=>`\x1B[${38+r};5;${e}m`,Fd=(r=0)=>(e,t,n)=>`\x1B[${38+r};2;${e};${t};${n}m`;function yb(){let r=new Map,e={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]}};e.color.gray=e.color.blackBright,e.bgColor.bgGray=e.bgColor.bgBlackBright,e.color.grey=e.color.blackBright,e.bgColor.bgGrey=e.bgColor.bgBlackBright;for(let[t,n]of Object.entries(e)){for(let[i,s]of Object.entries(n))e[i]={open:`\x1B[${s[0]}m`,close:`\x1B[${s[1]}m`},n[i]=e[i],r.set(s[0],s[1]);Object.defineProperty(e,t,{value:n,enumerable:!1})}return Object.defineProperty(e,"codes",{value:r,enumerable:!1}),e.color.close="\x1B[39m",e.bgColor.close="\x1B[49m",e.color.ansi256=Ud(),e.color.ansi16m=Fd(),e.bgColor.ansi256=Ud(10),e.bgColor.ansi16m=Fd(10),Object.defineProperties(e,{rgbToAnsi256:{value:(t,n,i)=>t===n&&n===i?t<8?16:t>248?231:Math.round((t-8)/247*24)+232:16+36*Math.round(t/255*5)+6*Math.round(n/255*5)+Math.round(i/255*5),enumerable:!1},hexToRgb:{value:t=>{let n=/(?<colorString>[a-f\d]{6}|[a-f\d]{3})/i.exec(t.toString(16));if(!n)return[0,0,0];let{colorString:i}=n.groups;i.length===3&&(i=i.split("").map(a=>a+a).join(""));let s=Number.parseInt(i,16);return[s>>16&255,s>>8&255,s&255]},enumerable:!1},hexToAnsi256:{value:t=>e.rgbToAnsi256(...e.hexToRgb(t)),enumerable:!1}}),e}Object.defineProperty(Zd,"exports",{enumerable:!0,get:yb})});var qp={};le(qp,{BasePromptValue:()=>Sr,ChatPromptValue:()=>Fs,ImagePromptValue:()=>Zs,StringPromptValue:()=>Qr});var Dp={};le(Dp,{Serializable:()=>Ze,get_lc_unique_name:()=>Mn});var nu=ot(Ko(),1),iu=ot(ru(),1);function su(r,e){return e?.[r]||(0,nu.default)(r)}function kv(r,e){return e?.[r]||(0,iu.default)(r)}function au(r,e,t){let n={};for(let i in r)Object.hasOwn(r,i)&&(n[e(i,t)]=r[i]);return n}var zn="__lc_escaped__";function Cp(r){return"lc"in r||Object.keys(r).length===1&&zn in r}function jp(r){return{[zn]:r}}function Lp(r){return Object.keys(r).length===1&&zn in r}function zp(r){return r!==null&&typeof r=="object"&&"lc_serializable"in r&&typeof r.toJSON=="function"}function Ln(r){if(r!==null&&typeof r=="object"&&!Array.isArray(r)){if(zp(r))return r;let e=r;if(Cp(e))return jp(e);let t={};for(let[n,i]of Object.entries(e))t[n]=Ln(i);return t}return Array.isArray(r)?r.map(e=>Ln(e)):r}function ou(r){if(r!==null&&typeof r=="object"&&!Array.isArray(r)){let e=r;if(Lp(e))return e[zn];let t={};for(let[n,i]of Object.entries(e))t[n]=ou(i);return t}return Array.isArray(r)?r.map(e=>ou(e)):r}function uu(r){return Array.isArray(r)?[...r]:{...r}}function Mp(r,e){let t=uu(r);for(let[n,i]of Object.entries(e)){let[s,...a]=n.split(".").reverse(),o=t;for(let u of a.reverse()){if(o[u]===void 0)break;o[u]=uu(o[u]),o=o[u]}o[s]!==void 0&&(o[s]={lc:1,type:"secret",id:[i]})}return t}function Mn(r){let e=Object.getPrototypeOf(r);return typeof r.lc_name=="function"&&(typeof e.lc_name!="function"||r.lc_name()!==e.lc_name())?r.lc_name():r.name}var Ze=class r{static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,Mn(this.constructor)]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}constructor(e,...t){Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"lc_kwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.lc_serializable_keys!==void 0?this.lc_kwargs=Object.fromEntries(Object.entries(e||{}).filter(([n])=>this.lc_serializable_keys?.includes(n))):this.lc_kwargs=e??{}}toJSON(){if(!this.lc_serializable)return this.toJSONNotImplemented();if(this.lc_kwargs instanceof r||typeof this.lc_kwargs!="object"||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();let e={},t={},n=Object.keys(this.lc_kwargs).reduce((o,u)=>(o[u]=u in this?this[u]:this.lc_kwargs[u],o),{});for(let o=Object.getPrototypeOf(this);o;o=Object.getPrototypeOf(o))Object.assign(e,Reflect.get(o,"lc_aliases",this)),Object.assign(t,Reflect.get(o,"lc_secrets",this)),Object.assign(n,Reflect.get(o,"lc_attributes",this));Object.keys(t).forEach(o=>{let u=this,c=n,[l,...d]=o.split(".").reverse();for(let f of d.reverse()){if(!(f in u)||u[f]===void 0)return;(!(f in c)||c[f]===void 0)&&(typeof u[f]=="object"&&u[f]!=null?c[f]={}:Array.isArray(u[f])&&(c[f]=[])),u=u[f],c=c[f]}l in u&&u[l]!==void 0&&(c[l]=c[l]||u[l])});let i={};for(let[o,u]of Object.entries(n))i[o]=Ln(u);let s=Object.keys(t).length?Mp(i,t):i,a=au(s,su,e);return{lc:1,type:"constructor",id:this.lc_id,kwargs:a}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}};function kt(r){return typeof r=="object"&&r!==null&&"type"in r&&typeof r.type=="string"&&"source_type"in r&&(r.source_type==="url"||r.source_type==="base64"||r.source_type==="text"||r.source_type==="id")}function jv(r){return kt(r)&&r.source_type==="url"&&"url"in r&&typeof r.url=="string"}function Lv(r){return kt(r)&&r.source_type==="base64"&&"data"in r&&typeof r.data=="string"}function zv(r){return kt(r)&&r.source_type==="text"&&"text"in r&&typeof r.text=="string"}function Mv(r){return kt(r)&&r.source_type==="id"&&"id"in r&&typeof r.id=="string"}function Dv(r){if(kt(r)){if(r.source_type==="url")return{type:"image_url",image_url:{url:r.url}};if(r.source_type==="base64"){if(!r.mime_type)throw new Error("mime_type key is required for base64 data.");return{type:"image_url",image_url:{url:`data:${r.mime_type};base64,${r.data}`}}}}throw new Error("Unsupported source type. Only 'url' and 'base64' are supported.")}function Uv(r){let e=r.split(";")[0].split("/");if(e.length!==2)throw new Error(`Invalid mime type: "${r}" - does not match type/subtype format.`);let t=e[0].trim(),n=e[1].trim();if(t===""||n==="")throw new Error(`Invalid mime type: "${r}" - type or subtype is empty.`);let i={};for(let s of r.split(";").slice(1)){let a=s.split("=");if(a.length!==2)throw new Error(`Invalid parameter syntax in mime type: "${r}".`);let o=a[0].trim(),u=a[1].trim();if(o==="")throw new Error(`Invalid parameter syntax in mime type: "${r}".`);i[o]=u}return{type:t,subtype:n,parameters:i}}function Fv({dataUrl:r,asTypedArray:e=!1}){let t=r.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/),n;if(t){n=t[1].toLowerCase();let i=e?Uint8Array.from(atob(t[2]),s=>s.charCodeAt(0)):t[2];return{mime_type:n,data:i}}}function Zv(r,e){if(r.type==="text"){if(!e.fromStandardTextBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardTextBlock\` method.`);return e.fromStandardTextBlock(r)}if(r.type==="image"){if(!e.fromStandardImageBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardImageBlock\` method.`);return e.fromStandardImageBlock(r)}if(r.type==="audio"){if(!e.fromStandardAudioBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardAudioBlock\` method.`);return e.fromStandardAudioBlock(r)}if(r.type==="file"){if(!e.fromStandardFileBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardFileBlock\` method.`);return e.fromStandardFileBlock(r)}throw new Error(`Unable to convert content block type '${r.type}' to provider-specific format: not recognized.`)}function Be(r,e){return typeof r=="string"?r===""?e:typeof e=="string"?r+e:Array.isArray(e)&&e.some(t=>kt(t))?[{type:"text",source_type:"text",text:r},...e]:[{type:"text",text:r},...e]:Array.isArray(e)?Wr(r,e)??[...r,...e]:e===""?r:Array.isArray(r)&&r.some(t=>kt(t))?[...r,{type:"file",source_type:"text",text:e}]:[...r,{type:"text",text:e}]}function cu(r,e){return r==="error"||e==="error"?"error":"success"}function Up(r,e){function t(n,i){if(typeof n!="object"||n===null||n===void 0)return n;if(i>=e)return Array.isArray(n)?"[Array]":"[Object]";if(Array.isArray(n))return n.map(a=>t(a,i+1));let s={};for(let a of Object.keys(n))s[a]=t(n[a],i+1);return s}return JSON.stringify(t(r,0),null,2)}var de=class extends Ze{get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}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(""):""}getType(){return this._getType()}constructor(e,t){typeof e=="string"&&(e={content:e,additional_kwargs:t,response_metadata:{}}),e.additional_kwargs||(e.additional_kwargs={}),e.response_metadata||(e.response_metadata={}),super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","messages"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"content",{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,"additional_kwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"response_metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=e.name,this.content=e.content,this.additional_kwargs=e.additional_kwargs,this.response_metadata=e.response_metadata,this.id=e.id}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}}_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=Up(this._printableFields,Math.max(4,e));return`${this.constructor.lc_name()} ${t}`}};function Vv(r){return Array.isArray(r)&&r.every(e=>typeof e.index=="number")}function re(r,e){let t={...r};for(let[n,i]of Object.entries(e))if(t[n]==null)t[n]=i;else{if(i==null)continue;if(typeof t[n]!=typeof i||Array.isArray(t[n])!==Array.isArray(i))throw new Error(`field[${n}] already exists in the message chunk, but with a different type.`);if(typeof t[n]=="string"){if(n==="type")continue;["id","name","output_version","model_provider"].includes(n)?t[n]=i:t[n]+=i}else if(typeof t[n]=="object"&&!Array.isArray(t[n]))t[n]=re(t[n],i);else if(Array.isArray(t[n]))t[n]=Wr(t[n],i);else{if(t[n]===i)continue;console.warn(`field[${n}] already exists in this message chunk and value has unsupported type.`)}}return t}function Wr(r,e){if(!(r===void 0&&e===void 0)){if(r===void 0||e===void 0)return r||e;{let t=[...r];for(let n of e)if(typeof n=="object"&&n!==null&&"index"in n&&typeof n.index=="number"){let i=t.findIndex(s=>{let a=typeof s=="object",o="index"in s&&s.index===n.index,u="id"in s&&"id"in n&&s?.id===n?.id,c=!("id"in s)||!s?.id||!("id"in n)||!n?.id;return a&&o&&(u||c)});i!==-1&&typeof t[i]=="object"&&t[i]!==null?t[i]=re(t[i],n):t.push(n)}else{if(typeof n=="object"&&n!==null&&"text"in n&&n.text==="")continue;t.push(n)}return t}}}function lu(r,e){if(!r&&!e)throw new Error("Cannot merge two undefined objects.");if(!r||!e)return r||e;if(typeof r!=typeof e)throw new Error(`Cannot merge objects of different types.
5
+ Left ${typeof r}
6
+ Right ${typeof e}`);if(typeof r=="string"&&typeof e=="string")return r+e;if(Array.isArray(r)&&Array.isArray(e))return Wr(r,e);if(typeof r=="object"&&typeof e=="object")return re(r,e);if(r===e)return r;throw new Error(`Can not merge objects of different types.
7
+ Left ${r}
8
+ Right ${e}`)}var ke=class extends de{};function du(r){return typeof r.role=="string"}function Ms(r){return typeof r?._getType=="function"}function Hv(r){return Ms(r)&&typeof r.concat=="function"}var wt=class extends de{static lc_name(){return"HumanMessage"}_getType(){return"human"}constructor(e,t){super(e,t)}},Dn=class r extends ke{static lc_name(){return"HumanMessageChunk"}_getType(){return"human"}constructor(e,t){super(e,t)}concat(e){return new r({content:Be(this.content,e.content),additional_kwargs:re(this.additional_kwargs,e.additional_kwargs),response_metadata:re(this.response_metadata,e.response_metadata),id:this.id??e.id})}};function Wv(r){return r.getType()==="human"}function Yv(r){return r.getType()==="human"}function Un(r,e){return r.lc_error_code=e,r.message=`${r.message}
9
+
10
+ Troubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${e}/
11
+ `,r}function Zn(r){return!!(r&&typeof r=="object"&&"type"in r&&r.type==="tool_call")}function ex(r){return!!(r&&typeof r=="object"&&"toolCall"in r&&r.toolCall!=null&&typeof r.toolCall=="object"&&"id"in r.toolCall&&typeof r.toolCall.id=="string")}var Fn=class extends Error{constructor(e,t){super(e),Object.defineProperty(this,"output",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.output=t}};function rx(r,e=Ds){r=r.trim();let t=r.indexOf("```");if(t===-1)return e(r);let n=r.substring(t+3);n.startsWith(`json
12
+ `)?n=n.substring(5):n.startsWith("json")?n=n.substring(4):n.startsWith(`
13
+ `)&&(n=n.substring(1));let i=n.indexOf("```"),s=n;return i!==-1&&(s=n.substring(0,i)),e(s.trim())}function Ds(r){if(typeof r>"u")return null;try{return JSON.parse(r)}catch{}let e="",t=[],n=!1,i=!1;for(let s of r){if(n)s==='"'&&!i?n=!1:s===`
14
+ `&&!i?s="\\n":s==="\\"?i=!i:i=!1;else if(s==='"')n=!0,i=!1;else if(s==="{")t.push("}");else if(s==="[")t.push("]");else if(s==="}"||s==="]")if(t&&t[t.length-1]===s)t.pop();else return null;e+=s}n&&(e+='"');for(let s=t.length-1;s>=0;s-=1)e+=t[s];try{return JSON.parse(e)}catch{return null}}function sx(r){return r!=null&&typeof r=="object"&&"lc_direct_tool_output"in r&&r.lc_direct_tool_output===!0}var Yr=class extends de{static lc_name(){return"ToolMessage"}get lc_aliases(){return{tool_call_id:"tool_call_id"}}constructor(e,t,n){typeof e=="string"&&(e={content:e,name:n,tool_call_id:t}),super(e),Object.defineProperty(this,"lc_direct_tool_output",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tool_call_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"artifact",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.tool_call_id=e.tool_call_id,this.artifact=e.artifact,this.status=e.status,this.metadata=e.metadata}_getType(){return"tool"}static isInstance(e){return e._getType()==="tool"}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}},fu=class r extends ke{constructor(e){super(e),Object.defineProperty(this,"tool_call_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"artifact",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.tool_call_id=e.tool_call_id,this.artifact=e.artifact,this.status=e.status}static lc_name(){return"ToolMessageChunk"}_getType(){return"tool"}concat(e){return new r({content:Be(this.content,e.content),additional_kwargs:re(this.additional_kwargs,e.additional_kwargs),response_metadata:re(this.response_metadata,e.response_metadata),artifact:lu(this.artifact,e.artifact),tool_call_id:this.tool_call_id,id:this.id??e.id,status:cu(this.status,e.status)})}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}};function pu(r){let e=[],t=[];for(let n of r)if(n.function){let i=n.function.name;try{let s=JSON.parse(n.function.arguments),a={name:i||"",args:s||{},id:n.id};e.push(a)}catch{t.push({name:i,args:n.function.arguments,id:n.id,error:"Malformed args."})}}else continue;return[e,t]}function ax(r){return r._getType()==="tool"}function ox(r){return r._getType()==="tool"}var xr=class extends de{get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls"}}constructor(e,t){let n;if(typeof e=="string")n={content:e,tool_calls:[],invalid_tool_calls:[],additional_kwargs:t??{}};else{n=e;let i=n.additional_kwargs?.tool_calls,s=n.tool_calls;i!=null&&i.length>0&&(s===void 0||s.length===0)&&console.warn(["New LangChain packages are available that more efficiently handle",`tool calling.
15
+
16
+ Please upgrade your packages to versions that set`,"message tool calls. e.g., `yarn add @langchain/anthropic`,","yarn add @langchain/openai`, etc."].join(" "));try{if(i!=null&&s===void 0){let[a,o]=pu(i);n.tool_calls=a??[],n.invalid_tool_calls=o??[]}else n.tool_calls=n.tool_calls??[],n.invalid_tool_calls=n.invalid_tool_calls??[]}catch{n.tool_calls=[],n.invalid_tool_calls=[]}}super(n),Object.defineProperty(this,"tool_calls",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"invalid_tool_calls",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"usage_metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),typeof n!="string"&&(this.tool_calls=n.tool_calls??this.tool_calls,this.invalid_tool_calls=n.invalid_tool_calls??this.invalid_tool_calls),this.usage_metadata=n.usage_metadata}static lc_name(){return"AIMessage"}_getType(){return"ai"}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}};function fx(r){return r._getType()==="ai"}function px(r){return r._getType()==="ai"}var Pt=class r extends ke{constructor(e){let t;if(typeof e=="string")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 i=(e.tool_call_chunks??[]).reduce((o,u)=>{let c=o.findIndex(([l])=>"id"in u&&u.id&&"index"in u&&u.index!==void 0?u.id===l.id&&u.index===l.index:"id"in u&&u.id?u.id===l.id:"index"in u&&u.index!==void 0?u.index===l.index:!1);return c!==-1?o[c].push(u):o.push([u]),o},[]),s=[],a=[];for(let o of i){let u={},c=o[0]?.name??"",l=o.map(p=>p.args||"").join(""),d=l.length?l:"{}",f=o[0]?.id;try{if(u=Ds(d),!f||u===null||typeof u!="object"||Array.isArray(u))throw new Error("Malformed tool call chunk args.");s.push({name:c,args:u,id:f,type:"tool_call"})}catch{a.push({name:c,args:d,id:f,error:"Malformed args.",type:"invalid_tool_call"})}}t={...e,tool_calls:s,invalid_tool_calls:a,usage_metadata:e.usage_metadata!==void 0?e.usage_metadata:void 0}}super(t),Object.defineProperty(this,"tool_calls",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"invalid_tool_calls",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"tool_call_chunks",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"usage_metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),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"}_getType(){return"ai"}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:Be(this.content,e.content),additional_kwargs:re(this.additional_kwargs,e.additional_kwargs),response_metadata:re(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=Wr(this.tool_call_chunks,e.tool_call_chunks);n!==void 0&&n.length>0&&(t.tool_call_chunks=n)}if(this.usage_metadata!==void 0||e.usage_metadata!==void 0){let n={...(this.usage_metadata?.input_token_details?.audio!==void 0||e.usage_metadata?.input_token_details?.audio!==void 0)&&{audio:(this.usage_metadata?.input_token_details?.audio??0)+(e.usage_metadata?.input_token_details?.audio??0)},...(this.usage_metadata?.input_token_details?.cache_read!==void 0||e.usage_metadata?.input_token_details?.cache_read!==void 0)&&{cache_read:(this.usage_metadata?.input_token_details?.cache_read??0)+(e.usage_metadata?.input_token_details?.cache_read??0)},...(this.usage_metadata?.input_token_details?.cache_creation!==void 0||e.usage_metadata?.input_token_details?.cache_creation!==void 0)&&{cache_creation:(this.usage_metadata?.input_token_details?.cache_creation??0)+(e.usage_metadata?.input_token_details?.cache_creation??0)}},i={...(this.usage_metadata?.output_token_details?.audio!==void 0||e.usage_metadata?.output_token_details?.audio!==void 0)&&{audio:(this.usage_metadata?.output_token_details?.audio??0)+(e.usage_metadata?.output_token_details?.audio??0)},...(this.usage_metadata?.output_token_details?.reasoning!==void 0||e.usage_metadata?.output_token_details?.reasoning!==void 0)&&{reasoning:(this.usage_metadata?.output_token_details?.reasoning??0)+(e.usage_metadata?.output_token_details?.reasoning??0)}},s=this.usage_metadata??{input_tokens:0,output_tokens:0,total_tokens:0},a=e.usage_metadata??{input_tokens:0,output_tokens:0,total_tokens:0},o={input_tokens:s.input_tokens+a.input_tokens,output_tokens:s.output_tokens+a.output_tokens,total_tokens:s.total_tokens+a.total_tokens,...Object.keys(n).length>0&&{input_token_details:n},...Object.keys(i).length>0&&{output_token_details:i}};t.usage_metadata=o}return new r(t)}};var Xr=class r extends de{static lc_name(){return"ChatMessage"}static _chatMessageClass(){return r}constructor(e,t){typeof e=="string"&&(e={content:e,role:t}),super(e),Object.defineProperty(this,"role",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.role=e.role}_getType(){return"generic"}static isInstance(e){return e._getType()==="generic"}get _printableFields(){return{...super._printableFields,role:this.role}}},Bn=class r extends ke{static lc_name(){return"ChatMessageChunk"}constructor(e,t){typeof e=="string"&&(e={content:e,role:t}),super(e),Object.defineProperty(this,"role",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.role=e.role}_getType(){return"generic"}concat(e){return new r({content:Be(this.content,e.content),additional_kwargs:re(this.additional_kwargs,e.additional_kwargs),response_metadata:re(this.response_metadata,e.response_metadata),role:this.role,id:this.id??e.id})}get _printableFields(){return{...super._printableFields,role:this.role}}};function gx(r){return r._getType()==="generic"}function _x(r){return r._getType()==="generic"}var Gn=class extends de{static lc_name(){return"FunctionMessage"}constructor(e,t){typeof e=="string"&&(e={content:e,name:t}),super(e)}_getType(){return"function"}},qn=class r extends ke{static lc_name(){return"FunctionMessageChunk"}_getType(){return"function"}concat(e){return new r({content:Be(this.content,e.content),additional_kwargs:re(this.additional_kwargs,e.additional_kwargs),response_metadata:re(this.response_metadata,e.response_metadata),name:this.name??"",id:this.id??e.id})}};function wx(r){return r._getType()==="function"}function vx(r){return r._getType()==="function"}var Vn=class extends de{constructor(e){super({...e,content:""}),Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.id=e.id}_getType(){return"remove"}get _printableFields(){return{...super._printableFields,id:this.id}}};var Er=class extends de{static lc_name(){return"SystemMessage"}_getType(){return"system"}constructor(e,t){super(e,t)}},Hn=class r extends ke{static lc_name(){return"SystemMessageChunk"}_getType(){return"system"}constructor(e,t){super(e,t)}concat(e){return new r({content:Be(this.content,e.content),additional_kwargs:re(this.additional_kwargs,e.additional_kwargs),response_metadata:re(this.response_metadata,e.response_metadata),id:this.id??e.id})}};function Ox(r){return r._getType()==="system"}function $x(r){return r._getType()==="system"}function Fp(r){return Zn(r)?r:typeof r.id=="string"&&r.type==="function"&&typeof r.function=="object"&&r.function!==null&&"arguments"in r.function&&typeof r.function.arguments=="string"&&"name"in r.function&&typeof r.function.name=="string"?{id:r.id,args:JSON.parse(r.function.arguments),name:r.function.name,type:"tool_call"}:r}function Zp(r){return typeof r=="object"&&r!=null&&r.lc===1&&Array.isArray(r.id)&&r.kwargs!=null&&typeof r.kwargs=="object"}function Us(r){let e,t;if(Zp(r)){let n=r.id.at(-1);n==="HumanMessage"||n==="HumanMessageChunk"?e="user":n==="AIMessage"||n==="AIMessageChunk"?e="assistant":n==="SystemMessage"||n==="SystemMessageChunk"?e="system":n==="FunctionMessage"||n==="FunctionMessageChunk"?e="function":n==="ToolMessage"||n==="ToolMessageChunk"?e="tool":e="unknown",t=r.kwargs}else{let{type:n,...i}=r;e=n,t=i}if(e==="human"||e==="user")return new wt(t);if(e==="ai"||e==="assistant"){let{tool_calls:n,...i}=t;if(!Array.isArray(n))return new xr(t);let s=n.map(Fp);return new xr({...i,tool_calls:s})}else{if(e==="system")return new Er(t);if(e==="developer")return new Er({...t,additional_kwargs:{...t.additional_kwargs,__openai_role__:"developer"}});if(e==="tool"&&"tool_call_id"in t)return new Yr({...t,content:t.content,tool_call_id:t.tool_call_id,name:t.name});if(e==="remove"&&"id"in t&&typeof t.id=="string")return new Vn({...t,id:t.id});throw Un(new Error(`Unable to coerce message from array: only human, AI, system, developer, or tool message coercion is currently supported.
17
+
18
+ Received: ${JSON.stringify(r,null,2)}`),"MESSAGE_COERCION_FAILURE")}}function Dx(r){if(typeof r=="string")return new wt(r);if(Ms(r))return r;if(Array.isArray(r)){let[e,t]=r;return Us({type:e,content:t})}else if(du(r)){let{role:e,...t}=r;return Us({...t,type:e})}else return Us(r)}function Jn(r,e="Human",t="AI"){let n=[];for(let i of r){let s;if(i._getType()==="human")s=e;else if(i._getType()==="ai")s=t;else if(i._getType()==="system")s="System";else if(i._getType()==="function")s="Function";else if(i._getType()==="tool")s="Tool";else if(i._getType()==="generic")s=i.role;else throw new Error(`Got unsupported message type: ${i._getType()}`);let a=i.name?`${i.name}, `:"",o=typeof i.content=="string"?i.content:JSON.stringify(i.content,null,2);n.push(`${s}: ${a}${o}`)}return n.join(`
19
+ `)}function Bp(r){if(r.data!==void 0)return r;{let e=r;return{type:e.type,data:{content:e.text,role:e.role,name:void 0,tool_call_id:void 0}}}}function Gp(r){let e=Bp(r);switch(e.type){case"human":return new wt(e.data);case"ai":return new xr(e.data);case"system":return new Er(e.data);case"function":if(e.data.name===void 0)throw new Error("Name must be defined for function messages");return new Gn(e.data);case"tool":if(e.data.tool_call_id===void 0)throw new Error("Tool call ID must be defined for tool messages");return new Yr(e.data);case"generic":{if(e.data.role===void 0)throw new Error("Role must be defined for chat messages");return new Xr(e.data)}default:throw new Error(`Got unexpected type: ${e.type}`)}}function Ux(r){return r.map(Gp)}function Fx(r){return r.map(e=>e.toDict())}function Zx(r){let e=r._getType();if(e==="human")return new Dn({...r});if(e==="ai"){let t={...r};return"tool_calls"in t&&(t={...t,tool_call_chunks:t.tool_calls?.map(n=>({...n,type:"tool_call_chunk",index:void 0,args:JSON.stringify(n.args)}))}),new Pt({...t})}else{if(e==="system")return new Hn({...r});if(e==="function")return new qn({...r});if(Xr.isInstance(r))return new Bn({...r});throw new Error("Unknown message type.")}}var Sr=class extends Ze{},Qr=class extends Sr{static lc_name(){return"StringPromptValue"}constructor(e){super({value:e}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompt_values"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"value",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.value=e}toString(){return this.value}toChatMessages(){return[new wt(this.value)]}},Fs=class extends Sr{static lc_name(){return"ChatPromptValue"}constructor(e){Array.isArray(e)&&(e={messages:e}),super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompt_values"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"messages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.messages=e.messages}toString(){return Jn(this.messages)}toChatMessages(){return this.messages}},Zs=class extends Sr{static lc_name(){return"ImagePromptValue"}constructor(e){"imageUrl"in e||(e={imageUrl:e}),super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompt_values"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"imageUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"value",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.imageUrl=e.imageUrl}toString(){return this.imageUrl.url}toChatMessages(){return[new wt({content:[{type:"image_url",image_url:{detail:this.imageUrl.detail,url:this.imageUrl.url}}]})]}};var Tt={};le(Tt,{BRAND:()=>_h,DIRTY:()=>Vt,EMPTY_PATH:()=>Kp,INVALID:()=>j,NEVER:()=>tm,OK:()=>_e,ParseStatus:()=>fe,Schema:()=>G,ZodAny:()=>Ct,ZodArray:()=>St,ZodBigInt:()=>Jt,ZodBoolean:()=>Kt,ZodBranded:()=>tn,ZodCatch:()=>ar,ZodDate:()=>Wt,ZodDefault:()=>sr,ZodDiscriminatedUnion:()=>Yn,ZodEffects:()=>Ve,ZodEnum:()=>nr,ZodError:()=>Pe,ZodFirstPartyTypeKind:()=>b,ZodFunction:()=>Qn,ZodIntersection:()=>er,ZodIssueCode:()=>y,ZodLazy:()=>tr,ZodLiteral:()=>rr,ZodMap:()=>kr,ZodNaN:()=>Rr,ZodNativeEnum:()=>ir,ZodNever:()=>tt,ZodNull:()=>Xt,ZodNullable:()=>lt,ZodNumber:()=>Ht,ZodObject:()=>Re,ZodOptional:()=>Ge,ZodParsedType:()=>S,ZodPipeline:()=>rn,ZodPromise:()=>jt,ZodReadonly:()=>or,ZodRecord:()=>Xn,ZodSchema:()=>G,ZodSet:()=>Pr,ZodString:()=>Nt,ZodSymbol:()=>Ir,ZodTransformer:()=>Ve,ZodTuple:()=>ct,ZodType:()=>G,ZodUndefined:()=>Yt,ZodUnion:()=>Qt,ZodUnknown:()=>Et,ZodVoid:()=>Ar,addIssueToContext:()=>x,any:()=>Oh,array:()=>kh,bigint:()=>vh,boolean:()=>Su,coerce:()=>em,custom:()=>vu,date:()=>xh,datetimeRegex:()=>bu,defaultErrorMap:()=>vt,discriminatedUnion:()=>Ch,effect:()=>Vh,enum:()=>Bh,function:()=>Uh,getErrorMap:()=>Tr,getParsedType:()=>ut,instanceof:()=>bh,intersection:()=>jh,isAborted:()=>Kn,isAsync:()=>Or,isDirty:()=>Wn,isValid:()=>Rt,late:()=>yh,lazy:()=>Fh,literal:()=>Zh,makeIssue:()=>en,map:()=>Mh,nan:()=>wh,nativeEnum:()=>Gh,never:()=>Ih,null:()=>Th,nullable:()=>Jh,number:()=>Eu,object:()=>Ph,objectUtil:()=>Bs,oboolean:()=>Qh,onumber:()=>Xh,optional:()=>Hh,ostring:()=>Yh,pipeline:()=>Wh,preprocess:()=>Kh,promise:()=>qh,quotelessJson:()=>Vp,record:()=>zh,set:()=>Dh,setErrorMap:()=>Jp,strictObject:()=>Rh,string:()=>xu,symbol:()=>Eh,transformer:()=>Vh,tuple:()=>Lh,undefined:()=>Sh,union:()=>Nh,unknown:()=>$h,util:()=>q,void:()=>Ah});var q;(function(r){r.assertEqual=i=>{};function e(i){}r.assertIs=e;function t(i){throw new Error}r.assertNever=t,r.arrayToEnum=i=>{let s={};for(let a of i)s[a]=a;return s},r.getValidEnumValues=i=>{let s=r.objectKeys(i).filter(o=>typeof i[i[o]]!="number"),a={};for(let o of s)a[o]=i[o];return r.objectValues(a)},r.objectValues=i=>r.objectKeys(i).map(function(s){return i[s]}),r.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let s=[];for(let a in i)Object.prototype.hasOwnProperty.call(i,a)&&s.push(a);return s},r.find=(i,s)=>{for(let a of i)if(s(a))return a},r.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(a=>typeof a=="string"?`'${a}'`:a).join(s)}r.joinValues=n,r.jsonStringifyReplacer=(i,s)=>typeof s=="bigint"?s.toString():s})(q||(q={}));var Bs;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(Bs||(Bs={}));var S=q.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ut=r=>{switch(typeof r){case"undefined":return S.undefined;case"string":return S.string;case"number":return Number.isNaN(r)?S.nan:S.number;case"boolean":return S.boolean;case"function":return S.function;case"bigint":return S.bigint;case"symbol":return S.symbol;case"object":return Array.isArray(r)?S.array:r===null?S.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?S.promise:typeof Map<"u"&&r instanceof Map?S.map:typeof Set<"u"&&r instanceof Set?S.set:typeof Date<"u"&&r instanceof Date?S.date:S.object;default:return S.unknown}};var y=q.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"]),Vp=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:"),Pe=class r extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(s){return s.message},n={_errors:[]},i=s=>{for(let a of s.issues)if(a.code==="invalid_union")a.unionErrors.map(i);else if(a.code==="invalid_return_type")i(a.returnTypeError);else if(a.code==="invalid_arguments")i(a.argumentsError);else if(a.path.length===0)n._errors.push(t(a));else{let o=n,u=0;for(;u<a.path.length;){let c=a.path[u];u===a.path.length-1?(o[c]=o[c]||{_errors:[]},o[c]._errors.push(t(a))):o[c]=o[c]||{_errors:[]},o=o[c],u++}}};return i(this),n}static assert(e){if(!(e instanceof r))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,q.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){let t={},n=[];for(let i of this.issues)if(i.path.length>0){let s=i.path[0];t[s]=t[s]||[],t[s].push(e(i))}else n.push(e(i));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};Pe.create=r=>new Pe(r);var Hp=(r,e)=>{let t;switch(r.code){case y.invalid_type:r.received===S.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case y.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,q.jsonStringifyReplacer)}`;break;case y.unrecognized_keys:t=`Unrecognized key(s) in object: ${q.joinValues(r.keys,", ")}`;break;case y.invalid_union:t="Invalid input";break;case y.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${q.joinValues(r.options)}`;break;case y.invalid_enum_value:t=`Invalid enum value. Expected ${q.joinValues(r.options)}, received '${r.received}'`;break;case y.invalid_arguments:t="Invalid function arguments";break;case y.invalid_return_type:t="Invalid function return type";break;case y.invalid_date:t="Invalid date";break;case y.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(t=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?t=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?t=`Invalid input: must end with "${r.validation.endsWith}"`:q.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case y.too_small:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="bigint"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:t="Invalid input";break;case y.too_big:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?t=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:t="Invalid input";break;case y.custom:t="Invalid input";break;case y.invalid_intersection_types:t="Intersection results could not be merged";break;case y.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case y.not_finite:t="Number must be finite";break;default:t=e.defaultError,q.assertNever(r)}return{message:t}},vt=Hp;var hu=vt;function Jp(r){hu=r}function Tr(){return hu}var en=r=>{let{data:e,path:t,errorMaps:n,issueData:i}=r,s=[...t,...i.path||[]],a={...i,path:s};if(i.message!==void 0)return{...i,path:s,message:i.message};let o="",u=n.filter(c=>!!c).slice().reverse();for(let c of u)o=c(a,{data:e,defaultError:o}).message;return{...i,path:s,message:o}},Kp=[];function x(r,e){let t=Tr(),n=en({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===vt?void 0:vt].filter(i=>!!i)});r.common.issues.push(n)}var fe=class r{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){let n=[];for(let i of t){if(i.status==="aborted")return j;i.status==="dirty"&&e.dirty(),n.push(i.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){let n=[];for(let i of t){let s=await i.key,a=await i.value;n.push({key:s,value:a})}return r.mergeObjectSync(e,n)}static mergeObjectSync(e,t){let n={};for(let i of t){let{key:s,value:a}=i;if(s.status==="aborted"||a.status==="aborted")return j;s.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof a.value<"u"||i.alwaysSet)&&(n[s.value]=a.value)}return{status:e.value,value:n}}},j=Object.freeze({status:"aborted"}),Vt=r=>({status:"dirty",value:r}),_e=r=>({status:"valid",value:r}),Kn=r=>r.status==="aborted",Wn=r=>r.status==="dirty",Rt=r=>r.status==="valid",Or=r=>typeof Promise<"u"&&r instanceof Promise;var k;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e?.message})(k||(k={}));var qe=class{constructor(e,t,n,i){this._cachedPath=[],this.parent=e,this.data=t,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}},mu=(r,e)=>{if(Rt(e))return{success:!0,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new Pe(r.common.issues);return this._error=t,this._error}}};function B(r){if(!r)return{};let{errorMap:e,invalid_type_error:t,required_error:n,description:i}=r;if(e&&(t||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:i}:{errorMap:(a,o)=>{let{message:u}=r;return a.code==="invalid_enum_value"?{message:u??o.defaultError}:typeof o.data>"u"?{message:u??n??o.defaultError}:a.code!=="invalid_type"?{message:o.defaultError}:{message:u??t??o.defaultError}},description:i}}var G=class{get description(){return this._def.description}_getType(e){return ut(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:ut(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new fe,ctx:{common:e.parent.common,data:e.data,parsedType:ut(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(Or(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ut(e)},i=this._parseSync({data:e,path:n.path,parent:n});return mu(n,i)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ut(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:t});return Rt(n)?{value:n.value}:{issues:t.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(n=>Rt(n)?{value:n.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ut(e)},i=this._parse({data:e,path:n.path,parent:n}),s=await(Or(i)?i:Promise.resolve(i));return mu(n,s)}refine(e,t){let n=i=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(i):t;return this._refinement((i,s)=>{let a=e(i),o=()=>s.addIssue({code:y.custom,...n(i)});return typeof Promise<"u"&&a instanceof Promise?a.then(u=>u?!0:(o(),!1)):a?!0:(o(),!1)})}refinement(e,t){return this._refinement((n,i)=>e(n)?!0:(i.addIssue(typeof t=="function"?t(n,i):t),!1))}_refinement(e){return new Ve({schema:this,typeName:b.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return Ge.create(this,this._def)}nullable(){return lt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return St.create(this)}promise(){return jt.create(this,this._def)}or(e){return Qt.create([this,e],this._def)}and(e){return er.create(this,e,this._def)}transform(e){return new Ve({...B(this._def),schema:this,typeName:b.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new sr({...B(this._def),innerType:this,defaultValue:t,typeName:b.ZodDefault})}brand(){return new tn({typeName:b.ZodBranded,type:this,...B(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new ar({...B(this._def),innerType:this,catchValue:t,typeName:b.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return rn.create(this,e)}readonly(){return or.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Wp=/^c[^\s-]{8,}$/i,Yp=/^[0-9a-z]+$/,Xp=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Qp=/^[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,eh=/^[a-z0-9_-]{21}$/i,th=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,rh=/^[-+]?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)?)??$/,nh=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,ih="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Gs,sh=/^(?:(?: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])$/,ah=/^(?:(?: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])$/,oh=/^(([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]))$/,uh=/^(([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])$/,ch=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,lh=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,_u="((\\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])))",dh=new RegExp(`^${_u}$`);function yu(r){let e="[0-5]\\d";r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`);let t=r.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function fh(r){return new RegExp(`^${yu(r)}$`)}function bu(r){let e=`${_u}T${yu(r)}`,t=[];return t.push(r.local?"Z?":"Z"),r.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function ph(r,e){return!!((e==="v4"||!e)&&sh.test(r)||(e==="v6"||!e)&&oh.test(r))}function hh(r,e){if(!th.test(r))return!1;try{let[t]=r.split(".");if(!t)return!1;let n=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),i=JSON.parse(atob(n));return!(typeof i!="object"||i===null||"typ"in i&&i?.typ!=="JWT"||!i.alg||e&&i.alg!==e)}catch{return!1}}function mh(r,e){return!!((e==="v4"||!e)&&ah.test(r)||(e==="v6"||!e)&&uh.test(r))}var Nt=class r extends G{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==S.string){let s=this._getOrReturnCtx(e);return x(s,{code:y.invalid_type,expected:S.string,received:s.parsedType}),j}let n=new fe,i;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(i=this._getOrReturnCtx(e,i),x(i,{code:y.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")e.data.length>s.value&&(i=this._getOrReturnCtx(e,i),x(i,{code:y.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){let a=e.data.length>s.value,o=e.data.length<s.value;(a||o)&&(i=this._getOrReturnCtx(e,i),a?x(i,{code:y.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):o&&x(i,{code:y.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")nh.test(e.data)||(i=this._getOrReturnCtx(e,i),x(i,{validation:"email",code:y.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")Gs||(Gs=new RegExp(ih,"u")),Gs.test(e.data)||(i=this._getOrReturnCtx(e,i),x(i,{validation:"emoji",code:y.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")Qp.test(e.data)||(i=this._getOrReturnCtx(e,i),x(i,{validation:"uuid",code:y.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")eh.test(e.data)||(i=this._getOrReturnCtx(e,i),x(i,{validation:"nanoid",code:y.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")Wp.test(e.data)||(i=this._getOrReturnCtx(e,i),x(i,{validation:"cuid",code:y.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")Yp.test(e.data)||(i=this._getOrReturnCtx(e,i),x(i,{validation:"cuid2",code:y.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")Xp.test(e.data)||(i=this._getOrReturnCtx(e,i),x(i,{validation:"ulid",code:y.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{i=this._getOrReturnCtx(e,i),x(i,{validation:"url",code:y.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(i=this._getOrReturnCtx(e,i),x(i,{validation:"regex",code:y.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(i=this._getOrReturnCtx(e,i),x(i,{code:y.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(i=this._getOrReturnCtx(e,i),x(i,{code:y.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(i=this._getOrReturnCtx(e,i),x(i,{code:y.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?bu(s).test(e.data)||(i=this._getOrReturnCtx(e,i),x(i,{code:y.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?dh.test(e.data)||(i=this._getOrReturnCtx(e,i),x(i,{code:y.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?fh(s).test(e.data)||(i=this._getOrReturnCtx(e,i),x(i,{code:y.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?rh.test(e.data)||(i=this._getOrReturnCtx(e,i),x(i,{validation:"duration",code:y.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?ph(e.data,s.version)||(i=this._getOrReturnCtx(e,i),x(i,{validation:"ip",code:y.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?hh(e.data,s.alg)||(i=this._getOrReturnCtx(e,i),x(i,{validation:"jwt",code:y.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?mh(e.data,s.version)||(i=this._getOrReturnCtx(e,i),x(i,{validation:"cidr",code:y.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?ch.test(e.data)||(i=this._getOrReturnCtx(e,i),x(i,{validation:"base64",code:y.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?lh.test(e.data)||(i=this._getOrReturnCtx(e,i),x(i,{validation:"base64url",code:y.invalid_string,message:s.message}),n.dirty()):q.assertNever(s);return{status:n.value,value:e.data}}_regex(e,t,n){return this.refinement(i=>e.test(i),{validation:t,code:y.invalid_string,...k.errToObj(n)})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...k.errToObj(e)})}url(e){return this._addCheck({kind:"url",...k.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...k.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...k.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...k.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...k.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...k.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...k.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...k.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...k.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...k.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...k.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...k.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...k.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...k.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...k.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...k.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...k.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...k.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...k.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...k.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...k.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...k.errToObj(t)})}nonempty(e){return this.min(1,k.errToObj(e))}trim(){return new r({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};Nt.create=r=>new Nt({checks:[],typeName:b.ZodString,coerce:r?.coerce??!1,...B(r)});function gh(r,e){let t=(r.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,i=t>n?t:n,s=Number.parseInt(r.toFixed(i).replace(".","")),a=Number.parseInt(e.toFixed(i).replace(".",""));return s%a/10**i}var Ht=class r extends G{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==S.number){let s=this._getOrReturnCtx(e);return x(s,{code:y.invalid_type,expected:S.number,received:s.parsedType}),j}let n,i=new fe;for(let s of this._def.checks)s.kind==="int"?q.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),x(n,{code:y.invalid_type,expected:"integer",received:"float",message:s.message}),i.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),x(n,{code:y.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),x(n,{code:y.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):s.kind==="multipleOf"?gh(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),x(n,{code:y.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),x(n,{code:y.not_finite,message:s.message}),i.dirty()):q.assertNever(s);return{status:i.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,k.toString(t))}gt(e,t){return this.setLimit("min",e,!1,k.toString(t))}lte(e,t){return this.setLimit("max",e,!0,k.toString(t))}lt(e,t){return this.setLimit("max",e,!1,k.toString(t))}setLimit(e,t,n,i){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:k.toString(i)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:k.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:k.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:k.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:k.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:k.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:k.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:k.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:k.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:k.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&q.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(t===null||n.value>t)&&(t=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(t)&&Number.isFinite(e)}};Ht.create=r=>new Ht({checks:[],typeName:b.ZodNumber,coerce:r?.coerce||!1,...B(r)});var Jt=class r extends G{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==S.bigint)return this._getInvalidInput(e);let n,i=new fe;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),x(n,{code:y.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),x(n,{code:y.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),x(n,{code:y.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):q.assertNever(s);return{status:i.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return x(t,{code:y.invalid_type,expected:S.bigint,received:t.parsedType}),j}gte(e,t){return this.setLimit("min",e,!0,k.toString(t))}gt(e,t){return this.setLimit("min",e,!1,k.toString(t))}lte(e,t){return this.setLimit("max",e,!0,k.toString(t))}lt(e,t){return this.setLimit("max",e,!1,k.toString(t))}setLimit(e,t,n,i){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:k.toString(i)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:k.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:k.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:k.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:k.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:k.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};Jt.create=r=>new Jt({checks:[],typeName:b.ZodBigInt,coerce:r?.coerce??!1,...B(r)});var Kt=class extends G{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==S.boolean){let n=this._getOrReturnCtx(e);return x(n,{code:y.invalid_type,expected:S.boolean,received:n.parsedType}),j}return _e(e.data)}};Kt.create=r=>new Kt({typeName:b.ZodBoolean,coerce:r?.coerce||!1,...B(r)});var Wt=class r extends G{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==S.date){let s=this._getOrReturnCtx(e);return x(s,{code:y.invalid_type,expected:S.date,received:s.parsedType}),j}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return x(s,{code:y.invalid_date}),j}let n=new fe,i;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(i=this._getOrReturnCtx(e,i),x(i,{code:y.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(i=this._getOrReturnCtx(e,i),x(i,{code:y.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):q.assertNever(s);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:k.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:k.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}};Wt.create=r=>new Wt({checks:[],coerce:r?.coerce||!1,typeName:b.ZodDate,...B(r)});var Ir=class extends G{_parse(e){if(this._getType(e)!==S.symbol){let n=this._getOrReturnCtx(e);return x(n,{code:y.invalid_type,expected:S.symbol,received:n.parsedType}),j}return _e(e.data)}};Ir.create=r=>new Ir({typeName:b.ZodSymbol,...B(r)});var Yt=class extends G{_parse(e){if(this._getType(e)!==S.undefined){let n=this._getOrReturnCtx(e);return x(n,{code:y.invalid_type,expected:S.undefined,received:n.parsedType}),j}return _e(e.data)}};Yt.create=r=>new Yt({typeName:b.ZodUndefined,...B(r)});var Xt=class extends G{_parse(e){if(this._getType(e)!==S.null){let n=this._getOrReturnCtx(e);return x(n,{code:y.invalid_type,expected:S.null,received:n.parsedType}),j}return _e(e.data)}};Xt.create=r=>new Xt({typeName:b.ZodNull,...B(r)});var Ct=class extends G{constructor(){super(...arguments),this._any=!0}_parse(e){return _e(e.data)}};Ct.create=r=>new Ct({typeName:b.ZodAny,...B(r)});var Et=class extends G{constructor(){super(...arguments),this._unknown=!0}_parse(e){return _e(e.data)}};Et.create=r=>new Et({typeName:b.ZodUnknown,...B(r)});var tt=class extends G{_parse(e){let t=this._getOrReturnCtx(e);return x(t,{code:y.invalid_type,expected:S.never,received:t.parsedType}),j}};tt.create=r=>new tt({typeName:b.ZodNever,...B(r)});var Ar=class extends G{_parse(e){if(this._getType(e)!==S.undefined){let n=this._getOrReturnCtx(e);return x(n,{code:y.invalid_type,expected:S.void,received:n.parsedType}),j}return _e(e.data)}};Ar.create=r=>new Ar({typeName:b.ZodVoid,...B(r)});var St=class r extends G{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),i=this._def;if(t.parsedType!==S.array)return x(t,{code:y.invalid_type,expected:S.array,received:t.parsedType}),j;if(i.exactLength!==null){let a=t.data.length>i.exactLength.value,o=t.data.length<i.exactLength.value;(a||o)&&(x(t,{code:a?y.too_big:y.too_small,minimum:o?i.exactLength.value:void 0,maximum:a?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),n.dirty())}if(i.minLength!==null&&t.data.length<i.minLength.value&&(x(t,{code:y.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),n.dirty()),i.maxLength!==null&&t.data.length>i.maxLength.value&&(x(t,{code:y.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((a,o)=>i.type._parseAsync(new qe(t,a,t.path,o)))).then(a=>fe.mergeArray(n,a));let s=[...t.data].map((a,o)=>i.type._parseSync(new qe(t,a,t.path,o)));return fe.mergeArray(n,s)}get element(){return this._def.type}min(e,t){return new r({...this._def,minLength:{value:e,message:k.toString(t)}})}max(e,t){return new r({...this._def,maxLength:{value:e,message:k.toString(t)}})}length(e,t){return new r({...this._def,exactLength:{value:e,message:k.toString(t)}})}nonempty(e){return this.min(1,e)}};St.create=(r,e)=>new St({type:r,minLength:null,maxLength:null,exactLength:null,typeName:b.ZodArray,...B(e)});function $r(r){if(r instanceof Re){let e={};for(let t in r.shape){let n=r.shape[t];e[t]=Ge.create($r(n))}return new Re({...r._def,shape:()=>e})}else return r instanceof St?new St({...r._def,type:$r(r.element)}):r instanceof Ge?Ge.create($r(r.unwrap())):r instanceof lt?lt.create($r(r.unwrap())):r instanceof ct?ct.create(r.items.map(e=>$r(e))):r}var Re=class r extends G{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=q.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==S.object){let c=this._getOrReturnCtx(e);return x(c,{code:y.invalid_type,expected:S.object,received:c.parsedType}),j}let{status:n,ctx:i}=this._processInputParams(e),{shape:s,keys:a}=this._getCached(),o=[];if(!(this._def.catchall instanceof tt&&this._def.unknownKeys==="strip"))for(let c in i.data)a.includes(c)||o.push(c);let u=[];for(let c of a){let l=s[c],d=i.data[c];u.push({key:{status:"valid",value:c},value:l._parse(new qe(i,d,i.path,c)),alwaysSet:c in i.data})}if(this._def.catchall instanceof tt){let c=this._def.unknownKeys;if(c==="passthrough")for(let l of o)u.push({key:{status:"valid",value:l},value:{status:"valid",value:i.data[l]}});else if(c==="strict")o.length>0&&(x(i,{code:y.unrecognized_keys,keys:o}),n.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let l of o){let d=i.data[l];u.push({key:{status:"valid",value:l},value:c._parse(new qe(i,d,i.path,l)),alwaysSet:l in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let c=[];for(let l of u){let d=await l.key,f=await l.value;c.push({key:d,value:f,alwaysSet:l.alwaysSet})}return c}).then(c=>fe.mergeObjectSync(n,c)):fe.mergeObjectSync(n,u)}get shape(){return this._def.shape()}strict(e){return k.errToObj,new r({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,n)=>{let i=this._def.errorMap?.(t,n).message??n.defaultError;return t.code==="unrecognized_keys"?{message:k.errToObj(e).message??i}:{message:i}}}:{}})}strip(){return new r({...this._def,unknownKeys:"strip"})}passthrough(){return new r({...this._def,unknownKeys:"passthrough"})}extend(e){return new r({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new r({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:b.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new r({...this._def,catchall:e})}pick(e){let t={};for(let n of q.objectKeys(e))e[n]&&this.shape[n]&&(t[n]=this.shape[n]);return new r({...this._def,shape:()=>t})}omit(e){let t={};for(let n of q.objectKeys(this.shape))e[n]||(t[n]=this.shape[n]);return new r({...this._def,shape:()=>t})}deepPartial(){return $r(this)}partial(e){let t={};for(let n of q.objectKeys(this.shape)){let i=this.shape[n];e&&!e[n]?t[n]=i:t[n]=i.optional()}return new r({...this._def,shape:()=>t})}required(e){let t={};for(let n of q.objectKeys(this.shape))if(e&&!e[n])t[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof Ge;)s=s._def.innerType;t[n]=s}return new r({...this._def,shape:()=>t})}keyof(){return wu(q.objectKeys(this.shape))}};Re.create=(r,e)=>new Re({shape:()=>r,unknownKeys:"strip",catchall:tt.create(),typeName:b.ZodObject,...B(e)});Re.strictCreate=(r,e)=>new Re({shape:()=>r,unknownKeys:"strict",catchall:tt.create(),typeName:b.ZodObject,...B(e)});Re.lazycreate=(r,e)=>new Re({shape:r,unknownKeys:"strip",catchall:tt.create(),typeName:b.ZodObject,...B(e)});var Qt=class extends G{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function i(s){for(let o of s)if(o.result.status==="valid")return o.result;for(let o of s)if(o.result.status==="dirty")return t.common.issues.push(...o.ctx.common.issues),o.result;let a=s.map(o=>new Pe(o.ctx.common.issues));return x(t,{code:y.invalid_union,unionErrors:a}),j}if(t.common.async)return Promise.all(n.map(async s=>{let a={...t,common:{...t.common,issues:[]},parent:null};return{result:await s._parseAsync({data:t.data,path:t.path,parent:a}),ctx:a}})).then(i);{let s,a=[];for(let u of n){let c={...t,common:{...t.common,issues:[]},parent:null},l=u._parseSync({data:t.data,path:t.path,parent:c});if(l.status==="valid")return l;l.status==="dirty"&&!s&&(s={result:l,ctx:c}),c.common.issues.length&&a.push(c.common.issues)}if(s)return t.common.issues.push(...s.ctx.common.issues),s.result;let o=a.map(u=>new Pe(u));return x(t,{code:y.invalid_union,unionErrors:o}),j}}get options(){return this._def.options}};Qt.create=(r,e)=>new Qt({options:r,typeName:b.ZodUnion,...B(e)});var xt=r=>r instanceof tr?xt(r.schema):r instanceof Ve?xt(r.innerType()):r instanceof rr?[r.value]:r instanceof nr?r.options:r instanceof ir?q.objectValues(r.enum):r instanceof sr?xt(r._def.innerType):r instanceof Yt?[void 0]:r instanceof Xt?[null]:r instanceof Ge?[void 0,...xt(r.unwrap())]:r instanceof lt?[null,...xt(r.unwrap())]:r instanceof tn||r instanceof or?xt(r.unwrap()):r instanceof ar?xt(r._def.innerType):[],Yn=class r extends G{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==S.object)return x(t,{code:y.invalid_type,expected:S.object,received:t.parsedType}),j;let n=this.discriminator,i=t.data[n],s=this.optionsMap.get(i);return s?t.common.async?s._parseAsync({data:t.data,path:t.path,parent:t}):s._parseSync({data:t.data,path:t.path,parent:t}):(x(t,{code:y.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),j)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,n){let i=new Map;for(let s of t){let a=xt(s.shape[e]);if(!a.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let o of a){if(i.has(o))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(o)}`);i.set(o,s)}}return new r({typeName:b.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:i,...B(n)})}};function qs(r,e){let t=ut(r),n=ut(e);if(r===e)return{valid:!0,data:r};if(t===S.object&&n===S.object){let i=q.objectKeys(e),s=q.objectKeys(r).filter(o=>i.indexOf(o)!==-1),a={...r,...e};for(let o of s){let u=qs(r[o],e[o]);if(!u.valid)return{valid:!1};a[o]=u.data}return{valid:!0,data:a}}else if(t===S.array&&n===S.array){if(r.length!==e.length)return{valid:!1};let i=[];for(let s=0;s<r.length;s++){let a=r[s],o=e[s],u=qs(a,o);if(!u.valid)return{valid:!1};i.push(u.data)}return{valid:!0,data:i}}else return t===S.date&&n===S.date&&+r==+e?{valid:!0,data:r}:{valid:!1}}var er=class extends G{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),i=(s,a)=>{if(Kn(s)||Kn(a))return j;let o=qs(s.value,a.value);return o.valid?((Wn(s)||Wn(a))&&t.dirty(),{status:t.value,value:o.data}):(x(n,{code:y.invalid_intersection_types}),j)};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,a])=>i(s,a)):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}))}};er.create=(r,e,t)=>new er({left:r,right:e,typeName:b.ZodIntersection,...B(t)});var ct=class r extends G{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==S.array)return x(n,{code:y.invalid_type,expected:S.array,received:n.parsedType}),j;if(n.data.length<this._def.items.length)return x(n,{code:y.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),j;!this._def.rest&&n.data.length>this._def.items.length&&(x(n,{code:y.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let s=[...n.data].map((a,o)=>{let u=this._def.items[o]||this._def.rest;return u?u._parse(new qe(n,a,n.path,o)):null}).filter(a=>!!a);return n.common.async?Promise.all(s).then(a=>fe.mergeArray(t,a)):fe.mergeArray(t,s)}get items(){return this._def.items}rest(e){return new r({...this._def,rest:e})}};ct.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ct({items:r,typeName:b.ZodTuple,rest:null,...B(e)})};var Xn=class r extends G{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==S.object)return x(n,{code:y.invalid_type,expected:S.object,received:n.parsedType}),j;let i=[],s=this._def.keyType,a=this._def.valueType;for(let o in n.data)i.push({key:s._parse(new qe(n,o,n.path,o)),value:a._parse(new qe(n,n.data[o],n.path,o)),alwaysSet:o in n.data});return n.common.async?fe.mergeObjectAsync(t,i):fe.mergeObjectSync(t,i)}get element(){return this._def.valueType}static create(e,t,n){return t instanceof G?new r({keyType:e,valueType:t,typeName:b.ZodRecord,...B(n)}):new r({keyType:Nt.create(),valueType:e,typeName:b.ZodRecord,...B(t)})}},kr=class extends G{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==S.map)return x(n,{code:y.invalid_type,expected:S.map,received:n.parsedType}),j;let i=this._def.keyType,s=this._def.valueType,a=[...n.data.entries()].map(([o,u],c)=>({key:i._parse(new qe(n,o,n.path,[c,"key"])),value:s._parse(new qe(n,u,n.path,[c,"value"]))}));if(n.common.async){let o=new Map;return Promise.resolve().then(async()=>{for(let u of a){let c=await u.key,l=await u.value;if(c.status==="aborted"||l.status==="aborted")return j;(c.status==="dirty"||l.status==="dirty")&&t.dirty(),o.set(c.value,l.value)}return{status:t.value,value:o}})}else{let o=new Map;for(let u of a){let c=u.key,l=u.value;if(c.status==="aborted"||l.status==="aborted")return j;(c.status==="dirty"||l.status==="dirty")&&t.dirty(),o.set(c.value,l.value)}return{status:t.value,value:o}}}};kr.create=(r,e,t)=>new kr({valueType:e,keyType:r,typeName:b.ZodMap,...B(t)});var Pr=class r extends G{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==S.set)return x(n,{code:y.invalid_type,expected:S.set,received:n.parsedType}),j;let i=this._def;i.minSize!==null&&n.data.size<i.minSize.value&&(x(n,{code:y.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),t.dirty()),i.maxSize!==null&&n.data.size>i.maxSize.value&&(x(n,{code:y.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),t.dirty());let s=this._def.valueType;function a(u){let c=new Set;for(let l of u){if(l.status==="aborted")return j;l.status==="dirty"&&t.dirty(),c.add(l.value)}return{status:t.value,value:c}}let o=[...n.data.values()].map((u,c)=>s._parse(new qe(n,u,n.path,c)));return n.common.async?Promise.all(o).then(u=>a(u)):a(o)}min(e,t){return new r({...this._def,minSize:{value:e,message:k.toString(t)}})}max(e,t){return new r({...this._def,maxSize:{value:e,message:k.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};Pr.create=(r,e)=>new Pr({valueType:r,minSize:null,maxSize:null,typeName:b.ZodSet,...B(e)});var Qn=class r extends G{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==S.function)return x(t,{code:y.invalid_type,expected:S.function,received:t.parsedType}),j;function n(o,u){return en({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Tr(),vt].filter(c=>!!c),issueData:{code:y.invalid_arguments,argumentsError:u}})}function i(o,u){return en({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Tr(),vt].filter(c=>!!c),issueData:{code:y.invalid_return_type,returnTypeError:u}})}let s={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof jt){let o=this;return _e(async function(...u){let c=new Pe([]),l=await o._def.args.parseAsync(u,s).catch(p=>{throw c.addIssue(n(u,p)),c}),d=await Reflect.apply(a,this,l);return await o._def.returns._def.type.parseAsync(d,s).catch(p=>{throw c.addIssue(i(d,p)),c})})}else{let o=this;return _e(function(...u){let c=o._def.args.safeParse(u,s);if(!c.success)throw new Pe([n(u,c.error)]);let l=Reflect.apply(a,this,c.data),d=o._def.returns.safeParse(l,s);if(!d.success)throw new Pe([i(l,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new r({...this._def,args:ct.create(e).rest(Et.create())})}returns(e){return new r({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,n){return new r({args:e||ct.create([]).rest(Et.create()),returns:t||Et.create(),typeName:b.ZodFunction,...B(n)})}},tr=class extends G{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};tr.create=(r,e)=>new tr({getter:r,typeName:b.ZodLazy,...B(e)});var rr=class extends G{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return x(t,{received:t.data,code:y.invalid_literal,expected:this._def.value}),j}return{status:"valid",value:e.data}}get value(){return this._def.value}};rr.create=(r,e)=>new rr({value:r,typeName:b.ZodLiteral,...B(e)});function wu(r,e){return new nr({values:r,typeName:b.ZodEnum,...B(e)})}var nr=class r extends G{_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),n=this._def.values;return x(t,{expected:q.joinValues(n),received:t.parsedType,code:y.invalid_type}),j}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return x(t,{received:t.data,code:y.invalid_enum_value,options:n}),j}return _e(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return r.create(e,{...this._def,...t})}exclude(e,t=this._def){return r.create(this.options.filter(n=>!e.includes(n)),{...this._def,...t})}};nr.create=wu;var ir=class extends G{_parse(e){let t=q.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==S.string&&n.parsedType!==S.number){let i=q.objectValues(t);return x(n,{expected:q.joinValues(i),received:n.parsedType,code:y.invalid_type}),j}if(this._cache||(this._cache=new Set(q.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let i=q.objectValues(t);return x(n,{received:n.data,code:y.invalid_enum_value,options:i}),j}return _e(e.data)}get enum(){return this._def.values}};ir.create=(r,e)=>new ir({values:r,typeName:b.ZodNativeEnum,...B(e)});var jt=class extends G{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==S.promise&&t.common.async===!1)return x(t,{code:y.invalid_type,expected:S.promise,received:t.parsedType}),j;let n=t.parsedType===S.promise?t.data:Promise.resolve(t.data);return _e(n.then(i=>this._def.type.parseAsync(i,{path:t.path,errorMap:t.common.contextualErrorMap})))}};jt.create=(r,e)=>new jt({type:r,typeName:b.ZodPromise,...B(e)});var Ve=class extends G{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===b.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),i=this._def.effect||null,s={addIssue:a=>{x(n,a),a.fatal?t.abort():t.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),i.type==="preprocess"){let a=i.transform(n.data,s);if(n.common.async)return Promise.resolve(a).then(async o=>{if(t.value==="aborted")return j;let u=await this._def.schema._parseAsync({data:o,path:n.path,parent:n});return u.status==="aborted"?j:u.status==="dirty"?Vt(u.value):t.value==="dirty"?Vt(u.value):u});{if(t.value==="aborted")return j;let o=this._def.schema._parseSync({data:a,path:n.path,parent:n});return o.status==="aborted"?j:o.status==="dirty"?Vt(o.value):t.value==="dirty"?Vt(o.value):o}}if(i.type==="refinement"){let a=o=>{let u=i.refinement(o,s);if(n.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(n.common.async===!1){let o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?j:(o.status==="dirty"&&t.dirty(),a(o.value),{status:t.value,value:o.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>o.status==="aborted"?j:(o.status==="dirty"&&t.dirty(),a(o.value).then(()=>({status:t.value,value:o.value}))))}if(i.type==="transform")if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Rt(a))return j;let o=i.transform(a.value,s);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:o}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>Rt(a)?Promise.resolve(i.transform(a.value,s)).then(o=>({status:t.value,value:o})):j);q.assertNever(i)}};Ve.create=(r,e,t)=>new Ve({schema:r,typeName:b.ZodEffects,effect:e,...B(t)});Ve.createWithPreprocess=(r,e,t)=>new Ve({schema:e,effect:{type:"preprocess",transform:r},typeName:b.ZodEffects,...B(t)});var Ge=class extends G{_parse(e){return this._getType(e)===S.undefined?_e(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Ge.create=(r,e)=>new Ge({innerType:r,typeName:b.ZodOptional,...B(e)});var lt=class extends G{_parse(e){return this._getType(e)===S.null?_e(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};lt.create=(r,e)=>new lt({innerType:r,typeName:b.ZodNullable,...B(e)});var sr=class extends G{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===S.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};sr.create=(r,e)=>new sr({innerType:r,typeName:b.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...B(e)});var ar=class extends G{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},i=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Or(i)?i.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Pe(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Pe(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};ar.create=(r,e)=>new ar({innerType:r,typeName:b.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...B(e)});var Rr=class extends G{_parse(e){if(this._getType(e)!==S.nan){let n=this._getOrReturnCtx(e);return x(n,{code:y.invalid_type,expected:S.nan,received:n.parsedType}),j}return{status:"valid",value:e.data}}};Rr.create=r=>new Rr({typeName:b.ZodNaN,...B(r)});var _h=Symbol("zod_brand"),tn=class extends G{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},rn=class r extends G{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);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"?j:s.status==="dirty"?(t.dirty(),Vt(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"?j:i.status==="dirty"?(t.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:n.path,parent:n})}}static create(e,t){return new r({in:e,out:t,typeName:b.ZodPipeline})}},or=class extends G{_parse(e){let t=this._def.innerType._parse(e),n=i=>(Rt(i)&&(i.value=Object.freeze(i.value)),i);return Or(t)?t.then(i=>n(i)):n(t)}unwrap(){return this._def.innerType}};or.create=(r,e)=>new or({innerType:r,typeName:b.ZodReadonly,...B(e)});function gu(r,e){let t=typeof r=="function"?r(e):typeof r=="string"?{message:r}:r;return typeof t=="string"?{message:t}:t}function vu(r,e={},t){return r?Ct.create().superRefine((n,i)=>{let s=r(n);if(s instanceof Promise)return s.then(a=>{if(!a){let o=gu(e,n),u=o.fatal??t??!0;i.addIssue({code:"custom",...o,fatal:u})}});if(!s){let a=gu(e,n),o=a.fatal??t??!0;i.addIssue({code:"custom",...a,fatal:o})}}):Ct.create()}var yh={object:Re.lazycreate},b;(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly"})(b||(b={}));var bh=(r,e={message:`Input not instance of ${r.name}`})=>vu(t=>t instanceof r,e),xu=Nt.create,Eu=Ht.create,wh=Rr.create,vh=Jt.create,Su=Kt.create,xh=Wt.create,Eh=Ir.create,Sh=Yt.create,Th=Xt.create,Oh=Ct.create,$h=Et.create,Ih=tt.create,Ah=Ar.create,kh=St.create,Ph=Re.create,Rh=Re.strictCreate,Nh=Qt.create,Ch=Yn.create,jh=er.create,Lh=ct.create,zh=Xn.create,Mh=kr.create,Dh=Pr.create,Uh=Qn.create,Fh=tr.create,Zh=rr.create,Bh=nr.create,Gh=ir.create,qh=jt.create,Vh=Ve.create,Hh=Ge.create,Jh=lt.create,Kh=Ve.createWithPreprocess,Wh=rn.create,Yh=()=>xu().optional(),Xh=()=>Eu().optional(),Qh=()=>Su().optional(),em={string:(r=>Nt.create({...r,coerce:!0})),number:(r=>Ht.create({...r,coerce:!0})),boolean:(r=>Kt.create({...r,coerce:!0})),bigint:(r=>Jt.create({...r,coerce:!0})),date:(r=>Wt.create({...r,coerce:!0}))};var tm=j;var Po=ot(ri(),1);var Pu=/^(?:[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 om(r){return typeof r=="string"&&Pu.test(r)}var Nr=om;var pe=[];for(ni=0;ni<256;++ni)pe.push((ni+256).toString(16).slice(1));var ni;function Ru(r,e=0){return(pe[r[e+0]]+pe[r[e+1]]+pe[r[e+2]]+pe[r[e+3]]+"-"+pe[r[e+4]]+pe[r[e+5]]+"-"+pe[r[e+6]]+pe[r[e+7]]+"-"+pe[r[e+8]]+pe[r[e+9]]+"-"+pe[r[e+10]]+pe[r[e+11]]+pe[r[e+12]]+pe[r[e+13]]+pe[r[e+14]]+pe[r[e+15]]).toLowerCase()}var ii,um=new Uint8Array(16);function Vs(){if(!ii&&(ii=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!ii))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return ii(um)}var cm=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Hs={randomUUID:cm};function lm(r,e,t){if(Hs.randomUUID&&!e&&!r)return Hs.randomUUID();r=r||{};var n=r.random||(r.rng||Vs)();if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,e){t=t||0;for(var i=0;i<16;++i)e[t+i]=n[i];return e}return Ru(n)}var Ne=lm;var Ks=class{getStore(){}run(e,t){return t()}},Js=Symbol.for("ls:tracing_async_local_storage"),fm=new Ks,Ws=class{getInstance(){return globalThis[Js]??fm}initializeGlobalInstance(e){globalThis[Js]===void 0&&(globalThis[Js]=e)}},pm=new Ws;function Nu(r=!1){let e=pm.getInstance().getStore();if(!r&&e===void 0)throw new Error(`Could not get the current run tree.
20
+
21
+ Please make sure you are calling this method within a traceable function and that tracing is enabled.`);return e}var jE=Symbol.for("langsmith:traceable:root");function si(r){return typeof r=="function"&&"langsmith:traceable"in r}var Nb={};le(Nb,{LogStreamCallbackHandler:()=>Ur,RunLog:()=>Dr,RunLogPatch:()=>Qe,isLogStreamHandler:()=>oo});var Ys={};le(Ys,{JsonPatchError:()=>ee,_areEquals:()=>sn,applyOperation:()=>lr,applyPatch:()=>dr,applyReducer:()=>_m,deepClone:()=>mm,getValueByPointer:()=>li,validate:()=>ju,validator:()=>di});var hm=Object.prototype.hasOwnProperty;function oi(r,e){return hm.call(r,e)}function ui(r){if(Array.isArray(r)){let t=new Array(r.length);for(let n=0;n<t.length;n++)t[n]=""+n;return t}if(Object.keys)return Object.keys(r);let e=[];for(let t in r)oi(r,t)&&e.push(t);return e}function ye(r){switch(typeof r){case"object":return JSON.parse(JSON.stringify(r));case"undefined":return null;default:return r}}function ci(r){let e=0,t=r.length,n;for(;e<t;){if(n=r.charCodeAt(e),n>=48&&n<=57){e++;continue}return!1}return!0}function dt(r){return r.indexOf("/")===-1&&r.indexOf("~")===-1?r:r.replace(/~/g,"~0").replace(/\//g,"~1")}function nn(r){return r.replace(/~1/g,"/").replace(/~0/g,"~")}function ai(r){if(r===void 0)return!0;if(r){if(Array.isArray(r)){for(let t=0,n=r.length;t<n;t++)if(ai(r[t]))return!0}else if(typeof r=="object"){let t=ui(r),n=t.length;for(var e=0;e<n;e++)if(ai(r[t[e]]))return!0}}return!1}function Cu(r,e){let t=[r];for(let n in e){let i=typeof e[n]=="object"?JSON.stringify(e[n],null,2):e[n];typeof i<"u"&&t.push(`${n}: ${i}`)}return t.join(`
22
+ `)}var cr=class extends Error{constructor(e,t,n,i,s){super(Cu(e,{name:t,index:n,operation:i,tree:s})),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"index",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"operation",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"tree",{enumerable:!0,configurable:!0,writable:!0,value:s}),Object.setPrototypeOf(this,new.target.prototype),this.message=Cu(e,{name:t,index:n,operation:i,tree:s})}};var ee=cr,mm=ye,Cr={add:function(r,e,t){return r[e]=this.value,{newDocument:t}},remove:function(r,e,t){var n=r[e];return delete r[e],{newDocument:t,removed:n}},replace:function(r,e,t){var n=r[e];return r[e]=this.value,{newDocument:t,removed:n}},move:function(r,e,t){let n=li(t,this.path);n&&(n=ye(n));let i=lr(t,{op:"remove",path:this.from}).removed;return lr(t,{op:"add",path:this.path,value:i}),{newDocument:t,removed:n}},copy:function(r,e,t){let n=li(t,this.from);return lr(t,{op:"add",path:this.path,value:ye(n)}),{newDocument:t}},test:function(r,e,t){return{newDocument:t,test:sn(r[e],this.value)}},_get:function(r,e,t){return this.value=r[e],{newDocument:t}}},gm={add:function(r,e,t){return ci(e)?r.splice(e,0,this.value):r[e]=this.value,{newDocument:t,index:e}},remove:function(r,e,t){var n=r.splice(e,1);return{newDocument:t,removed:n[0]}},replace:function(r,e,t){var n=r[e];return r[e]=this.value,{newDocument:t,removed:n}},move:Cr.move,copy:Cr.copy,test:Cr.test,_get:Cr._get};function li(r,e){if(e=="")return r;var t={op:"_get",path:e};return lr(r,t),t.value}function lr(r,e,t=!1,n=!0,i=!0,s=0){if(t&&(typeof t=="function"?t(e,0,r,e.path):di(e,0)),e.path===""){let a={newDocument:r};if(e.op==="add")return a.newDocument=e.value,a;if(e.op==="replace")return a.newDocument=e.value,a.removed=r,a;if(e.op==="move"||e.op==="copy")return a.newDocument=li(r,e.from),e.op==="move"&&(a.removed=r),a;if(e.op==="test"){if(a.test=sn(r,e.value),a.test===!1)throw new ee("Test operation failed","TEST_OPERATION_FAILED",s,e,r);return a.newDocument=r,a}else{if(e.op==="remove")return a.removed=r,a.newDocument=null,a;if(e.op==="_get")return e.value=r,a;if(t)throw new ee("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",s,e,r);return a}}else{n||(r=ye(r));let o=(e.path||"").split("/"),u=r,c=1,l=o.length,d,f,p;for(typeof t=="function"?p=t:p=di;;){if(f=o[c],f&&f.indexOf("~")!=-1&&(f=nn(f)),i&&(f=="__proto__"||f=="prototype"&&c>0&&o[c-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(t&&d===void 0&&(u[f]===void 0?d=o.slice(0,c).join("/"):c==l-1&&(d=e.path),d!==void 0&&p(e,0,r,d)),c++,Array.isArray(u)){if(f==="-")f=u.length;else{if(t&&!ci(f))throw new ee("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,e,r);ci(f)&&(f=~~f)}if(c>=l){if(t&&e.op==="add"&&f>u.length)throw new ee("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",s,e,r);let h=gm[e.op].call(e,u,f,r);if(h.test===!1)throw new ee("Test operation failed","TEST_OPERATION_FAILED",s,e,r);return h}}else if(c>=l){let h=Cr[e.op].call(e,u,f,r);if(h.test===!1)throw new ee("Test operation failed","TEST_OPERATION_FAILED",s,e,r);return h}if(u=u[f],t&&c<l&&(!u||typeof u!="object"))throw new ee("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",s,e,r)}}}function dr(r,e,t,n=!0,i=!0){if(t&&!Array.isArray(e))throw new ee("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");n||(r=ye(r));let s=new Array(e.length);for(let a=0,o=e.length;a<o;a++)s[a]=lr(r,e[a],t,!0,i,a),r=s[a].newDocument;return s.newDocument=r,s}function _m(r,e,t){let n=lr(r,e);if(n.test===!1)throw new ee("Test operation failed","TEST_OPERATION_FAILED",t,e,r);return n.newDocument}function di(r,e,t,n){if(typeof r!="object"||r===null||Array.isArray(r))throw new ee("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,r,t);if(Cr[r.op]){if(typeof r.path!="string")throw new ee("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,r,t);if(r.path.indexOf("/")!==0&&r.path.length>0)throw new ee('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,r,t);if((r.op==="move"||r.op==="copy")&&typeof r.from!="string")throw new ee("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,r,t);if((r.op==="add"||r.op==="replace"||r.op==="test")&&r.value===void 0)throw new ee("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,r,t);if((r.op==="add"||r.op==="replace"||r.op==="test")&&ai(r.value))throw new ee("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,r,t);if(t){if(r.op=="add"){var i=r.path.split("/").length,s=n.split("/").length;if(i!==s+1&&i!==s)throw new ee("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",e,r,t)}else if(r.op==="replace"||r.op==="remove"||r.op==="_get"){if(r.path!==n)throw new ee("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",e,r,t)}else if(r.op==="move"||r.op==="copy"){var a={op:"_get",path:r.from,value:void 0},o=ju([a],t);if(o&&o.name==="OPERATION_PATH_UNRESOLVABLE")throw new ee("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,r,t)}}}else throw new ee("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,r,t)}function ju(r,e,t){try{if(!Array.isArray(r))throw new ee("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)dr(ye(e),ye(r),t||!0);else{t=t||di;for(var n=0;n<r.length;n++)t(r[n],n,e,void 0)}}catch(i){if(i instanceof ee)return i;throw i}}function sn(r,e){if(r===e)return!0;if(r&&e&&typeof r=="object"&&typeof e=="object"){var t=Array.isArray(r),n=Array.isArray(e),i,s,a;if(t&&n){if(s=r.length,s!=e.length)return!1;for(i=s;i--!==0;)if(!sn(r[i],e[i]))return!1;return!0}if(t!=n)return!1;var o=Object.keys(r);if(s=o.length,s!==Object.keys(e).length)return!1;for(i=s;i--!==0;)if(!e.hasOwnProperty(o[i]))return!1;for(i=s;i--!==0;)if(a=o[i],!sn(r[a],e[a]))return!1;return!0}return r!==r&&e!==e}function Lu(r,e,t,n,i){if(e!==r){typeof e.toJSON=="function"&&(e=e.toJSON());for(var s=ui(e),a=ui(r),o=!1,u=!1,c=a.length-1;c>=0;c--){var l=a[c],d=r[l];if(oi(e,l)&&!(e[l]===void 0&&d!==void 0&&Array.isArray(e)===!1)){var f=e[l];typeof d=="object"&&d!=null&&typeof f=="object"&&f!=null&&Array.isArray(d)===Array.isArray(f)?Lu(d,f,t,n+"/"+dt(l),i):d!==f&&(o=!0,i&&t.push({op:"test",path:n+"/"+dt(l),value:ye(d)}),t.push({op:"replace",path:n+"/"+dt(l),value:ye(f)}))}else Array.isArray(r)===Array.isArray(e)?(i&&t.push({op:"test",path:n+"/"+dt(l),value:ye(d)}),t.push({op:"remove",path:n+"/"+dt(l)}),u=!0):(i&&t.push({op:"test",path:n,value:r}),t.push({op:"replace",path:n,value:e}),o=!0)}if(!(!u&&s.length==a.length))for(var c=0;c<s.length;c++){var l=s[c];!oi(r,l)&&e[l]!==void 0&&t.push({op:"add",path:n+"/"+dt(l),value:ye(e[l])})}}}function BE(r,e,t=!1){var n=[];return Lu(r,e,n,"",t),n}var VE={...Ys,JsonPatchError:cr,deepClone:ye,escapePathComponent:dt,unescapePathComponent:nn};var _b={};le(_b,{BaseTracer:()=>De,isBaseTracer:()=>hr});var zu=/^(?:[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 ym(r){return typeof r=="string"&&zu.test(r)}var Mu=ym;function bm(r){if(!Mu(r))throw TypeError("Invalid UUID");var e,t=new Uint8Array(16);return t[0]=(e=parseInt(r.slice(0,8),16))>>>24,t[1]=e>>>16&255,t[2]=e>>>8&255,t[3]=e&255,t[4]=(e=parseInt(r.slice(9,13),16))>>>8,t[5]=e&255,t[6]=(e=parseInt(r.slice(14,18),16))>>>8,t[7]=e&255,t[8]=(e=parseInt(r.slice(19,23),16))>>>8,t[9]=e&255,t[10]=(e=parseInt(r.slice(24,36),16))/1099511627776&255,t[11]=e/4294967296&255,t[12]=e>>>24&255,t[13]=e>>>16&255,t[14]=e>>>8&255,t[15]=e&255,t}var Du=bm;var he=[];for(fi=0;fi<256;++fi)he.push((fi+256).toString(16).slice(1));var fi;function pi(r,e=0){return(he[r[e+0]]+he[r[e+1]]+he[r[e+2]]+he[r[e+3]]+"-"+he[r[e+4]]+he[r[e+5]]+"-"+he[r[e+6]]+he[r[e+7]]+"-"+he[r[e+8]]+he[r[e+9]]+"-"+he[r[e+10]]+he[r[e+11]]+he[r[e+12]]+he[r[e+13]]+he[r[e+14]]+he[r[e+15]]).toLowerCase()}var hi,wm=new Uint8Array(16);function Xs(){if(!hi&&(hi=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!hi))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return hi(wm)}function vm(r){r=unescape(encodeURIComponent(r));for(var e=[],t=0;t<r.length;++t)e.push(r.charCodeAt(t));return e}var xm="6ba7b810-9dad-11d1-80b4-00c04fd430c8",Em="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function Qs(r,e,t){function n(i,s,a,o){var u;if(typeof i=="string"&&(i=vm(i)),typeof s=="string"&&(s=Du(s)),((u=s)===null||u===void 0?void 0:u.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");var c=new Uint8Array(16+i.length);if(c.set(s),c.set(i,s.length),c=t(c),c[6]=c[6]&15|e,c[8]=c[8]&63|128,a){o=o||0;for(var l=0;l<16;++l)a[o+l]=c[l];return a}return pi(c)}try{n.name=r}catch{}return n.DNS=xm,n.URL=Em,n}var Sm=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),ea={randomUUID:Sm};function Tm(r,e,t){if(ea.randomUUID&&!e&&!r)return ea.randomUUID();r=r||{};var n=r.random||(r.rng||Xs)();if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,e){t=t||0;for(var i=0;i<16;++i)e[t+i]=n[i];return e}return pi(n)}var Ot=Tm;function Om(r,e,t,n){switch(r){case 0:return e&t^~e&n;case 1:return e^t^n;case 2:return e&t^e&n^t&n;case 3:return e^t^n}}function ta(r,e){return r<<e|r>>>32-e}function $m(r){var e=[1518500249,1859775393,2400959708,3395469782],t=[1732584193,4023233417,2562383102,271733878,3285377520];if(typeof r=="string"){var n=unescape(encodeURIComponent(r));r=[];for(var i=0;i<n.length;++i)r.push(n.charCodeAt(i))}else Array.isArray(r)||(r=Array.prototype.slice.call(r));r.push(128);for(var s=r.length/4+2,a=Math.ceil(s/16),o=new Array(a),u=0;u<a;++u){for(var c=new Uint32Array(16),l=0;l<16;++l)c[l]=r[u*64+l*4]<<24|r[u*64+l*4+1]<<16|r[u*64+l*4+2]<<8|r[u*64+l*4+3];o[u]=c}o[a-1][14]=(r.length-1)*8/Math.pow(2,32),o[a-1][14]=Math.floor(o[a-1][14]),o[a-1][15]=(r.length-1)*8&4294967295;for(var d=0;d<a;++d){for(var f=new Uint32Array(80),p=0;p<16;++p)f[p]=o[d][p];for(var h=16;h<80;++h)f[h]=ta(f[h-3]^f[h-8]^f[h-14]^f[h-16],1);for(var m=t[0],g=t[1],_=t[2],w=t[3],v=t[4],N=0;N<80;++N){var I=Math.floor(N/20),H=ta(m,5)+Om(I,g,_,w)+v+e[I]+f[N]>>>0;v=w,w=_,_=ta(g,30)>>>0,g=m,m=H}t[0]=t[0]+m>>>0,t[1]=t[1]+g>>>0,t[2]=t[2]+_>>>0,t[3]=t[3]+w>>>0,t[4]=t[4]+v>>>0}return[t[0]>>24&255,t[0]>>16&255,t[0]>>8&255,t[0]&255,t[1]>>24&255,t[1]>>16&255,t[1]>>8&255,t[1]&255,t[2]>>24&255,t[2]>>16&255,t[2]>>8&255,t[2]&255,t[3]>>24&255,t[3]>>16&255,t[3]>>8&255,t[3]&255,t[4]>>24&255,t[4]>>16&255,t[4]>>8&255,t[4]&255]}var Uu=$m;var Im=Qs("v5",80,Uu),mi=Im;var Zu="gen_ai.operation.name",Bu="gen_ai.system",ra="gen_ai.request.model",Gu="gen_ai.response.model",na="gen_ai.usage.input_tokens",ia="gen_ai.usage.output_tokens",sa="gen_ai.usage.total_tokens",qu="gen_ai.request.max_tokens",Vu="gen_ai.request.temperature",Hu="gen_ai.request.top_p",Ju="gen_ai.request.frequency_penalty",Ku="gen_ai.request.presence_penalty",Wu="gen_ai.response.finish_reasons",Yu="gen_ai.prompt",Xu="gen_ai.completion",Qu="gen_ai.request.extra_query",ec="gen_ai.request.extra_body",tc="gen_ai.serialized.name",rc="gen_ai.serialized.signature",nc="gen_ai.serialized.doc",ic="gen_ai.response.id",sc="gen_ai.response.service_tier",ac="gen_ai.response.system_fingerprint",oc="gen_ai.usage.input_token_details",uc="gen_ai.usage.output_token_details",cc="langsmith.trace.session_id",lc="langsmith.trace.session_name",dc="langsmith.span.kind",fc="langsmith.trace.name",pc="langsmith.metadata",aa="langsmith.span.tags";var hc="langsmith.request.streaming",mc="langsmith.request.headers";var km=(...r)=>fetch(...r),gc=Symbol.for("ls:fetch_implementation");var _c=()=>{let r=globalThis[gc];return r?typeof r=="function"&&"Headers"in r&&"Request"in r&&"Response"in r:!1},yc=r=>async(...e)=>{if(r||ne("DEBUG")==="true"){let[n,i]=e;console.log(`\u2192 ${i?.method||"GET"} ${n}`)}let t=await(globalThis[gc]??km)(...e);return(r||ne("DEBUG")==="true")&&console.log(`\u2190 ${t.status} ${t.statusText} ${t.url}`),t};var an=()=>ne("PROJECT")??Me("LANGCHAIN_SESSION")??"default";var gi="0.3.74";var ft,Pm=()=>typeof window<"u"&&typeof window.document<"u",Rm=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",Nm=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),bc=()=>typeof Deno<"u",Cm=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!bc(),ca=()=>ft||(typeof Bun<"u"?ft="bun":Pm()?ft="browser":Cm()?ft="node":Rm()?ft="webworker":Nm()?ft="jsdom":bc()?ft="deno":ft="other",ft),oa;function _i(){if(oa===void 0){let r=ca(),e=Lm();oa={library:"langsmith",runtime:r,sdk:"langsmith-js",sdk_version:gi,...e}}return oa}function la(){let r=jm(),e={},t=["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(r))typeof i=="string"&&!t.includes(n)&&!n.toLowerCase().includes("key")&&!n.toLowerCase().includes("secret")&&!n.toLowerCase().includes("token")&&(n==="LANGCHAIN_REVISION_ID"?e.revision_id=i:e[n]=i);return e}function jm(){let r={};try{if(typeof process<"u"&&process.env)for(let[e,t]of Object.entries(process.env))(e.startsWith("LANGCHAIN_")||e.startsWith("LANGSMITH_"))&&t!=null&&((e.toLowerCase().includes("key")||e.toLowerCase().includes("secret")||e.toLowerCase().includes("token"))&&typeof t=="string"?r[e]=t.slice(0,2)+"*".repeat(t.length-4)+t.slice(-2):r[e]=t)}catch{}return r}function Me(r){try{return typeof process<"u"?process.env?.[r]:void 0}catch{return}}function ne(r){return Me(`LANGSMITH_${r}`)||Me(`LANGCHAIN_${r}`)}var ua;function Lm(){if(ua!==void 0)return ua;let r=["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"],e={};for(let t of r){let n=Me(t);n!==void 0&&(e[t]=n)}return ua=e,e}function yi(){return Me("OTEL_ENABLED")==="true"||ne("OTEL_ENABLED")==="true"}var pa=class{constructor(){Object.defineProperty(this,"hasWarned",{enumerable:!0,configurable:!0,writable:!0,value:!1})}startActiveSpan(e,...t){!this.hasWarned&&yi()&&(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(t.length===1&&typeof t[0]=="function"?n=t[0]:t.length===2&&typeof t[1]=="function"?n=t[1]:t.length===3&&typeof t[2]=="function"&&(n=t[2]),typeof n=="function")return n()}},ha=class{constructor(){Object.defineProperty(this,"mockTracer",{enumerable:!0,configurable:!0,writable:!0,value:new pa})}getTracer(e,t){return this.mockTracer}getActiveSpan(){}setSpan(e,t){return e}getSpan(e){}setSpanContext(e,t){return e}getTracerProvider(){}setGlobalTracerProvider(e){return!1}},ma=class{active(){return{}}with(e,t){return t()}},da=Symbol.for("ls:otel_trace"),fa=Symbol.for("ls:otel_context"),wc=Symbol.for("ls:otel_get_default_otlp_tracer_provider"),zm=new ha,Mm=new ma,ga=class{getTraceInstance(){return globalThis[da]??zm}getContextInstance(){return globalThis[fa]??Mm}initializeGlobalInstances(e){globalThis[da]===void 0&&(globalThis[da]=e.trace),globalThis[fa]===void 0&&(globalThis[fa]=e.context)}setDefaultOTLPTracerComponents(e){globalThis[wc]=e}getDefaultOTLPTracerComponents(){return globalThis[wc]??void 0}},_a=new ga;function bi(){return _a.getTraceInstance()}function vc(){return _a.getContextInstance()}function xc(){return _a.getDefaultOTLPTracerComponents()}var Dm={llm:"chat",tool:"execute_tool",retriever:"embeddings",embedding:"embeddings",prompt:"chat"};function Um(r){return Dm[r]||r}var wi=class{constructor(){Object.defineProperty(this,"spans",{enumerable:!0,configurable:!0,writable:!0,value:new Map})}exportBatch(e,t){for(let n of e)try{if(!n.run)continue;if(n.operation==="post"){let i=this.createSpanForRun(n,n.run,t.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(e,t,n){let i=n&&bi().getSpan(n);if(i)try{return this.finishSpanSetup(i,t,e)}catch(s){console.error(`Failed to create span for run ${e.id}:`,s);return}}finishSpanSetup(e,t,n){return this.setSpanAttributes(e,t,n),t.error?(e.setStatus({code:2}),e.recordException(new Error(t.error))):e.setStatus({code:1}),t.end_time&&e.end(new Date(t.end_time)),e}updateSpanForRun(e,t){try{let n=this.spans.get(e.id);if(!n){console.debug(`No span found for run ${e.id} during update`);return}this.setSpanAttributes(n,t,e),t.error?(n.setStatus({code:2}),n.recordException(new Error(t.error))):n.setStatus({code:1});let i=t.end_time;i&&(n.end(new Date(i)),this.spans.delete(e.id))}catch(n){console.error(`Failed to update span for run ${e.id}:`,n)}}extractModelName(e){if(e.extra?.metadata){let t=e.extra.metadata;if(t.ls_model_name)return t.ls_model_name;if(t.invocation_params){let n=t.invocation_params;if(n.model)return n.model;if(n.model_name)return n.model_name}}}setSpanAttributes(e,t,n){if("run_type"in t&&t.run_type){e.setAttribute(dc,t.run_type);let o=Um(t.run_type||"chain");e.setAttribute(Zu,o)}"name"in t&&t.name&&e.setAttribute(fc,t.name),"session_id"in t&&t.session_id&&e.setAttribute(cc,t.session_id),"session_name"in t&&t.session_name&&e.setAttribute(lc,t.session_name),this.setGenAiSystem(e,t);let i=this.extractModelName(t);i&&e.setAttribute(ra,i),"prompt_tokens"in t&&typeof t.prompt_tokens=="number"&&e.setAttribute(na,t.prompt_tokens),"completion_tokens"in t&&typeof t.completion_tokens=="number"&&e.setAttribute(ia,t.completion_tokens),"total_tokens"in t&&typeof t.total_tokens=="number"&&e.setAttribute(sa,t.total_tokens),this.setInvocationParameters(e,t);let s=t.extra?.metadata||{};for(let[o,u]of Object.entries(s))u!=null&&e.setAttribute(`${pc}.${o}`,String(u));let a=t.tags;if(a&&Array.isArray(a)?e.setAttribute(aa,a.join(", ")):a&&e.setAttribute(aa,String(a)),"serialized"in t&&typeof t.serialized=="object"){let o=t.serialized;o.name&&e.setAttribute(tc,String(o.name)),o.signature&&e.setAttribute(rc,String(o.signature)),o.doc&&e.setAttribute(nc,String(o.doc))}this.setIOAttributes(e,n)}setGenAiSystem(e,t){let n="langchain",i=this.extractModelName(t);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")}e.setAttribute(Bu,n)}setInvocationParameters(e,t){if(!t.extra?.metadata?.invocation_params)return;let n=t.extra.metadata.invocation_params;n.max_tokens!==void 0&&e.setAttribute(qu,n.max_tokens),n.temperature!==void 0&&e.setAttribute(Vu,n.temperature),n.top_p!==void 0&&e.setAttribute(Hu,n.top_p),n.frequency_penalty!==void 0&&e.setAttribute(Ju,n.frequency_penalty),n.presence_penalty!==void 0&&e.setAttribute(Ku,n.presence_penalty)}setIOAttributes(e,t){if(t.run.inputs)try{let n=t.run.inputs;typeof n=="object"&&n!==null&&(n.model&&Array.isArray(n.messages)&&e.setAttribute(ra,n.model),n.stream!==void 0&&e.setAttribute(hc,n.stream),n.extra_headers&&e.setAttribute(mc,JSON.stringify(n.extra_headers)),n.extra_query&&e.setAttribute(Qu,JSON.stringify(n.extra_query)),n.extra_body&&e.setAttribute(ec,JSON.stringify(n.extra_body))),e.setAttribute(Yu,JSON.stringify(n))}catch(n){console.debug(`Failed to process inputs for run ${t.id}`,n)}if(t.run.outputs)try{let n=t.run.outputs,i=this.getUnifiedRunTokens(n);if(i&&(e.setAttribute(na,i[0]),e.setAttribute(ia,i[1]),e.setAttribute(sa,i[0]+i[1])),n&&typeof n=="object"){if(n.model&&e.setAttribute(Gu,String(n.model)),n.id&&e.setAttribute(ic,n.id),n.choices&&Array.isArray(n.choices)){let s=n.choices.map(a=>a.finish_reason).filter(a=>a).map(String);s.length>0&&e.setAttribute(Wu,s.join(", "))}if(n.service_tier&&e.setAttribute(sc,n.service_tier),n.system_fingerprint&&e.setAttribute(ac,n.system_fingerprint),n.usage_metadata&&typeof n.usage_metadata=="object"){let s=n.usage_metadata;s.input_token_details&&e.setAttribute(oc,JSON.stringify(s.input_token_details)),s.output_token_details&&e.setAttribute(uc,JSON.stringify(s.output_token_details))}}e.setAttribute(Xu,JSON.stringify(n))}catch(n){console.debug(`Failed to process outputs for run ${t.id}`,n)}}getUnifiedRunTokens(e){if(!e)return null;let t=this.extractUnifiedRunTokens(e.usage_metadata);if(t)return t;let n=Object.keys(e);for(let a of n){let o=e[a];if(!(!o||typeof o!="object")&&(t=this.extractUnifiedRunTokens(o.usage_metadata),t||o.lc===1&&o.kwargs&&typeof o.kwargs=="object"&&(t=this.extractUnifiedRunTokens(o.kwargs.usage_metadata),t)))return t}let i=e.generations||[];if(!Array.isArray(i))return null;let s=Array.isArray(i[0])?i.flat():i;for(let a of s)if(typeof a=="object"&&a.message&&typeof a.message=="object"&&a.message.kwargs&&typeof a.message.kwargs=="object"&&(t=this.extractUnifiedRunTokens(a.message.kwargs.usage_metadata),t))return t;return null}extractUnifiedRunTokens(e){return!e||typeof e!="object"||typeof e.input_tokens!="number"||typeof e.output_tokens!="number"?null:[e.input_tokens,e.output_tokens]}};var Rc=ot(ri(),1),Oi=ot(Ti(),1),Km=[429,500,502,503,504],un=class{constructor(e){Object.defineProperty(this,"maxConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxRetries",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onFailedResponseHook",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,"default"in Oi.default?this.queue=new Oi.default.default({concurrency:this.maxConcurrency}):this.queue=new Oi.default({concurrency:this.maxConcurrency}),this.onFailedResponseHook=e?.onFailedResponseHook}call(e,...t){let n=this.onFailedResponseHook;return this.queue.add(()=>(0,Rc.default)(()=>e(...t).catch(i=>{throw i instanceof Error?i:new Error(i)}),{async onFailedAttempt(i){if(i.message.startsWith("Cancel")||i.message.startsWith("TimeoutError")||i.name==="TimeoutError"||i.message.startsWith("AbortError")||i?.code==="ECONNABORTED")throw i;let s=i?.response;if(n&&await n(s))return;let a=s?.status??i?.status;if(a&&!Km.includes(+a))throw i},retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(e,t,...n){return e.signal?Promise.race([this.call(t,...n),new Promise((i,s)=>{e.signal?.addEventListener("abort",()=>{s(new Error("AbortError"))})})]):this.call(t,...n)}};function Sa(r){return typeof r?._getType=="function"}function Ta(r){let e={type:r._getType(),data:{content:r.content}};return r?.additional_kwargs&&Object.keys(r.additional_kwargs).length>0&&(e.data.additional_kwargs={...r.additional_kwargs}),e}var Wm=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function F(r,e){if(!Wm.test(r)){let t=e!==void 0?`Invalid UUID for ${e}: ${r}`:`Invalid UUID: ${r}`;throw new Error(t)}return r}var Nc={};function cn(r){Nc[r]||(console.warn(r),Nc[r]=!0)}var Vy=ot(xd(),1);function $t(r){if(!r||r.split("/").length>2||r.startsWith("/")||r.endsWith("/")||r.split(":").length>2)throw new Error(`Invalid identifier format: ${r}`);let[e,t]=r.split(":"),n=t||"latest";if(e.includes("/")){let[i,s]=e.split("/",2);if(!i||!s)throw new Error(`Invalid identifier format: ${r}`);return[i,s,n]}else{if(!e)throw new Error(`Invalid identifier format: ${r}`);return["-",e,n]}}var qa=class extends Error{constructor(e){super(e),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="LangSmithConflictError",this.status=409}};async function R(r,e,t){let n;if(r.ok){t&&(n=await r.text());return}if(r.status===403)try{(await r.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 o=new Error(`${r.status} ${r.statusText}`);throw o.status=r?.status,o}if(n===void 0)try{n=await r.text()}catch{n=""}let i=`Failed to ${e}. Received status [${r.status}]: ${r.statusText}. Message: ${n}`;if(r.status===409)throw new qa(i);let s=new Error(i);throw s.status=r.status,s}var Ed="ERR_CONFLICTING_ENDPOINTS",Di=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:Ed}),this.name="ConflictingEndpointsError"}};function Sd(r){return typeof r=="object"&&r!==null&&r.code===Ed}var Td="[...]",Hy={result:"[Circular]"},Fi=[],Lr=[],Jy=new TextEncoder;function Ky(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function Ui(r){return Jy.encode(r)}function Od(r){if(r&&typeof r=="object"&&r!==null){if(r instanceof Map)return Object.fromEntries(r);if(r instanceof Set)return Array.from(r);if(r instanceof Date)return r.toISOString();if(r instanceof RegExp)return r.toString();if(r instanceof Error)return{name:r.name,message:r.message}}else if(typeof r=="bigint")return r.toString();return r}function Wy(r){return function(e,t){if(r){let n=r.call(this,e,t);if(n!==void 0)return n}return Od(t)}}function Ce(r,e,t,n,i){try{let s=JSON.stringify(r,Wy(t),n);return Ui(s)}catch(s){if(!s.message?.includes("Converting circular structure to JSON"))return console.warn(`[WARNING]: LangSmith received unserializable value.${e?`
23
+ Context: ${e}`:""}`),Ui("[Unserializable]");ne("SUPPRESS_CIRCULAR_JSON_WARNINGS")!=="true"&&console.warn(`[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. ${e?`
24
+ Context: ${e}`:""}`),typeof i>"u"&&(i=Ky()),Ha(r,"",0,[],void 0,0,i);let a;try{Lr.length===0?a=JSON.stringify(r,t,n):a=JSON.stringify(r,Yy(t),n)}catch{return Ui("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;Fi.length!==0;){let o=Fi.pop();o.length===4?Object.defineProperty(o[0],o[1],o[3]):o[0][o[1]]=o[2]}}return Ui(a)}}function Va(r,e,t,n){var i=Object.getOwnPropertyDescriptor(n,t);i.get!==void 0?i.configurable?(Object.defineProperty(n,t,{value:r}),Fi.push([n,t,e,i])):Lr.push([e,t,r]):(n[t]=r,Fi.push([n,t,e]))}function Ha(r,e,t,n,i,s,a){s+=1;var o;if(typeof r=="object"&&r!==null){for(o=0;o<n.length;o++)if(n[o]===r){Va(Hy,r,e,i);return}if(typeof a.depthLimit<"u"&&s>a.depthLimit){Va(Td,r,e,i);return}if(typeof a.edgesLimit<"u"&&t+1>a.edgesLimit){Va(Td,r,e,i);return}if(n.push(r),Array.isArray(r))for(o=0;o<r.length;o++)Ha(r[o],o,o,n,r,s,a);else{r=Od(r);var u=Object.keys(r);for(o=0;o<u.length;o++){var c=u[o];Ha(r[c],c,o,n,r,s,a)}}n.pop()}}function Yy(r){return r=typeof r<"u"?r:function(e,t){return t},function(e,t){if(Lr.length>0)for(var n=0;n<Lr.length;n++){var i=Lr[n];if(i[1]===e&&i[0]===t){t=i[2],Lr.splice(n,1);break}}return r.call(this,e,t)}}function $d(r,e){let t=_i(),n=e??la(),i=r.extra??{},s=i.metadata;return r.extra={...i,runtime:{...t,...i?.runtime},metadata:{...n,...n.revision_id||"revision_id"in r&&r.revision_id?{revision_id:("revision_id"in r?r.revision_id:void 0)??n.revision_id}:{},...s}},r}var Xy=r=>{let e=r?.toString()??ne("TRACING_SAMPLING_RATE");if(e===void 0)return;let t=parseFloat(e);if(t<0||t>1)throw new Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${t}`);return t},Qy=r=>{let t=r.replace("http://","").replace("https://","").split("/")[0].split(":")[0];return t==="localhost"||t==="127.0.0.1"||t==="::1"};async function eb(r){let e=[];for await(let t of r)e.push(t);return e}function Zi(r){if(r!==void 0)return r.trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}var tb=async r=>{if(r?.status===429){let e=parseInt(r.headers.get("retry-after")??"10",10)*1e3;if(e>0)return await new Promise(t=>setTimeout(t,e)),!0}return!1};function Id(r){return typeof r=="number"?Number(r.toFixed(4)):r}var Ja=class{constructor(){Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"sizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0})}peek(){return this.items[0]}push(e){let t,n=new Promise(s=>{t=s}),i=Ce(e.item,`Serializing run with id: ${e.item.id}`).length;return this.items.push({action:e.action,payload:e.item,otelContext:e.otelContext,apiKey:e.apiKey,apiUrl:e.apiUrl,itemPromiseResolve:t,itemPromise:n,size:i}),this.sizeBytes+=i,n}pop({upToSizeBytes:e,upToSize:t}){if(e<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)<e&&this.items.length>0&&n.length<t;){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})),()=>n.forEach(s=>s.itemPromiseResolve())]}},rb=24*1024*1024,nb=1e4,ib=100,Ad="https://api.smith.langchain.com",fr=class r{get _fetch(){return this.fetchImplementation||yc(this.debug)}constructor(e={}){Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"apiUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"webUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"workspaceId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"caller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchIngestCaller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"timeout_ms",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_tenantId",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"hideInputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"hideOutputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"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:new Ja}),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:Me("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,"multipartStreamingDisabled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"debug",{enumerable:!0,configurable:!0,writable:!0,value:Me("LANGSMITH_DEBUG")==="true"});let t=r.getDefaultClientConfig();if(this.tracingSampleRate=Xy(e.tracingSamplingRate),this.apiUrl=Zi(e.apiUrl??t.apiUrl)??"",this.apiUrl.endsWith("/")&&(this.apiUrl=this.apiUrl.slice(0,-1)),this.apiKey=Zi(e.apiKey??t.apiKey),this.webUrl=Zi(e.webUrl??t.webUrl),this.webUrl?.endsWith("/")&&(this.webUrl=this.webUrl.slice(0,-1)),this.workspaceId=Zi(e.workspaceId??ne("WORKSPACE_ID")),this.timeout_ms=e.timeout_ms??9e4,this.caller=new un({...e.callerOptions??{},maxRetries:4,debug:e.debug??this.debug}),this.traceBatchConcurrency=e.traceBatchConcurrency??this.traceBatchConcurrency,this.traceBatchConcurrency<1)throw new Error("Trace batch concurrency must be positive.");this.debug=e.debug??this.debug,this.fetchImplementation=e.fetchImplementation,this.batchIngestCaller=new un({maxRetries:2,maxConcurrency:this.traceBatchConcurrency,...e.callerOptions??{},onFailedResponseHook:tb,debug:e.debug??this.debug}),this.hideInputs=e.hideInputs??e.anonymizer??t.hideInputs,this.hideOutputs=e.hideOutputs??e.anonymizer??t.hideOutputs,this.autoBatchTracing=e.autoBatchTracing??this.autoBatchTracing,this.blockOnRootRunFinalization=e.blockOnRootRunFinalization??this.blockOnRootRunFinalization,this.batchSizeBytesLimit=e.batchSizeBytesLimit,this.batchSizeLimit=e.batchSizeLimit,this.fetchOptions=e.fetchOptions||{},this.manualFlushMode=e.manualFlushMode??this.manualFlushMode,yi()&&(this.langSmithToOTELTranslator=new wi),this.cachedLSEnvVarsForMetadata=la()}static getDefaultClientConfig(){let e=ne("API_KEY"),t=ne("ENDPOINT")??Ad,n=ne("HIDE_INPUTS")==="true",i=ne("HIDE_OUTPUTS")==="true";return{apiUrl:t,apiKey:e,webUrl:void 0,hideInputs:n,hideOutputs:i}}getHostUrl(){return this.webUrl?this.webUrl:Qy(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 e={"User-Agent":`langsmith-js/${gi}`};return this.apiKey&&(e["x-api-key"]=`${this.apiKey}`),this.workspaceId&&(e["x-tenant-id"]=this.workspaceId),e}_getPlatformEndpointPath(e){return this.apiUrl.slice(-3)!=="/v1"&&this.apiUrl.slice(-4)!=="/v1/"?`/v1/platform/${e}`:`/platform/${e}`}async processInputs(e){return this.hideInputs===!1?e:this.hideInputs===!0?{}:typeof this.hideInputs=="function"?this.hideInputs(e):e}async processOutputs(e){return this.hideOutputs===!1?e:this.hideOutputs===!0?{}:typeof this.hideOutputs=="function"?this.hideOutputs(e):e}async prepareRunCreateOrUpdateInputs(e){let t={...e};return t.inputs!==void 0&&(t.inputs=await this.processInputs(t.inputs)),t.outputs!==void 0&&(t.outputs=await this.processOutputs(t.outputs)),t}async _getResponse(e,t){let n=t?.toString()??"",i=`${this.apiUrl}${e}?${n}`;return await this.caller.call(async()=>{let a=await this._fetch(i,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await R(a,`fetch ${e}`),a})}async _get(e,t){return(await this._getResponse(e,t)).json()}async*_getPaginated(e,t=new URLSearchParams,n){let i=Number(t.get("offset"))||0,s=Number(t.get("limit"))||100;for(;;){t.set("offset",String(i)),t.set("limit",String(s));let a=`${this.apiUrl}${e}?${t}`,o=await this.caller.call(async()=>{let c=await this._fetch(a,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await R(c,`fetch ${e}`),c}),u=n?n(await o.json()):await o.json();if(u.length===0||(yield u,u.length<s))break;i+=u.length}}async*_getCursorPaginatedList(e,t=null,n="POST",i="runs"){let s=t?{...t}:{};for(;;){let a=JSON.stringify(s),u=await(await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}${e}`,{method:n,headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await R(l,`fetch ${e}`),l})).json();if(!u||!u[i])break;yield u[i];let c=u.cursors;if(!c||!c.next)break;s.cursor=c.next}}_shouldSample(){return this.tracingSampleRate===void 0?!0:Math.random()<this.tracingSampleRate}_filterForSampling(e,t=!1){if(this.tracingSampleRate===void 0)return e;if(t){let n=[];for(let i of e)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 e){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 e=await this._ensureServerInfo();return this.batchSizeBytesLimit??e.batch_ingest_config?.size_limit_bytes??rb}async _getBatchSizeLimit(){let e=await this._ensureServerInfo();return this.batchSizeLimit??e.batch_ingest_config?.size_limit??ib}async _getDatasetExamplesMultiPartSupport(){return(await this._ensureServerInfo()).instance_flags?.dataset_examples_multipart_enabled??!1}drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:t}){let n=[];for(;this.autoBatchQueue.items.length>0;){let[i,s]=this.autoBatchQueue.pop({upToSizeBytes:e,upToSize:t});if(!i.length){s();break}let a=i.reduce((c,l)=>{let d=l.apiUrl??this.apiUrl,f=l.apiKey??this.apiKey,h=l.apiKey===this.apiKey&&l.apiUrl===this.apiUrl?"default":`${d}|${f}`;return c[h]||(c[h]=[]),c[h].push(l),c},{}),o=[];for(let[c,l]of Object.entries(a)){let d=this._processBatch(l,{apiUrl:c==="default"?void 0:c.split("|")[0],apiKey:c==="default"?void 0:c.split("|")[1]});o.push(d)}let u=Promise.all(o).finally(s);n.push(u)}return Promise.all(n)}async _processBatch(e,t){if(e.length)try{if(this.langSmithToOTELTranslator!==void 0)this._sendBatchToOTELTranslator(e);else{let n={runCreates:e.filter(s=>s.action==="create").map(s=>s.item),runUpdates:e.filter(s=>s.action==="update").map(s=>s.item)},i=await this._ensureServerInfo();if(i?.batch_ingest_config?.use_multipart_endpoint){let s=i?.instance_flags?.gzip_body_enabled;await this.multipartIngestRuns(n,{...t,useGzip:s})}else await this.batchIngestRuns(n,t)}}catch(n){console.error("Error exporting batch:",n)}}_sendBatchToOTELTranslator(e){if(this.langSmithToOTELTranslator!==void 0){let t=new Map,n=[];for(let i of e)i.item.id&&i.otelContext&&(t.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,t)}}async processRunOperation(e){clearTimeout(this.autoBatchTimeout),this.autoBatchTimeout=void 0,e.item=$d(e.item,this.cachedLSEnvVarsForMetadata);let t=this.autoBatchQueue.push(e);if(this.manualFlushMode)return t;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)),t}async _getServerInfo(){let t=await(await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/info`,{method:"GET",headers:{Accept:"application/json"},signal:AbortSignal.timeout(nb),...this.fetchOptions});return await R(n,"get server info"),n})).json();return this.debug&&console.log(`
25
+ === LangSmith Server Configuration ===
26
+ `+JSON.stringify(t,null,2)+`
27
+ `),t}async _ensureServerInfo(){return this._getServerInfoPromise===void 0&&(this._getServerInfoPromise=(async()=>{if(this._serverInfo===void 0)try{this._serverInfo=await this._getServerInfo()}catch(e){console.warn(`[LANGSMITH]: Failed to fetch info on supported operations. Falling back to batch operations and default limits. Info: ${e.status??"Unspecified status code"} ${e.message}`)}return this._serverInfo??{}})()),this._getServerInfoPromise.then(e=>(this._serverInfo===void 0&&(this._getServerInfoPromise=void 0),e))}async _getSettings(){return this.settings||(this.settings=this._get("/settings")),await this.settings}async flush(){let e=await this._getBatchSizeLimitBytes(),t=await this._getBatchSizeLimit();await this.drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:t})}_cloneCurrentOTELContext(){let e=bi(),t=vc();if(this.langSmithToOTELTranslator!==void 0){let n=e.getActiveSpan();if(n)return e.setSpan(t.active(),n)}}async createRun(e,t){if(!this._filterForSampling([e]).length)return;let n={...this.headers,"Content-Type":"application/json"},i=e.project_name;delete e.project_name;let s=await this.prepareRunCreateOrUpdateInputs({session_name:i,...e,start_time:e.start_time??Date.now()});if(this.autoBatchTracing&&s.trace_id!==void 0&&s.dotted_order!==void 0){let u=this._cloneCurrentOTELContext();this.processRunOperation({action:"create",item:s,otelContext:u,apiKey:t?.apiKey,apiUrl:t?.apiUrl}).catch(console.error);return}let a=$d(s,this.cachedLSEnvVarsForMetadata);t?.apiKey!==void 0&&(n["x-api-key"]=t.apiKey),t?.workspaceId!==void 0&&(n["x-tenant-id"]=t.workspaceId);let o=Ce(a,`Creating run with id: ${a.id}`);await this.caller.call(async()=>{let u=await this._fetch(`${t?.apiUrl??this.apiUrl}/runs`,{method:"POST",headers:n,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await R(u,"create run",!0),u})}async batchIngestRuns({runCreates:e,runUpdates:t},n){if(e===void 0&&t===void 0)return;let i=await Promise.all(e?.map(u=>this.prepareRunCreateOrUpdateInputs(u))??[]),s=await Promise.all(t?.map(u=>this.prepareRunCreateOrUpdateInputs(u))??[]);if(i.length>0&&s.length>0){let u=i.reduce((l,d)=>(d.id&&(l[d.id]=d),l),{}),c=[];for(let l of s)l.id!==void 0&&u[l.id]?u[l.id]={...u[l.id],...l}:c.push(l);i=Object.values(u),s=c}let a={post:i,patch:s};if(!a.post.length&&!a.patch.length)return;let o={post:[],patch:[]};for(let u of["post","patch"]){let c=u,l=a[c].reverse(),d=l.pop();for(;d!==void 0;)o[c].push(d),d=l.pop()}if(o.post.length>0||o.patch.length>0){let u=o.post.map(c=>c.id).concat(o.patch.map(c=>c.id)).join(",");await this._postBatchIngestRuns(Ce(o,`Ingesting runs with ids: ${u}`),n)}}async _postBatchIngestRuns(e,t){let n={...this.headers,"Content-Type":"application/json",Accept:"application/json"};t?.apiKey!==void 0&&(n["x-api-key"]=t.apiKey),await this.batchIngestCaller.call(async()=>{let i=await this._fetch(`${t?.apiUrl??this.apiUrl}/runs/batch`,{method:"POST",headers:n,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:e});return await R(i,"batch create run",!0),i})}async multipartIngestRuns({runCreates:e,runUpdates:t},n){if(e===void 0&&t===void 0)return;let i={},s=[];for(let d of e??[]){let f=await this.prepareRunCreateOrUpdateInputs(d);f.id!==void 0&&f.attachments!==void 0&&(i[f.id]=f.attachments),delete f.attachments,s.push(f)}let a=[];for(let d of t??[])a.push(await this.prepareRunCreateOrUpdateInputs(d));if(s.find(d=>d.trace_id===void 0||d.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(a.find(d=>d.trace_id===void 0||d.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&&a.length>0){let d=s.reduce((p,h)=>(h.id&&(p[h.id]=h),p),{}),f=[];for(let p of a)p.id!==void 0&&d[p.id]?d[p.id]={...d[p.id],...p}:f.push(p);s=Object.values(d),a=f}if(s.length===0&&a.length===0)return;let c=[],l=[];for(let[d,f]of[["post",s],["patch",a]])for(let p of f){let{inputs:h,outputs:m,events:g,extra:_,error:w,serialized:v,attachments:N,...I}=p,H={inputs:h,outputs:m,events:g,extra:_,error:w,serialized:v},K=Ce(I,`Serializing for multipart ingestion of run with id: ${I.id}`);l.push({name:`${d}.${I.id}`,payload:new Blob([K],{type:`application/json; length=${K.length}`})});for(let[J,ce]of Object.entries(H)){if(ce===void 0)continue;let ze=Ce(ce,`Serializing ${J} for multipart ingestion of run with id: ${I.id}`);l.push({name:`${d}.${I.id}.${J}`,payload:new Blob([ze],{type:`application/json; length=${ze.length}`})})}if(I.id!==void 0){let J=i[I.id];if(J){delete i[I.id];for(let[ce,ze]of Object.entries(J)){let yt,Bt;if(Array.isArray(ze)?[yt,Bt]=ze:(yt=ze.mimeType,Bt=ze.data),ce.includes(".")){console.warn(`Skipping attachment '${ce}' for run ${I.id}: Invalid attachment name. Attachment names must not contain periods ('.'). Please rename the attachment and try again.`);continue}l.push({name:`attachment.${I.id}.${ce}`,payload:new Blob([Bt],{type:`${yt}; length=${Bt.byteLength}`})})}}}c.push(`trace=${I.trace_id},id=${I.id}`)}await this._sendMultipartRequest(l,c.join("; "),n)}async _createNodeFetchBody(e,t){let n=[];for(let a of e)n.push(new Blob([`--${t}\r
28
+ `])),n.push(new Blob([`Content-Disposition: form-data; name="${a.name}"\r
29
+ `,`Content-Type: ${a.payload.type}\r
30
+ \r
31
+ `])),n.push(a.payload),n.push(new Blob([`\r
32
+ `]));return n.push(new Blob([`--${t}--\r
33
+ `])),await new Blob(n).arrayBuffer()}async _createMultipartStream(e,t){let n=new TextEncoder;return new ReadableStream({async start(s){let a=async o=>{typeof o=="string"?s.enqueue(n.encode(o)):s.enqueue(o)};for(let o of e){await a(`--${t}\r
34
+ `),await a(`Content-Disposition: form-data; name="${o.name}"\r
35
+ `),await a(`Content-Type: ${o.payload.type}\r
36
+ \r
37
+ `);let c=o.payload.stream().getReader();try{let l;for(;!(l=await c.read()).done;)s.enqueue(l.value)}finally{c.releaseLock()}await a(`\r
38
+ `)}await a(`--${t}--\r
39
+ `),s.close()}})}async _sendMultipartRequest(e,t,n){let i="----LangSmithFormBoundary"+Math.random().toString(36).slice(2),s=_c(),a=()=>this._createNodeFetchBody(e,i),o=()=>this._createMultipartStream(e,i),u=async c=>this.batchIngestCaller.call(async()=>{let l=await c(),d={...this.headers,"Content-Type":`multipart/form-data; boundary=${i}`};n?.apiKey!==void 0&&(d["x-api-key"]=n.apiKey);let f=l;n?.useGzip&&typeof l=="object"&&"pipeThrough"in l&&(f=l.pipeThrough(new CompressionStream("gzip")),d["Content-Encoding"]="gzip");let p=await this._fetch(`${n?.apiUrl??this.apiUrl}/runs/multipart`,{method:"POST",headers:d,body:f,duplex:"half",signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await R(p,"Failed to send multipart request",!0),p});try{let c,l=!1;!s&&!this.multipartStreamingDisabled&&ca()!=="bun"?(l=!0,c=await u(o)):c=await u(a),(!this.multipartStreamingDisabled||l)&&c.status===422&&(n?.apiUrl??this.apiUrl)!==Ad&&(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 "${t}".`),this.multipartStreamingDisabled=!0,c=await u(a))}catch(c){console.warn(`${c.message.trim()}
40
+
41
+ Context: ${t}`)}}async updateRun(e,t,n){F(e),t.inputs&&(t.inputs=await this.processInputs(t.inputs)),t.outputs&&(t.outputs=await this.processOutputs(t.outputs));let i={...t,id:e};if(!this._filterForSampling([i],!0).length)return;if(this.autoBatchTracing&&i.trace_id!==void 0&&i.dotted_order!==void 0){let o=this._cloneCurrentOTELContext();if(t.end_time!==void 0&&i.parent_run_id===void 0&&this.blockOnRootRunFinalization&&!this.manualFlushMode){await this.processRunOperation({action:"update",item:i,otelContext:o,apiKey:n?.apiKey,apiUrl:n?.apiUrl}).catch(console.error);return}else this.processRunOperation({action:"update",item:i,otelContext:o,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 a=Ce(t,`Serializing payload to update run with id: ${e}`);await this.caller.call(async()=>{let o=await this._fetch(`${n?.apiUrl??this.apiUrl}/runs/${e}`,{method:"PATCH",headers:s,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await R(o,"update run",!0),o})}async readRun(e,{loadChildRuns:t}={loadChildRuns:!1}){F(e);let n=await this._get(`/runs/${e}`);return t&&(n=await this._loadChildRuns(n)),n}async getRunUrl({runId:e,run:t,projectOpts:n}){if(t!==void 0){let i;t.session_id?i=t.session_id:n?.projectName?i=(await this.readProject({projectName:n?.projectName})).id:n?.projectId?i=n?.projectId:i=(await this.readProject({projectName:ne("PROJECT")||"default"})).id;let s=await this._getTenantId();return`${this.getHostUrl()}/o/${s}/projects/p/${i}/r/${t.id}?poll=true`}else if(e!==void 0){let i=await this.readRun(e);if(!i.app_path)throw new Error(`Run ${e} has no app_path`);return`${this.getHostUrl()}${i.app_path}`}else throw new Error("Must provide either runId or run")}async _loadChildRuns(e){let t=await eb(this.listRuns({isRoot:!1,projectId:e.session_id,traceId:e.trace_id})),n={},i={};t.sort((s,a)=>(s?.dotted_order??"").localeCompare(a?.dotted_order??""));for(let s of t){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(e.dotted_order??"")&&s.id!==e.id&&(s.parent_run_id in n||(n[s.parent_run_id]=[]),n[s.parent_run_id].push(s),i[s.id]=s)}e.child_runs=n[e.id]||[];for(let s in n)s!==e.id&&(i[s].child_runs=n[s]);return e}async*listRuns(e){let{projectId:t,projectName:n,parentRunId:i,traceId:s,referenceExampleId:a,startTime:o,executionOrder:u,isRoot:c,runType:l,error:d,id:f,query:p,filter:h,traceFilter:m,treeFilter:g,limit:_,select:w,order:v}=e,N=[];if(t&&(N=Array.isArray(t)?t:[t]),n){let J=Array.isArray(n)?n:[n],ce=await Promise.all(J.map(ze=>this.readProject({projectName:ze}).then(yt=>yt.id)));N.push(...ce)}let I=["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"],H={session:N.length?N:null,run_type:l,reference_example:a,query:p,filter:h,trace_filter:m,tree_filter:g,execution_order:u,parent_run:i,start_time:o?o.toISOString():null,error:d,id:f,limit:_,trace:s,select:w||I,is_root:c,order:v};H.select.includes("child_run_ids")&&cn("Deprecated: 'child_run_ids' in the listRuns select parameter is deprecated and will be removed in a future version.");let K=0;for await(let J of this._getCursorPaginatedList("/runs/query",H))if(_){if(K>=_)break;if(J.length+K>_){yield*J.slice(0,_-K);break}K+=J.length,yield*J}else yield*J}async*listGroupRuns(e){let{projectId:t,projectName:n,groupBy:i,filter:s,startTime:a,endTime:o,limit:u,offset:c}=e,d={session_id:t||(await this.readProject({projectName:n})).id,group_by:i,filter:s,start_time:a?a.toISOString():null,end_time:o?o.toISOString():null,limit:Number(u)||100},f=Number(c)||0,p="/runs/group",h=`${this.apiUrl}${p}`;for(;;){let m={...d,offset:f},g=Object.fromEntries(Object.entries(m).filter(([H,K])=>K!==void 0)),_=JSON.stringify(g),v=await(await this.caller.call(async()=>{let H=await this._fetch(h,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:_});return await R(H,`Failed to fetch ${p}`),H})).json(),{groups:N,total:I}=v;if(N.length===0)break;for(let H of N)yield H;if(f+=N.length,f>=I)break}}async getRunStats({id:e,trace:t,parentRun:n,runType:i,projectNames:s,projectIds:a,referenceExampleIds:o,startTime:u,endTime:c,error:l,query:d,filter:f,traceFilter:p,treeFilter:h,isRoot:m,dataSourceType:g}){let _=a||[];s&&(_=[...a||[],...await Promise.all(s.map(K=>this.readProject({projectName:K}).then(J=>J.id)))]);let v=Object.fromEntries(Object.entries({id:e,trace:t,parent_run:n,run_type:i,session:_,reference_example:o,start_time:u,end_time:c,error:l,query:d,filter:f,trace_filter:p,tree_filter:h,is_root:m,data_source_type:g}).filter(([K,J])=>J!==void 0)),N=JSON.stringify(v);return await(await this.caller.call(async()=>{let K=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:N});return await R(K,"get run stats"),K})).json()}async shareRun(e,{shareId:t}={}){let n={run_id:e,share_token:t||Ot()};F(e);let i=JSON.stringify(n),a=await(await this.caller.call(async()=>{let o=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"PUT",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await R(o,"share run"),o})).json();if(a===null||!("share_token"in a))throw new Error("Invalid response from server");return`${this.getHostUrl()}/public/${a.share_token}/r`}async unshareRun(e){F(e),await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await R(t,"unshare run",!0),t})}async readRunSharedLink(e){F(e);let n=await(await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await R(i,"read run shared link"),i})).json();if(!(n===null||!("share_token"in n)))return`${this.getHostUrl()}/public/${n.share_token}/r`}async listSharedRuns(e,{runIds:t}={}){let n=new URLSearchParams({share_token:e});if(t!==void 0)for(let a of t)n.append("id",a);return F(e),await(await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}/public/${e}/runs${n}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await R(a,"list shared runs"),a})).json()}async readDatasetSharedSchema(e,t){if(!e&&!t)throw new Error("Either datasetId or datasetName must be given");e||(e=(await this.readDataset({datasetName:t})).id),F(e);let i=await(await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await R(s,"read dataset shared schema"),s})).json();return i.url=`${this.getHostUrl()}/public/${i.share_token}/d`,i}async shareDataset(e,t){if(!e&&!t)throw new Error("Either datasetId or datasetName must be given");e||(e=(await this.readDataset({datasetName:t})).id);let n={dataset_id:e};F(e);let i=JSON.stringify(n),a=await(await this.caller.call(async()=>{let o=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"PUT",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await R(o,"share dataset"),o})).json();return a.url=`${this.getHostUrl()}/public/${a.share_token}/d`,a}async unshareDataset(e){F(e),await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await R(t,"unshare dataset",!0),t})}async readSharedDataset(e){return F(e),await(await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}/public/${e}/datasets`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await R(i,"read shared dataset"),i})).json()}async listSharedExamples(e,t){let n={};t?.exampleIds&&(n.id=t.exampleIds);let i=new URLSearchParams;Object.entries(n).forEach(([o,u])=>{Array.isArray(u)?u.forEach(c=>i.append(o,c)):i.append(o,u)});let s=await this.caller.call(async()=>{let o=await this._fetch(`${this.apiUrl}/public/${e}/examples?${i.toString()}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await R(o,"list shared examples"),o}),a=await s.json();if(!s.ok)throw"detail"in a?new Error(`Failed to list shared examples.
42
+ Status: ${s.status}
43
+ Message: ${Array.isArray(a.detail)?a.detail.join(`
44
+ `):"Unspecified error"}`):new Error(`Failed to list shared examples: ${s.status} ${s.statusText}`);return a.map(o=>({...o,_hostUrl:this.getHostUrl()}))}async createProject({projectName:e,description:t=null,metadata:n=null,upsert:i=!1,projectExtra:s=null,referenceDatasetId:a=null}){let o=i?"?upsert=true":"",u=`${this.apiUrl}/sessions${o}`,c=s||{};n&&(c.metadata=n);let l={name:e,extra:c,description:t};a!==null&&(l.reference_dataset_id=a);let d=JSON.stringify(l);return await(await this.caller.call(async()=>{let h=await this._fetch(u,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:d});return await R(h,"create project"),h})).json()}async updateProject(e,{name:t=null,description:n=null,metadata:i=null,projectExtra:s=null,endTime:a=null}){let o=`${this.apiUrl}/sessions/${e}`,u=s;i&&(u={...u||{},metadata:i});let c=JSON.stringify({name:t,extra:u,description:n,end_time:a?new Date(a).toISOString():null});return await(await this.caller.call(async()=>{let f=await this._fetch(o,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await R(f,"update project"),f})).json()}async hasProject({projectId:e,projectName:t}){let n="/sessions",i=new URLSearchParams;if(e!==void 0&&t!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(e!==void 0)F(e),n+=`/${e}`;else if(t!==void 0)i.append("name",t);else throw new Error("Must provide projectName or projectId");let s=await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}${n}?${i}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await R(a,"has project"),a});try{let a=await s.json();return s.ok?Array.isArray(a)?a.length>0:!0:!1}catch{return!1}}async readProject({projectId:e,projectName:t,includeStats:n}){let i="/sessions",s=new URLSearchParams;if(e!==void 0&&t!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(e!==void 0)F(e),i+=`/${e}`;else if(t!==void 0)s.append("name",t);else throw new Error("Must provide projectName or projectId");n!==void 0&&s.append("include_stats",n.toString());let a=await this._get(i,s),o;if(Array.isArray(a)){if(a.length===0)throw new Error(`Project[id=${e}, name=${t}] not found`);o=a[0]}else o=a;return o}async getProjectUrl({projectId:e,projectName:t}){if(e===void 0&&t===void 0)throw new Error("Must provide either projectName or projectId");let n=await this.readProject({projectId:e,projectName:t}),i=await this._getTenantId();return`${this.getHostUrl()}/o/${i}/projects/p/${n.id}`}async getDatasetUrl({datasetId:e,datasetName:t}){if(e===void 0&&t===void 0)throw new Error("Must provide either datasetName or datasetId");let n=await this.readDataset({datasetId:e,datasetName:t}),i=await this._getTenantId();return`${this.getHostUrl()}/o/${i}/datasets/${n.id}`}async _getTenantId(){if(this._tenantId!==null)return this._tenantId;let e=new URLSearchParams({limit:"1"});for await(let t of this._getPaginated("/sessions",e))return this._tenantId=t[0].tenant_id,t[0].tenant_id;throw new Error("No projects found to resolve tenant.")}async*listProjects({projectIds:e,name:t,nameContains:n,referenceDatasetId:i,referenceDatasetName:s,includeStats:a,datasetVersion:o,referenceFree:u,metadata:c}={}){let l=new URLSearchParams;if(e!==void 0)for(let d of e)l.append("id",d);if(t!==void 0&&l.append("name",t),n!==void 0&&l.append("name_contains",n),i!==void 0)l.append("reference_dataset",i);else if(s!==void 0){let d=await this.readDataset({datasetName:s});l.append("reference_dataset",d.id)}a!==void 0&&l.append("include_stats",a.toString()),o!==void 0&&l.append("dataset_version",o),u!==void 0&&l.append("reference_free",u.toString()),c!==void 0&&l.append("metadata",JSON.stringify(c));for await(let d of this._getPaginated("/sessions",l))yield*d}async deleteProject({projectId:e,projectName:t}){let n;if(e===void 0&&t===void 0)throw new Error("Must provide projectName or projectId");if(e!==void 0&&t!==void 0)throw new Error("Must provide either projectName or projectId, not both");e===void 0?n=(await this.readProject({projectName:t})).id:n=e,F(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 R(i,`delete session ${n} (${t})`,!0),i})}async uploadCsv({csvFile:e,fileName:t,inputKeys:n,outputKeys:i,description:s,dataType:a,name:o}){let u=`${this.apiUrl}/datasets/upload`,c=new FormData;return c.append("file",e,t),n.forEach(f=>{c.append("input_keys",f)}),i.forEach(f=>{c.append("output_keys",f)}),s&&c.append("description",s),a&&c.append("data_type",a),o&&c.append("name",o),await(await this.caller.call(async()=>{let f=await this._fetch(u,{method:"POST",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await R(f,"upload CSV"),f})).json()}async createDataset(e,{description:t,dataType:n,inputsSchema:i,outputsSchema:s,metadata:a}={}){let o={name:e,description:t,extra:a?{metadata:a}:void 0};n&&(o.data_type=n),i&&(o.inputs_schema_definition=i),s&&(o.outputs_schema_definition=s);let u=JSON.stringify(o);return await(await this.caller.call(async()=>{let d=await this._fetch(`${this.apiUrl}/datasets`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await R(d,"create dataset"),d})).json()}async readDataset({datasetId:e,datasetName:t}){let n="/datasets",i=new URLSearchParams({limit:"1"});if(e&&t)throw new Error("Must provide either datasetName or datasetId, not both");if(e)F(e),n+=`/${e}`;else if(t)i.append("name",t);else throw new Error("Must provide datasetName or datasetId");let s=await this._get(n,i),a;if(Array.isArray(s)){if(s.length===0)throw new Error(`Dataset[id=${e}, name=${t}] not found`);a=s[0]}else a=s;return a}async hasDataset({datasetId:e,datasetName:t}){try{return await this.readDataset({datasetId:e,datasetName:t}),!0}catch(n){if(n instanceof Error&&n.message.toLocaleLowerCase().includes("not found"))return!1;throw n}}async diffDatasetVersions({datasetId:e,datasetName:t,fromVersion:n,toVersion:i}){let s=e;if(s===void 0&&t===void 0)throw new Error("Must provide either datasetName or datasetId");if(s!==void 0&&t!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");s===void 0&&(s=(await this.readDataset({datasetName:t})).id);let a=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`,a)}async readDatasetOpenaiFinetuning({datasetId:e,datasetName:t}){let n="/datasets";if(e===void 0)if(t!==void 0)e=(await this.readDataset({datasetName:t})).id;else throw new Error("Must provide either datasetName or datasetId");return(await(await this._getResponse(`${n}/${e}/openai_ft`)).text()).trim().split(`
45
+ `).map(o=>JSON.parse(o))}async*listDatasets({limit:e=100,offset:t=0,datasetIds:n,datasetName:i,datasetNameContains:s,metadata:a}={}){let o="/datasets",u=new URLSearchParams({limit:e.toString(),offset:t.toString()});if(n!==void 0)for(let c of n)u.append("id",c);i!==void 0&&u.append("name",i),s!==void 0&&u.append("name_contains",s),a!==void 0&&u.append("metadata",JSON.stringify(a));for await(let c of this._getPaginated(o,u))yield*c}async updateDataset(e){let{datasetId:t,datasetName:n,...i}=e;if(!t&&!n)throw new Error("Must provide either datasetName or datasetId");let s=t??(await this.readDataset({datasetName:n})).id;F(s);let a=JSON.stringify(i);return await(await this.caller.call(async()=>{let u=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:a});return await R(u,"update dataset"),u})).json()}async updateDatasetTag(e){let{datasetId:t,datasetName:n,asOf:i,tag:s}=e;if(!t&&!n)throw new Error("Must provide either datasetName or datasetId");let a=t??(await this.readDataset({datasetName:n})).id;F(a);let o=JSON.stringify({as_of:typeof i=="string"?i:i.toISOString(),tag:s});await this.caller.call(async()=>{let u=await this._fetch(`${this.apiUrl}/datasets/${a}/tags`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await R(u,"update dataset tags",!0),u})}async deleteDataset({datasetId:e,datasetName:t}){let n="/datasets",i=e;if(e!==void 0&&t!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(t!==void 0&&(i=(await this.readDataset({datasetName:t})).id),i!==void 0)F(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 R(s,`delete ${n}`,!0),s})}async indexDataset({datasetId:e,datasetName:t,tag:n}){let i=e;if(!i&&!t)throw new Error("Must provide either datasetName or datasetId");if(i&&t)throw new Error("Must provide either datasetName or datasetId, not both");i||(i=(await this.readDataset({datasetName:t})).id),F(i);let a=JSON.stringify({tag:n});await(await this.caller.call(async()=>{let u=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:a});return await R(u,"index dataset"),u})).json()}async similarExamples(e,t,n,{filter:i}={}){let s={limit:n,inputs:e};i!==void 0&&(s.filter=i),F(t);let a=JSON.stringify(s);return(await(await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/datasets/${t}/search`,{headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,method:"POST",body:a});return await R(c,"fetch similar examples"),c})).json()).examples}async createExample(e,t,n){if(kd(e)&&(t!==void 0||n!==void 0))throw new Error("Cannot provide outputs or options when using ExampleCreate object");let i=t?n?.datasetId:e.dataset_id,s=t?n?.datasetName:e.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 a=(t?n?.createdAt:e.created_at)||new Date,o;kd(e)?o=e:o={inputs:e,outputs:t,created_at:a?.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 u=await this._uploadExamplesMultipart(i,[o]);return await this.readExample(u.example_ids?.[0]??Ot())}async createExamples(e){if(Array.isArray(e)){if(e.length===0)return[];let w=e,v=w[0].dataset_id,N=w[0].dataset_name;if(v===void 0&&N===void 0)throw new Error("Must provide either datasetName or datasetId");if(v!==void 0&&N!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");v===void 0&&(v=(await this.readDataset({datasetName:N})).id);let I=await this._uploadExamplesMultipart(v,w);return await Promise.all(I.example_ids.map(K=>this.readExample(K)))}let{inputs:t,outputs:n,metadata:i,splits:s,sourceRunIds:a,useSourceRunIOs:o,useSourceRunAttachments:u,attachments:c,exampleIds:l,datasetId:d,datasetName:f}=e;if(t===void 0)throw new Error("Must provide inputs when using legacy parameters");let p=d,h=f;if(p===void 0&&h===void 0)throw new Error("Must provide either datasetName or datasetId");if(p!==void 0&&h!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");p===void 0&&(p=(await this.readDataset({datasetName:h})).id);let m=t.map((w,v)=>({dataset_id:p,inputs:w,outputs:n?.[v],metadata:i?.[v],split:s?.[v],id:l?.[v],attachments:c?.[v],source_run_id:a?.[v],use_source_run_io:o?.[v],use_source_run_attachments:u?.[v]})),g=await this._uploadExamplesMultipart(p,m);return await Promise.all(g.example_ids.map(w=>this.readExample(w)))}async createLLMExample(e,t,n){return this.createExample({input:e},{output:t},n)}async createChatExample(e,t,n){let i=e.map(a=>Sa(a)?Ta(a):a),s=Sa(t)?Ta(t):t;return this.createExample({input:i},{output:s},n)}async readExample(e){F(e);let t=`/examples/${e}`,n=await this._get(t),{attachment_urls:i,...s}=n,a=s;return i&&(a.attachments=Object.entries(i).reduce((o,[u,c])=>(o[u.slice(11)]={presigned_url:c.presigned_url,mime_type:c.mime_type},o),{})),a}async*listExamples({datasetId:e,datasetName:t,exampleIds:n,asOf:i,splits:s,inlineS3Urls:a,metadata:o,limit:u,offset:c,filter:l,includeAttachments:d}={}){let f;if(e!==void 0&&t!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(e!==void 0)f=e;else if(t!==void 0)f=(await this.readDataset({datasetName:t})).id;else throw new Error("Must provide a datasetName or datasetId");let p=new URLSearchParams({dataset:f}),h=i?typeof i=="string"?i:i?.toISOString():void 0;h&&p.append("as_of",h);let m=a??!0;if(p.append("inline_s3_urls",m.toString()),n!==void 0)for(let _ of n)p.append("id",_);if(s!==void 0)for(let _ of s)p.append("splits",_);if(o!==void 0){let _=JSON.stringify(o);p.append("metadata",_)}u!==void 0&&p.append("limit",u.toString()),c!==void 0&&p.append("offset",c.toString()),l!==void 0&&p.append("filter",l),d===!0&&["attachment_urls","outputs","metadata"].forEach(_=>p.append("select",_));let g=0;for await(let _ of this._getPaginated("/examples",p)){for(let w of _){let{attachment_urls:v,...N}=w,I=N;v&&(I.attachments=Object.entries(v).reduce((H,[K,J])=>(H[K.slice(11)]={presigned_url:J.presigned_url,mime_type:J.mime_type||void 0},H),{})),yield I,g++}if(u!==void 0&&g>=u)break}}async deleteExample(e){F(e);let t=`/examples/${e}`;await this.caller.call(async()=>{let n=await this._fetch(this.apiUrl+t,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await R(n,`delete ${t}`,!0),n})}async updateExample(e,t){let n;t?n=e:n=e.id,F(n);let i;t?i={id:n,...t}:i=e;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(e){let t;return e[0].dataset_id===void 0?t=(await this.readExample(e[0].id)).dataset_id:t=e[0].dataset_id,this._updateExamplesMultipart(t,e)}async readDatasetVersion({datasetId:e,datasetName:t,asOf:n,tag:i}){let s;if(e?s=e:s=(await this.readDataset({datasetName:t})).id,F(s),n&&i||!n&&!i)throw new Error("Exactly one of asOf and tag must be specified.");let a=new URLSearchParams;return n!==void 0&&a.append("as_of",typeof n=="string"?n:n.toISOString()),i!==void 0&&a.append("tag",i),await(await this.caller.call(async()=>{let u=await this._fetch(`${this.apiUrl}/datasets/${s}/version?${a.toString()}`,{method:"GET",headers:{...this.headers},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await R(u,"read dataset version"),u})).json()}async listDatasetSplits({datasetId:e,datasetName:t,asOf:n}){let i;if(e===void 0&&t===void 0)throw new Error("Must provide dataset name or ID");if(e!==void 0&&t!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");e===void 0?i=(await this.readDataset({datasetName:t})).id:i=e,F(i);let s=new URLSearchParams,a=n?typeof n=="string"?n:n?.toISOString():void 0;return a&&s.append("as_of",a),await this._get(`/datasets/${i}/splits`,s)}async updateDatasetSplits({datasetId:e,datasetName:t,splitName:n,exampleIds:i,remove:s=!1}){let a;if(e===void 0&&t===void 0)throw new Error("Must provide dataset name or ID");if(e!==void 0&&t!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");e===void 0?a=(await this.readDataset({datasetName:t})).id:a=e,F(a);let o={split_name:n,examples:i.map(c=>(F(c),c)),remove:s},u=JSON.stringify(o);await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/datasets/${a}/splits`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await R(c,"update dataset splits",!0),c})}async evaluateRun(e,t,{sourceInfo:n,loadChildRuns:i,referenceExample:s}={loadChildRuns:!1}){cn("This method is deprecated and will be removed in future LangSmith versions, use `evaluate` from `langsmith/evaluation` instead.");let a;if(typeof e=="string")a=await this.readRun(e,{loadChildRuns:i});else if(typeof e=="object"&&"id"in e)a=e;else throw new Error(`Invalid run type: ${typeof e}`);a.reference_example_id!==null&&a.reference_example_id!==void 0&&(s=await this.readExample(a.reference_example_id));let o=await t.evaluateRun(a,s),[u,c]=await this._logEvaluationFeedback(o,a,n);return c[0]}async createFeedback(e,t,{score:n,value:i,correction:s,comment:a,sourceInfo:o,feedbackSourceType:u="api",sourceRunId:c,feedbackId:l,feedbackConfig:d,projectId:f,comparativeExperimentId:p}){if(!e&&!f)throw new Error("One of runId or projectId must be provided");if(e&&f)throw new Error("Only one of runId or projectId can be provided");let h={type:u??"api",metadata:o??{}};c!==void 0&&h?.metadata!==void 0&&!h.metadata.__run&&(h.metadata.__run={run_id:c}),h?.metadata!==void 0&&h.metadata.__run?.run_id!==void 0&&F(h.metadata.__run.run_id);let m={id:l??Ot(),run_id:e,key:t,score:Id(n),value:i,correction:s,comment:a,feedback_source:h,comparative_experiment_id:p,feedbackConfig:d,session_id:f},g=JSON.stringify(m),_=`${this.apiUrl}/feedback`;return await this.caller.call(async()=>{let w=await this._fetch(_,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:g});return await R(w,"create feedback",!0),w}),m}async updateFeedback(e,{score:t,value:n,correction:i,comment:s}){let a={};t!=null&&(a.score=Id(t)),n!=null&&(a.value=n),i!=null&&(a.correction=i),s!=null&&(a.comment=s),F(e);let o=JSON.stringify(a);await this.caller.call(async()=>{let u=await this._fetch(`${this.apiUrl}/feedback/${e}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await R(u,"update feedback",!0),u})}async readFeedback(e){F(e);let t=`/feedback/${e}`;return await this._get(t)}async deleteFeedback(e){F(e);let t=`/feedback/${e}`;await this.caller.call(async()=>{let n=await this._fetch(this.apiUrl+t,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await R(n,`delete ${t}`,!0),n})}async*listFeedback({runIds:e,feedbackKeys:t,feedbackSourceTypes:n}={}){let i=new URLSearchParams;if(e)for(let s of e)F(s),i.append("run",s);if(t)for(let s of t)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(e,t,{expiration:n,feedbackConfig:i}={}){let s={run_id:e,feedback_key:t,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 a=JSON.stringify(s);return await(await this.caller.call(async()=>{let u=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:a});return await R(u,"create presigned feedback token"),u})).json()}async createComparativeExperiment({name:e,experimentIds:t,referenceDatasetId:n,createdAt:i,description:s,metadata:a,id:o}){if(t.length===0)throw new Error("At least one experiment is required");if(n||(n=(await this.readProject({projectId:t[0]})).reference_dataset_id),!n==null)throw new Error("A reference dataset is required");let u={id:o,name:e,experiment_ids:t,reference_dataset_id:n,description:s,created_at:(i??new Date)?.toISOString(),extra:{}};a&&(u.extra.metadata=a);let c=JSON.stringify(u);return(await this.caller.call(async()=>{let d=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:c});return await R(d,"create comparative experiment"),d})).json()}async*listPresignedFeedbackTokens(e){F(e);let t=new URLSearchParams({run_id:e});for await(let n of this._getPaginated("/feedback/tokens",t))yield*n}_selectEvalResults(e){let t;return"results"in e?t=e.results:Array.isArray(e)?t=e:t=[e],t}async _logEvaluationFeedback(e,t,n){let i=this._selectEvalResults(e),s=[];for(let a of i){let o=n||{};a.evaluatorInfo&&(o={...a.evaluatorInfo,...o});let u=null;a.targetRunId?u=a.targetRunId:t&&(u=t.id),s.push(await this.createFeedback(u,a.key,{score:a.score,value:a.value,comment:a.comment,correction:a.correction,sourceInfo:o,sourceRunId:a.sourceRunId,feedbackConfig:a.feedbackConfig,feedbackSourceType:"model"}))}return[i,s]}async logEvaluationFeedback(e,t,n){let[i]=await this._logEvaluationFeedback(e,t,n);return i}async*listAnnotationQueues(e={}){let{queueIds:t,name:n,nameContains:i,limit:s}=e,a=new URLSearchParams;t&&t.forEach((u,c)=>{F(u,`queueIds[${c}]`),a.append("ids",u)}),n&&a.append("name",n),i&&a.append("name_contains",i),a.append("limit",(s!==void 0?Math.min(s,100):100).toString());let o=0;for await(let u of this._getPaginated("/annotation-queues",a))if(yield*u,o++,s!==void 0&&o>=s)break}async createAnnotationQueue(e){let{name:t,description:n,queueId:i,rubricInstructions:s}=e,a={name:t,description:n,id:i||Ot(),rubric_instructions:s},o=JSON.stringify(Object.fromEntries(Object.entries(a).filter(([c,l])=>l!==void 0)));return(await this.caller.call(async()=>{let c=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:o});return await R(c,"create annotation queue"),c})).json()}async readAnnotationQueue(e){return(await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/annotation-queues/${F(e,"queueId")}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await R(n,"read annotation queue"),n})).json()}async updateAnnotationQueue(e,t){let{name:n,description:i,rubricInstructions:s}=t,a=JSON.stringify({name:n,description:i,rubric_instructions:s});await this.caller.call(async()=>{let o=await this._fetch(`${this.apiUrl}/annotation-queues/${F(e,"queueId")}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await R(o,"update annotation queue",!0),o})}async deleteAnnotationQueue(e){await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/annotation-queues/${F(e,"queueId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await R(t,"delete annotation queue",!0),t})}async addRunsToAnnotationQueue(e,t){let n=JSON.stringify(t.map((i,s)=>F(i,`runIds[${s}]`).toString()));await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}/annotation-queues/${F(e,"queueId")}/runs`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await R(i,"add runs to annotation queue",!0),i})}async getRunFromAnnotationQueue(e,t){let n=`/annotation-queues/${F(e,"queueId")}/run`;return(await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}${n}/${t}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await R(s,"get run from annotation queue"),s})).json()}async deleteRunFromAnnotationQueue(e,t){await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/annotation-queues/${F(e,"queueId")}/runs/${F(t,"queueRunId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await R(n,"delete run from annotation queue",!0),n})}async getSizeFromAnnotationQueue(e){return(await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/annotation-queues/${F(e,"queueId")}/size`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await R(n,"get size from annotation queue"),n})).json()}async _currentTenantIsOwner(e){let t=await this._getSettings();return e=="-"||t.tenant_handle===e}async _ownerConflictError(e,t){let n=await this._getSettings();return new Error(`Cannot ${e} for another tenant.
46
+
47
+ Current tenant: ${n.tenant_handle}
48
+
49
+ Requested tenant: ${t}`)}async _getLatestCommitHash(e){let n=await(await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}/commits/${e}/?limit=1&offset=0`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await R(i,"get latest commit hash"),i})).json();if(n.commits.length!==0)return n.commits[0].commit_hash}async _likeOrUnlikePrompt(e,t){let[n,i,s]=$t(e),a=JSON.stringify({like:t});return(await this.caller.call(async()=>{let u=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:a});return await R(u,`${t?"like":"unlike"} prompt`),u})).json()}async _getPromptUrl(e){let[t,n,i]=$t(e);if(await this._currentTenantIsOwner(t)){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/${t}/${n}/${i.substring(0,8)}`:`${this.getHostUrl()}/hub/${t}/${n}`}async promptExists(e){return!!await this.getPrompt(e)}async likePrompt(e){return this._likeOrUnlikePrompt(e,!0)}async unlikePrompt(e){return this._likeOrUnlikePrompt(e,!1)}async*listCommits(e){for await(let t of this._getPaginated(`/commits/${e}/`,new URLSearchParams,n=>n.commits))yield*t}async*listPrompts(e){let t=new URLSearchParams;t.append("sort_field",e?.sortField??"updated_at"),t.append("sort_direction","desc"),t.append("is_archived",(!!e?.isArchived).toString()),e?.isPublic!==void 0&&t.append("is_public",e.isPublic.toString()),e?.query&&t.append("query",e.query);for await(let n of this._getPaginated("/repos",t,i=>i.repos))yield*n}async getPrompt(e){let[t,n,i]=$t(e),a=await(await this.caller.call(async()=>{let o=await this._fetch(`${this.apiUrl}/repos/${t}/${n}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return o?.status===404?null:(await R(o,"get prompt"),o)}))?.json();return a?.repo?a.repo:null}async createPrompt(e,t){let n=await this._getSettings();if(t?.isPublic&&!n.tenant_handle)throw new Error(`Cannot create a public prompt without first
50
+
51
+ creating a LangChain Hub handle.
52
+ You can add a handle by creating a public prompt at:
53
+
54
+ https://smith.langchain.com/prompts`);let[i,s,a]=$t(e);if(!await this._currentTenantIsOwner(i))throw await this._ownerConflictError("create a prompt",i);let o={repo_handle:s,...t?.description&&{description:t.description},...t?.readme&&{readme:t.readme},...t?.tags&&{tags:t.tags},is_public:!!t?.isPublic},u=JSON.stringify(o),c=await this.caller.call(async()=>{let d=await this._fetch(`${this.apiUrl}/repos/`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await R(d,"create prompt"),d}),{repo:l}=await c.json();return l}async createCommit(e,t,n){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");let[i,s,a]=$t(e),o=n?.parentCommitHash==="latest"||!n?.parentCommitHash?await this._getLatestCommitHash(`${i}/${s}`):n?.parentCommitHash,u={manifest:JSON.parse(JSON.stringify(t)),parent_commit:o},c=JSON.stringify(u),d=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:c});return await R(f,"create commit"),f})).json();return this._getPromptUrl(`${i}/${s}${d.commit_hash?`:${d.commit_hash}`:""}`)}async updateExamplesMultipart(e,t=[]){return this._updateExamplesMultipart(e,t)}async _updateExamplesMultipart(e,t=[]){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 a of t){let o=a.id,u={...a.metadata&&{metadata:a.metadata},...a.split&&{split:a.split}},c=Ce(u,`Serializing body for example with id: ${o}`),l=new Blob([c],{type:"application/json"});if(n.append(o,l),a.inputs){let d=Ce(a.inputs,`Serializing inputs for example with id: ${o}`),f=new Blob([d],{type:"application/json"});n.append(`${o}.inputs`,f)}if(a.outputs){let d=Ce(a.outputs,`Serializing outputs whle updating example with id: ${o}`),f=new Blob([d],{type:"application/json"});n.append(`${o}.outputs`,f)}if(a.attachments)for(let[d,f]of Object.entries(a.attachments)){let p,h;Array.isArray(f)?[p,h]=f:(p=f.mimeType,h=f.data);let m=new Blob([h],{type:`${p}; length=${h.byteLength}`});n.append(`${o}.attachment.${d}`,m)}if(a.attachments_operations){let d=Ce(a.attachments_operations,`Serializing attachments while updating example with id: ${o}`),f=new Blob([d],{type:"application/json"});n.append(`${o}.attachments_operations`,f)}}let i=e??t[0]?.dataset_id;return(await this.caller.call(async()=>{let a=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 R(a,"update examples"),a})).json()}async uploadExamplesMultipart(e,t=[]){return this._uploadExamplesMultipart(e,t)}async _uploadExamplesMultipart(e,t=[]){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 t){let a=(s.id??Ot()).toString(),o={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}},u=Ce(o,`Serializing body for uploaded example with id: ${a}`),c=new Blob([u],{type:"application/json"});if(n.append(a,c),s.inputs){let l=Ce(s.inputs,`Serializing inputs for uploaded example with id: ${a}`),d=new Blob([l],{type:"application/json"});n.append(`${a}.inputs`,d)}if(s.outputs){let l=Ce(s.outputs,`Serializing outputs for uploaded example with id: ${a}`),d=new Blob([l],{type:"application/json"});n.append(`${a}.outputs`,d)}if(s.attachments)for(let[l,d]of Object.entries(s.attachments)){let f,p;Array.isArray(d)?[f,p]=d:(f=d.mimeType,p=d.data);let h=new Blob([p],{type:`${f}; length=${p.byteLength}`});n.append(`${a}.attachment.${l}`,h)}}return(await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${e}/examples`)}`,{method:"POST",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await R(s,"upload examples"),s})).json()}async updatePrompt(e,t){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");let[n,i]=$t(e);if(!await this._currentTenantIsOwner(n))throw await this._ownerConflictError("update a prompt",n);let s={};if(t?.description!==void 0&&(s.description=t.description),t?.readme!==void 0&&(s.readme=t.readme),t?.tags!==void 0&&(s.tags=t.tags),t?.isPublic!==void 0&&(s.is_public=t.isPublic),t?.isArchived!==void 0&&(s.is_archived=t.isArchived),Object.keys(s).length===0)throw new Error("No valid update options provided");let a=JSON.stringify(s);return(await this.caller.call(async()=>{let u=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:a});return await R(u,"update prompt"),u})).json()}async deletePrompt(e){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");let[t,n,i]=$t(e);if(!await this._currentTenantIsOwner(t))throw await this._ownerConflictError("delete a prompt",t);return(await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}/repos/${t}/${n}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await R(a,"delete prompt"),a})).json()}async pullPromptCommit(e,t){let[n,i,s]=$t(e),o=await(await this.caller.call(async()=>{let u=await this._fetch(`${this.apiUrl}/commits/${n}/${i}/${s}${t?.includeModel?"?include_model=true":""}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await R(u,"pull prompt commit"),u})).json();return{owner:n,repo:i,commit_hash:o.commit_hash,manifest:o.manifest,examples:o.examples}}async _pullPrompt(e,t){let n=await this.pullPromptCommit(e,{includeModel:t?.includeModel});return JSON.stringify(n.manifest)}async pushPrompt(e,t){return await this.promptExists(e)?t&&Object.keys(t).some(i=>i!=="object")&&await this.updatePrompt(e,{description:t?.description,readme:t?.readme,tags:t?.tags,isPublic:t?.isPublic}):await this.createPrompt(e,{description:t?.description,readme:t?.readme,tags:t?.tags,isPublic:t?.isPublic}),t?.object?await this.createCommit(e,t?.object,{parentCommitHash:t?.parentCommitHash}):await this._getPromptUrl(e)}async clonePublicDataset(e,t={}){let{sourceApiUrl:n=this.apiUrl,datasetName:i}=t,[s,a]=this.parseTokenOrUrl(e,n),o=new r({apiUrl:s,apiKey:"placeholder"}),u=await o.readSharedDataset(a),c=i||u.name;try{if(await this.hasDataset({datasetId:c})){console.log(`Dataset ${c} already exists in your tenant. Skipping.`);return}}catch{}let l=await o.listSharedExamples(a),d=await this.createDataset(c,{description:u.description,dataType:u.data_type||"kv",inputsSchema:u.inputs_schema_definition??void 0,outputsSchema:u.outputs_schema_definition??void 0});try{await this.createExamples({inputs:l.map(f=>f.inputs),outputs:l.flatMap(f=>f.outputs?[f.outputs]:[]),datasetId:d.id})}catch(f){throw console.error(`An error occurred while creating dataset ${c}. You should delete it manually.`),f}}parseTokenOrUrl(e,t,n=2,i="dataset"){try{return F(e),[t,e]}catch{}try{let a=new URL(e).pathname.split("/").filter(o=>o!=="");if(a.length>=n){let o=a[a.length-n];return[t,o]}else throw new Error(`Invalid public ${i} URL: ${e}`)}catch{throw new Error(`Invalid public ${i} URL or token: ${e}`)}}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 Promise.all([...this.autoBatchQueue.items.map(({itemPromise:e})=>e),this.batchIngestCaller.queue.onIdle()]),this.langSmithToOTELTranslator!==void 0&&await xc()?.DEFAULT_LANGSMITH_SPAN_PROCESSOR?.forceFlush()}};function kd(r){return"dataset_id"in r||"dataset_name"in r}var Pd=r=>r!==void 0?r:!!["TRACING_V2","TRACING"].find(t=>ne(t)==="true");var Bi=Symbol.for("lc:context_variables");function sb(r){return r.replace(/[-:.]/g,"")}function Ka(r,e,t=1){let n=t.toFixed(0).slice(0,3).padStart(3,"0"),i=`${new Date(r).toISOString().slice(0,-1)}${n}Z`;return{dottedOrder:sb(i)+e,microsecondPrecisionDatestring:i}}var Gi=class r{constructor(e,t,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=e,this.tags=t,this.project_name=n,this.replicas=i}static fromHeader(e){let t=e.split(","),n={},i=[],s,a;for(let o of t){let[u,c]=o.split("="),l=decodeURIComponent(c);u==="langsmith-metadata"?n=JSON.parse(l):u==="langsmith-tags"?i=l.split(","):u==="langsmith-project"?s=l:u==="langsmith-replicas"&&(a=JSON.parse(l))}return new r(n,i,s,a)}toHeader(){let e=[];return this.metadata&&Object.keys(this.metadata).length>0&&e.push(`langsmith-metadata=${encodeURIComponent(JSON.stringify(this.metadata))}`),this.tags&&this.tags.length>0&&e.push(`langsmith-tags=${encodeURIComponent(this.tags.join(","))}`),this.project_name&&e.push(`langsmith-project=${encodeURIComponent(this.project_name)}`),e.join(",")}},rt=class r{constructor(e){if(Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"run_type",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"project_name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parent_run",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parent_run_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_runs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"end_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"extra",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"error",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"serialized",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"inputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"outputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reference_example_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"events",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"trace_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dotted_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingEnabled",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"attachments",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"replicas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_serialized_start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Nd(e)){Object.assign(this,{...e});return}let t=r.getDefaultConfig(),{metadata:n,...i}=e,s=i.client??r.getSharedClient(),a={...n,...i?.extra?.metadata};if(i.extra={...i.extra,metadata:a},Object.assign(this,{...t,...i,client:s}),this.trace_id||(this.parent_run?this.trace_id=this.parent_run.trace_id??this.id:this.trace_id=this.id),this.replicas=lb(this.replicas),this.execution_order??=1,this.child_execution_order??=1,!this.dotted_order){let{dottedOrder:o,microsecondPrecisionDatestring:u}=Ka(this.start_time,this.id,this.execution_order);this.parent_run?this.dotted_order=this.parent_run.dotted_order+"."+o:this.dotted_order=o,this._serialized_start_time=u}}set metadata(e){this.extra={...this.extra,metadata:{...this.extra?.metadata,...e}}}get metadata(){return this.extra?.metadata}static getDefaultConfig(){return{id:Ot(),run_type:"chain",project_name:an(),child_runs:[],api_url:Me("LANGCHAIN_ENDPOINT")??"http://localhost:1984",api_key:Me("LANGCHAIN_API_KEY"),caller_options:{},start_time:Date.now(),serialized:{},inputs:{},extra:{}}}static getSharedClient(){return r.sharedClient||(r.sharedClient=new fr),r.sharedClient}createChild(e){let t=this.child_execution_order+1,n=new r({...e,parent_run:this,project_name:this.project_name,replicas:this.replicas,client:this.client,tracingEnabled:this.tracingEnabled,execution_order:t,child_execution_order:t});Bi in this&&(n[Bi]=this[Bi]);let i=Symbol.for("lc:child_config"),s=e.extra?.[i]??this.extra[i];if(ob(s)){let u={...s},c=ab(u.callbacks)?u.callbacks.copy?.():void 0;c&&(Object.assign(c,{_parentRunId:n.id}),c.handlers?.find(Cd)?.updateFromRunTree?.(n),u.callbacks=c),n.extra[i]=u}let a=new Set,o=this;for(;o!=null&&!a.has(o.id);)a.add(o.id),o.child_execution_order=Math.max(o.child_execution_order,t),o=o.parent_run;return this.child_runs.push(n),n}async end(e,t,n=Date.now(),i){this.outputs=this.outputs??e,this.error=this.error??t,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(e,t,n=!0){let i=e.extra??{};if(i?.runtime?.library===void 0&&(i.runtime||(i.runtime={}),t))for(let[o,u]of Object.entries(t))i.runtime[o]||(i.runtime[o]=u);let s,a;return n?(a=e.parent_run?.id??e.parent_run_id,s=[]):(s=e.child_runs.map(o=>this._convertToCreate(o,t,n)),a=void 0),{id:e.id,name:e.name,start_time:e._serialized_start_time??e.start_time,end_time:e.end_time,run_type:e.run_type,reference_example_id:e.reference_example_id,extra:i,serialized:e.serialized,error:e.error,inputs:e.inputs,outputs:e.outputs,session_name:e.project_name,child_runs:s,parent_run_id:a,trace_id:e.trace_id,dotted_order:e.dotted_order,tags:e.tags,attachments:e.attachments,events:e.events}}_remapForProject(e,t,n=!0){let i=this._convertToCreate(this,t,n);if(e===this.project_name)return i;let s=d=>mi(`${d}:${e}`,mi.DNS),a=s(i.id),o=i.trace_id?s(i.trace_id):void 0,u=i.parent_run_id?s(i.parent_run_id):void 0,c;if(i.dotted_order){let d=ub(i.dotted_order),f=[];for(let h=0;h<d.length-1;h++){let[m,g]=d[h],_=s(g);f.push(m.toISOString().replace(/[-:]/g,"").replace(".","")+_)}let[p]=d[d.length-1];f.push(p.toISOString().replace(/[-:]/g,"").replace(".","")+a),c=f.join(".")}else c=void 0;return{...i,id:a,trace_id:o,parent_run_id:u,dotted_order:c,session_name:e}}async postRun(e=!0){try{let t=_i();if(this.replicas&&this.replicas.length>0)for(let{projectName:n,apiKey:i,apiUrl:s,workspaceId:a}of this.replicas){let o=this._remapForProject(n??this.project_name,t,!0);await this.client.createRun(o,{apiKey:i,apiUrl:s,workspaceId:a})}else{let n=this._convertToCreate(this,t,e);await this.client.createRun(n)}if(!e){cn("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)}}catch(t){console.error(`Error in postRun for run ${this.id}:`,t)}}async patchRun(e){if(this.replicas&&this.replicas.length>0)for(let{projectName:t,apiKey:n,apiUrl:i,workspaceId:s,updates:a}of this.replicas){let o=this._remapForProject(t??this.project_name),u={id:o.id,outputs:o.outputs,error:o.error,parent_run_id:o.parent_run_id,session_name:o.session_name,reference_example_id:o.reference_example_id,end_time:o.end_time,dotted_order:o.dotted_order,trace_id:o.trace_id,events:o.events,tags:o.tags,extra:o.extra,attachments:this.attachments,...a};e?.excludeInputs||(u.inputs=o.inputs),await this.client.updateRun(o.id,u,{apiKey:n,apiUrl:i,workspaceId:s})}else try{let t={end_time:this.end_time,error:this.error,outputs:this.outputs,parent_run_id:this.parent_run?.id??this.parent_run_id,reference_example_id:this.reference_example_id,extra:this.extra,events:this.events,dotted_order:this.dotted_order,trace_id:this.trace_id,tags:this.tags,attachments:this.attachments,session_name:this.project_name};e?.excludeInputs||(t.inputs=this.inputs),await this.client.updateRun(this.id,t)}catch(t){console.error(`Error in patchRun for run ${this.id}`,t)}}toJSON(){return this._convertToCreate(this,void 0,!1)}addEvent(e){this.events||(this.events=[]),typeof e=="string"?this.events.push({name:"event",time:new Date().toISOString(),message:e}):this.events.push({...e,time:e.time??new Date().toISOString()})}static fromRunnableConfig(e,t){let n=e?.callbacks,i,s,a,o=Pd();if(n){let c=n?.getParentRunId?.()??"",l=n?.handlers?.find(d=>d?.name=="langchain_tracer");i=l?.getRun?.(c),s=l?.projectName,a=l?.client,o=o||!!l}return i?new r({name:i.name,id:i.id,trace_id:i.trace_id,dotted_order:i.dotted_order,client:a,tracingEnabled:o,project_name:s,tags:[...new Set((i?.tags??[]).concat(e?.tags??[]))],extra:{metadata:{...i?.extra?.metadata,...e?.metadata}}}).createChild(t):new r({...t,client:a,tracingEnabled:o,project_name:s})}static fromDottedOrder(e){return this.fromHeaders({"langsmith-trace":e})}static fromHeaders(e,t){let n="get"in e&&typeof e.get=="function"?{"langsmith-trace":e.get("langsmith-trace"),baggage:e.get("baggage")}:e,i=n["langsmith-trace"];if(!i||typeof i!="string")return;let s=i.trim(),a=s.split(".").map(c=>{let[l,d]=c.split("Z");return{strTime:l,time:Date.parse(l+"Z"),uuid:d}}),o=a[0].uuid,u={...t,name:t?.name??"parent",run_type:t?.run_type??"chain",start_time:t?.start_time??Date.now(),id:a.at(-1)?.uuid,trace_id:o,dotted_order:s};if(n.baggage&&typeof n.baggage=="string"){let c=Gi.fromHeader(n.baggage);u.metadata=c.metadata,u.tags=c.tags,u.project_name=c.project_name,u.replicas=c.replicas}return new r(u)}toHeaders(e){let t={"langsmith-trace":this.dotted_order,baggage:new Gi(this.extra?.metadata,this.tags,this.project_name,this.replicas).toHeader()};if(e)for(let[n,i]of Object.entries(t))e.set(n,i);return t}};Object.defineProperty(rt,"sharedClient",{enumerable:!0,configurable:!0,writable:!0,value:null});function Nd(r){return r!=null&&typeof r.createChild=="function"&&typeof r.postRun=="function"}function Cd(r){return typeof r=="object"&&r!=null&&typeof r.name=="string"&&r.name==="langchain_tracer"}function Rd(r){return Array.isArray(r)&&r.some(e=>Cd(e))}function ab(r){return typeof r=="object"&&r!=null&&Array.isArray(r.handlers)}function ob(r){return r!=null&&typeof r.callbacks=="object"&&(Rd(r.callbacks?.handlers)||Rd(r.callbacks))}function ub(r){return r.split(".").map(t=>{let n=t.slice(0,-36),i=t.slice(-36),s=parseInt(n.slice(0,4)),a=parseInt(n.slice(4,6))-1,o=parseInt(n.slice(6,8)),u=parseInt(n.slice(9,11)),c=parseInt(n.slice(11,13)),l=parseInt(n.slice(13,15)),d=parseInt(n.slice(15,21));return[new Date(s,a,o,u,c,l,d/1e3),i]})}function cb(){let r=Me("LANGSMITH_RUNS_ENDPOINTS");if(!r)return[];try{let e=JSON.parse(r);if(Array.isArray(e)){let t=[];for(let n of e){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}t.push({apiUrl:n.api_url.replace(/\/$/,""),apiKey:n.api_key})}return t}else if(typeof e=="object"&&e!==null){db(e);let t=[];for(let[n,i]of Object.entries(e)){let s=n.replace(/\/$/,"");if(typeof i=="string")t.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 t}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 e}`),[]}catch(e){if(Sd(e))throw e;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 lb(r){return r?r.map(e=>Array.isArray(e)?{projectName:e[0],updates:e[1]}:e):cb()}function db(r){if(Object.keys(r).length>0&&ne("ENDPOINT"))throw new Di}var mb={};le(mb,{BaseCallbackHandler:()=>Lt,callbackHandlerPrefersStreaming:()=>hb,isBaseCallbackHandler:()=>Xa});var pb={};le(pb,{getEnv:()=>Dd,getEnvironmentVariable:()=>nt,getRuntimeEnvironment:()=>fb,getRuntimeEnvironmentSync:()=>Vi,isBrowser:()=>jd,isDeno:()=>qi,isJsDom:()=>zd,isNode:()=>Md,isWebWorker:()=>Ld});var jd=()=>typeof window<"u"&&typeof window.document<"u",Ld=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",zd=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),qi=()=>typeof Deno<"u",Md=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!qi(),Dd=()=>{let r;return jd()?r="browser":Md()?r="node":Ld()?r="webworker":zd()?r="jsdom":qi()?r="deno":r="other",r},Wa;async function fb(){return Vi()}function Vi(){return Wa===void 0&&(Wa={library:"langchain-js",runtime:Dd()}),Wa}function nt(r){try{return typeof process<"u"?process.env?.[r]:qi()?Deno?.env.get(r):void 0}catch{return}}var Ya=class{};function hb(r){return"lc_prefer_streaming"in r&&r.lc_prefer_streaming}var Lt=class r extends Ya{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,Mn(this.constructor)]}constructor(e){super(),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"lc_kwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ignoreLLM",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"ignoreChain",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"ignoreAgent",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"ignoreRetriever",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"ignoreCustomEvent",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"raiseError",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"awaitHandlers",{enumerable:!0,configurable:!0,writable:!0,value:nt("LANGCHAIN_CALLBACKS_BACKGROUND")==="false"}),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 Ze.prototype.toJSON.call(this)}toJSONNotImplemented(){return Ze.prototype.toJSONNotImplemented.call(this)}static fromMethods(e){class t extends r{constructor(){super(),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:Ne()}),Object.assign(this,e)}}return new t}},Xa=r=>{let e=r;return e!==void 0&&typeof e.copy=="function"&&typeof e.name=="string"&&typeof e.awaitHandlers=="boolean"};var gb=r=>{if(r)return r.events=r.events??[],r.child_runs=r.child_runs??[],r};function eo(r,e){if(r)return new rt({...r,start_time:r._serialized_start_time??r.start_time,parent_run:eo(e),child_runs:r.child_runs.map(t=>eo(t)).filter(t=>t!==void 0),extra:{...r.extra,runtime:Vi()},tracingEnabled:!1})}function Qa(r,e){return r&&!Array.isArray(r)&&typeof r=="object"?r:{[e]:r}}function hr(r){return typeof r._addRunToRunMap=="function"}var De=class extends Lt{constructor(e){super(...arguments),Object.defineProperty(this,"runMap",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"runTreeMap",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"usesRunTreeMap",{enumerable:!0,configurable:!0,writable:!0,value:!1})}copy(){return this}getRunById(e){if(e!==void 0)return this.usesRunTreeMap?gb(this.runTreeMap.get(e)):this.runMap.get(e)}stringifyError(e){return e instanceof Error?e.message+(e?.stack?`
55
+
56
+ ${e.stack}`:""):typeof e=="string"?e:`${e}`}_addChildRun(e,t){e.child_runs.push(t)}_addRunToRunMap(e){let{dottedOrder:t,microsecondPrecisionDatestring:n}=Ka(new Date(e.start_time).getTime(),e.id,e.execution_order),i={...e},s=this.getRunById(i.parent_run_id);if(i.parent_run_id!==void 0?s&&(this._addChildRun(s,i),s.child_execution_order=Math.max(s.child_execution_order,i.child_execution_order),i.trace_id=s.trace_id,s.dotted_order!==void 0&&(i.dotted_order=[s.dotted_order,t].join("."),i._serialized_start_time=n)):(i.trace_id=i.id,i.dotted_order=t,i._serialized_start_time=n),this.usesRunTreeMap){let a=eo(i,s);a!==void 0&&this.runTreeMap.set(i.id,a)}else this.runMap.set(i.id,i);return i}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,n,i,s,a,o,u){let c=this._getExecutionOrder(i),l=Date.now(),d=o?{...s,metadata:o}:s,f={id:n,name:u??e.id[e.id.length-1],parent_run_id:i,start_time:l,serialized:e,events:[{name:"start",time:new Date(l).toISOString()}],inputs:{prompts:t},execution_order:c,child_runs:[],child_execution_order:c,run_type:"llm",extra:d??{},tags:a||[]};return this._addRunToRunMap(f)}async handleLLMStart(e,t,n,i,s,a,o,u){let c=this.getRunById(n)??this._createRunForLLMStart(e,t,n,i,s,a,o,u);return await this.onRunCreate?.(c),await this.onLLMStart?.(c),c}_createRunForChatModelStart(e,t,n,i,s,a,o,u){let c=this._getExecutionOrder(i),l=Date.now(),d=o?{...s,metadata:o}:s,f={id:n,name:u??e.id[e.id.length-1],parent_run_id:i,start_time:l,serialized:e,events:[{name:"start",time:new Date(l).toISOString()}],inputs:{messages:t},execution_order:c,child_runs:[],child_execution_order:c,run_type:"llm",extra:d??{},tags:a||[]};return this._addRunToRunMap(f)}async handleChatModelStart(e,t,n,i,s,a,o,u){let c=this.getRunById(n)??this._createRunForChatModelStart(e,t,n,i,s,a,o,u);return await this.onRunCreate?.(c),await this.onLLMStart?.(c),c}async handleLLMEnd(e,t,n,i,s){let a=this.getRunById(t);if(!a||a?.run_type!=="llm")throw new Error("No LLM run to end.");return a.end_time=Date.now(),a.outputs=e,a.events.push({name:"end",time:new Date(a.end_time).toISOString()}),a.extra={...a.extra,...s},await this.onLLMEnd?.(a),await this._endTrace(a),a}async handleLLMError(e,t,n,i,s){let a=this.getRunById(t);if(!a||a?.run_type!=="llm")throw new Error("No LLM run to end.");return a.end_time=Date.now(),a.error=this.stringifyError(e),a.events.push({name:"error",time:new Date(a.end_time).toISOString()}),a.extra={...a.extra,...s},await this.onLLMError?.(a),await this._endTrace(a),a}_createRunForChainStart(e,t,n,i,s,a,o,u){let c=this._getExecutionOrder(i),l=Date.now(),d={id:n,name:u??e.id[e.id.length-1],parent_run_id:i,start_time:l,serialized:e,events:[{name:"start",time:new Date(l).toISOString()}],inputs:t,execution_order:c,child_execution_order:c,run_type:o??"chain",child_runs:[],extra:a?{metadata:a}:{},tags:s||[]};return this._addRunToRunMap(d)}async handleChainStart(e,t,n,i,s,a,o,u){let c=this.getRunById(n)??this._createRunForChainStart(e,t,n,i,s,a,o,u);return await this.onRunCreate?.(c),await this.onChainStart?.(c),c}async handleChainEnd(e,t,n,i,s){let a=this.getRunById(t);if(!a)throw new Error("No chain run to end.");return a.end_time=Date.now(),a.outputs=Qa(e,"output"),a.events.push({name:"end",time:new Date(a.end_time).toISOString()}),s?.inputs!==void 0&&(a.inputs=Qa(s.inputs,"input")),await this.onChainEnd?.(a),await this._endTrace(a),a}async handleChainError(e,t,n,i,s){let a=this.getRunById(t);if(!a)throw new Error("No chain run to end.");return a.end_time=Date.now(),a.error=this.stringifyError(e),a.events.push({name:"error",time:new Date(a.end_time).toISOString()}),s?.inputs!==void 0&&(a.inputs=Qa(s.inputs,"input")),await this.onChainError?.(a),await this._endTrace(a),a}_createRunForToolStart(e,t,n,i,s,a,o){let u=this._getExecutionOrder(i),c=Date.now(),l={id:n,name:o??e.id[e.id.length-1],parent_run_id:i,start_time:c,serialized:e,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{input:t},execution_order:u,child_execution_order:u,run_type:"tool",child_runs:[],extra:a?{metadata:a}:{},tags:s||[]};return this._addRunToRunMap(l)}async handleToolStart(e,t,n,i,s,a,o){let u=this.getRunById(n)??this._createRunForToolStart(e,t,n,i,s,a,o);return await this.onRunCreate?.(u),await this.onToolStart?.(u),u}async handleToolEnd(e,t){let n=this.getRunById(t);if(!n||n?.run_type!=="tool")throw new Error("No tool run to end");return n.end_time=Date.now(),n.outputs={output:e},n.events.push({name:"end",time:new Date(n.end_time).toISOString()}),await this.onToolEnd?.(n),await this._endTrace(n),n}async handleToolError(e,t){let n=this.getRunById(t);if(!n||n?.run_type!=="tool")throw new Error("No tool run to end");return n.end_time=Date.now(),n.error=this.stringifyError(e),n.events.push({name:"error",time:new Date(n.end_time).toISOString()}),await this.onToolError?.(n),await this._endTrace(n),n}async handleAgentAction(e,t){let n=this.getRunById(t);if(!n||n?.run_type!=="chain")return;let i=n;i.actions=i.actions||[],i.actions.push(e),i.events.push({name:"agent_action",time:new Date().toISOString(),kwargs:{action:e}}),await this.onAgentAction?.(n)}async handleAgentEnd(e,t){let n=this.getRunById(t);!n||n?.run_type!=="chain"||(n.events.push({name:"agent_end",time:new Date().toISOString(),kwargs:{action:e}}),await this.onAgentEnd?.(n))}_createRunForRetrieverStart(e,t,n,i,s,a,o){let u=this._getExecutionOrder(i),c=Date.now(),l={id:n,name:o??e.id[e.id.length-1],parent_run_id:i,start_time:c,serialized:e,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{query:t},execution_order:u,child_execution_order:u,run_type:"retriever",child_runs:[],extra:a?{metadata:a}:{},tags:s||[]};return this._addRunToRunMap(l)}async handleRetrieverStart(e,t,n,i,s,a,o){let u=this.getRunById(n)??this._createRunForRetrieverStart(e,t,n,i,s,a,o);return await this.onRunCreate?.(u),await this.onRetrieverStart?.(u),u}async handleRetrieverEnd(e,t){let n=this.getRunById(t);if(!n||n?.run_type!=="retriever")throw new Error("No retriever run to end");return n.end_time=Date.now(),n.outputs={documents:e},n.events.push({name:"end",time:new Date(n.end_time).toISOString()}),await this.onRetrieverEnd?.(n),await this._endTrace(n),n}async handleRetrieverError(e,t){let n=this.getRunById(t);if(!n||n?.run_type!=="retriever")throw new Error("No retriever run to end");return n.end_time=Date.now(),n.error=this.stringifyError(e),n.events.push({name:"error",time:new Date(n.end_time).toISOString()}),await this.onRetrieverError?.(n),await this._endTrace(n),n}async handleText(e,t){let n=this.getRunById(t);!n||n?.run_type!=="chain"||(n.events.push({name:"text",time:new Date().toISOString(),kwargs:{text:e}}),await this.onText?.(n))}async handleLLMNewToken(e,t,n,i,s,a){let o=this.getRunById(n);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:a?.chunk}}),await this.onLLMNewToken?.(o,e,{chunk:a?.chunk}),o}};var Pb={};le(Pb,{AsyncGeneratorWithSetup:()=>mt,IterableReadableStream:()=>ge,atee:()=>rs,concat:()=>ns,pipeGeneratorWithSetup:()=>ao});var Ib={};le(Ib,{BaseCallbackManager:()=>Ki,BaseRunManager:()=>_r,CallbackManager:()=>Ye,CallbackManagerForChainRun:()=>Yi,CallbackManagerForLLMRun:()=>_n,CallbackManagerForRetrieverRun:()=>Wi,CallbackManagerForToolRun:()=>Xi,TraceGroup:()=>Qi,ensureHandler:()=>Mr,parseCallbackConfigArg:()=>Tb,traceAsGroup:()=>$b});var bb={};le(bb,{ConsoleCallbackHandler:()=>zr});var to=ot(Bd(),1);function Te(r,e){return`${r.open}${e}${r.close}`}function We(r,e){try{return JSON.stringify(r,null,2)}catch{return e}}function Gd(r){return typeof r=="string"?r.trim():r==null?r:We(r,r.toString())}function zt(r){if(!r.end_time)return"";let e=r.end_time-r.start_time;return e<1e3?`${e}ms`:`${(e/1e3).toFixed(2)}s`}var{color:je}=to.default,zr=class extends De{constructor(){super(...arguments),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"console_callback_handler"})}persistRun(e){return Promise.resolve()}getParents(e){let t=[],n=e;for(;n.parent_run_id;){let i=this.runMap.get(n.parent_run_id);if(i)t.push(i),n=i;else break}return t}getBreadcrumbs(e){let n=[...this.getParents(e).reverse(),e].map((i,s,a)=>{let o=`${i.execution_order}:${i.run_type}:${i.name}`;return s===a.length-1?Te(to.default.bold,o):o}).join(" > ");return Te(je.grey,n)}onChainStart(e){let t=this.getBreadcrumbs(e);console.log(`${Te(je.green,"[chain/start]")} [${t}] Entering Chain run with input: ${We(e.inputs,"[inputs]")}`)}onChainEnd(e){let t=this.getBreadcrumbs(e);console.log(`${Te(je.cyan,"[chain/end]")} [${t}] [${zt(e)}] Exiting Chain run with output: ${We(e.outputs,"[outputs]")}`)}onChainError(e){let t=this.getBreadcrumbs(e);console.log(`${Te(je.red,"[chain/error]")} [${t}] [${zt(e)}] Chain run errored with error: ${We(e.error,"[error]")}`)}onLLMStart(e){let t=this.getBreadcrumbs(e),n="prompts"in e.inputs?{prompts:e.inputs.prompts.map(i=>i.trim())}:e.inputs;console.log(`${Te(je.green,"[llm/start]")} [${t}] Entering LLM run with input: ${We(n,"[inputs]")}`)}onLLMEnd(e){let t=this.getBreadcrumbs(e);console.log(`${Te(je.cyan,"[llm/end]")} [${t}] [${zt(e)}] Exiting LLM run with output: ${We(e.outputs,"[response]")}`)}onLLMError(e){let t=this.getBreadcrumbs(e);console.log(`${Te(je.red,"[llm/error]")} [${t}] [${zt(e)}] LLM run errored with error: ${We(e.error,"[error]")}`)}onToolStart(e){let t=this.getBreadcrumbs(e);console.log(`${Te(je.green,"[tool/start]")} [${t}] Entering Tool run with input: "${Gd(e.inputs.input)}"`)}onToolEnd(e){let t=this.getBreadcrumbs(e);console.log(`${Te(je.cyan,"[tool/end]")} [${t}] [${zt(e)}] Exiting Tool run with output: "${Gd(e.outputs?.output)}"`)}onToolError(e){let t=this.getBreadcrumbs(e);console.log(`${Te(je.red,"[tool/error]")} [${t}] [${zt(e)}] Tool run errored with error: ${We(e.error,"[error]")}`)}onRetrieverStart(e){let t=this.getBreadcrumbs(e);console.log(`${Te(je.green,"[retriever/start]")} [${t}] Entering Retriever run with input: ${We(e.inputs,"[inputs]")}`)}onRetrieverEnd(e){let t=this.getBreadcrumbs(e);console.log(`${Te(je.cyan,"[retriever/end]")} [${t}] [${zt(e)}] Exiting Retriever run with output: ${We(e.outputs,"[outputs]")}`)}onRetrieverError(e){let t=this.getBreadcrumbs(e);console.log(`${Te(je.red,"[retriever/error]")} [${t}] [${zt(e)}] Retriever run errored with error: ${We(e.error,"[error]")}`)}onAgentAction(e){let t=e,n=this.getBreadcrumbs(e);console.log(`${Te(je.blue,"[agent/action]")} [${n}] Agent selected action: ${We(t.actions[t.actions.length-1],"[action]")}`)}};var wb={};le(wb,{LangChainTracer:()=>Mt});var ro,Hi=()=>{if(ro===void 0){let r=nt("LANGCHAIN_CALLBACKS_BACKGROUND")==="false"?{blockOnRootRunFinalization:!0}:{};ro=new fr(r)}return ro};var Mt=class r extends De{constructor(e={}){super(e),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"langchain_tracer"}),Object.defineProperty(this,"projectName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"exampleId",{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,"replicas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"usesRunTreeMap",{enumerable:!0,configurable:!0,writable:!0,value:!0});let{exampleId:t,projectName:n,client:i,replicas:s}=e;this.projectName=n??an(),this.replicas=s,this.exampleId=t,this.client=i??Hi();let a=r.getTraceableRunTree();a&&this.updateFromRunTree(a)}async persistRun(e){}async onRunCreate(e){await this.getRunTreeWithTracingConfig(e.id)?.postRun()}async onRunUpdate(e){await this.getRunTreeWithTracingConfig(e.id)?.patchRun()}getRun(e){return this.runTreeMap.get(e)}updateFromRunTree(e){this.runTreeMap.set(e.id,e);let t=e,n=new Set;for(;t.parent_run&&!(n.has(t.id)||(n.add(t.id),!t.parent_run));)t=t.parent_run;n.clear();let i=[t];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=e.client??this.client,this.replicas=e.replicas??this.replicas,this.projectName=e.project_name??this.projectName,this.exampleId=e.reference_example_id??this.exampleId}getRunTreeWithTracingConfig(e){let t=this.runTreeMap.get(e);if(t)return new rt({...t,client:this.client,project_name:this.projectName,replicas:this.replicas,reference_example_id:this.exampleId,tracingEnabled:!0})}static getTraceableRunTree(){try{return Nu(!0)}catch{return}}};var Eb={};le(Eb,{awaitAllCallbacks:()=>Hd,consumeCallback:()=>te});var Ji=ot(Ti(),1);var qd=Symbol.for("ls:tracing_async_local_storage"),mr=Symbol.for("lc:context_variables"),Vd=r=>{globalThis[qd]=r},Dt=()=>globalThis[qd];var gr;function vb(){let r="default"in Ji.default?Ji.default.default:Ji.default;return new r({autoStart:!0,concurrency:1})}function xb(){return typeof gr>"u"&&(gr=vb()),gr}async function te(r,e){if(e===!0){let t=Dt();t!==void 0?await t.run(void 0,async()=>r()):await r()}else gr=xb(),gr.add(async()=>{let t=Dt();t!==void 0?await t.run(void 0,async()=>r()):await r()})}async function Hd(){let r=Hi();await Promise.allSettled([typeof gr<"u"?gr.onIdle():Promise.resolve(),r.awaitPendingTraceBatches()])}var Jd=r=>r!==void 0?r:!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find(t=>nt(t)==="true");function no(r){let e=Dt();return e===void 0?void 0:e.getStore()?.[mr]?.[r]}var Sb=Symbol("lc:configure_hooks"),Kd=()=>no(Sb)||[];function Tb(r){return r?Array.isArray(r)||"name"in r?{callbacks:r}:r:{}}var Ki=class{setHandler(e){return this.setHandlers([e])}},_r=class{constructor(e,t,n,i,s,a,o,u){Object.defineProperty(this,"runId",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"handlers",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"inheritableHandlers",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"inheritableTags",{enumerable:!0,configurable:!0,writable:!0,value:s}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:a}),Object.defineProperty(this,"inheritableMetadata",{enumerable:!0,configurable:!0,writable:!0,value:o}),Object.defineProperty(this,"_parentRunId",{enumerable:!0,configurable:!0,writable:!0,value:u})}get parentRunId(){return this._parentRunId}async handleText(e){await Promise.all(this.handlers.map(t=>te(async()=>{try{await t.handleText?.(e,this.runId,this._parentRunId,this.tags)}catch(n){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleText: ${n}`),t.raiseError)throw n}},t.awaitHandlers)))}async handleCustomEvent(e,t,n,i,s){await Promise.all(this.handlers.map(a=>te(async()=>{try{await a.handleCustomEvent?.(e,t,this.runId,this.tags,this.metadata)}catch(o){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleCustomEvent: ${o}`),a.raiseError)throw o}},a.awaitHandlers)))}},Wi=class extends _r{getChild(e){let t=new Ye(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=>te(async()=>{if(!t.ignoreRetriever)try{await t.handleRetrieverEnd?.(e,this.runId,this._parentRunId,this.tags)}catch(n){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleRetriever`),t.raiseError)throw n}},t.awaitHandlers)))}async handleRetrieverError(e){await Promise.all(this.handlers.map(t=>te(async()=>{if(!t.ignoreRetriever)try{await t.handleRetrieverError?.(e,this.runId,this._parentRunId,this.tags)}catch(n){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleRetrieverError: ${n}`),t.raiseError)throw e}},t.awaitHandlers)))}},_n=class extends _r{async handleLLMNewToken(e,t,n,i,s,a){await Promise.all(this.handlers.map(o=>te(async()=>{if(!o.ignoreLLM)try{await o.handleLLMNewToken?.(e,t??{prompt:0,completion:0},this.runId,this._parentRunId,this.tags,a)}catch(u){if((o.raiseError?console.error:console.warn)(`Error in handler ${o.constructor.name}, handleLLMNewToken: ${u}`),o.raiseError)throw u}},o.awaitHandlers)))}async handleLLMError(e,t,n,i,s){await Promise.all(this.handlers.map(a=>te(async()=>{if(!a.ignoreLLM)try{await a.handleLLMError?.(e,this.runId,this._parentRunId,this.tags,s)}catch(o){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleLLMError: ${o}`),a.raiseError)throw o}},a.awaitHandlers)))}async handleLLMEnd(e,t,n,i,s){await Promise.all(this.handlers.map(a=>te(async()=>{if(!a.ignoreLLM)try{await a.handleLLMEnd?.(e,this.runId,this._parentRunId,this.tags,s)}catch(o){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleLLMEnd: ${o}`),a.raiseError)throw o}},a.awaitHandlers)))}},Yi=class extends _r{getChild(e){let t=new Ye(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,n,i,s){await Promise.all(this.handlers.map(a=>te(async()=>{if(!a.ignoreChain)try{await a.handleChainError?.(e,this.runId,this._parentRunId,this.tags,s)}catch(o){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleChainError: ${o}`),a.raiseError)throw o}},a.awaitHandlers)))}async handleChainEnd(e,t,n,i,s){await Promise.all(this.handlers.map(a=>te(async()=>{if(!a.ignoreChain)try{await a.handleChainEnd?.(e,this.runId,this._parentRunId,this.tags,s)}catch(o){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleChainEnd: ${o}`),a.raiseError)throw o}},a.awaitHandlers)))}async handleAgentAction(e){await Promise.all(this.handlers.map(t=>te(async()=>{if(!t.ignoreAgent)try{await t.handleAgentAction?.(e,this.runId,this._parentRunId,this.tags)}catch(n){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleAgentAction: ${n}`),t.raiseError)throw n}},t.awaitHandlers)))}async handleAgentEnd(e){await Promise.all(this.handlers.map(t=>te(async()=>{if(!t.ignoreAgent)try{await t.handleAgentEnd?.(e,this.runId,this._parentRunId,this.tags)}catch(n){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleAgentEnd: ${n}`),t.raiseError)throw n}},t.awaitHandlers)))}},Xi=class extends _r{getChild(e){let t=new Ye(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=>te(async()=>{if(!t.ignoreAgent)try{await t.handleToolError?.(e,this.runId,this._parentRunId,this.tags)}catch(n){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleToolError: ${n}`),t.raiseError)throw n}},t.awaitHandlers)))}async handleToolEnd(e){await Promise.all(this.handlers.map(t=>te(async()=>{if(!t.ignoreAgent)try{await t.handleToolEnd?.(e,this.runId,this._parentRunId,this.tags)}catch(n){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleToolEnd: ${n}`),t.raiseError)throw n}},t.awaitHandlers)))}},Ye=class r extends Ki{constructor(e,t){super(),Object.defineProperty(this,"handlers",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"inheritableHandlers",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"inheritableTags",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"inheritableMetadata",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"callback_manager"}),Object.defineProperty(this,"_parentRunId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.handlers=t?.handlers??this.handlers,this.inheritableHandlers=t?.inheritableHandlers??this.inheritableHandlers,this.tags=t?.tags??this.tags,this.inheritableTags=t?.inheritableTags??this.inheritableTags,this.metadata=t?.metadata??this.metadata,this.inheritableMetadata=t?.inheritableMetadata??this.inheritableMetadata,this._parentRunId=e}getParentRunId(){return this._parentRunId}async handleLLMStart(e,t,n=void 0,i=void 0,s=void 0,a=void 0,o=void 0,u=void 0){return Promise.all(t.map(async(c,l)=>{let d=l===0&&n?n:Ne();return await Promise.all(this.handlers.map(f=>{if(!f.ignoreLLM)return hr(f)&&f._createRunForLLMStart(e,[c],d,this._parentRunId,s,this.tags,this.metadata,u),te(async()=>{try{await f.handleLLMStart?.(e,[c],d,this._parentRunId,s,this.tags,this.metadata,u)}catch(p){if((f.raiseError?console.error:console.warn)(`Error in handler ${f.constructor.name}, handleLLMStart: ${p}`),f.raiseError)throw p}},f.awaitHandlers)})),new _n(d,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChatModelStart(e,t,n=void 0,i=void 0,s=void 0,a=void 0,o=void 0,u=void 0){return Promise.all(t.map(async(c,l)=>{let d=l===0&&n?n:Ne();return await Promise.all(this.handlers.map(f=>{if(!f.ignoreLLM)return hr(f)&&f._createRunForChatModelStart(e,[c],d,this._parentRunId,s,this.tags,this.metadata,u),te(async()=>{try{if(f.handleChatModelStart)await f.handleChatModelStart?.(e,[c],d,this._parentRunId,s,this.tags,this.metadata,u);else if(f.handleLLMStart){let p=Jn(c);await f.handleLLMStart?.(e,[p],d,this._parentRunId,s,this.tags,this.metadata,u)}}catch(p){if((f.raiseError?console.error:console.warn)(`Error in handler ${f.constructor.name}, handleLLMStart: ${p}`),f.raiseError)throw p}},f.awaitHandlers)})),new _n(d,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChainStart(e,t,n=Ne(),i=void 0,s=void 0,a=void 0,o=void 0){return await Promise.all(this.handlers.map(u=>{if(!u.ignoreChain)return hr(u)&&u._createRunForChainStart(e,t,n,this._parentRunId,this.tags,this.metadata,i,o),te(async()=>{try{await u.handleChainStart?.(e,t,n,this._parentRunId,this.tags,this.metadata,i,o)}catch(c){if((u.raiseError?console.error:console.warn)(`Error in handler ${u.constructor.name}, handleChainStart: ${c}`),u.raiseError)throw c}},u.awaitHandlers)})),new Yi(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleToolStart(e,t,n=Ne(),i=void 0,s=void 0,a=void 0,o=void 0){return await Promise.all(this.handlers.map(u=>{if(!u.ignoreAgent)return hr(u)&&u._createRunForToolStart(e,t,n,this._parentRunId,this.tags,this.metadata,o),te(async()=>{try{await u.handleToolStart?.(e,t,n,this._parentRunId,this.tags,this.metadata,o)}catch(c){if((u.raiseError?console.error:console.warn)(`Error in handler ${u.constructor.name}, handleToolStart: ${c}`),u.raiseError)throw c}},u.awaitHandlers)})),new Xi(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleRetrieverStart(e,t,n=Ne(),i=void 0,s=void 0,a=void 0,o=void 0){return await Promise.all(this.handlers.map(u=>{if(!u.ignoreRetriever)return hr(u)&&u._createRunForRetrieverStart(e,t,n,this._parentRunId,this.tags,this.metadata,o),te(async()=>{try{await u.handleRetrieverStart?.(e,t,n,this._parentRunId,this.tags,this.metadata,o)}catch(c){if((u.raiseError?console.error:console.warn)(`Error in handler ${u.constructor.name}, handleRetrieverStart: ${c}`),u.raiseError)throw c}},u.awaitHandlers)})),new Wi(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleCustomEvent(e,t,n,i,s){await Promise.all(this.handlers.map(a=>te(async()=>{if(!a.ignoreCustomEvent)try{await a.handleCustomEvent?.(e,t,n,this.tags,this.metadata)}catch(o){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleCustomEvent: ${o}`),a.raiseError)throw o}},a.awaitHandlers)))}addHandler(e,t=!0){this.handlers.push(e),t&&this.inheritableHandlers.push(e)}removeHandler(e){this.handlers=this.handlers.filter(t=>t!==e),this.inheritableHandlers=this.inheritableHandlers.filter(t=>t!==e)}setHandlers(e,t=!0){this.handlers=[],this.inheritableHandlers=[];for(let n of e)this.addHandler(n,t)}addTags(e,t=!0){this.removeTags(e),this.tags.push(...e),t&&this.inheritableTags.push(...e)}removeTags(e){this.tags=this.tags.filter(t=>!e.includes(t)),this.inheritableTags=this.inheritableTags.filter(t=>!e.includes(t))}addMetadata(e,t=!0){this.metadata={...this.metadata,...e},t&&(this.inheritableMetadata={...this.inheritableMetadata,...e})}removeMetadata(e){for(let t of Object.keys(e))delete this.metadata[t],delete this.inheritableMetadata[t]}copy(e=[],t=!0){let n=new r(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 e)n.handlers.filter(s=>s.name==="console_callback_handler").some(s=>s.name===i.name)||n.addHandler(i,t);return n}static fromHandlers(e){class t extends Lt{constructor(){super(),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:Ne()}),Object.assign(this,e)}}let n=new this;return n.addHandler(new t),n}static configure(e,t,n,i,s,a,o){return this._configureSync(e,t,n,i,s,a,o)}static _configureSync(e,t,n,i,s,a,o){let u;(e||t)&&(Array.isArray(e)||!e?(u=new r,u.setHandlers(e?.map(Mr)??[],!0)):u=e,u=u.copy(Array.isArray(t)?t.map(Mr):t?.handlers,!1));let c=nt("LANGCHAIN_VERBOSE")==="true"||o?.verbose,l=Mt.getTraceableRunTree()?.tracingEnabled||Jd(),d=l||(nt("LANGCHAIN_TRACING")??!1);if(c||d){if(u||(u=new r),c&&!u.handlers.some(f=>f.name===zr.prototype.name)){let f=new zr;u.addHandler(f,!0)}if(d&&!u.handlers.some(f=>f.name==="langchain_tracer")&&l){let f=new Mt;u.addHandler(f,!0)}if(l){let f=Mt.getTraceableRunTree();f&&u._parentRunId===void 0&&(u._parentRunId=f.id,u.handlers.find(h=>h.name==="langchain_tracer")?.updateFromRunTree(f))}}for(let{contextVar:f,inheritable:p=!0,handlerClass:h,envVar:m}of Kd()){let g=m&&nt(m)==="true"&&h,_,w=f!==void 0?no(f):void 0;w&&Xa(w)?_=w:g&&(_=new h({})),_!==void 0&&(u||(u=new r),u.handlers.some(v=>v.name===_.name)||u.addHandler(_,p))}return(n||i)&&u&&(u.addTags(n??[]),u.addTags(i??[],!1)),(s||a)&&u&&(u.addMetadata(s??{}),u.addMetadata(a??{},!1)),u}};function Mr(r){return"name"in r?r:Lt.fromMethods(r)}var Qi=class{constructor(e,t){Object.defineProperty(this,"groupName",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"runManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}async getTraceGroupCallbackManager(e,t,n){let i=new Mt(n),a=await(await Ye.configure([i]))?.handleChainStart({lc:1,type:"not_implemented",id:["langchain","callbacks","groups",e]},t??{});if(!a)throw new Error("Failed to create run group callback manager.");return a}async start(e){return this.runManager||(this.runManager=await this.getTraceGroupCallbackManager(this.groupName,e,this.options)),this.runManager.getChild()}async error(e){this.runManager&&(await this.runManager.handleChainError(e),this.runManager=void 0)}async end(e){this.runManager&&(await this.runManager.handleChainEnd(e??{}),this.runManager=void 0)}};function Ob(r,e){return r&&!Array.isArray(r)&&typeof r=="object"?r:{[e]:r}}async function $b(r,e,...t){let n=new Qi(r.name,r),i=await n.start({...t});try{let s=await e(i,...t);return await n.end(Ob(s,"output")),s}catch(s){throw await n.error(s),s}}var es=class{getStore(){}run(e,t){return t()}enterWith(e){}},Ab=new es,Wd=Symbol.for("lc:child_config"),io=class{getInstance(){return Dt()??Ab}getRunnableConfig(){return this.getInstance().getStore()?.extra?.[Wd]}runWithConfig(e,t,n){let i=Ye._configureSync(e?.callbacks,void 0,e?.tags,void 0,e?.metadata),s=this.getInstance(),a=s.getStore(),o=i?.getParentRunId(),u=i?.handlers?.find(l=>l?.name==="langchain_tracer"),c;return u&&o?c=u.getRunTreeWithTracingConfig(o):n||(c=new rt({name:"<runnable_lambda>",tracingEnabled:!1})),c&&(c.extra={...c.extra,[Wd]:e}),a!==void 0&&a[mr]!==void 0&&(c===void 0&&(c={}),c[mr]=a[mr]),s.run(c,t)}initializeGlobalInstance(e){Dt()===void 0&&Vd(e)}},Ue=new io;var ts=25;async function Xe(r){return Ye._configureSync(r?.callbacks,void 0,r?.tags,void 0,r?.metadata)}function so(...r){let e={};for(let t of r.filter(n=>!!n))for(let n of Object.keys(t))if(n==="metadata")e[n]={...e[n],...t[n]};else if(n==="tags"){let i=e[n]??[];e[n]=[...new Set(i.concat(t[n]??[]))]}else if(n==="configurable")e[n]={...e[n],...t[n]};else if(n==="timeout")e.timeout===void 0?e.timeout=t.timeout:t.timeout!==void 0&&(e.timeout=Math.min(e.timeout,t.timeout));else if(n==="signal")e.signal===void 0?e.signal=t.signal:t.signal!==void 0&&("any"in AbortSignal?e.signal=AbortSignal.any([e.signal,t.signal]):e.signal=t.signal);else if(n==="callbacks"){let i=e.callbacks,s=t.callbacks;if(Array.isArray(s))if(!i)e.callbacks=s;else if(Array.isArray(i))e.callbacks=i.concat(s);else{let a=i.copy();for(let o of s)a.addHandler(Mr(o),!0);e.callbacks=a}else if(s)if(!i)e.callbacks=s;else if(Array.isArray(i)){let a=s.copy();for(let o of i)a.addHandler(Mr(o),!0);e.callbacks=a}else e.callbacks=new Ye(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;e[i]=t[i]??e[i]}return e}var kb=new Set(["string","number","boolean"]);function W(r){let e=Ue.getRunnableConfig(),t={tags:[],metadata:{},recursionLimit:25,runId:void 0};if(e){let{runId:n,runName:i,...s}=e;t=Object.entries(s).reduce((a,[o,u])=>(u!==void 0&&(a[o]=u),a),t)}if(r&&(t=Object.entries(r).reduce((n,[i,s])=>(s!==void 0&&(n[i]=s),n),t)),t?.configurable)for(let n of Object.keys(t.configurable))kb.has(typeof t.configurable[n])&&!t.metadata?.[n]&&(t.metadata||(t.metadata={}),t.metadata[n]=t.configurable[n]);if(t.timeout!==void 0){if(t.timeout<=0)throw new Error("Timeout must be a positive number");let n=AbortSignal.timeout(t.timeout);t.signal!==void 0?"any"in AbortSignal&&(t.signal=AbortSignal.any([t.signal,n])):t.signal=n,delete t.timeout}return t}function me(r={},{callbacks:e,maxConcurrency:t,recursionLimit:n,runName:i,configurable:s,runId:a}={}){let o=W(r);return e!==void 0&&(delete o.runName,o.callbacks=e),n!==void 0&&(o.recursionLimit=n),t!==void 0&&(o.maxConcurrency=t),i!==void 0&&(o.runName=i),s!==void 0&&(o.configurable={...o.configurable,...s}),a!==void 0&&delete o.runId,o}function It(r){return r?{configurable:r.configurable,recursionLimit:r.recursionLimit,callbacks:r.callbacks,tags:r.tags,metadata:r.metadata,maxConcurrency:r.maxConcurrency,timeout:r.timeout,signal:r.signal}:void 0}async function ht(r,e){if(e===void 0)return r;let t;return Promise.race([r.catch(n=>{if(!e?.aborted)throw n}),new Promise((n,i)=>{t=()=>{i(new Error("Aborted"))},e.addEventListener("abort",t),e.aborted&&i(new Error("Aborted"))})]).finally(()=>e.removeEventListener("abort",t))}var ge=class r extends ReadableStream{constructor(){super(...arguments),Object.defineProperty(this,"reader",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}ensureReader(){this.reader||(this.reader=this.getReader())}async next(){this.ensureReader();try{let e=await this.reader.read();return e.done?(this.reader.releaseLock(),{done:!0,value:void 0}):{done:!1,value:e.value}}catch(e){throw this.reader.releaseLock(),e}}async return(){if(this.ensureReader(),this.locked){let e=this.reader.cancel();this.reader.releaseLock(),await e}return{done:!0,value:void 0}}async throw(e){if(this.ensureReader(),this.locked){let t=this.reader.cancel();this.reader.releaseLock(),await t}throw e}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}static fromReadableStream(e){let t=e.getReader();return new r({start(n){return i();function i(){return t.read().then(({done:s,value:a})=>{if(s){n.close();return}return n.enqueue(a),i()})}},cancel(){t.releaseLock()}})}static fromAsyncGenerator(e){return new r({async pull(t){let{value:n,done:i}=await e.next();i&&t.close(),t.enqueue(n)},async cancel(t){await e.return(t)}})}};function rs(r,e=2){let t=Array.from({length:e},()=>[]);return t.map(async function*(i){for(;;)if(i.length===0){let s=await r.next();for(let a of t)a.push(s)}else{if(i[0].done)return;yield i.shift().value}})}function ns(r,e){if(Array.isArray(r)&&Array.isArray(e))return r.concat(e);if(typeof r=="string"&&typeof e=="string")return r+e;if(typeof r=="number"&&typeof e=="number")return r+e;if("concat"in r&&typeof r.concat=="function")return r.concat(e);if(typeof r=="object"&&typeof e=="object"){let t={...r};for(let[n,i]of Object.entries(e))n in t&&!Array.isArray(t[n])?t[n]=ns(t[n],i):t[n]=i;return t}else throw new Error(`Cannot concat ${typeof r} and ${typeof e}`)}var mt=class{constructor(e){Object.defineProperty(this,"generator",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"setup",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"signal",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"firstResult",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"firstResultUsed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),this.generator=e.generator,this.config=e.config,this.signal=e.signal??this.config?.signal,this.setup=new Promise((t,n)=>{Ue.runWithConfig(It(e.config),async()=>{this.firstResult=e.generator.next(),e.startSetup?this.firstResult.then(e.startSetup).then(t,n):this.firstResult.then(i=>t(void 0),n)},!0)})}async next(...e){return this.signal?.throwIfAborted(),this.firstResultUsed?Ue.runWithConfig(It(this.config),this.signal?async()=>ht(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 ao(r,e,t,n,...i){let s=new mt({generator:e,startSetup:t,signal:n}),a=await s.setup;return{output:r(s,a,...i),setup:a}}var Qe=class{constructor(e){Object.defineProperty(this,"ops",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.ops=e.ops??[]}concat(e){let t=this.ops.concat(e.ops),n=dr({},t);return new Dr({ops:t,state:n[n.length-1].newDocument})}},Dr=class r extends Qe{constructor(e){super(e),Object.defineProperty(this,"state",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.state=e.state}concat(e){let t=this.ops.concat(e.ops),n=dr(this.state,e.ops);return new r({ops:t,state:n[n.length-1].newDocument})}static fromRunLogPatch(e){let t=dr({},e.ops);return new r({ops:e.ops,state:t[t.length-1].newDocument})}},oo=r=>r.name==="log_stream_tracer";async function Yd(r,e){if(e==="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:t}=r;if(["retriever","llm","prompt"].includes(r.run_type))return t;if(!(Object.keys(t).length===1&&t?.input===""))return t.input}async function Xd(r,e){let{outputs:t}=r;return e==="original"||["retriever","llm","prompt"].includes(r.run_type)?t:t!==void 0&&Object.keys(t).length===1&&t?.output!==void 0?t.output:t}function Rb(r){return r!==void 0&&r.message!==void 0}var Ur=class extends De{constructor(e){super({_awaitHandler:!0,...e}),Object.defineProperty(this,"autoClose",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"includeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_schemaFormat",{enumerable:!0,configurable:!0,writable:!0,value:"original"}),Object.defineProperty(this,"rootId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"keyMapByRunId",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"counterMapByRunName",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"transformStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"writer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"receiveStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"log_stream_tracer"}),Object.defineProperty(this,"lc_prefer_streaming",{enumerable:!0,configurable:!0,writable:!0,value:!0}),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=ge.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??[],n=this.includeNames===void 0&&this.includeTags===void 0&&this.includeTypes===void 0;return this.includeNames!==void 0&&(n=n||this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(n=n||this.includeTypes.includes(e.run_type)),this.includeTags!==void 0&&(n=n||t.find(i=>this.includeTags?.includes(i))!==void 0),this.excludeNames!==void 0&&(n=n&&!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(n=n&&!this.excludeTypes.includes(e.run_type)),this.excludeTags!==void 0&&(n=n&&t.every(i=>!this.excludeTags?.includes(i))),n}async*tapOutputIterable(e,t){for await(let n of t){if(e!==this.rootId){let i=this.keyMapByRunId[e];i&&await this.writer.write(new Qe({ops:[{op:"add",path:`/logs/${i}/streamed_output/-`,value:n}]}))}yield n}}async onRunCreate(e){if(this.rootId===void 0&&(this.rootId=e.id,await this.writer.write(new Qe({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 n={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"&&(n.inputs=await Yd(e,this._schemaFormat)),await this.writer.write(new Qe({ops:[{op:"add",path:`/logs/${this.keyMapByRunId[e.id]}`,value:n}]}))}async onRunUpdate(e){try{let t=this.keyMapByRunId[e.id];if(t===void 0)return;let n=[];this._schemaFormat==="streaming_events"&&n.push({op:"replace",path:`/logs/${t}/inputs`,value:await Yd(e,this._schemaFormat)}),n.push({op:"add",path:`/logs/${t}/final_output`,value:await Xd(e,this._schemaFormat)}),e.end_time!==void 0&&n.push({op:"add",path:`/logs/${t}/end_time`,value:new Date(e.end_time).toISOString()});let i=new Qe({ops:n});await this.writer.write(i)}finally{if(e.id===this.rootId){let t=new Qe({ops:[{op:"replace",path:"/final_output",value:await Xd(e,this._schemaFormat)}]});await this.writer.write(t),this.autoClose&&await this.writer.close()}}}async onLLMNewToken(e,t,n){let i=this.keyMapByRunId[e.id];if(i===void 0)return;let s=e.inputs.messages!==void 0,a;s?Rb(n?.chunk)?a=n?.chunk:a=new Pt({id:`run-${e.id}`,content:t}):a=t;let o=new Qe({ops:[{op:"add",path:`/logs/${i}/streamed_output_str/-`,value:t},{op:"add",path:`/logs/${i}/streamed_output/-`,value:a}]});await this.writer.write(o)}};var jb={};le(jb,{ChatGenerationChunk:()=>uo,GenerationChunk:()=>yr,RUN_KEY:()=>Cb});var Cb="__run",yr=class r{constructor(e){Object.defineProperty(this,"text",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"generationInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.text=e.text,this.generationInfo=e.generationInfo}concat(e){return new r({text:this.text+e.text,generationInfo:{...this.generationInfo,...e.generationInfo}})}},uo=class r extends yr{constructor(e){super(e),Object.defineProperty(this,"message",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.message=e.message}concat(e){return new r({text:this.text+e.text,generationInfo:{...this.generationInfo,...e.generationInfo},message:this.message.concat(e.message)})}};function is({name:r,serialized:e}){return r!==void 0?r:e?.name!==void 0?e.name:e?.id!==void 0&&Array.isArray(e?.id)?e.id[e.id.length-1]:"Unnamed"}var Qd=r=>r.name==="event_stream_tracer",ss=class extends De{constructor(e){super({_awaitHandler:!0,...e}),Object.defineProperty(this,"autoClose",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"includeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"runInfoMap",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"tappedPromises",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"transformStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"writer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"receiveStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"event_stream_tracer"}),Object.defineProperty(this,"lc_prefer_streaming",{enumerable:!0,configurable:!0,writable:!0,value:!0}),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,this.writer=this.transformStream.writable.getWriter(),this.receiveStream=ge.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){let t=e.tags??[],n=this.includeNames===void 0&&this.includeTags===void 0&&this.includeTypes===void 0;return this.includeNames!==void 0&&(n=n||this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(n=n||this.includeTypes.includes(e.runType)),this.includeTags!==void 0&&(n=n||t.find(i=>this.includeTags?.includes(i))!==void 0),this.excludeNames!==void 0&&(n=n&&!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(n=n&&!this.excludeTypes.includes(e.runType)),this.excludeTags!==void 0&&(n=n&&t.every(i=>!this.excludeTags?.includes(i))),n}async*tapOutputIterable(e,t){let n=await t.next();if(n.done)return;let i=this.runInfoMap.get(e);if(i===void 0){yield n.value;return}function s(o,u){return o==="llm"&&typeof u=="string"?new yr({text:u}):u}let a=this.tappedPromises.get(e);if(a===void 0){let o;a=new Promise(u=>{o=u}),this.tappedPromises.set(e,a);try{let u={event:`on_${i.runType}_stream`,run_id:e,name:i.name,tags:i.tags,metadata:i.metadata,data:{}};await this.send({...u,data:{chunk:s(i.runType,n.value)}},i),yield n.value;for await(let c of t)i.runType!=="tool"&&i.runType!=="retriever"&&await this.send({...u,data:{chunk:s(i.runType,c)}},i),yield c}finally{o()}}else{yield n.value;for await(let o of t)yield o}}async send(e,t){this._includeRun(t)&&await this.writer.write(e)}async sendEndEvent(e,t){let n=this.tappedPromises.get(e.run_id);n!==void 0?n.then(()=>{this.send(e,t)}):await this.send(e,t)}async onLLMStart(e){let t=is(e),n=e.inputs.messages!==void 0?"chat_model":"llm",i={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:n,inputs:e.inputs};this.runInfoMap.set(e.id,i);let s=`on_${n}_start`;await this.send({event:s,data:{input:e.inputs},name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},i)}async onLLMNewToken(e,t,n){let i=this.runInfoMap.get(e.id),s,a;if(i===void 0)throw new Error(`onLLMNewToken: Run ID ${e.id} not found in run map.`);if(this.runInfoMap.size!==1){if(i.runType==="chat_model")a="on_chat_model_stream",n?.chunk===void 0?s=new Pt({content:t,id:`run-${e.id}`}):s=n.chunk.message;else if(i.runType==="llm")a="on_llm_stream",n?.chunk===void 0?s=new yr({text:t}):s=n.chunk;else throw new Error(`Unexpected run type ${i.runType}`);await this.send({event:a,data:{chunk:s},run_id:e.id,name:i.name,tags:i.tags,metadata:i.metadata},i)}}async onLLMEnd(e){let t=this.runInfoMap.get(e.id);this.runInfoMap.delete(e.id);let n;if(t===void 0)throw new Error(`onLLMEnd: Run ID ${e.id} not found in run map.`);let i=e.outputs?.generations,s;if(t.runType==="chat_model"){for(let a of i??[]){if(s!==void 0)break;s=a[0]?.message}n="on_chat_model_end"}else if(t.runType==="llm")s={generations:i?.map(a=>a.map(o=>({text:o.text,generationInfo:o.generationInfo}))),llmOutput:e.outputs?.llmOutput??{}},n="on_llm_end";else throw new Error(`onLLMEnd: Unexpected run type: ${t.runType}`);await this.sendEndEvent({event:n,data:{output:s,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onChainStart(e){let t=is(e),n=e.run_type??"chain",i={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:e.run_type},s={};e.inputs.input===""&&Object.keys(e.inputs).length===1?(s={},i.inputs={}):e.inputs.input!==void 0?(s.input=e.inputs.input,i.inputs=e.inputs.input):(s.input=e.inputs,i.inputs=e.inputs),this.runInfoMap.set(e.id,i),await this.send({event:`on_${n}_start`,data:s,name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},i)}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 n=`on_${e.run_type}_end`,i=e.inputs??t.inputs??{},a={output:e.outputs?.output??e.outputs,input:i};i.input&&Object.keys(i).length===1&&(a.input=i.input,t.inputs=i.input),await this.sendEndEvent({event:n,data:a,run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata??{}},t)}async onToolStart(e){let t=is(e),n={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:"tool",inputs:e.inputs??{}};this.runInfoMap.set(e.id,n),await this.send({event:"on_tool_start",data:{input:e.inputs??{}},name:t,run_id:e.id,tags:e.tags??[],metadata:e.extra?.metadata??{}},n)}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 n=e.outputs?.output===void 0?e.outputs:e.outputs.output;await this.sendEndEvent({event:"on_tool_end",data:{output:n,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onRetrieverStart(e){let t=is(e),i={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:"retriever",inputs:{query:e.inputs.query}};this.runInfoMap.set(e.id,i),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??{}},i)}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,n){let i=this.runInfoMap.get(n);if(i===void 0)throw new Error(`handleCustomEvent: Run ID ${n} not found in run map.`);await this.send({event:"on_custom_event",run_id:n,name:e,tags:i.tags,metadata:i.metadata,data:t},i)}async finish(){let e=[...this.tappedPromises.values()];Promise.all(e).finally(()=>{this.writer.close()})}};var Mb={};le(Mb,{AsyncCaller:()=>yn});var ef=ot(ri(),1),as=ot(Ti(),1),Lb=[400,401,402,403,404,405,406,407,409],zb=r=>{if(r.message.startsWith("Cancel")||r.message.startsWith("AbortError")||r.name==="AbortError"||r?.code==="ECONNABORTED")throw r;let e=r?.response?.status??r?.status;if(e&&Lb.includes(+e))throw r;if(r?.error?.code==="insufficient_quota"){let t=new Error(r?.message);throw t.name="InsufficientQuotaError",t}},yn=class{constructor(e){Object.defineProperty(this,"maxConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxRetries",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onFailedAttempt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,this.onFailedAttempt=e.onFailedAttempt??zb;let t="default"in as.default?as.default.default:as.default;this.queue=new t({concurrency:this.maxConcurrency})}call(e,...t){return this.queue.add(()=>(0,ef.default)(()=>e(...t).catch(n=>{throw n instanceof Error?n:new Error(n)}),{onFailedAttempt:this.onFailedAttempt,retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(e,t,...n){return e.signal?Promise.race([this.call(t,...n),new Promise((i,s)=>{e.signal?.addEventListener("abort",()=>{s(new Error("AbortError"))})})]):this.call(t,...n)}fetch(...e){return this.call(()=>fetch(...e).then(t=>t.ok?t:Promise.reject(t)))}};var bn=class extends De{constructor({config:e,onStart:t,onEnd:n,onError:i}){super({_awaitHandler:!0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"RootListenersTracer"}),Object.defineProperty(this,"rootId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"argOnStart",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"argOnEnd",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"argOnError",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.config=e,this.argOnStart=t,this.argOnEnd=n,this.argOnError=i}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 wn(r){return r?r.lc_runnable:!1}var os=class{constructor(e){Object.defineProperty(this,"includeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 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}includeEvent(e,t){let n=this.includeNames===void 0&&this.includeTypes===void 0&&this.includeTags===void 0,i=e.tags??[];return this.includeNames!==void 0&&(n=n||this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(n=n||this.includeTypes.includes(t)),this.includeTags!==void 0&&(n=n||i.some(s=>this.includeTags?.includes(s))),this.excludeNames!==void 0&&(n=n&&!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(n=n&&!this.excludeTypes.includes(t)),this.excludeTags!==void 0&&(n=n&&i.every(s=>!this.excludeTags?.includes(s))),n}};function co(r){return r.replace(/[^a-zA-Z-_0-9]/g,"_")}var Db=["*","_","`"];function Ub(r){let e="";for(let[t,n]of Object.entries(r))e+=` classDef ${t} ${n};
57
+ `;return e}function tf(r,e,t){let{firstNode:n,lastNode:i,nodeColors:s,withStyles:a=!0,curveStyle:o="linear",wrapLabelNWords:u=9}=t??{},c=a?`%%{init: {'flowchart': {'curve': '${o}'}}}%%
58
+ graph TD;
59
+ `:`graph TD;
60
+ `;if(a){let p="default",h={[p]:"{0}({1})"};n!==void 0&&(h[n]="{0}([{1}]):::first"),i!==void 0&&(h[i]="{0}([{1}]):::last");for(let[m,g]of Object.entries(r)){let _=g.name.split(":").pop()??"",v=Db.some(I=>_.startsWith(I)&&_.endsWith(I))?`<p>${_}</p>`:_;Object.keys(g.metadata??{}).length&&(v+=`<hr/><small><em>${Object.entries(g.metadata??{}).map(([I,H])=>`${I} = ${H}`).join(`
61
+ `)}</em></small>`);let N=(h[m]??h[p]).replace("{0}",co(m)).replace("{1}",v);c+=` ${N}
62
+ `}}let l={};for(let p of e){let h=p.source.split(":"),m=p.target.split(":"),g=h.filter((_,w)=>_===m[w]).join(":");l[g]||(l[g]=[]),l[g].push(p)}let d=new Set;function f(p,h){let m=p.length===1&&p[0].source===p[0].target;if(h&&!m){let g=h.split(":").pop();if(d.has(g))throw new Error(`Found duplicate subgraph '${g}' -- 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.`);d.add(g),c+=` subgraph ${g}
63
+ `}for(let g of p){let{source:_,target:w,data:v,conditional:N}=g,I="";if(v!==void 0){let H=v,K=H.split(" ");K.length>u&&(H=Array.from({length:Math.ceil(K.length/u)},(J,ce)=>K.slice(ce*u,(ce+1)*u).join(" ")).join("&nbsp;<br>&nbsp;")),I=N?` -. &nbsp;${H}&nbsp; .-> `:` -- &nbsp;${H}&nbsp; --> `}else I=N?" -.-> ":" --> ";c+=` ${co(_)}${I}${co(w)};
64
+ `}for(let g in l)g.startsWith(`${h}:`)&&g!==h&&f(l[g],g);h&&!m&&(c+=` end
65
+ `)}f(l[""]??[],"");for(let p in l)!p.includes(":")&&p!==""&&f(l[p],p);return a&&(c+=Ub(s??{})),c}async function rf(r,e){return Fb(r,{...e,imageType:"png"})}async function Fb(r,e){let t=e?.backgroundColor??"white",n=e?.imageType??"png",i=btoa(r);t!==void 0&&(/^#(?:[0-9a-fA-F]{3}){1,2}$/.test(t)||(t=`!${t}`));let s=`https://mermaid.ink/img/${i}?bgColor=${t}&type=${n}`,a=await fetch(s);if(!a.ok)throw new Error(["Failed to render the graph using the Mermaid.INK API.",`Status code: ${a.status}`,`Status text: ${a.statusText}`].join(`
66
+ `));return await a.blob()}var nv={};le(nv,{Validator:()=>_s,deepCompareStrict:()=>Zt,toJsonSchema:()=>Io,validatesOnlyStrings:()=>bs});var vO=Object.freeze({status:"aborted"});function Ft(r,e,t){function n(o,u){var c;Object.defineProperty(o,"_zod",{value:o._zod??{},enumerable:!1}),(c=o._zod).traits??(c.traits=new Set),o._zod.traits.add(r),e(o,u);for(let l in a.prototype)l in o||Object.defineProperty(o,l,{value:a.prototype[l].bind(o)});o._zod.constr=a,o._zod.def=u}let i=t?.Parent??Object;class s extends i{}Object.defineProperty(s,"name",{value:r});function a(o){var u;let c=t?.Parent?new s:this;n(c,o),(u=c._zod).deferred??(u.deferred=[]);for(let l of c._zod.deferred)l();return c}return Object.defineProperty(a,"init",{value:n}),Object.defineProperty(a,Symbol.hasInstance,{value:o=>t?.Parent&&o instanceof t.Parent?!0:o?._zod?.traits?.has(r)}),Object.defineProperty(a,"name",{value:r}),a}var xO=Symbol("zod_brand"),Ut=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},lo={};function Fr(r){return r&&Object.assign(lo,r),lo}var At={};le(At,{BIGINT_FORMAT_RANGES:()=>nw,Class:()=>fo,NUMBER_FORMAT_RANGES:()=>rw,aborted:()=>xn,allowsEval:()=>af,assert:()=>Vb,assertEqual:()=>Zb,assertIs:()=>Gb,assertNever:()=>qb,assertNotEqual:()=>Bb,assignProp:()=>go,cached:()=>ho,captureStackTrace:()=>ds,cleanEnum:()=>fw,cleanRegex:()=>mo,clone:()=>Oe,createTransparentProxy:()=>tw,defineLazy:()=>ls,esc:()=>sf,escapeRegex:()=>cf,extend:()=>aw,finalizeIssue:()=>br,floatSafeRemainder:()=>Kb,getElementAtPath:()=>Wb,getEnumValues:()=>cs,getLengthableOrigin:()=>dw,getParsedType:()=>ew,getSizableOrigin:()=>lw,isObject:()=>us,isPlainObject:()=>_o,issue:()=>pf,joinValues:()=>Hb,jsonStringifyReplacer:()=>po,merge:()=>ow,normalizeParams:()=>yo,nullish:()=>Jb,numKeys:()=>Qb,omit:()=>sw,optionalKeys:()=>df,partial:()=>uw,pick:()=>iw,prefixIssues:()=>ff,primitiveTypes:()=>uf,promiseAllObject:()=>Yb,propertyKeyTypes:()=>of,randomString:()=>Xb,required:()=>cw,stringifyPrimitive:()=>lf,unwrapMessage:()=>vn});function Zb(r){return r}function Bb(r){return r}function Gb(r){}function qb(r){throw new Error}function Vb(r){}function cs(r){let e=Object.values(r).filter(n=>typeof n=="number");return Object.entries(r).filter(([n,i])=>e.indexOf(+n)===-1).map(([n,i])=>i)}function Hb(r,e="|"){return r.map(t=>lf(t)).join(e)}function po(r,e){return typeof e=="bigint"?e.toString():e}function ho(r){return{get value(){{let t=r();return Object.defineProperty(this,"value",{value:t}),t}throw new Error("cached value already set")}}}function Jb(r){return r==null}function mo(r){let e=r.startsWith("^")?1:0,t=r.endsWith("$")?r.length-1:r.length;return r.slice(e,t)}function Kb(r,e){let t=(r.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,i=t>n?t:n,s=Number.parseInt(r.toFixed(i).replace(".","")),a=Number.parseInt(e.toFixed(i).replace(".",""));return s%a/10**i}function ls(r,e,t){Object.defineProperty(r,e,{get(){{let i=t();return r[e]=i,i}throw new Error("cached value already set")},set(i){Object.defineProperty(r,e,{value:i})},configurable:!0})}function go(r,e,t){Object.defineProperty(r,e,{value:t,writable:!0,enumerable:!0,configurable:!0})}function Wb(r,e){return e?e.reduce((t,n)=>t?.[n],r):r}function Yb(r){let e=Object.keys(r),t=e.map(n=>r[n]);return Promise.all(t).then(n=>{let i={};for(let s=0;s<e.length;s++)i[e[s]]=n[s];return i})}function Xb(r=10){let e="abcdefghijklmnopqrstuvwxyz",t="";for(let n=0;n<r;n++)t+=e[Math.floor(Math.random()*e.length)];return t}function sf(r){return JSON.stringify(r)}var ds=Error.captureStackTrace?Error.captureStackTrace:(...r)=>{};function us(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}var af=ho(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let r=Function;return new r(""),!0}catch{return!1}});function _o(r){if(us(r)===!1)return!1;let e=r.constructor;if(e===void 0)return!0;let t=e.prototype;return!(us(t)===!1||Object.prototype.hasOwnProperty.call(t,"isPrototypeOf")===!1)}function Qb(r){let e=0;for(let t in r)Object.prototype.hasOwnProperty.call(r,t)&&e++;return e}var ew=r=>{let e=typeof r;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(r)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(r)?"array":r===null?"null":r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?"promise":typeof Map<"u"&&r instanceof Map?"map":typeof Set<"u"&&r instanceof Set?"set":typeof Date<"u"&&r instanceof Date?"date":typeof File<"u"&&r instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},of=new Set(["string","number","symbol"]),uf=new Set(["string","number","bigint","boolean","symbol","undefined"]);function cf(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Oe(r,e,t){let n=new r._zod.constr(e??r._zod.def);return(!e||t?.parent)&&(n._zod.parent=r),n}function yo(r){let e=r;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function tw(r){let e;return new Proxy({},{get(t,n,i){return e??(e=r()),Reflect.get(e,n,i)},set(t,n,i,s){return e??(e=r()),Reflect.set(e,n,i,s)},has(t,n){return e??(e=r()),Reflect.has(e,n)},deleteProperty(t,n){return e??(e=r()),Reflect.deleteProperty(e,n)},ownKeys(t){return e??(e=r()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(t,n){return e??(e=r()),Reflect.getOwnPropertyDescriptor(e,n)},defineProperty(t,n,i){return e??(e=r()),Reflect.defineProperty(e,n,i)}})}function lf(r){return typeof r=="bigint"?r.toString()+"n":typeof r=="string"?`"${r}"`:`${r}`}function df(r){return Object.keys(r).filter(e=>r[e]._zod.optin==="optional"&&r[e]._zod.optout==="optional")}var rw={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]},nw={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function iw(r,e){let t={},n=r._zod.def;for(let i in e){if(!(i in n.shape))throw new Error(`Unrecognized key: "${i}"`);e[i]&&(t[i]=n.shape[i])}return Oe(r,{...r._zod.def,shape:t,checks:[]})}function sw(r,e){let t={...r._zod.def.shape},n=r._zod.def;for(let i in e){if(!(i in n.shape))throw new Error(`Unrecognized key: "${i}"`);e[i]&&delete t[i]}return Oe(r,{...r._zod.def,shape:t,checks:[]})}function aw(r,e){if(!_o(e))throw new Error("Invalid input to extend: expected a plain object");let t={...r._zod.def,get shape(){let n={...r._zod.def.shape,...e};return go(this,"shape",n),n},checks:[]};return Oe(r,t)}function ow(r,e){return Oe(r,{...r._zod.def,get shape(){let t={...r._zod.def.shape,...e._zod.def.shape};return go(this,"shape",t),t},catchall:e._zod.def.catchall,checks:[]})}function uw(r,e,t){let n=e._zod.def.shape,i={...n};if(t)for(let s in t){if(!(s in n))throw new Error(`Unrecognized key: "${s}"`);t[s]&&(i[s]=r?new r({type:"optional",innerType:n[s]}):n[s])}else for(let s in n)i[s]=r?new r({type:"optional",innerType:n[s]}):n[s];return Oe(e,{...e._zod.def,shape:i,checks:[]})}function cw(r,e,t){let n=e._zod.def.shape,i={...n};if(t)for(let s in t){if(!(s in i))throw new Error(`Unrecognized key: "${s}"`);t[s]&&(i[s]=new r({type:"nonoptional",innerType:n[s]}))}else for(let s in n)i[s]=new r({type:"nonoptional",innerType:n[s]});return Oe(e,{...e._zod.def,shape:i,checks:[]})}function xn(r,e=0){for(let t=e;t<r.issues.length;t++)if(r.issues[t]?.continue!==!0)return!0;return!1}function ff(r,e){return e.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(r),t})}function vn(r){return typeof r=="string"?r:r?.message}function br(r,e,t){let n={...r,path:r.path??[]};if(!r.message){let i=vn(r.inst?._zod.def?.error?.(r))??vn(e?.error?.(r))??vn(t.customError?.(r))??vn(t.localeError?.(r))??"Invalid input";n.message=i}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function lw(r){return r instanceof Set?"set":r instanceof Map?"map":r instanceof File?"file":"unknown"}function dw(r){return Array.isArray(r)?"array":typeof r=="string"?"string":"unknown"}function pf(...r){let[e,t,n]=r;return typeof e=="string"?{message:e,code:"custom",input:t,inst:n}:{...e}}function fw(r){return Object.entries(r).filter(([e,t])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var fo=class{constructor(...e){}};var hf=(r,e)=>{r.name="$ZodError",Object.defineProperty(r,"_zod",{value:r._zod,enumerable:!1}),Object.defineProperty(r,"issues",{value:e,enumerable:!1}),Object.defineProperty(r,"message",{get(){return JSON.stringify(e,po,2)},enumerable:!0}),Object.defineProperty(r,"toString",{value:()=>r.message,enumerable:!1})},mf=Ft("$ZodError",hf),En=Ft("$ZodError",hf,{Parent:Error});var hw=r=>(e,t,n,i)=>{let s=n?Object.assign(n,{async:!1}):{async:!1},a=e._zod.run({value:t,issues:[]},s);if(a instanceof Promise)throw new Ut;if(a.issues.length){let o=new(i?.Err??r)(a.issues.map(u=>br(u,s,Fr())));throw ds(o,i?.callee),o}return a.value},Sn=hw(En),mw=r=>async(e,t,n,i)=>{let s=n?Object.assign(n,{async:!0}):{async:!0},a=e._zod.run({value:t,issues:[]},s);if(a instanceof Promise&&(a=await a),a.issues.length){let o=new(i?.Err??r)(a.issues.map(u=>br(u,s,Fr())));throw ds(o,i?.callee),o}return a.value},gf=mw(En),gw=r=>(e,t,n)=>{let i=n?{...n,async:!1}:{async:!1},s=e._zod.run({value:t,issues:[]},i);if(s instanceof Promise)throw new Ut;return s.issues.length?{success:!1,error:new(r??mf)(s.issues.map(a=>br(a,i,Fr())))}:{success:!0,data:s.value}},_f=gw(En),_w=r=>async(e,t,n)=>{let i=n?Object.assign(n,{async:!0}):{async:!0},s=e._zod.run({value:t,issues:[]},i);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new r(s.issues.map(a=>br(a,i,Fr())))}:{success:!0,data:s.value}},yf=_w(En);var bf={major:4,minor:0,patch:0};var bo=Ft("$ZodType",(r,e)=>{var t;r??(r={}),r._zod.def=e,r._zod.bag=r._zod.bag||{},r._zod.version=bf;let n=[...r._zod.def.checks??[]];r._zod.traits.has("$ZodCheck")&&n.unshift(r);for(let i of n)for(let s of i._zod.onattach)s(r);if(n.length===0)(t=r._zod).deferred??(t.deferred=[]),r._zod.deferred?.push(()=>{r._zod.run=r._zod.parse});else{let i=(s,a,o)=>{let u=xn(s),c;for(let l of a){if(l._zod.def.when){if(!l._zod.def.when(s))continue}else if(u)continue;let d=s.issues.length,f=l._zod.check(s);if(f instanceof Promise&&o?.async===!1)throw new Ut;if(c||f instanceof Promise)c=(c??Promise.resolve()).then(async()=>{await f,s.issues.length!==d&&(u||(u=xn(s,d)))});else{if(s.issues.length===d)continue;u||(u=xn(s,d))}}return c?c.then(()=>s):s};r._zod.run=(s,a)=>{let o=r._zod.parse(s,a);if(o instanceof Promise){if(a.async===!1)throw new Ut;return o.then(u=>i(u,n,a))}return i(o,n,a)}}r["~standard"]={validate:i=>{try{let s=_f(r,i);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return yf(r,i).then(a=>a.success?{value:a.data}:{issues:a.error?.issues})}},vendor:"zod",version:1}});var wf=Ft("$ZodUnknown",(r,e)=>{bo.init(r,e),r._zod.parse=t=>t}),vf=Ft("$ZodNever",(r,e)=>{bo.init(r,e),r._zod.parse=(t,n)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:r}),t)});var xf=Ft("$ZodOptional",(r,e)=>{bo.init(r,e),r._zod.optin="optional",r._zod.optout="optional",ls(r._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),ls(r._zod,"pattern",()=>{let t=e.innerType._zod.pattern;return t?new RegExp(`^(${mo(t.source)})?$`):void 0}),r._zod.parse=(t,n)=>e.innerType._zod.optin==="optional"?e.innerType._zod.run(t,n):t.value===void 0?t:e.innerType._zod.run(t,n)});var kO=Symbol("ZodOutput"),PO=Symbol("ZodInput"),Tn=class{constructor(){this._map=new Map,this._idmap=new Map}add(e,...t){let n=t[0];if(this._map.set(e,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,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&typeof t=="object"&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};return delete n.id,{...n,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}};function yw(){return new Tn}var Le=yw();function Ef(r){return new r({type:"unknown"})}function Sf(r,e){return new r({type:"never",...yo(e)})}var fs=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??Le,this.target=e?.target??"draft-2020-12",this.unrepresentable=e?.unrepresentable??"throw",this.override=e?.override??(()=>{}),this.io=e?.io??"output",this.seen=new Map}process(e,t={path:[],schemaPath:[]}){var n;let i=e._zod.def,s={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},a=this.seen.get(e);if(a)return a.count++,t.schemaPath.includes(e)&&(a.cycle=t.path),a.schema;let o={schema:{},count:1,cycle:void 0,path:t.path};this.seen.set(e,o);let u=e._zod.toJSONSchema?.();if(u)o.schema=u;else{let d={...t,schemaPath:[...t.schemaPath,e],path:t.path},f=e._zod.parent;if(f)o.ref=f,this.process(f,d),this.seen.get(f).isParent=!0;else{let p=o.schema;switch(i.type){case"string":{let h=p;h.type="string";let{minimum:m,maximum:g,format:_,patterns:w,contentEncoding:v}=e._zod.bag;if(typeof m=="number"&&(h.minLength=m),typeof g=="number"&&(h.maxLength=g),_&&(h.format=s[_]??_,h.format===""&&delete h.format),v&&(h.contentEncoding=v),w&&w.size>0){let N=[...w];N.length===1?h.pattern=N[0].source:N.length>1&&(o.schema.allOf=[...N.map(I=>({...this.target==="draft-7"?{type:"string"}:{},pattern:I.source}))])}break}case"number":{let h=p,{minimum:m,maximum:g,format:_,multipleOf:w,exclusiveMaximum:v,exclusiveMinimum:N}=e._zod.bag;typeof _=="string"&&_.includes("int")?h.type="integer":h.type="number",typeof N=="number"&&(h.exclusiveMinimum=N),typeof m=="number"&&(h.minimum=m,typeof N=="number"&&(N>=m?delete h.minimum:delete h.exclusiveMinimum)),typeof v=="number"&&(h.exclusiveMaximum=v),typeof g=="number"&&(h.maximum=g,typeof v=="number"&&(v<=g?delete h.maximum:delete h.exclusiveMaximum)),typeof w=="number"&&(h.multipleOf=w);break}case"boolean":{let h=p;h.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":{p.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":{p.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{let h=p,{minimum:m,maximum:g}=e._zod.bag;typeof m=="number"&&(h.minItems=m),typeof g=="number"&&(h.maxItems=g),h.type="array",h.items=this.process(i.element,{...d,path:[...d.path,"items"]});break}case"object":{let h=p;h.type="object",h.properties={};let m=i.shape;for(let w in m)h.properties[w]=this.process(m[w],{...d,path:[...d.path,"properties",w]});let g=new Set(Object.keys(m)),_=new Set([...g].filter(w=>{let v=i.shape[w]._zod;return this.io==="input"?v.optin===void 0:v.optout===void 0}));_.size>0&&(h.required=Array.from(_)),i.catchall?._zod.def.type==="never"?h.additionalProperties=!1:i.catchall?i.catchall&&(h.additionalProperties=this.process(i.catchall,{...d,path:[...d.path,"additionalProperties"]})):this.io==="output"&&(h.additionalProperties=!1);break}case"union":{let h=p;h.anyOf=i.options.map((m,g)=>this.process(m,{...d,path:[...d.path,"anyOf",g]}));break}case"intersection":{let h=p,m=this.process(i.left,{...d,path:[...d.path,"allOf",0]}),g=this.process(i.right,{...d,path:[...d.path,"allOf",1]}),_=v=>"allOf"in v&&Object.keys(v).length===1,w=[..._(m)?m.allOf:[m],..._(g)?g.allOf:[g]];h.allOf=w;break}case"tuple":{let h=p;h.type="array";let m=i.items.map((w,v)=>this.process(w,{...d,path:[...d.path,"prefixItems",v]}));if(this.target==="draft-2020-12"?h.prefixItems=m:h.items=m,i.rest){let w=this.process(i.rest,{...d,path:[...d.path,"items"]});this.target==="draft-2020-12"?h.items=w:h.additionalItems=w}i.rest&&(h.items=this.process(i.rest,{...d,path:[...d.path,"items"]}));let{minimum:g,maximum:_}=e._zod.bag;typeof g=="number"&&(h.minItems=g),typeof _=="number"&&(h.maxItems=_);break}case"record":{let h=p;h.type="object",h.propertyNames=this.process(i.keyType,{...d,path:[...d.path,"propertyNames"]}),h.additionalProperties=this.process(i.valueType,{...d,path:[...d.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 h=p,m=cs(i.entries);m.every(g=>typeof g=="number")&&(h.type="number"),m.every(g=>typeof g=="string")&&(h.type="string"),h.enum=m;break}case"literal":{let h=p,m=[];for(let g of i.values)if(g===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof g=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");m.push(Number(g))}else m.push(g);if(m.length!==0)if(m.length===1){let g=m[0];h.type=g===null?"null":typeof g,h.const=g}else m.every(g=>typeof g=="number")&&(h.type="number"),m.every(g=>typeof g=="string")&&(h.type="string"),m.every(g=>typeof g=="boolean")&&(h.type="string"),m.every(g=>g===null)&&(h.type="null"),h.enum=m;break}case"file":{let h=p,m={type:"string",format:"binary",contentEncoding:"binary"},{minimum:g,maximum:_,mime:w}=e._zod.bag;g!==void 0&&(m.minLength=g),_!==void 0&&(m.maxLength=_),w?w.length===1?(m.contentMediaType=w[0],Object.assign(h,m)):h.anyOf=w.map(v=>({...m,contentMediaType:v})):Object.assign(h,m);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let h=this.process(i.innerType,d);p.anyOf=[h,{type:"null"}];break}case"nonoptional":{this.process(i.innerType,d),o.ref=i.innerType;break}case"success":{let h=p;h.type="boolean";break}case"default":{this.process(i.innerType,d),o.ref=i.innerType,p.default=JSON.parse(JSON.stringify(i.defaultValue));break}case"prefault":{this.process(i.innerType,d),o.ref=i.innerType,this.io==="input"&&(p._prefault=JSON.parse(JSON.stringify(i.defaultValue)));break}case"catch":{this.process(i.innerType,d),o.ref=i.innerType;let h;try{h=i.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}p.default=h;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let h=p,m=e._zod.pattern;if(!m)throw new Error("Pattern not found in template literal");h.type="string",h.pattern=m.source;break}case"pipe":{let h=this.io==="input"?i.in._zod.def.type==="transform"?i.out:i.in:i.out;this.process(h,d),o.ref=h;break}case"readonly":{this.process(i.innerType,d),o.ref=i.innerType,p.readOnly=!0;break}case"promise":{this.process(i.innerType,d),o.ref=i.innerType;break}case"optional":{this.process(i.innerType,d),o.ref=i.innerType;break}case"lazy":{let h=e._zod.innerType;this.process(h,d),o.ref=h;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}default:}}}let c=this.metadataRegistry.get(e);return c&&Object.assign(o.schema,c),this.io==="input"&&ie(e)&&(delete o.schema.examples,delete o.schema.default),this.io==="input"&&o.schema._prefault&&((n=o.schema).default??(n.default=o.schema._prefault)),delete o.schema._prefault,this.seen.get(e).schema}emit(e,t){let n={cycles:t?.cycles??"ref",reused:t?.reused??"inline",external:t?.external??void 0},i=this.seen.get(e);if(!i)throw new Error("Unprocessed schema. This is a bug in Zod.");let s=l=>{let d=this.target==="draft-2020-12"?"$defs":"definitions";if(n.external){let m=n.external.registry.get(l[0])?.id,g=n.external.uri??(w=>w);if(m)return{ref:g(m)};let _=l[1].defId??l[1].schema.id??`schema${this.counter++}`;return l[1].defId=_,{defId:_,ref:`${g("__shared")}#/${d}/${_}`}}if(l[1]===i)return{ref:"#"};let p=`#/${d}/`,h=l[1].schema.id??`__schema${this.counter++}`;return{defId:h,ref:p+h}},a=l=>{if(l[1].schema.$ref)return;let d=l[1],{ref:f,defId:p}=s(l);d.def={...d.schema},p&&(d.defId=p);let h=d.schema;for(let m in h)delete h[m];h.$ref=f};if(n.cycles==="throw")for(let l of this.seen.entries()){let d=l[1];if(d.cycle)throw new Error(`Cycle detected: #/${d.cycle?.join("/")}/<root>
67
+
68
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let l of this.seen.entries()){let d=l[1];if(e===l[0]){a(l);continue}if(n.external){let p=n.external.registry.get(l[0])?.id;if(e!==l[0]&&p){a(l);continue}}if(this.metadataRegistry.get(l[0])?.id){a(l);continue}if(d.cycle){a(l);continue}if(d.count>1&&n.reused==="ref"){a(l);continue}}let o=(l,d)=>{let f=this.seen.get(l),p=f.def??f.schema,h={...p};if(f.ref===null)return;let m=f.ref;if(f.ref=null,m){o(m,d);let g=this.seen.get(m).schema;g.$ref&&d.target==="draft-7"?(p.allOf=p.allOf??[],p.allOf.push(g)):(Object.assign(p,g),Object.assign(p,h))}f.isParent||this.override({zodSchema:l,jsonSchema:p,path:f.path??[]})};for(let l of[...this.seen.entries()].reverse())o(l[0],{target:this.target});let u={};if(this.target==="draft-2020-12"?u.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?u.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),n.external?.uri){let l=n.external.registry.get(e)?.id;if(!l)throw new Error("Schema is missing an `id` property");u.$id=n.external.uri(l)}Object.assign(u,i.def);let c=n.external?.defs??{};for(let l of this.seen.entries()){let d=l[1];d.def&&d.defId&&(c[d.defId]=d.def)}n.external||Object.keys(c).length>0&&(this.target==="draft-2020-12"?u.$defs=c:u.definitions=c);try{return JSON.parse(JSON.stringify(u))}catch{throw new Error("Error converting schema to JSON.")}}};function wo(r,e){if(r instanceof Tn){let n=new fs(e),i={};for(let o of r._idmap.entries()){let[u,c]=o;n.process(c)}let s={},a={registry:r,uri:e?.uri,defs:i};for(let o of r._idmap.entries()){let[u,c]=o;s[u]=n.emit(c,{...e,external:a})}if(Object.keys(i).length>0){let o=n.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[o]:i}}return{schemas:s}}let t=new fs(e);return t.process(r),t.emit(r,e)}function ie(r,e){let t=e??{seen:new Set};if(t.seen.has(r))return!1;t.seen.add(r);let i=r._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 ie(i.element,t);case"object":{for(let s in i.shape)if(ie(i.shape[s],t))return!0;return!1}case"union":{for(let s of i.options)if(ie(s,t))return!0;return!1}case"intersection":return ie(i.left,t)||ie(i.right,t);case"tuple":{for(let s of i.items)if(ie(s,t))return!0;return!!(i.rest&&ie(i.rest,t))}case"record":return ie(i.keyType,t)||ie(i.valueType,t);case"map":return ie(i.keyType,t)||ie(i.valueType,t);case"set":return ie(i.valueType,t);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return ie(i.innerType,t);case"lazy":return ie(i.getter(),t);case"default":return ie(i.innerType,t);case"prefault":return ie(i.innerType,t);case"custom":return!1;case"transform":return!0;case"pipe":return ie(i.in,t)||ie(i.out,t);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${i.type}`)}var Of=Symbol("Let zodToJsonSchema decide on which parser to use");var Tf={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"},$f=r=>typeof r=="string"?{...Tf,name:r}:{...Tf,...r};var If=r=>{let e=$f(r),t=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:t,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,i])=>[i._def,{def:i._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};function vo(r,e,t,n){n?.errorMessages&&t&&(r.errorMessage={...r.errorMessage,[e]:t})}function V(r,e,t,n,i){r[e]=t,vo(r,e,n,i)}var ps=(r,e)=>{let t=0;for(;t<r.length&&t<e.length&&r[t]===e[t];t++);return[(r.length-t).toString(),...e.slice(t)].join("/")};var n$=Tt;function X(r){if(r.target!=="openAi")return{};let e=[...r.basePath,r.definitionPath,r.openAiAnyTypeName];return r.flags.hasReferencedOpenAiAnyType=!0,{$ref:r.$refStrategy==="relative"?ps(e,r.currentPath):e.join("/")}}function Af(r,e){let t={type:"array"};return r.type?._def&&r.type?._def?.typeName!==b.ZodAny&&(t.items=L(r.type._def,{...e,currentPath:[...e.currentPath,"items"]})),r.minLength&&V(t,"minItems",r.minLength.value,r.minLength.message,e),r.maxLength&&V(t,"maxItems",r.maxLength.value,r.maxLength.message,e),r.exactLength&&(V(t,"minItems",r.exactLength.value,r.exactLength.message,e),V(t,"maxItems",r.exactLength.value,r.exactLength.message,e)),t}function kf(r,e){let t={type:"integer",format:"int64"};if(!r.checks)return t;for(let n of r.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?V(t,"minimum",n.value,n.message,e):V(t,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(t.exclusiveMinimum=!0),V(t,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?V(t,"maximum",n.value,n.message,e):V(t,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(t.exclusiveMaximum=!0),V(t,"maximum",n.value,n.message,e));break;case"multipleOf":V(t,"multipleOf",n.value,n.message,e);break}return t}function Pf(){return{type:"boolean"}}function hs(r,e){return L(r.type._def,e)}var Rf=(r,e)=>L(r.innerType._def,e);function xo(r,e,t){let n=t??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((i,s)=>xo(r,e,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 bw(r,e)}}var bw=(r,e)=>{let t={type:"integer",format:"unix-time"};if(e.target==="openApi3")return t;for(let n of r.checks)switch(n.kind){case"min":V(t,"minimum",n.value,n.message,e);break;case"max":V(t,"maximum",n.value,n.message,e);break}return t};function Nf(r,e){return{...L(r.innerType._def,e),default:r.defaultValue()}}function Cf(r,e){return e.effectStrategy==="input"?L(r.schema._def,e):X(e)}function jf(r){return{type:"string",enum:Array.from(r.values)}}var ww=r=>"type"in r&&r.type==="string"?!1:"allOf"in r;function Lf(r,e){let t=[L(r.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),L(r.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,i=[];return t.forEach(s=>{if(ww(s))i.push(...s.allOf),s.unevaluatedProperties===void 0&&(n=void 0);else{let a=s;if("additionalProperties"in s&&s.additionalProperties===!1){let{additionalProperties:o,...u}=s;a=u}else n=void 0;i.push(a)}}),i.length?{allOf:i,...n}:void 0}function zf(r,e){let t=typeof r.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(r.value)?"array":"object"}:e.target==="openApi3"?{type:t==="bigint"?"integer":t,enum:[r.value]}:{type:t==="bigint"?"integer":t,const:r.value}}var Eo,it={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:()=>(Eo===void 0&&(Eo=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Eo),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 ms(r,e){let t={type:"string"};if(r.checks)for(let n of r.checks)switch(n.kind){case"min":V(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,n.value):n.value,n.message,e);break;case"max":V(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":st(t,"email",n.message,e);break;case"format:idn-email":st(t,"idn-email",n.message,e);break;case"pattern:zod":$e(t,it.email,n.message,e);break}break;case"url":st(t,"uri",n.message,e);break;case"uuid":st(t,"uuid",n.message,e);break;case"regex":$e(t,n.regex,n.message,e);break;case"cuid":$e(t,it.cuid,n.message,e);break;case"cuid2":$e(t,it.cuid2,n.message,e);break;case"startsWith":$e(t,RegExp(`^${So(n.value,e)}`),n.message,e);break;case"endsWith":$e(t,RegExp(`${So(n.value,e)}$`),n.message,e);break;case"datetime":st(t,"date-time",n.message,e);break;case"date":st(t,"date",n.message,e);break;case"time":st(t,"time",n.message,e);break;case"duration":st(t,"duration",n.message,e);break;case"length":V(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,n.value):n.value,n.message,e),V(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,n.value):n.value,n.message,e);break;case"includes":{$e(t,RegExp(So(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&st(t,"ipv4",n.message,e),n.version!=="v4"&&st(t,"ipv6",n.message,e);break}case"base64url":$e(t,it.base64url,n.message,e);break;case"jwt":$e(t,it.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&$e(t,it.ipv4Cidr,n.message,e),n.version!=="v4"&&$e(t,it.ipv6Cidr,n.message,e);break}case"emoji":$e(t,it.emoji(),n.message,e);break;case"ulid":{$e(t,it.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{st(t,"binary",n.message,e);break}case"contentEncoding:base64":{V(t,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{$e(t,it.base64,n.message,e);break}}break}case"nanoid":$e(t,it.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return t}function So(r,e){return e.patternStrategy==="escape"?xw(r):r}var vw=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function xw(r){let e="";for(let t=0;t<r.length;t++)vw.has(r[t])||(e+="\\"),e+=r[t];return e}function st(r,e,t,n){r.format||r.anyOf?.some(i=>i.format)?(r.anyOf||(r.anyOf=[]),r.format&&(r.anyOf.push({format:r.format,...r.errorMessage&&n.errorMessages&&{errorMessage:{format:r.errorMessage.format}}}),delete r.format,r.errorMessage&&(delete r.errorMessage.format,Object.keys(r.errorMessage).length===0&&delete r.errorMessage)),r.anyOf.push({format:e,...t&&n.errorMessages&&{errorMessage:{format:t}}})):V(r,"format",e,t,n)}function $e(r,e,t,n){r.pattern||r.allOf?.some(i=>i.pattern)?(r.allOf||(r.allOf=[]),r.pattern&&(r.allOf.push({pattern:r.pattern,...r.errorMessage&&n.errorMessages&&{errorMessage:{pattern:r.errorMessage.pattern}}}),delete r.pattern,r.errorMessage&&(delete r.errorMessage.pattern,Object.keys(r.errorMessage).length===0&&delete r.errorMessage)),r.allOf.push({pattern:Mf(e,n),...t&&n.errorMessages&&{errorMessage:{pattern:t}}})):V(r,"pattern",Mf(e,n),t,n)}function Mf(r,e){if(!e.applyRegexFlags||!r.flags)return r.source;let t={i:r.flags.includes("i"),m:r.flags.includes("m"),s:r.flags.includes("s")},n=t.i?r.source.toLowerCase():r.source,i="",s=!1,a=!1,o=!1;for(let u=0;u<n.length;u++){if(s){i+=n[u],s=!1;continue}if(t.i){if(a){if(n[u].match(/[a-z]/)){o?(i+=n[u],i+=`${n[u-2]}-${n[u]}`.toUpperCase(),o=!1):n[u+1]==="-"&&n[u+2]?.match(/[a-z]/)?(i+=n[u],o=!0):i+=`${n[u]}${n[u].toUpperCase()}`;continue}}else if(n[u].match(/[a-z]/)){i+=`[${n[u]}${n[u].toUpperCase()}]`;continue}}if(t.m){if(n[u]==="^"){i+=`(^|(?<=[\r
69
+ ]))`;continue}else if(n[u]==="$"){i+=`($|(?=[\r
70
+ ]))`;continue}}if(t.s&&n[u]==="."){i+=a?`${n[u]}\r
71
+ `:`[${n[u]}\r
72
+ ]`;continue}i+=n[u],n[u]==="\\"?s=!0:a&&n[u]==="]"?a=!1:!a&&n[u]==="["&&(a=!0)}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),r.source}return i}function gs(r,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&r.keyType?._def.typeName===b.ZodEnum)return{type:"object",required:r.keyType._def.values,properties:r.keyType._def.values.reduce((n,i)=>({...n,[i]:L(r.valueType._def,{...e,currentPath:[...e.currentPath,"properties",i]})??X(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let t={type:"object",additionalProperties:L(r.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return t;if(r.keyType?._def.typeName===b.ZodString&&r.keyType._def.checks?.length){let{type:n,...i}=ms(r.keyType._def,e);return{...t,propertyNames:i}}else{if(r.keyType?._def.typeName===b.ZodEnum)return{...t,propertyNames:{enum:r.keyType._def.values}};if(r.keyType?._def.typeName===b.ZodBranded&&r.keyType._def.type._def.typeName===b.ZodString&&r.keyType._def.type._def.checks?.length){let{type:n,...i}=hs(r.keyType._def,e);return{...t,propertyNames:i}}}return t}function Df(r,e){if(e.mapStrategy==="record")return gs(r,e);let t=L(r.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||X(e),n=L(r.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||X(e);return{type:"array",maxItems:125,items:{type:"array",items:[t,n],minItems:2,maxItems:2}}}function Uf(r){let e=r.values,n=Object.keys(r.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[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 Ff(r){return r.target==="openAi"?void 0:{not:X({...r,currentPath:[...r.currentPath,"not"]})}}function Zf(r){return r.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var On={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Gf(r,e){if(e.target==="openApi3")return Bf(r,e);let t=r.options instanceof Map?Array.from(r.options.values()):r.options;if(t.every(n=>n._def.typeName in On&&(!n._def.checks||!n._def.checks.length))){let n=t.reduce((i,s)=>{let a=On[s._def.typeName];return a&&!i.includes(a)?[...i,a]:i},[]);return{type:n.length>1?n:n[0]}}else if(t.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=t.reduce((i,s)=>{let a=typeof s._def.value;switch(a){case"string":case"number":case"boolean":return[...i,a];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===t.length){let i=n.filter((s,a,o)=>o.indexOf(s)===a);return{type:i.length>1?i:i[0],enum:t.reduce((s,a)=>s.includes(a._def.value)?s:[...s,a._def.value],[])}}}else if(t.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:t.reduce((n,i)=>[...n,...i._def.values.filter(s=>!n.includes(s))],[])};return Bf(r,e)}var Bf=(r,e)=>{let t=(r.options instanceof Map?Array.from(r.options.values()):r.options).map((n,i)=>L(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${i}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return t.length?{anyOf:t}:void 0};function qf(r,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(r.innerType._def.typeName)&&(!r.innerType._def.checks||!r.innerType._def.checks.length))return e.target==="openApi3"?{type:On[r.innerType._def.typeName],nullable:!0}:{type:[On[r.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=L(r.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let t=L(r.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return t&&{anyOf:[t,{type:"null"}]}}function Vf(r,e){let t={type:"number"};if(!r.checks)return t;for(let n of r.checks)switch(n.kind){case"int":t.type="integer",vo(t,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?V(t,"minimum",n.value,n.message,e):V(t,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(t.exclusiveMinimum=!0),V(t,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?V(t,"maximum",n.value,n.message,e):V(t,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(t.exclusiveMaximum=!0),V(t,"maximum",n.value,n.message,e));break;case"multipleOf":V(t,"multipleOf",n.value,n.message,e);break}return t}function Hf(r,e){let t=e.target==="openAi",n={type:"object",properties:{}},i=[],s=r.shape();for(let o in s){let u=s[o];if(u===void 0||u._def===void 0)continue;let c=Sw(u);c&&t&&(u._def.typeName==="ZodOptional"&&(u=u._def.innerType),u.isNullable()||(u=u.nullable()),c=!1);let l=L(u._def,{...e,currentPath:[...e.currentPath,"properties",o],propertyPath:[...e.currentPath,"properties",o]});l!==void 0&&(n.properties[o]=l,c||i.push(o))}i.length&&(n.required=i);let a=Ew(r,e);return a!==void 0&&(n.additionalProperties=a),n}function Ew(r,e){if(r.catchall._def.typeName!=="ZodNever")return L(r.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(r.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function Sw(r){try{return r.isOptional()}catch{return!0}}var Jf=(r,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return L(r.innerType._def,e);let t=L(r.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return t?{anyOf:[{not:X(e)},t]}:X(e)};var Kf=(r,e)=>{if(e.pipeStrategy==="input")return L(r.in._def,e);if(e.pipeStrategy==="output")return L(r.out._def,e);let t=L(r.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=L(r.out._def,{...e,currentPath:[...e.currentPath,"allOf",t?"1":"0"]});return{allOf:[t,n].filter(i=>i!==void 0)}};function Wf(r,e){return L(r.type._def,e)}function Yf(r,e){let n={type:"array",uniqueItems:!0,items:L(r.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return r.minSize&&V(n,"minItems",r.minSize.value,r.minSize.message,e),r.maxSize&&V(n,"maxItems",r.maxSize.value,r.maxSize.message,e),n}function Xf(r,e){return r.rest?{type:"array",minItems:r.items.length,items:r.items.map((t,n)=>L(t._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((t,n)=>n===void 0?t:[...t,n],[]),additionalItems:L(r.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:r.items.length,maxItems:r.items.length,items:r.items.map((t,n)=>L(t._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((t,n)=>n===void 0?t:[...t,n],[])}}function Qf(r){return{not:X(r)}}function ep(r){return X(r)}var tp=(r,e)=>L(r.innerType._def,e);var rp=(r,e,t)=>{switch(e){case b.ZodString:return ms(r,t);case b.ZodNumber:return Vf(r,t);case b.ZodObject:return Hf(r,t);case b.ZodBigInt:return kf(r,t);case b.ZodBoolean:return Pf();case b.ZodDate:return xo(r,t);case b.ZodUndefined:return Qf(t);case b.ZodNull:return Zf(t);case b.ZodArray:return Af(r,t);case b.ZodUnion:case b.ZodDiscriminatedUnion:return Gf(r,t);case b.ZodIntersection:return Lf(r,t);case b.ZodTuple:return Xf(r,t);case b.ZodRecord:return gs(r,t);case b.ZodLiteral:return zf(r,t);case b.ZodEnum:return jf(r);case b.ZodNativeEnum:return Uf(r);case b.ZodNullable:return qf(r,t);case b.ZodOptional:return Jf(r,t);case b.ZodMap:return Df(r,t);case b.ZodSet:return Yf(r,t);case b.ZodLazy:return()=>r.getter()._def;case b.ZodPromise:return Wf(r,t);case b.ZodNaN:case b.ZodNever:return Ff(t);case b.ZodEffects:return Cf(r,t);case b.ZodAny:return X(t);case b.ZodUnknown:return ep(t);case b.ZodDefault:return Nf(r,t);case b.ZodBranded:return hs(r,t);case b.ZodReadonly:return tp(r,t);case b.ZodCatch:return Rf(r,t);case b.ZodPipeline:return Kf(r,t);case b.ZodFunction:case b.ZodVoid:case b.ZodSymbol:return;default:return(n=>{})(e)}};function L(r,e,t=!1){let n=e.seen.get(r);if(e.override){let o=e.override?.(r,e,n,t);if(o!==Of)return o}if(n&&!t){let o=Tw(n,e);if(o!==void 0)return o}let i={def:r,path:e.currentPath,jsonSchema:void 0};e.seen.set(r,i);let s=rp(r,r.typeName,e),a=typeof s=="function"?L(s(),e):s;if(a&&Ow(r,e,a),e.postProcess){let o=e.postProcess(a,r,e);return i.jsonSchema=a,o}return i.jsonSchema=a,a}var Tw=(r,e)=>{switch(e.$refStrategy){case"root":return{$ref:r.path.join("/")};case"relative":return{$ref:ps(e.currentPath,r.path)};case"none":case"seen":return r.path.length<e.currentPath.length&&r.path.every((t,n)=>e.currentPath[n]===t)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),X(e)):e.$refStrategy==="seen"?X(e):void 0}},Ow=(r,e,t)=>(r.description&&(t.description=r.description,e.markdownDescription&&(t.markdownDescription=r.description)),t);var To=(r,e)=>{let t=If(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((u,[c,l])=>({...u,[c]:L(l._def,{...t,currentPath:[...t.basePath,t.definitionPath,c]},!0)??X(t)}),{}):void 0,i=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=L(r._def,i===void 0?t:{...t,currentPath:[...t.basePath,t.definitionPath,i]},!1)??X(t),a=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;a!==void 0&&(s.title=a),t.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[t.openAiAnyTypeName]||(n[t.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:t.$refStrategy==="relative"?"1":[...t.basePath,t.definitionPath,t.openAiAnyTypeName].join("/")}}));let o=i===void 0?n?{...s,[t.definitionPath]:n}:s:{$ref:[...t.$refStrategy==="relative"?[]:t.basePath,t.definitionPath,i].join("/"),[t.definitionPath]:{...n,[i]:s}};return t.target==="jsonSchema7"?o.$schema="http://json-schema.org/draft-07/schema#":(t.target==="jsonSchema2019-09"||t.target==="openAi")&&(o.$schema="https://json-schema.org/draft/2019-09/schema#"),t.target==="openAi"&&("anyOf"in o||"oneOf"in o||"allOf"in o||"type"in o&&Array.isArray(o.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),o};function Zt(r,e){let t=typeof r;if(t!==typeof e)return!1;if(Array.isArray(r)){if(!Array.isArray(e))return!1;let n=r.length;if(n!==e.length)return!1;for(let i=0;i<n;i++)if(!Zt(r[i],e[i]))return!1;return!0}if(t==="object"){if(!r||!e)return r===e;let n=Object.keys(r),i=Object.keys(e);if(n.length!==i.length)return!1;for(let a of n)if(!Zt(r[a],e[a]))return!1;return!0}return r===e}function Fe(r){return encodeURI($w(r))}function $w(r){return r.replace(/~/g,"~0").replace(/\//g,"~1")}var Iw={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},Aw={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},kw={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},Pw=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 at(r,e=Object.create(null),t=Pw,n=""){if(r&&typeof r=="object"&&!Array.isArray(r)){let s=r.$id||r.id;if(s){let a=new URL(s,t.href);a.hash.length>1?e[a.href]=r:(a.hash="",n===""?t=a:at(r,e,t))}}else if(r!==!0&&r!==!1)return e;let i=t.href+(n?"#"+n:"");if(e[i]!==void 0)throw new Error(`Duplicate schema URI "${i}".`);if(e[i]=r,r===!0||r===!1)return e;if(r.__absolute_uri__===void 0&&Object.defineProperty(r,"__absolute_uri__",{enumerable:!1,value:i}),r.$ref&&r.__absolute_ref__===void 0){let s=new URL(r.$ref,t.href);s.hash=s.hash,Object.defineProperty(r,"__absolute_ref__",{enumerable:!1,value:s.href})}if(r.$recursiveRef&&r.__absolute_recursive_ref__===void 0){let s=new URL(r.$recursiveRef,t.href);s.hash=s.hash,Object.defineProperty(r,"__absolute_recursive_ref__",{enumerable:!1,value:s.href})}if(r.$anchor){let s=new URL("#"+r.$anchor,t.href);e[s.href]=r}for(let s in r){if(kw[s])continue;let a=`${n}/${Fe(s)}`,o=r[s];if(Array.isArray(o)){if(Iw[s]){let u=o.length;for(let c=0;c<u;c++)at(o[c],e,t,`${a}/${c}`)}}else if(Aw[s])for(let u in o)at(o[u],e,t,`${a}/${Fe(u)}`);else at(o,e,t,a)}return e}var Rw=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Nw=[0,31,28,31,30,31,30,31,31,30,31,30,31],Cw=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,jw=/^(?=.{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,Lw=/^(?:[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,zw=/^(?:(?:[^\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,Mw=/^(?:(?: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,Dw=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,Uw=/^(?:\/(?:[^~/]|~0|~1)*)*$/,Fw=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,Zw=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,Bw=r=>{if(r[0]==='"')return!1;let[e,t,...n]=r.split("@");return!e||!t||n.length!==0||e.length>64||t.length>253||e[0]==="."||e.endsWith(".")||e.includes("..")||!/^[a-z0-9.-]+$/i.test(t)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(e)?!1:t.split(".").every(i=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(i))},Gw=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,qw=/^((([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,Vw=r=>r.length>1&&r.length<80&&(/^P\d+([.,]\d+)?W$/.test(r)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(r)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(r));function gt(r){return r.test.bind(r)}var Oo={date:np,time:ip.bind(void 0,!1),"date-time":Kw,duration:Vw,uri:Xw,"uri-reference":gt(Lw),"uri-template":gt(zw),url:gt(Mw),email:Bw,hostname:gt(jw),ipv4:gt(Gw),ipv6:gt(qw),regex:ev,uuid:gt(Dw),"json-pointer":gt(Uw),"json-pointer-uri-fragment":gt(Fw),"relative-json-pointer":gt(Zw)};function Hw(r){return r%4===0&&(r%100!==0||r%400===0)}function np(r){let e=r.match(Rw);if(!e)return!1;let t=+e[1],n=+e[2],i=+e[3];return n>=1&&n<=12&&i>=1&&i<=(n==2&&Hw(t)?29:Nw[n])}function ip(r,e){let t=e.match(Cw);if(!t)return!1;let n=+t[1],i=+t[2],s=+t[3],a=!!t[5];return(n<=23&&i<=59&&s<=59||n==23&&i==59&&s==60)&&(!r||a)}var Jw=/t|\s/i;function Kw(r){let e=r.split(Jw);return e.length==2&&np(e[0])&&ip(!0,e[1])}var Ww=/\/|:/,Yw=/^(?:[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 Xw(r){return Ww.test(r)&&Yw.test(r)}var Qw=/[^\\]\\Z/;function ev(r){if(Qw.test(r))return!1;try{return new RegExp(r,"u"),!0}catch{return!1}}var sp;(function(r){r[r.Flag=1]="Flag",r[r.Basic=2]="Basic",r[r.Detailed=4]="Detailed"})(sp||(sp={}));function ap(r){let e=0,t=r.length,n=0,i;for(;n<t;)e++,i=r.charCodeAt(n++),i>=55296&&i<=56319&&n<t&&(i=r.charCodeAt(n),(i&64512)==56320&&n++);return e}function Q(r,e,t="2019-09",n=at(e),i=!0,s=null,a="#",o="#",u=Object.create(null)){if(e===!0)return{valid:!0,errors:[]};if(e===!1)return{valid:!1,errors:[{instanceLocation:a,keyword:"false",keywordLocation:a,error:"False boolean schema."}]};let c=typeof r,l;switch(c){case"boolean":case"number":case"string":l=c;break;case"object":r===null?l="null":Array.isArray(r)?l="array":l="object";break;default:throw new Error(`Instances of "${c}" type are not supported.`)}let{$ref:d,$recursiveRef:f,$recursiveAnchor:p,type:h,const:m,enum:g,required:_,not:w,anyOf:v,allOf:N,oneOf:I,if:H,then:K,else:J,format:ce,properties:ze,patternProperties:yt,additionalProperties:Bt,unevaluatedProperties:Uo,minProperties:As,maxProperties:ks,propertyNames:Fo,dependentRequired:Ps,dependentSchemas:Rs,dependencies:Ns,prefixItems:Cs,items:Hr,additionalItems:Zo,unevaluatedItems:Bo,contains:Go,minContains:bt,maxContains:kn,minItems:js,maxItems:Ls,uniqueItems:Op,minimum:Gt,maximum:qt,exclusiveMinimum:Jr,exclusiveMaximum:Kr,multipleOf:Pn,minLength:Rn,maxLength:Nn,pattern:qo,__absolute_ref__:Cn,__absolute_recursive_ref__:$p}=e,$=[];if(p===!0&&s===null&&(s=e),f==="#"){let z=s===null?n[$p]:s,C=`${o}/$recursiveRef`,U=Q(r,s===null?e:s,t,n,i,z,a,C,u);U.valid||$.push({instanceLocation:a,keyword:"$recursiveRef",keywordLocation:C,error:"A subschema had errors."},...U.errors)}if(d!==void 0){let C=n[Cn||d];if(C===void 0){let E=`Unresolved $ref "${d}".`;throw Cn&&Cn!==d&&(E+=` Absolute URI "${Cn}".`),E+=`
73
+ Known schemas:
74
+ - ${Object.keys(n).join(`
75
+ - `)}`,new Error(E)}let U=`${o}/$ref`,A=Q(r,C,t,n,i,s,a,U,u);if(A.valid||$.push({instanceLocation:a,keyword:"$ref",keywordLocation:U,error:"A subschema had errors."},...A.errors),t==="4"||t==="7")return{valid:$.length===0,errors:$}}if(Array.isArray(h)){let z=h.length,C=!1;for(let U=0;U<z;U++)if(l===h[U]||h[U]==="integer"&&l==="number"&&r%1===0&&r===r){C=!0;break}C||$.push({instanceLocation:a,keyword:"type",keywordLocation:`${o}/type`,error:`Instance type "${l}" is invalid. Expected "${h.join('", "')}".`})}else h==="integer"?(l!=="number"||r%1||r!==r)&&$.push({instanceLocation:a,keyword:"type",keywordLocation:`${o}/type`,error:`Instance type "${l}" is invalid. Expected "${h}".`}):h!==void 0&&l!==h&&$.push({instanceLocation:a,keyword:"type",keywordLocation:`${o}/type`,error:`Instance type "${l}" is invalid. Expected "${h}".`});if(m!==void 0&&(l==="object"||l==="array"?Zt(r,m)||$.push({instanceLocation:a,keyword:"const",keywordLocation:`${o}/const`,error:`Instance does not match ${JSON.stringify(m)}.`}):r!==m&&$.push({instanceLocation:a,keyword:"const",keywordLocation:`${o}/const`,error:`Instance does not match ${JSON.stringify(m)}.`})),g!==void 0&&(l==="object"||l==="array"?g.some(z=>Zt(r,z))||$.push({instanceLocation:a,keyword:"enum",keywordLocation:`${o}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`}):g.some(z=>r===z)||$.push({instanceLocation:a,keyword:"enum",keywordLocation:`${o}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`})),w!==void 0){let z=`${o}/not`;Q(r,w,t,n,i,s,a,z).valid&&$.push({instanceLocation:a,keyword:"not",keywordLocation:z,error:'Instance matched "not" schema.'})}let jn=[];if(v!==void 0){let z=`${o}/anyOf`,C=$.length,U=!1;for(let A=0;A<v.length;A++){let E=v[A],D=Object.create(u),M=Q(r,E,t,n,i,p===!0?s:null,a,`${z}/${A}`,D);$.push(...M.errors),U=U||M.valid,M.valid&&jn.push(D)}U?$.length=C:$.splice(C,0,{instanceLocation:a,keyword:"anyOf",keywordLocation:z,error:"Instance does not match any subschemas."})}if(N!==void 0){let z=`${o}/allOf`,C=$.length,U=!0;for(let A=0;A<N.length;A++){let E=N[A],D=Object.create(u),M=Q(r,E,t,n,i,p===!0?s:null,a,`${z}/${A}`,D);$.push(...M.errors),U=U&&M.valid,M.valid&&jn.push(D)}U?$.length=C:$.splice(C,0,{instanceLocation:a,keyword:"allOf",keywordLocation:z,error:"Instance does not match every subschema."})}if(I!==void 0){let z=`${o}/oneOf`,C=$.length,U=I.filter((A,E)=>{let D=Object.create(u),M=Q(r,A,t,n,i,p===!0?s:null,a,`${z}/${E}`,D);return $.push(...M.errors),M.valid&&jn.push(D),M.valid}).length;U===1?$.length=C:$.splice(C,0,{instanceLocation:a,keyword:"oneOf",keywordLocation:z,error:`Instance does not match exactly one subschema (${U} matches).`})}if((l==="object"||l==="array")&&Object.assign(u,...jn),H!==void 0){let z=`${o}/if`;if(Q(r,H,t,n,i,s,a,z,u).valid){if(K!==void 0){let U=Q(r,K,t,n,i,s,a,`${o}/then`,u);U.valid||$.push({instanceLocation:a,keyword:"if",keywordLocation:z,error:'Instance does not match "then" schema.'},...U.errors)}}else if(J!==void 0){let U=Q(r,J,t,n,i,s,a,`${o}/else`,u);U.valid||$.push({instanceLocation:a,keyword:"if",keywordLocation:z,error:'Instance does not match "else" schema.'},...U.errors)}}if(l==="object"){if(_!==void 0)for(let A of _)A in r||$.push({instanceLocation:a,keyword:"required",keywordLocation:`${o}/required`,error:`Instance does not have required property "${A}".`});let z=Object.keys(r);if(As!==void 0&&z.length<As&&$.push({instanceLocation:a,keyword:"minProperties",keywordLocation:`${o}/minProperties`,error:`Instance does not have at least ${As} properties.`}),ks!==void 0&&z.length>ks&&$.push({instanceLocation:a,keyword:"maxProperties",keywordLocation:`${o}/maxProperties`,error:`Instance does not have at least ${ks} properties.`}),Fo!==void 0){let A=`${o}/propertyNames`;for(let E in r){let D=`${a}/${Fe(E)}`,M=Q(E,Fo,t,n,i,s,D,A);M.valid||$.push({instanceLocation:a,keyword:"propertyNames",keywordLocation:A,error:`Property name "${E}" does not match schema.`},...M.errors)}}if(Ps!==void 0){let A=`${o}/dependantRequired`;for(let E in Ps)if(E in r){let D=Ps[E];for(let M of D)M in r||$.push({instanceLocation:a,keyword:"dependentRequired",keywordLocation:A,error:`Instance has "${E}" but does not have "${M}".`})}}if(Rs!==void 0)for(let A in Rs){let E=`${o}/dependentSchemas`;if(A in r){let D=Q(r,Rs[A],t,n,i,s,a,`${E}/${Fe(A)}`,u);D.valid||$.push({instanceLocation:a,keyword:"dependentSchemas",keywordLocation:E,error:`Instance has "${A}" but does not match dependant schema.`},...D.errors)}}if(Ns!==void 0){let A=`${o}/dependencies`;for(let E in Ns)if(E in r){let D=Ns[E];if(Array.isArray(D))for(let M of D)M in r||$.push({instanceLocation:a,keyword:"dependencies",keywordLocation:A,error:`Instance has "${E}" but does not have "${M}".`});else{let M=Q(r,D,t,n,i,s,a,`${A}/${Fe(E)}`);M.valid||$.push({instanceLocation:a,keyword:"dependencies",keywordLocation:A,error:`Instance has "${E}" but does not match dependant schema.`},...M.errors)}}}let C=Object.create(null),U=!1;if(ze!==void 0){let A=`${o}/properties`;for(let E in ze){if(!(E in r))continue;let D=`${a}/${Fe(E)}`,M=Q(r[E],ze[E],t,n,i,s,D,`${A}/${Fe(E)}`);if(M.valid)u[E]=C[E]=!0;else if(U=i,$.push({instanceLocation:a,keyword:"properties",keywordLocation:A,error:`Property "${E}" does not match schema.`},...M.errors),U)break}}if(!U&&yt!==void 0){let A=`${o}/patternProperties`;for(let E in yt){let D=new RegExp(E,"u"),M=yt[E];for(let Ae in r){if(!D.test(Ae))continue;let Vo=`${a}/${Fe(Ae)}`,Ho=Q(r[Ae],M,t,n,i,s,Vo,`${A}/${Fe(E)}`);Ho.valid?u[Ae]=C[Ae]=!0:(U=i,$.push({instanceLocation:a,keyword:"patternProperties",keywordLocation:A,error:`Property "${Ae}" matches pattern "${E}" but does not match associated schema.`},...Ho.errors))}}}if(!U&&Bt!==void 0){let A=`${o}/additionalProperties`;for(let E in r){if(C[E])continue;let D=`${a}/${Fe(E)}`,M=Q(r[E],Bt,t,n,i,s,D,A);M.valid?u[E]=!0:(U=i,$.push({instanceLocation:a,keyword:"additionalProperties",keywordLocation:A,error:`Property "${E}" does not match additional properties schema.`},...M.errors))}}else if(!U&&Uo!==void 0){let A=`${o}/unevaluatedProperties`;for(let E in r)if(!u[E]){let D=`${a}/${Fe(E)}`,M=Q(r[E],Uo,t,n,i,s,D,A);M.valid?u[E]=!0:$.push({instanceLocation:a,keyword:"unevaluatedProperties",keywordLocation:A,error:`Property "${E}" does not match unevaluated properties schema.`},...M.errors)}}}else if(l==="array"){Ls!==void 0&&r.length>Ls&&$.push({instanceLocation:a,keyword:"maxItems",keywordLocation:`${o}/maxItems`,error:`Array has too many items (${r.length} > ${Ls}).`}),js!==void 0&&r.length<js&&$.push({instanceLocation:a,keyword:"minItems",keywordLocation:`${o}/minItems`,error:`Array has too few items (${r.length} < ${js}).`});let z=r.length,C=0,U=!1;if(Cs!==void 0){let A=`${o}/prefixItems`,E=Math.min(Cs.length,z);for(;C<E;C++){let D=Q(r[C],Cs[C],t,n,i,s,`${a}/${C}`,`${A}/${C}`);if(u[C]=!0,!D.valid&&(U=i,$.push({instanceLocation:a,keyword:"prefixItems",keywordLocation:A,error:"Items did not match schema."},...D.errors),U))break}}if(Hr!==void 0){let A=`${o}/items`;if(Array.isArray(Hr)){let E=Math.min(Hr.length,z);for(;C<E;C++){let D=Q(r[C],Hr[C],t,n,i,s,`${a}/${C}`,`${A}/${C}`);if(u[C]=!0,!D.valid&&(U=i,$.push({instanceLocation:a,keyword:"items",keywordLocation:A,error:"Items did not match schema."},...D.errors),U))break}}else for(;C<z;C++){let E=Q(r[C],Hr,t,n,i,s,`${a}/${C}`,A);if(u[C]=!0,!E.valid&&(U=i,$.push({instanceLocation:a,keyword:"items",keywordLocation:A,error:"Items did not match schema."},...E.errors),U))break}if(!U&&Zo!==void 0){let E=`${o}/additionalItems`;for(;C<z;C++){let D=Q(r[C],Zo,t,n,i,s,`${a}/${C}`,E);u[C]=!0,D.valid||(U=i,$.push({instanceLocation:a,keyword:"additionalItems",keywordLocation:E,error:"Items did not match additional items schema."},...D.errors))}}}if(Go!==void 0)if(z===0&&bt===void 0)$.push({instanceLocation:a,keyword:"contains",keywordLocation:`${o}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(bt!==void 0&&z<bt)$.push({instanceLocation:a,keyword:"minContains",keywordLocation:`${o}/minContains`,error:`Array has less items (${z}) than minContains (${bt}).`});else{let A=`${o}/contains`,E=$.length,D=0;for(let M=0;M<z;M++){let Ae=Q(r[M],Go,t,n,i,s,`${a}/${M}`,A);Ae.valid?(u[M]=!0,D++):$.push(...Ae.errors)}D>=(bt||0)&&($.length=E),bt===void 0&&kn===void 0&&D===0?$.splice(E,0,{instanceLocation:a,keyword:"contains",keywordLocation:A,error:"Array does not contain item matching schema."}):bt!==void 0&&D<bt?$.push({instanceLocation:a,keyword:"minContains",keywordLocation:`${o}/minContains`,error:`Array must contain at least ${bt} items matching schema. Only ${D} items were found.`}):kn!==void 0&&D>kn&&$.push({instanceLocation:a,keyword:"maxContains",keywordLocation:`${o}/maxContains`,error:`Array may contain at most ${kn} items matching schema. ${D} items were found.`})}if(!U&&Bo!==void 0){let A=`${o}/unevaluatedItems`;for(C;C<z;C++){if(u[C])continue;let E=Q(r[C],Bo,t,n,i,s,`${a}/${C}`,A);u[C]=!0,E.valid||$.push({instanceLocation:a,keyword:"unevaluatedItems",keywordLocation:A,error:"Items did not match unevaluated items schema."},...E.errors)}}if(Op)for(let A=0;A<z;A++){let E=r[A],D=typeof E=="object"&&E!==null;for(let M=0;M<z;M++){if(A===M)continue;let Ae=r[M];(E===Ae||D&&(typeof Ae=="object"&&Ae!==null)&&Zt(E,Ae))&&($.push({instanceLocation:a,keyword:"uniqueItems",keywordLocation:`${o}/uniqueItems`,error:`Duplicate items at indexes ${A} and ${M}.`}),A=Number.MAX_SAFE_INTEGER,M=Number.MAX_SAFE_INTEGER)}}}else if(l==="number"){if(t==="4"?(Gt!==void 0&&(Jr===!0&&r<=Gt||r<Gt)&&$.push({instanceLocation:a,keyword:"minimum",keywordLocation:`${o}/minimum`,error:`${r} is less than ${Jr?"or equal to ":""} ${Gt}.`}),qt!==void 0&&(Kr===!0&&r>=qt||r>qt)&&$.push({instanceLocation:a,keyword:"maximum",keywordLocation:`${o}/maximum`,error:`${r} is greater than ${Kr?"or equal to ":""} ${qt}.`})):(Gt!==void 0&&r<Gt&&$.push({instanceLocation:a,keyword:"minimum",keywordLocation:`${o}/minimum`,error:`${r} is less than ${Gt}.`}),qt!==void 0&&r>qt&&$.push({instanceLocation:a,keyword:"maximum",keywordLocation:`${o}/maximum`,error:`${r} is greater than ${qt}.`}),Jr!==void 0&&r<=Jr&&$.push({instanceLocation:a,keyword:"exclusiveMinimum",keywordLocation:`${o}/exclusiveMinimum`,error:`${r} is less than ${Jr}.`}),Kr!==void 0&&r>=Kr&&$.push({instanceLocation:a,keyword:"exclusiveMaximum",keywordLocation:`${o}/exclusiveMaximum`,error:`${r} is greater than or equal to ${Kr}.`})),Pn!==void 0){let z=r%Pn;Math.abs(0-z)>=11920929e-14&&Math.abs(Pn-z)>=11920929e-14&&$.push({instanceLocation:a,keyword:"multipleOf",keywordLocation:`${o}/multipleOf`,error:`${r} is not a multiple of ${Pn}.`})}}else if(l==="string"){let z=Rn===void 0&&Nn===void 0?0:ap(r);Rn!==void 0&&z<Rn&&$.push({instanceLocation:a,keyword:"minLength",keywordLocation:`${o}/minLength`,error:`String is too short (${z} < ${Rn}).`}),Nn!==void 0&&z>Nn&&$.push({instanceLocation:a,keyword:"maxLength",keywordLocation:`${o}/maxLength`,error:`String is too long (${z} > ${Nn}).`}),qo!==void 0&&!new RegExp(qo,"u").test(r)&&$.push({instanceLocation:a,keyword:"pattern",keywordLocation:`${o}/pattern`,error:"String does not match pattern."}),ce!==void 0&&Oo[ce]&&!Oo[ce](r)&&$.push({instanceLocation:a,keyword:"format",keywordLocation:`${o}/format`,error:`String does not match format "${ce}".`})}return{valid:$.length===0,errors:$}}var _s=class{schema;draft;shortCircuit;lookup;constructor(e,t="2019-09",n=!0){this.schema=e,this.draft=t,this.shortCircuit=n,this.lookup=at(e)}validate(e){return Q(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,t){t&&(e={...e,$id:t}),at(e,this.lookup)}};function se(r){if(typeof r!="object"||r===null)return!1;let e=r;if(!("_zod"in e))return!1;let t=e._zod;return typeof t=="object"&&t!==null&&"def"in t}function ae(r){if(typeof r!="object"||r===null)return!1;let e=r;if(!("_def"in e)||"_zod"in e)return!1;let t=e._def;return typeof t=="object"&&t!=null&&"typeName"in t}function yk(r){return se(r)&&console.warn("[WARNING] Attempting to use Zod 4 schema in a context where Zod 3 schema is expected. This may cause unexpected behavior."),ae(r)}function up(r){return!r||typeof r!="object"||Array.isArray(r)?!1:!!(se(r)||ae(r))}async function bk(r,e){if(se(r))try{return{success:!0,data:await gf(r,e)}}catch(t){return{success:!1,error:t}}if(ae(r))return r.safeParse(e);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}async function cp(r,e){if(se(r))return Sn(r,e);if(ae(r))return r.parse(e);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function wk(r,e){if(se(r))try{return{success:!0,data:Sn(r,e)}}catch(t){return{success:!1,error:t}}if(ae(r))return r.safeParse(e);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function vk(r,e){if(se(r))return Sn(r,e);if(ae(r))return r.parse(e);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function lp(r){if(se(r))return Le.get(r)?.description;if(ae(r)||"description"in r&&typeof r.description=="string")return r.description}function xk(r){if(!up(r))return!1;if(ae(r)){let e=r._def;if(e.typeName==="ZodObject"){let t=r;return!t.shape||Object.keys(t.shape).length===0}if(e.typeName==="ZodRecord")return!0}if(se(r)){let e=r._zod.def;if(e.type==="object"){let t=r;return!t.shape||Object.keys(t.shape).length===0}if(e.type==="record")return!0}return typeof r=="object"&&r!==null&&!("shape"in r)}function dp(r){return up(r)?ae(r)?r._def.typeName==="ZodString":se(r)?r._zod.def.type==="string":!1:!1}function fp(r){return typeof r=="object"&&r!==null&&"_def"in r&&typeof r._def=="object"&&r._def!==null&&"typeName"in r._def&&r._def.typeName==="ZodObject"}function _t(r){return se(r)?typeof r=="object"&&r!==null&&"_zod"in r&&typeof r._zod=="object"&&r._zod!==null&&"def"in r._zod&&typeof r._zod.def=="object"&&r._zod.def!==null&&"type"in r._zod.def&&r._zod.def.type==="object":!1}function $o(r){return se(r)?typeof r=="object"&&r!==null&&"_zod"in r&&typeof r._zod=="object"&&r._zod!==null&&"def"in r._zod&&typeof r._zod.def=="object"&&r._zod.def!==null&&"type"in r._zod.def&&r._zod.def.type==="array":!1}function Ek(r){return!!(fp(r)||_t(r))}function Sk(r){if(ae(r))return r.shape;if(se(r))return r._zod.def.shape;throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Tk(r,e){if(ae(r))return r.extend(e);if(se(r))return At.extend(r,e);throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Ok(r){if(ae(r))return r.partial();if(se(r))return At.partial(xf,r,void 0);throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function ys(r,e=!1){if(ae(r))return r.strict();if(_t(r)){let t=r._zod.def.shape;if(e)for(let[s,a]of Object.entries(r._zod.def.shape)){if(_t(a)){let u=ys(a,e);t[s]=u}else if($o(a)){let u=a._zod.def.element;_t(u)&&(u=ys(u,e)),t[s]=Oe(a,{...a._zod.def,element:u})}else t[s]=a;let o=Le.get(a);o&&Le.add(t[s],o)}let n=Oe(r,{...r._zod.def,shape:t,catchall:Sf(vf)}),i=Le.get(r);return i&&Le.add(n,i),n}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function op(r,e=!1){if(fp(r))return r.passthrough();if(_t(r)){let t=r._zod.def.shape;if(e)for(let[s,a]of Object.entries(r._zod.def.shape)){if(_t(a)){let u=op(a,e);t[s]=u}else if($o(a)){let u=a._zod.def.element;_t(u)&&(u=op(u,e)),t[s]=Oe(a,{...a._zod.def,element:u})}else t[s]=a;let o=Le.get(a);o&&Le.add(t[s],o)}let n=Oe(r,{...r._zod.def,shape:t,catchall:Ef(wf)}),i=Le.get(r);return i&&Le.add(n,i),n}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function $k(r){if(ae(r))try{let e=r.parse(void 0);return()=>e}catch{return}if(se(r))try{let e=Sn(r,void 0);return()=>e}catch{return}}function tv(r){return ae(r)&&"typeName"in r._def&&r._def.typeName==="ZodEffects"}function rv(r){return se(r)&&r._zod.def.type==="pipe"}function Zr(r,e=!1){if(ae(r))return tv(r)?Zr(r._def.schema,e):r;if(se(r)){let t=r;if(rv(r)&&(t=Zr(r._zod.def.in,e)),e){if(_t(t)){let i=t._zod.def.shape;for(let[s,a]of Object.entries(t._zod.def.shape))i[s]=Zr(a,e);t=Oe(t,{...t._zod.def,shape:i})}else if($o(t)){let i=Zr(t._zod.def.element,e);t=Oe(t,{...t._zod.def,element:i})}}let n=Le.get(r);return n&&Le.add(t,n),t}throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function Io(r){if(se(r)){let e=Zr(r,!0);if(_t(e)){let t=ys(e,!0);return wo(t)}else return wo(r)}return ae(r)?To(r):r}function bs(r){if(!r||typeof r!="object"||Object.keys(r).length===0||Array.isArray(r))return!1;if("type"in r)return typeof r.type=="string"?r.type==="string":Array.isArray(r.type)?r.type.every(e=>e==="string"):!1;if("enum"in r)return Array.isArray(r.enum)&&r.enum.length>0&&r.enum.every(e=>typeof e=="string");if("const"in r)return typeof r.const=="string";if("allOf"in r&&Array.isArray(r.allOf))return r.allOf.some(e=>bs(e));if("anyOf"in r&&Array.isArray(r.anyOf)||"oneOf"in r&&Array.isArray(r.oneOf)){let e="anyOf"in r?r.anyOf:r.oneOf;return e.length>0&&e.every(t=>bs(t))}if("not"in r)return!1;if("$ref"in r&&typeof r.$ref=="string"){let e=r.$ref,t=at(r);return t[e]?bs(t[e]):!1}return!1}function iv(r,e){if(r!==void 0&&!Nr(r))return r;if(wn(e))try{let t=e.getName();return t=t.startsWith("Runnable")?t.slice(8):t,t}catch{return e.getName()}else return e.name??"UnknownSchema"}function sv(r){return wn(r.data)?{type:"runnable",data:{id:r.data.lc_id,name:r.data.getName()}}:{type:"schema",data:{...Io(r.data.schema),title:r.data.name}}}var $n=class r{constructor(e){Object.defineProperty(this,"nodes",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"edges",{enumerable:!0,configurable:!0,writable:!0,value:[]}),this.nodes=e?.nodes??this.nodes,this.edges=e?.edges??this.edges}toJSON(){let e={};return Object.values(this.nodes).forEach((t,n)=>{e[t.id]=Nr(t.id)?n:t.id}),{nodes:Object.values(this.nodes).map(t=>({id:e[t.id],...sv(t)})),edges:this.edges.map(t=>{let n={source:e[t.source],target:e[t.target]};return typeof t.data<"u"&&(n.data=t.data),typeof t.conditional<"u"&&(n.conditional=t.conditional),n})}}addNode(e,t,n){if(t!==void 0&&this.nodes[t]!==void 0)throw new Error(`Node with id ${t} already exists`);let i=t??Ne(),s={id:i,data:e,name:iv(t,e),metadata:n};return this.nodes[i]=s,s}removeNode(e){delete this.nodes[e.id],this.edges=this.edges.filter(t=>t.source!==e.id&&t.target!==e.id)}addEdge(e,t,n,i){if(this.nodes[e.id]===void 0)throw new Error(`Source node ${e.id} not in graph`);if(this.nodes[t.id]===void 0)throw new Error(`Target node ${t.id} not in graph`);let s={source:e.id,target:t.id,data:n,conditional:i};return this.edges.push(s),s}firstNode(){return pp(this)}lastNode(){return hp(this)}extend(e,t=""){let n=t;Object.values(e.nodes).map(c=>c.id).every(Nr)&&(n="");let s=c=>n?`${n}:${c}`:c;Object.entries(e.nodes).forEach(([c,l])=>{this.nodes[s(c)]={...l,id:s(c)}});let a=e.edges.map(c=>({...c,source:s(c.source),target:s(c.target)}));this.edges=[...this.edges,...a];let o=e.firstNode(),u=e.lastNode();return[o?{id:s(o.id),data:o.data}:void 0,u?{id:s(u.id),data:u.data}:void 0]}trimFirstNode(){let e=this.firstNode();e&&pp(this,[e.id])&&this.removeNode(e)}trimLastNode(){let e=this.lastNode();e&&hp(this,[e.id])&&this.removeNode(e)}reid(){let e=Object.fromEntries(Object.values(this.nodes).map(i=>[i.id,i.name])),t=new Map;Object.values(e).forEach(i=>{t.set(i,(t.get(i)||0)+1)});let n=i=>{let s=e[i];return Nr(i)&&t.get(s)===1?s:i};return new r({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(e){let{withStyles:t,curveStyle:n,nodeColors:i={default:"fill:#f2f0ff,line-height:1.2",first:"fill-opacity:0",last:"fill:#bfb6fc"},wrapLabelNWords:s}=e??{},a=this.reid(),o=a.firstNode(),u=a.lastNode();return tf(a.nodes,a.edges,{firstNode:o?.id,lastNode:u?.id,withStyles:t,curveStyle:n,nodeColors:i,wrapLabelNWords:s})}async drawMermaidPng(e){let t=this.drawMermaid(e);return rf(t,{backgroundColor:e?.backgroundColor})}};function pp(r,e=[]){let t=new Set(r.edges.filter(i=>!e.includes(i.source)).map(i=>i.target)),n=[];for(let i of Object.values(r.nodes))!e.includes(i.id)&&!t.has(i.id)&&n.push(i);return n.length===1?n[0]:void 0}function hp(r,e=[]){let t=new Set(r.edges.filter(i=>!e.includes(i.target)).map(i=>i.source)),n=[];for(let i of Object.values(r.nodes))!e.includes(i.id)&&!t.has(i.id)&&n.push(i);return n.length===1?n[0]:void 0}function mp(r){let e=new TextEncoder,t=new ReadableStream({async start(n){for await(let i of r)n.enqueue(e.encode(`event: data
76
+ data: ${JSON.stringify(i)}
77
+
78
+ `));n.enqueue(e.encode(`event: end
79
+
80
+ `)),n.close()}});return ge.fromReadableStream(t)}function Ao(r){return typeof r=="object"&&r!==null&&typeof r[Symbol.iterator]=="function"&&typeof r.next=="function"}var gp=r=>r!=null&&typeof r=="object"&&"next"in r&&typeof r.next=="function";function ws(r){return typeof r=="object"&&r!==null&&typeof r[Symbol.asyncIterator]=="function"}function*ko(r,e){for(;;){let{value:t,done:n}=Ue.runWithConfig(It(r),e.next.bind(e),!0);if(n)break;yield t}}async function*vs(r,e){let t=e[Symbol.asyncIterator]();for(;;){let{value:n,done:i}=await Ue.runWithConfig(It(r),t.next.bind(e),!0);if(i)break;yield n}}function oe(r,e){return r&&!Array.isArray(r)&&!(r instanceof Date)&&typeof r=="object"?r:{[e]:r}}var ue=class extends Ze{constructor(){super(...arguments),Object.defineProperty(this,"lc_runnable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}getName(e){let t=this.name??this.constructor.lc_name()??this.constructor.name;return e?`${t}${e}`:t}bind(e){return new vr({bound:this,kwargs:e,config:{}})}map(){return new Ro({bound:this})}withRetry(e){return new xs({bound:this,kwargs:{},config:{},maxAttemptNumber:e?.stopAfterAttempt,...e})}withConfig(e){return new vr({bound:this,config:e,kwargs:{}})}withFallbacks(e){let t=Array.isArray(e)?e:e.fallbacks;return new Co({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(W);if(t>1&&!Array.isArray(e)&&e.runId){console.warn("Provided runId will be used only for the first element of the batch.");let n=Object.fromEntries(Object.entries(e).filter(([i])=>i!=="runId"));return Array.from({length:t},(i,s)=>W(s===0?e:n))}return Array.from({length:t},()=>W(e))}async batch(e,t,n){let i=this._getOptionsList(t??{},e.length),s=i[0]?.maxConcurrency??n?.maxConcurrency,a=new yn({maxConcurrency:s,onFailedAttempt:u=>{throw u}}),o=e.map((u,c)=>a.call(async()=>{try{return await this.invoke(u,i[c])}catch(l){if(n?.returnExceptions)return l;throw l}}));return Promise.all(o)}async*_streamIterator(e,t){yield this.invoke(e,t)}async stream(e,t){let n=W(t),i=new mt({generator:this._streamIterator(e,n),config:n});return await i.setup,ge.fromAsyncGenerator(i)}_separateRunnableConfigFromCallOptions(e){let t;e===void 0?t=W(e):t=W({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 n={...e};return delete n.callbacks,delete n.tags,delete n.metadata,delete n.runName,delete n.configurable,delete n.recursionLimit,delete n.maxConcurrency,delete n.runId,delete n.timeout,delete n.signal,[t,n]}async _callWithConfig(e,t,n){let i=W(n),a=await(await Xe(i))?.handleChainStart(this.toJSON(),oe(t,"input"),i.runId,i?.runType,void 0,void 0,i?.runName??this.getName());delete i.runId;let o;try{let u=e.call(this,t,i,a);o=await ht(u,n?.signal)}catch(u){throw await a?.handleChainError(u),u}return await a?.handleChainEnd(oe(o,"output")),o}async _batchWithConfig(e,t,n,i){let s=this._getOptionsList(n??{},t.length),a=await Promise.all(s.map(Xe)),o=await Promise.all(a.map(async(c,l)=>{let d=await c?.handleChainStart(this.toJSON(),oe(t[l],"input"),s[l].runId,s[l].runType,void 0,void 0,s[l].runName??this.getName());return delete s[l].runId,d})),u;try{let c=e.call(this,t,s,o,i);u=await ht(c,s?.[0]?.signal)}catch(c){throw await Promise.all(o.map(l=>l?.handleChainError(c))),c}return await Promise.all(o.map(c=>c?.handleChainEnd(oe(u,"output")))),u}_concatOutputChunks(e,t){return ns(e,t)}async*_transformStreamWithConfig(e,t,n){let i,s=!0,a,o=!0,u=W(n),c=await Xe(u),l=this;async function*d(){for await(let p of e){if(s)if(i===void 0)i=p;else try{i=l._concatOutputChunks(i,p)}catch{i=void 0,s=!1}yield p}}let f;try{let p=await ao(t.bind(this),d(),async()=>c?.handleChainStart(this.toJSON(),{input:""},u.runId,u.runType,void 0,void 0,u.runName??this.getName()),n?.signal,u);delete u.runId,f=p.setup;let h=f?.handlers.find(Qd),m=p.output;h!==void 0&&f!==void 0&&(m=h.tapOutputIterable(f.runId,m));let g=f?.handlers.find(oo);g!==void 0&&f!==void 0&&(m=g.tapOutputIterable(f.runId,m));for await(let _ of m)if(yield _,o)if(a===void 0)a=_;else try{a=this._concatOutputChunks(a,_)}catch{a=void 0,o=!1}}catch(p){throw await f?.handleChainError(p,void 0,void 0,void 0,{inputs:oe(i,"input")}),p}await f?.handleChainEnd(a??{},void 0,void 0,void 0,{inputs:oe(i,"input")})}getGraph(e){let t=new $n,n=t.addNode({name:`${this.getName()}Input`,schema:Tt.any()}),i=t.addNode(this),s=t.addNode({name:`${this.getName()}Output`,schema:Tt.any()});return t.addEdge(n,i),t.addEdge(i,s),t}pipe(e){return new Es({first:this,last:wr(e)})}pick(e){return this.pipe(new Lo(e))}assign(e){return this.pipe(new jo(new Br({steps:e})))}async*transform(e,t){let n;for await(let i of e)n===void 0?n=i:n=this._concatOutputChunks(n,i);yield*this._streamIterator(n,W(t))}async*streamLog(e,t,n){let i=new Ur({...n,autoClose:!1,_schemaFormat:"original"}),s=W(t);yield*this._streamLog(e,i,s)}async*_streamLog(e,t,n){let{callbacks:i}=n;if(i===void 0)n.callbacks=[t];else if(Array.isArray(i))n.callbacks=i.concat([t]);else{let u=i.copy();u.addHandler(t,!0),n.callbacks=u}let s=this.stream(e,n);async function a(){try{let u=await s;for await(let c of u){let l=new Qe({ops:[{op:"add",path:"/streamed_output/-",value:c}]});await t.writer.write(l)}}finally{await t.writer.close()}}let o=a();try{for await(let u of t)yield u}finally{await o}}streamEvents(e,t,n){let i;if(t.version==="v1")i=this._streamEventsV1(e,t,n);else if(t.version==="v2")i=this._streamEventsV2(e,t,n);else throw new Error('Only versions "v1" and "v2" of the schema are currently supported.');return t.encoding==="text/event-stream"?mp(i):ge.fromAsyncGenerator(i)}async*_streamEventsV2(e,t,n){let i=new ss({...n,autoClose:!1}),s=W(t),a=s.runId??Ne();s.runId=a;let o=s.callbacks;if(o===void 0)s.callbacks=[i];else if(Array.isArray(o))s.callbacks=o.concat(i);else{let h=o.copy();h.addHandler(i,!0),s.callbacks=h}let u=new AbortController,c=this;async function l(){let h,m=null;try{t?.signal?"any"in AbortSignal?h=AbortSignal.any([u.signal,t.signal]):(h=t.signal,m=()=>{u.abort()},t.signal.addEventListener("abort",m,{once:!0})):h=u.signal;let g=await c.stream(e,{...s,signal:h}),_=i.tapOutputIterable(a,g);for await(let w of _)if(u.signal.aborted)break}finally{await i.finish(),h&&m&&h.removeEventListener("abort",m)}}let d=l(),f=!1,p;try{for await(let h of i){if(!f){h.data.input=e,f=!0,p=h.run_id,yield h;continue}h.run_id===p&&h.event.endsWith("_end")&&h.data?.input&&delete h.data.input,yield h}}finally{u.abort(),await d}}async*_streamEventsV1(e,t,n){let i,s=!1,a=W(t),o=a.tags??[],u=a.metadata??{},c=a.runName??this.getName(),l=new Ur({...n,autoClose:!1,_schemaFormat:"streaming_events"}),d=new os({...n}),f=this._streamLog(e,l,a);for await(let h of f){if(i?i=i.concat(h):i=Dr.fromRunLogPatch(h),i.state===void 0)throw new Error('Internal error: "streamEvents" state is missing. Please open a bug report.');if(!s){s=!0;let w={...i.state},v={run_id:w.id,event:`on_${w.type}_start`,name:c,tags:o,metadata:u,data:{input:e}};d.includeEvent(v,w.type)&&(yield v)}let m=h.ops.filter(w=>w.path.startsWith("/logs/")).map(w=>w.path.split("/")[2]),g=[...new Set(m)];for(let w of g){let v,N={},I=i.state.logs[w];if(I.end_time===void 0?I.streamed_output.length>0?v="stream":v="start":v="end",v==="start")I.inputs!==void 0&&(N.input=I.inputs);else if(v==="end")I.inputs!==void 0&&(N.input=I.inputs),N.output=I.final_output;else if(v==="stream"){let H=I.streamed_output.length;if(H!==1)throw new Error(`Expected exactly one chunk of streamed output, got ${H} instead. Encountered in: "${I.name}"`);N={chunk:I.streamed_output[0]},I.streamed_output=[]}yield{event:`on_${I.type}_${v}`,name:I.name,run_id:I.id,tags:I.tags,metadata:I.metadata,data:N}}let{state:_}=i;if(_.streamed_output.length>0){let w=_.streamed_output.length;if(w!==1)throw new Error(`Expected exactly one chunk of streamed output, got ${w} instead. Encountered in: "${_.name}"`);let v={chunk:_.streamed_output[0]};_.streamed_output=[];let N={event:`on_${_.type}_stream`,run_id:_.id,tags:o,metadata:u,name:c,data:v};d.includeEvent(N,_.type)&&(yield N)}}let p=i?.state;if(p!==void 0){let h={event:`on_${p.type}_end`,name:c,run_id:p.id,tags:o,metadata:u,data:{output:p.final_output}};d.includeEvent(h,p.type)&&(yield h)}}static isRunnable(e){return wn(e)}withListeners({onStart:e,onEnd:t,onError:n}){return new vr({bound:this,config:{},configFactories:[i=>({callbacks:[new bn({config:i,onStart:e,onEnd:t,onError:n})]})]})}asTool(e){return ov(this,e)}},vr=class r extends ue{static lc_name(){return"RunnableBinding"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"bound",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"kwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"configFactories",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.bound=e.bound,this.kwargs=e.kwargs,this.config=e.config,this.configFactories=e.configFactories}getName(e){return this.bound.getName(e)}async _mergeConfig(...e){let t=so(this.config,...e);return so(t,...this.configFactories?await Promise.all(this.configFactories.map(async n=>await n(t))):[])}bind(e){return new this.constructor({bound:this.bound,kwargs:{...this.kwargs,...e},config:this.config})}withConfig(e){return new this.constructor({bound:this.bound,kwargs:this.kwargs,config:{...this.config,...e}})}withRetry(e){return new xs({bound:this.bound,kwargs:this.kwargs,config:this.config,maxAttemptNumber:e?.stopAfterAttempt,...e})}async invoke(e,t){return this.bound.invoke(e,await this._mergeConfig(W(t),this.kwargs))}async batch(e,t,n){let i=Array.isArray(t)?await Promise.all(t.map(async s=>this._mergeConfig(W(s),this.kwargs))):await this._mergeConfig(W(t),this.kwargs);return this.bound.batch(e,i,n)}_concatOutputChunks(e,t){return this.bound._concatOutputChunks(e,t)}async*_streamIterator(e,t){yield*this.bound._streamIterator(e,await this._mergeConfig(W(t),this.kwargs))}async stream(e,t){return this.bound.stream(e,await this._mergeConfig(W(t),this.kwargs))}async*transform(e,t){yield*this.bound.transform(e,await this._mergeConfig(W(t),this.kwargs))}streamEvents(e,t,n){let i=this,s=async function*(){yield*i.bound.streamEvents(e,{...await i._mergeConfig(W(t),i.kwargs),version:t.version},n)};return ge.fromAsyncGenerator(s())}static isRunnableBinding(e){return e.bound&&ue.isRunnable(e.bound)}withListeners({onStart:e,onEnd:t,onError:n}){return new r({bound:this.bound,kwargs:this.kwargs,config:this.config,configFactories:[i=>({callbacks:[new bn({config:i,onStart:e,onEnd:t,onError:n})]})]})}},Ro=class r extends ue{static lc_name(){return"RunnableEach"}constructor(e){super(e),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"bound",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.bound=e.bound}bind(e){return new r({bound:this.bound.bind(e)})}async invoke(e,t){return this._callWithConfig(this._invoke.bind(this),e,t)}async _invoke(e,t,n){return this.bound.batch(e,me(t,{callbacks:n?.getChild()}))}withListeners({onStart:e,onEnd:t,onError:n}){return new r({bound:this.bound.withListeners({onStart:e,onEnd:t,onError:n})})}},xs=class extends vr{static lc_name(){return"RunnableRetry"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"maxAttemptNumber",{enumerable:!0,configurable:!0,writable:!0,value:3}),Object.defineProperty(this,"onFailedAttempt",{enumerable:!0,configurable:!0,writable:!0,value:()=>{}}),this.maxAttemptNumber=e.maxAttemptNumber??this.maxAttemptNumber,this.onFailedAttempt=e.onFailedAttempt??this.onFailedAttempt}_patchConfigForRetry(e,t,n){let i=e>1?`retry:attempt:${e}`:void 0;return me(t,{callbacks:n?.getChild(i)})}async _invoke(e,t,n){return(0,Po.default)(i=>super.invoke(e,this._patchConfigForRetry(i,t,n)),{onFailedAttempt:i=>this.onFailedAttempt(i,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,n,i){let s={};try{await(0,Po.default)(async a=>{let o=e.map((f,p)=>p).filter(f=>s[f.toString()]===void 0||s[f.toString()]instanceof Error),u=o.map(f=>e[f]),c=o.map(f=>this._patchConfigForRetry(a,t?.[f],n?.[f])),l=await super.batch(u,c,{...i,returnExceptions:!0}),d;for(let f=0;f<l.length;f+=1){let p=l[f],h=o[f];p instanceof Error&&d===void 0&&(d=p,d.input=u[f]),s[h.toString()]=p}if(d)throw d;return l},{onFailedAttempt:a=>this.onFailedAttempt(a,a.input),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}catch(a){if(i?.returnExceptions!==!0)throw a}return Object.keys(s).sort((a,o)=>parseInt(a,10)-parseInt(o,10)).map(a=>s[parseInt(a,10)])}async batch(e,t,n){return this._batchWithConfig(this._batch.bind(this),e,t,n)}},Es=class r extends ue{static lc_name(){return"RunnableSequence"}constructor(e){super(e),Object.defineProperty(this,"first",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"middle",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"last",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"omitSequenceTags",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),this.first=e.first,this.middle=e.middle??this.middle,this.last=e.last,this.name=e.name,this.omitSequenceTags=e.omitSequenceTags??this.omitSequenceTags}get steps(){return[this.first,...this.middle,this.last]}async invoke(e,t){let n=W(t),s=await(await Xe(n))?.handleChainStart(this.toJSON(),oe(e,"input"),n.runId,void 0,void 0,void 0,n?.runName);delete n.runId;let a=e,o;try{let u=[this.first,...this.middle];for(let c=0;c<u.length;c+=1){let d=u[c].invoke(a,me(n,{callbacks:s?.getChild(this.omitSequenceTags?void 0:`seq:step:${c+1}`)}));a=await ht(d,t?.signal)}if(t?.signal?.aborted)throw new Error("Aborted");o=await this.last.invoke(a,me(n,{callbacks:s?.getChild(this.omitSequenceTags?void 0:`seq:step:${this.steps.length}`)}))}catch(u){throw await s?.handleChainError(u),u}return await s?.handleChainEnd(oe(o,"output")),o}async batch(e,t,n){let i=this._getOptionsList(t??{},e.length),s=await Promise.all(i.map(Xe)),a=await Promise.all(s.map(async(u,c)=>{let l=await u?.handleChainStart(this.toJSON(),oe(e[c],"input"),i[c].runId,void 0,void 0,void 0,i[c].runName);return delete i[c].runId,l})),o=e;try{for(let u=0;u<this.steps.length;u+=1){let l=this.steps[u].batch(o,a.map((d,f)=>{let p=d?.getChild(this.omitSequenceTags?void 0:`seq:step:${u+1}`);return me(i[f],{callbacks:p})}),n);o=await ht(l,i[0]?.signal)}}catch(u){throw await Promise.all(a.map(c=>c?.handleChainError(u))),u}return await Promise.all(a.map(u=>u?.handleChainEnd(oe(o,"output")))),o}_concatOutputChunks(e,t){return this.last._concatOutputChunks(e,t)}async*_streamIterator(e,t){let n=await Xe(t),{runId:i,...s}=t??{},a=await n?.handleChainStart(this.toJSON(),oe(e,"input"),i,void 0,void 0,void 0,s?.runName),o=[this.first,...this.middle,this.last],u=!0,c;async function*l(){yield e}try{let d=o[0].transform(l(),me(s,{callbacks:a?.getChild(this.omitSequenceTags?void 0:"seq:step:1")}));for(let f=1;f<o.length;f+=1)d=await o[f].transform(d,me(s,{callbacks:a?.getChild(this.omitSequenceTags?void 0:`seq:step:${f+1}`)}));for await(let f of d)if(t?.signal?.throwIfAborted(),yield f,u)if(c===void 0)c=f;else try{c=this._concatOutputChunks(c,f)}catch{c=void 0,u=!1}}catch(d){throw await a?.handleChainError(d),d}await a?.handleChainEnd(oe(c,"output"))}getGraph(e){let t=new $n,n=null;return this.steps.forEach((i,s)=>{let a=i.getGraph(e);s!==0&&a.trimFirstNode(),s!==this.steps.length-1&&a.trimLastNode(),t.extend(a);let o=a.firstNode();if(!o)throw new Error(`Runnable ${i} has no first node`);n&&t.addEdge(n,o),n=a.lastNode()}),t}pipe(e){return r.isRunnableSequence(e)?new r({first:this.first,middle:this.middle.concat([this.last,e.first,...e.middle]),last:e.last,name:this.name??e.name}):new r({first:this.first,middle:[...this.middle,this.last],last:wr(e),name:this.name})}static isRunnableSequence(e){return Array.isArray(e.middle)&&ue.isRunnable(e)}static from([e,...t],n){let i={};return typeof n=="string"?i.name=n:n!==void 0&&(i=n),new r({...i,first:wr(e),middle:t.slice(0,-1).map(wr),last:wr(t[t.length-1])})}},Br=class r extends ue{static lc_name(){return"RunnableMap"}getStepsKeys(){return Object.keys(this.steps)}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"steps",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.steps={};for(let[t,n]of Object.entries(e.steps))this.steps[t]=wr(n)}static from(e){return new r({steps:e})}async invoke(e,t){let n=W(t),s=await(await Xe(n))?.handleChainStart(this.toJSON(),{input:e},n.runId,void 0,void 0,void 0,n?.runName);delete n.runId;let a={};try{let o=Object.entries(this.steps).map(async([u,c])=>{a[u]=await c.invoke(e,me(n,{callbacks:s?.getChild(`map:key:${u}`)}))});await ht(Promise.all(o),t?.signal)}catch(o){throw await s?.handleChainError(o),o}return await s?.handleChainEnd(a),a}async*_transform(e,t,n){let i={...this.steps},s=rs(e,Object.keys(i).length),a=new Map(Object.entries(i).map(([o,u],c)=>{let l=u.transform(s[c],me(n,{callbacks:t?.getChild(`map:key:${o}`)}));return[o,l.next().then(d=>({key:o,gen:l,result:d}))]}));for(;a.size;){let o=Promise.race(a.values()),{key:u,result:c,gen:l}=await ht(o,n?.signal);a.delete(u),c.done||(yield{[u]:c.value},a.set(u,l.next().then(d=>({key:u,gen:l,result:d}))))}}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*n(){yield e}let i=W(t),s=new mt({generator:this.transform(n(),i),config:i});return await s.setup,ge.fromAsyncGenerator(s)}},No=class r extends ue{constructor(e){if(super(e),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"func",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),!si(e.func))throw new Error("RunnableTraceable requires a function that is wrapped in traceable higher-order function");this.func=e.func}async invoke(e,t){let[n]=this._getOptionsList(t??{},1),i=await Xe(n),s=this.func(me(n,{callbacks:i}),e);return ht(s,n?.signal)}async*_streamIterator(e,t){let[n]=this._getOptionsList(t??{},1),i=await this.invoke(e,t);if(ws(i)){for await(let s of i)n?.signal?.throwIfAborted(),yield s;return}if(gp(i)){for(;;){n?.signal?.throwIfAborted();let s=i.next();if(s.done)break;yield s.value}return}yield i}static from(e){return new r({func:e})}};function av(r){if(si(r))throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.")}var Ss=class r extends ue{static lc_name(){return"RunnableLambda"}constructor(e){if(si(e.func))return No.from(e.func);super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"func",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),av(e.func),this.func=e.func}static from(e){return new r({func:e})}async _invoke(e,t,n){return new Promise((i,s)=>{let a=me(t,{callbacks:n?.getChild(),recursionLimit:(t?.recursionLimit??ts)-1});Ue.runWithConfig(It(a),async()=>{try{let o=await this.func(e,{...a});if(o&&ue.isRunnable(o)){if(t?.recursionLimit===0)throw new Error("Recursion limit reached.");o=await o.invoke(e,{...a,recursionLimit:(a.recursionLimit??ts)-1})}else if(ws(o)){let u;for await(let c of vs(a,o))if(t?.signal?.throwIfAborted(),u===void 0)u=c;else try{u=this._concatOutputChunks(u,c)}catch{u=c}o=u}else if(Ao(o)){let u;for(let c of ko(a,o))if(t?.signal?.throwIfAborted(),u===void 0)u=c;else try{u=this._concatOutputChunks(u,c)}catch{u=c}o=u}i(o)}catch(o){s(o)}})})}async invoke(e,t){return this._callWithConfig(this._invoke.bind(this),e,t)}async*_transform(e,t,n){let i;for await(let o of e)if(i===void 0)i=o;else try{i=this._concatOutputChunks(i,o)}catch{i=o}let s=me(n,{callbacks:t?.getChild(),recursionLimit:(n?.recursionLimit??ts)-1}),a=await new Promise((o,u)=>{Ue.runWithConfig(It(s),async()=>{try{let c=await this.func(i,{...s,config:s});o(c)}catch(c){u(c)}})});if(a&&ue.isRunnable(a)){if(n?.recursionLimit===0)throw new Error("Recursion limit reached.");let o=await a.stream(i,s);for await(let u of o)yield u}else if(ws(a))for await(let o of vs(s,a))n?.signal?.throwIfAborted(),yield o;else if(Ao(a))for(let o of ko(s,a))n?.signal?.throwIfAborted(),yield o;else yield a}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*n(){yield e}let i=W(t),s=new mt({generator:this.transform(n(),i),config:i});return await s.setup,ge.fromAsyncGenerator(s)}},_p=class extends Br{},Co=class extends ue{static lc_name(){return"RunnableWithFallbacks"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"runnable",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fallbacks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),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 n=W(t),i=await Xe(n),{runId:s,...a}=n,o=await i?.handleChainStart(this.toJSON(),oe(e,"input"),s,void 0,void 0,void 0,a?.runName),u=me(a,{callbacks:o?.getChild()});return await Ue.runWithConfig(u,async()=>{let l;for(let d of this.runnables()){n?.signal?.throwIfAborted();try{let f=await d.invoke(e,u);return await o?.handleChainEnd(oe(f,"output")),f}catch(f){l===void 0&&(l=f)}}throw l===void 0?new Error("No error stored at end of fallback."):(await o?.handleChainError(l),l)})}async*_streamIterator(e,t){let n=W(t),i=await Xe(n),{runId:s,...a}=n,o=await i?.handleChainStart(this.toJSON(),oe(e,"input"),s,void 0,void 0,void 0,a?.runName),u,c;for(let d of this.runnables()){n?.signal?.throwIfAborted();let f=me(a,{callbacks:o?.getChild()});try{let p=await d.stream(e,f);c=vs(f,p);break}catch(p){u===void 0&&(u=p)}}if(c===void 0){let d=u??new Error("No error stored at end of fallback.");throw await o?.handleChainError(d),d}let l;try{for await(let d of c){yield d;try{l=l===void 0?l:this._concatOutputChunks(l,d)}catch{l=void 0}}}catch(d){throw await o?.handleChainError(d),d}await o?.handleChainEnd(oe(l,"output"))}async batch(e,t,n){if(n?.returnExceptions)throw new Error("Not implemented.");let i=this._getOptionsList(t??{},e.length),s=await Promise.all(i.map(u=>Xe(u))),a=await Promise.all(s.map(async(u,c)=>{let l=await u?.handleChainStart(this.toJSON(),oe(e[c],"input"),i[c].runId,void 0,void 0,void 0,i[c].runName);return delete i[c].runId,l})),o;for(let u of this.runnables()){i[0].signal?.throwIfAborted();try{let c=await u.batch(e,a.map((l,d)=>me(i[d],{callbacks:l?.getChild()})),n);return await Promise.all(a.map((l,d)=>l?.handleChainEnd(oe(c[d],"output")))),c}catch(c){o===void 0&&(o=c)}}throw o?(await Promise.all(a.map(u=>u?.handleChainError(o))),o):new Error("No error stored at end of fallbacks.")}};function wr(r){if(typeof r=="function")return new Ss({func:r});if(ue.isRunnable(r))return r;if(!Array.isArray(r)&&typeof r=="object"){let e={};for(let[t,n]of Object.entries(r))e[t]=wr(n);return new Br({steps:e})}else throw new Error(`Expected a Runnable, function or object.
81
+ Instead got an unsupported type.`)}var jo=class extends ue{static lc_name(){return"RunnableAssign"}constructor(e){e instanceof Br&&(e={mapper:e}),super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"mapper",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.mapper=e.mapper}async invoke(e,t){let n=await this.mapper.invoke(e,t);return{...e,...n}}async*_transform(e,t,n){let i=this.mapper.getStepsKeys(),[s,a]=rs(e),o=this.mapper.transform(a,me(n,{callbacks:t?.getChild()})),u=o.next();for await(let c of s){if(typeof c!="object"||Array.isArray(c))throw new Error(`RunnableAssign can only be used with objects as input, got ${typeof c}`);let l=Object.fromEntries(Object.entries(c).filter(([d])=>!i.includes(d)));Object.keys(l).length>0&&(yield l)}yield(await u).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*n(){yield e}let i=W(t),s=new mt({generator:this.transform(n(),i),config:i});return await s.setup,ge.fromAsyncGenerator(s)}},Lo=class extends ue{static lc_name(){return"RunnablePick"}constructor(e){(typeof e=="string"||Array.isArray(e))&&(e={keys:e}),super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"keys",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.keys=e.keys}async _pick(e){if(typeof this.keys=="string")return e[this.keys];{let t=this.keys.map(n=>[n,e[n]]).filter(n=>n[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 n=await this._pick(t);n!==void 0&&(yield n)}}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*n(){yield e}let i=W(t),s=new mt({generator:this.transform(n(),i),config:i});return await s.setup,ge.fromAsyncGenerator(s)}},Ts=class extends vr{constructor(e){let t=Es.from([Ss.from(async n=>{let i;if(Zn(n))try{i=await cp(this.schema,n.args)}catch{throw new Fn("Received tool input did not match expected schema",JSON.stringify(n.args))}else i=n;return i}).withConfig({runName:`${e.name}:parse_input`}),e.bound]).withConfig({runName:e.name});super({bound:t,config:e.config??{}}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"description",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"schema",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=e.name,this.description=e.description,this.schema=e.schema}static lc_name(){return"RunnableToolLike"}};function ov(r,e){let t=e.name??r.getName(),n=e.description??lp(e.schema);return dp(e.schema)?new Ts({name:t,description:n,schema:Tt.object({input:Tt.string()}).transform(i=>i.input),bound:r}):new Ts({name:t,description:n,schema:e.schema,bound:r})}var Os=class extends ue{get lc_attributes(){return{partialVariables:void 0}}constructor(e){super(e),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompts",this._getPromptType()]}),Object.defineProperty(this,"inputVariables",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"outputParser",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"partialVariables",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),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});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??{},n={};for(let[s,a]of Object.entries(t))typeof a=="string"?n[s]=a:n[s]=await a();return{...n,...e}}async invoke(e,t){let n={...this.metadata,...t?.metadata},i=[...this.tags??[],...t?.tags??[]];return this._callWithConfig(s=>this.formatPromptValue(s),e,{...t,tags:i,metadata:n,runType:"prompt"})}serialize(){throw new Error("Use .toJSON() instead")}static async deserialize(e){switch(e._type){case"prompt":{let{PromptTemplate:t}=await import("./EJW7PCMD.js");return t.deserialize(e)}case void 0:{let{PromptTemplate:t}=await import("./EJW7PCMD.js");return t.deserialize({...e,_type:"prompt"})}case"few_shot":{let{FewShotPromptTemplate:t}=await import("./HPGCDT6I.js").then(m=>m.default);return t.deserialize(e)}default:throw new Error(`Invalid prompt type in config: ${e._type}`)}}};var $s=class extends Os{async formatPromptValue(e){let t=await this.format(e);return new Qr(t)}};var uv=Object.prototype.toString,qr=Array.isArray||function(e){return uv.call(e)==="[object Array]"};function Mo(r){return typeof r=="function"}function cv(r){return qr(r)?"array":typeof r}function zo(r){return r.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function yp(r,e){return r!=null&&typeof r=="object"&&e in r}function lv(r,e){return r!=null&&typeof r!="object"&&r.hasOwnProperty&&r.hasOwnProperty(e)}var dv=RegExp.prototype.test;function fv(r,e){return dv.call(r,e)}var pv=/\S/;function hv(r){return!fv(pv,r)}var mv={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;","`":"&#x60;","=":"&#x3D;"};function gv(r){return String(r).replace(/[&<>"'`=\/]/g,function(t){return mv[t]})}var _v=/\s*/,yv=/\s+/,bp=/\s*=/,bv=/\s*\}/,wv=/#|\^|\/|>|\{|&|=|!/;function vv(r,e){if(!r)return[];var t=!1,n=[],i=[],s=[],a=!1,o=!1,u="",c=0;function l(){if(a&&!o)for(;s.length;)delete i[s.pop()];else s=[];a=!1,o=!1}var d,f,p;function h(J){if(typeof J=="string"&&(J=J.split(yv,2)),!qr(J)||J.length!==2)throw new Error("Invalid tags: "+J);d=new RegExp(zo(J[0])+"\\s*"),f=new RegExp("\\s*"+zo(J[1])),p=new RegExp("\\s*"+zo("}"+J[1]))}h(e||et.tags);for(var m=new An(r),g,_,w,v,N,I;!m.eos();){if(g=m.pos,w=m.scanUntil(d),w)for(var H=0,K=w.length;H<K;++H)v=w.charAt(H),hv(v)?(s.push(i.length),u+=v):(o=!0,t=!0,u+=" "),i.push(["text",v,g,g+1]),g+=1,v===`
82
+ `&&(l(),u="",c=0,t=!1);if(!m.scan(d))break;if(a=!0,_=m.scan(wv)||"name",m.scan(_v),_==="="?(w=m.scanUntil(bp),m.scan(bp),m.scanUntil(f)):_==="{"?(w=m.scanUntil(p),m.scan(bv),m.scanUntil(f),_="&"):w=m.scanUntil(f),!m.scan(f))throw new Error("Unclosed tag at "+m.pos);if(_==">"?N=[_,w,g,m.pos,u,c,t]:N=[_,w,g,m.pos],c++,i.push(N),_==="#"||_==="^")n.push(N);else if(_==="/"){if(I=n.pop(),!I)throw new Error('Unopened section "'+w+'" at '+g);if(I[1]!==w)throw new Error('Unclosed section "'+I[1]+'" at '+g)}else _==="name"||_==="{"||_==="&"?o=!0:_==="="&&h(w)}if(l(),I=n.pop(),I)throw new Error('Unclosed section "'+I[1]+'" at '+m.pos);return Ev(xv(i))}function xv(r){for(var e=[],t,n,i=0,s=r.length;i<s;++i)t=r[i],t&&(t[0]==="text"&&n&&n[0]==="text"?(n[1]+=t[1],n[3]=t[3]):(e.push(t),n=t));return e}function Ev(r){for(var e=[],t=e,n=[],i,s,a=0,o=r.length;a<o;++a)switch(i=r[a],i[0]){case"#":case"^":t.push(i),n.push(i),t=i[4]=[];break;case"/":s=n.pop(),s[5]=i[2],t=n.length>0?n[n.length-1][4]:e;break;default:t.push(i)}return e}function An(r){this.string=r,this.tail=r,this.pos=0}An.prototype.eos=function(){return this.tail===""};An.prototype.scan=function(e){var t=this.tail.match(e);if(!t||t.index!==0)return"";var n=t[0];return this.tail=this.tail.substring(n.length),this.pos+=n.length,n};An.prototype.scanUntil=function(e){var t=this.tail.search(e),n;switch(t){case-1:n=this.tail,this.tail="";break;case 0:n="";break;default:n=this.tail.substring(0,t),this.tail=this.tail.substring(t)}return this.pos+=n.length,n};function Gr(r,e){this.view=r,this.cache={".":this.view},this.parent=e}Gr.prototype.push=function(e){return new Gr(e,this)};Gr.prototype.lookup=function(e){var t=this.cache,n;if(t.hasOwnProperty(e))n=t[e];else{for(var i=this,s,a,o,u=!1;i;){if(e.indexOf(".")>0)for(s=i.view,a=e.split("."),o=0;s!=null&&o<a.length;)o===a.length-1&&(u=yp(s,a[o])||lv(s,a[o])),s=s[a[o++]];else s=i.view[e],u=yp(i.view,e);if(u){n=s;break}i=i.parent}t[e]=n}return Mo(n)&&(n=n.call(this.view)),n};function Ie(){this.templateCache={_cache:{},set:function(e,t){this._cache[e]=t},get:function(e){return this._cache[e]},clear:function(){this._cache={}}}}Ie.prototype.clearCache=function(){typeof this.templateCache<"u"&&this.templateCache.clear()};Ie.prototype.parse=function(e,t){var n=this.templateCache,i=e+":"+(t||et.tags).join(":"),s=typeof n<"u",a=s?n.get(i):void 0;return a==null&&(a=vv(e,t),s&&n.set(i,a)),a};Ie.prototype.render=function(e,t,n,i){var s=this.getConfigTags(i),a=this.parse(e,s),o=t instanceof Gr?t:new Gr(t,void 0);return this.renderTokens(a,o,n,e,i)};Ie.prototype.renderTokens=function(e,t,n,i,s){for(var a="",o,u,c,l=0,d=e.length;l<d;++l)c=void 0,o=e[l],u=o[0],u==="#"?c=this.renderSection(o,t,n,i,s):u==="^"?c=this.renderInverted(o,t,n,i,s):u===">"?c=this.renderPartial(o,t,n,s):u==="&"?c=this.unescapedValue(o,t):u==="name"?c=this.escapedValue(o,t,s):u==="text"&&(c=this.rawValue(o)),c!==void 0&&(a+=c);return a};Ie.prototype.renderSection=function(e,t,n,i,s){var a=this,o="",u=t.lookup(e[1]);function c(f){return a.render(f,t,n,s)}if(u){if(qr(u))for(var l=0,d=u.length;l<d;++l)o+=this.renderTokens(e[4],t.push(u[l]),n,i,s);else if(typeof u=="object"||typeof u=="string"||typeof u=="number")o+=this.renderTokens(e[4],t.push(u),n,i,s);else if(Mo(u)){if(typeof i!="string")throw new Error("Cannot use higher-order sections without the original template");u=u.call(t.view,i.slice(e[3],e[5]),c),u!=null&&(o+=u)}else o+=this.renderTokens(e[4],t,n,i,s);return o}};Ie.prototype.renderInverted=function(e,t,n,i,s){var a=t.lookup(e[1]);if(!a||qr(a)&&a.length===0)return this.renderTokens(e[4],t,n,i,s)};Ie.prototype.indentPartial=function(e,t,n){for(var i=t.replace(/[^ \t]/g,""),s=e.split(`
83
+ `),a=0;a<s.length;a++)s[a].length&&(a>0||!n)&&(s[a]=i+s[a]);return s.join(`
84
+ `)};Ie.prototype.renderPartial=function(e,t,n,i){if(n){var s=this.getConfigTags(i),a=Mo(n)?n(e[1]):n[e[1]];if(a!=null){var o=e[6],u=e[5],c=e[4],l=a;u==0&&c&&(l=this.indentPartial(a,c,o));var d=this.parse(l,s);return this.renderTokens(d,t,n,l,i)}}};Ie.prototype.unescapedValue=function(e,t){var n=t.lookup(e[1]);if(n!=null)return n};Ie.prototype.escapedValue=function(e,t,n){var i=this.getConfigEscape(n)||et.escape,s=t.lookup(e[1]);if(s!=null)return typeof s=="number"&&i===et.escape?String(s):i(s)};Ie.prototype.rawValue=function(e){return e[1]};Ie.prototype.getConfigTags=function(e){return qr(e)?e:e&&typeof e=="object"?e.tags:void 0};Ie.prototype.getConfigEscape=function(e){if(e&&typeof e=="object"&&!qr(e))return e.escape};var et={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(r){In.templateCache=r},get templateCache(){return In.templateCache}},In=new Ie;et.clearCache=function(){return In.clearCache()};et.parse=function(e,t){return In.parse(e,t)};et.render=function(e,t,n,i){if(typeof e!="string")throw new TypeError('Invalid template! Template should be a "string" but "'+cv(e)+'" was given as the first argument for mustache#render(template, view, partials)');return In.render(e,t,n,i)};et.escape=gv;et.Scanner=An;et.Context=Gr;et.Writer=Ie;var Is=et;function wp(){Is.escape=r=>r}var vp=r=>{let e=r.split(""),t=[],n=(s,a)=>{for(let o=a;o<e.length;o+=1)if(s.includes(e[o]))return o;return-1},i=0;for(;i<e.length;)if(e[i]==="{"&&i+1<e.length&&e[i+1]==="{")t.push({type:"literal",text:"{"}),i+=2;else if(e[i]==="}"&&i+1<e.length&&e[i+1]==="}")t.push({type:"literal",text:"}"}),i+=2;else if(e[i]==="{"){let s=n("}",i);if(s<0)throw new Error("Unclosed '{' in template.");t.push({type:"variable",name:e.slice(i+1,s).join("")}),i=s+1}else{if(e[i]==="}")throw new Error("Single '}' in template.");{let s=n("{}",i),a=(s<0?e.slice(i):e.slice(i,s)).join("");t.push({type:"literal",text:a}),i=s<0?e.length:s}}return t},xp=(r,e=[])=>{let t=[];for(let n of r)if(n[0]==="name"){let i=n[1].includes(".")?n[1].split(".")[0]:n[1];t.push({type:"variable",name:i})}else if(["#","&","^",">"].includes(n[0])){if(t.push({type:"variable",name:n[1]}),n[0]==="#"&&n.length>4&&Array.isArray(n[4])){let i=[...e,n[1]],s=xp(n[4],i);t.push(...s)}}else t.push({type:"literal",text:n[1]});return t},Sv=r=>{wp();let e=Is.parse(r);return xp(e)},Tv=(r,e)=>vp(r).reduce((t,n)=>{if(n.type==="variable"){if(n.name in e){let i=typeof e[n.name]=="string"?e[n.name]:JSON.stringify(e[n.name]);return t+i}throw new Error(`(f-string) Missing value for input ${n.name}`)}return t+n.text},""),Ov=(r,e)=>(wp(),Is.render(r,e)),Do={"f-string":Tv,mustache:Ov},$v={"f-string":vp,mustache:Sv},Vr=(r,e,t)=>{try{return Do[e](r,t)}catch(n){throw Un(n,"INVALID_PROMPT_INPUT")}},Ep=(r,e)=>$v[e](r),Sp=(r,e,t)=>{if(!(e in Do)){let n=Object.keys(Do);throw new Error(`Invalid template format. Got \`${e}\`;
85
+ should be one of ${n}`)}try{let n=t.reduce((i,s)=>(i[s]="foo",i),{});Array.isArray(r)?r.forEach(i=>{if(i.type==="text")Vr(i.text,e,n);else if(i.type==="image_url")if(typeof i.image_url=="string")Vr(i.image_url,e,n);else{let s=i.image_url.url;Vr(s,e,n)}else throw new Error(`Invalid message template received. ${JSON.stringify(i,null,2)}`)}):Vr(r,e,n)}catch(n){throw new Error(`Invalid prompt schema: ${n.message}`)}};var Tp=class r extends $s{static lc_name(){return"PromptTemplate"}constructor(e){if(super(e),Object.defineProperty(this,"template",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"templateFormat",{enumerable:!0,configurable:!0,writable:!0,value:"f-string"}),Object.defineProperty(this,"validateTemplate",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"additionalContentFields",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),e.templateFormat==="mustache"&&e.validateTemplate===void 0&&(this.validateTemplate=!1),Object.assign(this,e),this.validateTemplate){if(this.templateFormat==="mustache")throw new Error("Mustache templates cannot be validated.");let t=this.inputVariables;this.partialVariables&&(t=t.concat(Object.keys(this.partialVariables))),Sp(this.template,this.templateFormat,t)}}_getPromptType(){return"prompt"}async format(e){let t=await this.mergePartialAndUserVariables(e);return Vr(this.template,this.templateFormat,t)}static fromExamples(e,t,n,i=`
86
+
87
+ `,s=""){let a=[s,...e,t].join(i);return new r({inputVariables:n,template:a})}static fromTemplate(e,t){let{templateFormat:n="f-string",...i}=t??{},s=new Set;return Ep(e,n).forEach(a=>{a.type==="variable"&&s.add(a.name)}),new r({inputVariables:[...s],templateFormat:n,template:e,...i})}async partial(e){let t=this.inputVariables.filter(s=>!(s in e)),n={...this.partialVariables??{},...e},i={...this,inputVariables:t,partialVariables:n};return new r(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(e){if(!e.template)throw new Error("Prompt template must have a template");return new r({inputVariables:e.input_variables,template:e.template,templateFormat:e.template_format})}};export{kv as a,au as b,Lp as c,ou as d,Mn as e,Ze as f,Dp as g,Un as h,Zn as i,ex as j,Fn as k,rx as l,Ds as m,kt as n,jv as o,Lv as p,zv as q,Mv as r,Dv as s,Uv as t,Fv as u,Zv as v,Be as w,cu as x,de as y,Vv as z,re as A,Wr as B,lu as C,ke as D,du as E,Ms as F,Hv as G,sx as H,Yr as I,fu as J,ax as K,ox as L,xr as M,fx as N,px as O,Pt as P,Xr as Q,Bn as R,gx as S,_x as T,Gn as U,qn as V,wx as W,vx as X,wt as Y,Dn as Z,Wv as _,Yv as $,Vn as aa,Er as ba,Hn as ca,Ox as da,$x as ea,Dx as fa,Jn as ga,Gp as ha,Ux as ia,Fx as ja,Zx as ka,Dd as la,nt as ma,pb as na,hb as oa,Lt as pa,mb as qa,De as ra,_b as sa,bb as ta,Mt as ua,wb as va,Eb as wa,Tb as xa,Ye as ya,Ib as za,b as Aa,Tt as Ba,dr as Ca,BE as Da,Ue as Ea,Xe as Fa,so as Ga,W as Ha,me as Ia,It as Ja,ge as Ka,ns as La,Pb as Ma,Nb as Na,Cb as Oa,yr as Pa,uo as Qa,jb as Ra,yn as Sa,Mb as Ta,Sn as Ua,wo as Va,n$ as Wa,Zt as Xa,Q as Ya,se as Za,ae as _a,yk as $a,up as ab,bk as bb,cp as cb,wk as db,vk as eb,lp as fb,xk as gb,dp as hb,fp as ib,_t as jb,$o as kb,Ek as lb,Sk as mb,Tk as nb,Ok as ob,ys as pb,op as qb,$k as rb,Zr as sb,Io as tb,bs as ub,nv as vb,$n as wb,oe as xb,ue as yb,vr as zb,Ro as Ab,xs as Bb,Es as Cb,Br as Db,Ss as Eb,_p as Fb,Co as Gb,wr as Hb,jo as Ib,Lo as Jb,Ts as Kb,Qr as Lb,Fs as Mb,Zs as Nb,qp as Ob,$s as Pb,vp as Qb,Sv as Rb,Tv as Sb,Ov as Tb,Do as Ub,$v as Vb,Vr as Wb,Ep as Xb,Sp as Yb,Tp as Zb,Os as _b};