@arcgis/portal-components 6.0.0-next.7 → 6.0.0-next.8

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 (133) hide show
  1. package/dist/cdn/{REM3KCX6.js → 246SJJBA.js} +1 -1
  2. package/dist/cdn/{YYTEJVBL.js → 2JAJY2VO.js} +1 -1
  3. package/dist/cdn/{R3PK7XOP.js → 2TKT6SAB.js} +1 -1
  4. package/dist/cdn/{TXC7YBGL.js → 3Y4Q2QIO.js} +1 -1
  5. package/dist/cdn/{CFRJU6VA.js → 44QEELTO.js} +1 -1
  6. package/dist/cdn/45VDX7UP.js +2 -0
  7. package/dist/cdn/{JIJO4CAS.js → 4GW4GUU2.js} +1 -1
  8. package/dist/cdn/{74T6IXSN.js → 4PE6HPG5.js} +1 -1
  9. package/dist/cdn/{5C5GHX4D.js → 4ZBV347A.js} +1 -1
  10. package/dist/cdn/{LISDTBEX.js → 57MB3EJS.js} +1 -1
  11. package/dist/cdn/{D2YQWKME.js → 5A2EOWEO.js} +1 -1
  12. package/dist/cdn/{HCNTXLUT.js → 5B4JGREM.js} +1 -1
  13. package/dist/cdn/{UZP4YMTE.js → 5UJQ4NJH.js} +1 -1
  14. package/dist/cdn/{SVROAT3Z.js → 5XZ6DP7W.js} +1 -1
  15. package/dist/cdn/{QWHGLE3O.js → 62JOBFQ4.js} +1 -1
  16. package/dist/cdn/6GOK3RN3.js +2 -0
  17. package/dist/cdn/{JWBUJT43.js → 6GP2LNEV.js} +1 -1
  18. package/dist/cdn/{3EYB5GQX.js → 6NENX7Z3.js} +1 -1
  19. package/dist/cdn/{3NSHGKZA.js → 7BHYNG4B.js} +1 -1
  20. package/dist/cdn/{IERTEUOU.js → 7LVML2FZ.js} +1 -1
  21. package/dist/cdn/7TUFA422.js +2 -0
  22. package/dist/cdn/A55BLLIF.js +2 -0
  23. package/dist/cdn/{QROXYP6V.js → AWRRQ7RJ.js} +1 -1
  24. package/dist/cdn/{2CN754CY.js → AYS4RM4F.js} +1 -1
  25. package/dist/cdn/{MQK63FV7.js → BM5GFRA5.js} +1 -1
  26. package/dist/cdn/{MKSFNVXL.js → CSRZ3UYP.js} +1 -1
  27. package/dist/cdn/DG42CMOW.js +2 -0
  28. package/dist/cdn/{TUUUK3VX.js → DG6ZTIXN.js} +1 -1
  29. package/dist/cdn/EIY4PTKE.js +2 -0
  30. package/dist/cdn/EOOIJFXY.js +106 -0
  31. package/dist/cdn/{FNLBJ4ZQ.js → FCXGMUKN.js} +1 -1
  32. package/dist/cdn/{7ZWYUHGK.js → FJ3I3AJE.js} +1 -1
  33. package/dist/cdn/FYGYVFYN.js +2 -0
  34. package/dist/cdn/{DDBXEXOV.js → GI7FP7QS.js} +1 -1
  35. package/dist/cdn/GLSO37KO.js +2 -0
  36. package/dist/cdn/HL6DIHGB.js +2 -0
  37. package/dist/cdn/{JPUUMGX5.js → HNJ4WG6S.js} +1 -1
  38. package/dist/cdn/{URQML7KV.js → I2BD4LLC.js} +1 -1
  39. package/dist/cdn/I6JPDE5A.js +2 -0
  40. package/dist/cdn/{A2SQ4EMZ.js → I6WGLIEC.js} +1 -1
  41. package/dist/cdn/ICBR2OCU.js +2 -0
  42. package/dist/cdn/IQ5E2SBI.js +2 -0
  43. package/dist/cdn/J3TKEUDM.js +2 -0
  44. package/dist/cdn/{J5NPDIZM.js → JJMPNXBB.js} +1 -1
  45. package/dist/cdn/JQWP52DP.js +2 -0
  46. package/dist/cdn/{DHMNNIXZ.js → JYCYDBAG.js} +1 -1
  47. package/dist/cdn/JZ7EM2ZO.js +66 -0
  48. package/dist/cdn/{TNUCSWBN.js → KPPWXDMB.js} +1 -1
  49. package/dist/cdn/{LYLQCBVX.js → KPRVCJDS.js} +1 -1
  50. package/dist/cdn/{BYHX3UWV.js → LH2BYW64.js} +1 -1
  51. package/dist/cdn/LXCJCIZR.js +2 -0
  52. package/dist/cdn/{2TDHJSMP.js → MBED25WP.js} +1 -1
  53. package/dist/cdn/{VNU4QX7M.js → MEEQR6TP.js} +1 -1
  54. package/dist/cdn/{JN23JH3T.js → MFNIHL5Z.js} +1 -1
  55. package/dist/cdn/NH5FUP2R.js +68 -0
  56. package/dist/cdn/{ZKZDKJ6D.js → NQIA6PUB.js} +1 -1
  57. package/dist/cdn/{24QSQLRY.js → OFTSD4KV.js} +1 -1
  58. package/dist/cdn/{QTAYXO5T.js → OFWQLRQE.js} +1 -1
  59. package/dist/cdn/{E66BDC6N.js → QXBFIAOL.js} +1 -1
  60. package/dist/cdn/{RNWICLRH.js → SZBYKEBD.js} +1 -1
  61. package/dist/cdn/{Z3HGPBOR.js → U5V6FHGD.js} +1 -1
  62. package/dist/cdn/{ULFFGJXZ.js → UAOTCRUQ.js} +1 -1
  63. package/dist/cdn/UFSITLDM.js +409 -0
  64. package/dist/cdn/{EY5S6ICQ.js → UTIQNPTO.js} +1 -1
  65. package/dist/cdn/{OXPXXIWL.js → VKMH5MIX.js} +1 -1
  66. package/dist/cdn/{QUOLQGKP.js → WFCA26YH.js} +1 -1
  67. package/dist/cdn/{DLI4XKJ3.js → XARJNTJM.js} +1 -1
  68. package/dist/cdn/{4QFTKB6T.js → XQE23XTL.js} +1 -1
  69. package/dist/cdn/XWAEM6AR.js +2 -0
  70. package/dist/cdn/{JE2376SE.js → YGFVCV25.js} +1 -1
  71. package/dist/cdn/{J5FKIZAM.js → YLIARVQ3.js} +1 -1
  72. package/dist/cdn/Z3CMSP24.js +2 -0
  73. package/dist/cdn/{FIQZPIIK.js → Z6UZJYCX.js} +1 -1
  74. package/dist/cdn/{UEP2NYJK.js → ZSUK7J3T.js} +1 -1
  75. package/dist/cdn/index.js +1 -1
  76. package/dist/chunks/fieldAddDelete.js +1 -1
  77. package/dist/chunks/item.js +127 -33
  78. package/dist/chunks/item2.js +69 -126
  79. package/dist/chunks/portal-related-items-list-item.js +1 -1
  80. package/dist/chunks/portalEntitySelection.js +49 -0
  81. package/dist/chunks/query.js +10 -10
  82. package/dist/chunks/utils3.js +1 -1
  83. package/dist/components/arcgis-portal-add-gps-metadata/customElement.d.ts +6 -0
  84. package/dist/components/arcgis-portal-add-gps-metadata/customElement.js +10 -10
  85. package/dist/components/arcgis-portal-ai-assistant/customElement.d.ts +4 -0
  86. package/dist/components/arcgis-portal-ai-assistant/customElement.js +1241 -1145
  87. package/dist/components/arcgis-portal-ai-assistant/index.js +1 -0
  88. package/dist/components/arcgis-portal-ai-assistant/types/portalEntityTools.d.ts +13 -0
  89. package/dist/components/arcgis-portal-ai-assistant-interrupt/customElement.d.ts +27 -0
  90. package/dist/components/arcgis-portal-ai-assistant-interrupt/customElement.js +61 -26
  91. package/dist/components/arcgis-portal-ai-assistant-interrupt/index.js +3 -1
  92. package/dist/components/arcgis-portal-delete-items/customElement.js +344 -313
  93. package/dist/components/arcgis-portal-group-browser/customElement.js +8 -8
  94. package/dist/components/arcgis-portal-item-thumbnail/customElement.js +1 -1
  95. package/dist/components/arcgis-portal-mentionable-text-area/customElement.js +1 -1
  96. package/dist/components/arcgis-portal-navigation/customElement.js +1 -2
  97. package/dist/components/arcgis-portal-navigation/index.js +5 -5
  98. package/dist/components/arcgis-portal-replacement-item-redirect/customElement.js +1 -1
  99. package/dist/components/arcgis-portal-review-related-items/customElement.js +35 -20
  100. package/dist/components/portal-related-items-list-item/customElement.js +14 -14
  101. package/dist/docs/api.json +1 -1
  102. package/dist/docs/docs.json +1 -1
  103. package/dist/docs/vscode.html-custom-data.json +1 -1
  104. package/dist/docs/web-types.json +1 -1
  105. package/dist/index.d.ts +1 -0
  106. package/dist/loader.js +3 -3
  107. package/dist/types/lumina.d.ts +3 -3
  108. package/dist/types/preact.d.ts +3 -3
  109. package/dist/types/react.d.ts +3 -3
  110. package/dist/types/stencil.d.ts +3 -3
  111. package/package.json +7 -7
  112. package/dist/cdn/23NXHNPU.js +0 -2
  113. package/dist/cdn/26PILQCA.js +0 -2
  114. package/dist/cdn/2FQKDFEE.js +0 -2
  115. package/dist/cdn/2RDQX6UR.js +0 -2
  116. package/dist/cdn/3FSPL34I.js +0 -170
  117. package/dist/cdn/3LEQ37YT.js +0 -68
  118. package/dist/cdn/4PRXQFCV.js +0 -2
  119. package/dist/cdn/EEAVX4PP.js +0 -2
  120. package/dist/cdn/GSOBDGLK.js +0 -2
  121. package/dist/cdn/GXM3XY3J.js +0 -2
  122. package/dist/cdn/MRJO2LXU.js +0 -2
  123. package/dist/cdn/N4VOTJ25.js +0 -2
  124. package/dist/cdn/RDXUP624.js +0 -2
  125. package/dist/cdn/S6F7U36E.js +0 -400
  126. package/dist/cdn/SMX2LEJB.js +0 -2
  127. package/dist/cdn/TBZXKKGP.js +0 -2
  128. package/dist/cdn/WWEK2CFY.js +0 -2
  129. package/dist/cdn/YB3DR4VO.js +0 -2
  130. package/dist/cdn/ZDDN7UKS.js +0 -2
  131. package/dist/cdn/ZXNF77OB.js +0 -2
  132. package/dist/chunks/functional.js +0 -9
  133. /package/dist/cdn/{XYMBRPC7.js → ZDMCDQRC.js} +0 -0
@@ -0,0 +1,106 @@
1
+ /* COPYRIGHT Esri - https://js.arcgis.com/6.0/LICENSE.txt */
2
+ import{$ as _e,$a as Vt,A as _i,Aa as Zi,B as vi,C as bi,D as wi,Da as Ui,E as ki,Ea as tn,F as We,G as _r,Ha as wr,I as Pn,J as Tt,Ja as $n,K as Gr,Ka as Vi,L as xi,M as Ti,Ma as iu,N as Si,P as Ei,Pa as kr,Q as vr,R as Ai,Ra as Dn,S as Ra,U as zt,V as Jr,Va as Ln,W as Ci,Wa as tt,X as Oi,Y as Ge,Ya as Ce,Z as br,_ as qr,_a as he,a as M,aa as Hr,ab as q,b as gr,ba as Kr,bb as Y,c as si,ca as Ii,cb as xe,d as yr,da as Ni,ea as Yr,fa as Xr,ga as Pi,ha as Ri,ia as et,ja as Qr,k as Cn,ka as Mi,l as ii,la as $i,m as On,ma as en,n as In,na as Bt,o as oi,oa as Zt,p as ci,pa as Di,q as Nn,qa as Li,r as ui,ra as ji,s as li,sa as St,t as di,ta as Rn,u as fi,ua as Mn,v as pi,va as Fi,w as mi,wa as zi,x as hi,xa as Ut,y as gi,ya as Bi,z as yi}from"./GGDOGNH4.js";import{a as rt,b as Ma,c as jn,d as $a,e as Wi,f as Gi,g as Da,j as Te,k as Ji,l as qi,m as La,o as ja}from"./JZ7EM2ZO.js";import{a as au,b as su,c as ai}from"./5PV2GUZW.js";var pc=au(_a=>{"use strict";_a.byteLength=Pd;_a.toByteArray=Md;_a.fromByteArray=Ld;var lt=[],Be=[],Nd=typeof Uint8Array<"u"?Uint8Array:Array,Us="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(fr=0,dc=Us.length;fr<dc;++fr)lt[fr]=Us[fr],Be[Us.charCodeAt(fr)]=fr;var fr,dc;Be[45]=62;Be[95]=63;function fc(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");r===-1&&(r=t);var n=r===t?0:4-r%4;return[r,n]}function Pd(e){var t=fc(e),r=t[0],n=t[1];return(r+n)*3/4-n}function Rd(e,t,r){return(t+r)*3/4-r}function Md(e){var t,r=fc(e),n=r[0],a=r[1],s=new Nd(Rd(e,n,a)),i=0,o=a>0?n-4:n,c;for(c=0;c<o;c+=4)t=Be[e.charCodeAt(c)]<<18|Be[e.charCodeAt(c+1)]<<12|Be[e.charCodeAt(c+2)]<<6|Be[e.charCodeAt(c+3)],s[i++]=t>>16&255,s[i++]=t>>8&255,s[i++]=t&255;return a===2&&(t=Be[e.charCodeAt(c)]<<2|Be[e.charCodeAt(c+1)]>>4,s[i++]=t&255),a===1&&(t=Be[e.charCodeAt(c)]<<10|Be[e.charCodeAt(c+1)]<<4|Be[e.charCodeAt(c+2)]>>2,s[i++]=t>>8&255,s[i++]=t&255),s}function $d(e){return lt[e>>18&63]+lt[e>>12&63]+lt[e>>6&63]+lt[e&63]}function Dd(e,t,r){for(var n,a=[],s=t;s<r;s+=3)n=(e[s]<<16&16711680)+(e[s+1]<<8&65280)+(e[s+2]&255),a.push($d(n));return a.join("")}function Ld(e){for(var t,r=e.length,n=r%3,a=[],s=16383,i=0,o=r-n;i<o;i+=s)a.push(Dd(e,i,i+s>o?o:i+s));return n===1?(t=e[r-1],a.push(lt[t>>2]+lt[t<<4&63]+"==")):n===2&&(t=(e[r-2]<<8)+e[r-1],a.push(lt[t>>10]+lt[t>>4&63]+lt[t<<2&63]+"=")),a.join("")}});async function Oe(e,t){if(t===void 0)return e;let r;return Promise.race([e.catch(n=>{if(!t?.aborted)throw n}),new Promise((n,a)=>{r=()=>{a(Et(t))},t.addEventListener("abort",r,{once:!0}),t.aborted&&a(Et(t))})]).finally(()=>t.removeEventListener("abort",r))}function Et(e){return e?.reason instanceof Error?e.reason:typeof e?.reason=="string"?new Error(e.reason):new Error("Aborted")}function te(e){if(typeof e!="object"||e===null)return!1;let t=e;if(!("_zod"in t))return!1;let r=t._zod;return typeof r=="object"&&r!==null&&"def"in r}function oe(e){if(typeof e!="object"||e===null)return!1;let t=e;if(!("_def"in t)||"_zod"in t)return!1;let r=t._def;return typeof r=="object"&&r!=null&&"typeName"in r}function Hi(e){return te(e)&&console.warn("[WARNING] Attempting to use Zod 4 schema in a context where Zod 3 schema is expected. This may cause unexpected behavior."),oe(e)}function Se(e){return!e||typeof e!="object"||Array.isArray(e)?!1:!!(te(e)||oe(e))}function Fa(e){return typeof e=="object"&&e!==null&&"_def"in e&&typeof e._def=="object"&&e._def!==null&&"typeName"in e._def&&e._def.typeName==="ZodLiteral"}function za(e){return te(e)?typeof e=="object"&&e!==null&&"_zod"in e&&typeof e._zod=="object"&&e._zod!==null&&"def"in e._zod&&typeof e._zod.def=="object"&&e._zod.def!==null&&"type"in e._zod.def&&e._zod.def.type==="literal":!1}function Ki(e){return!!(Fa(e)||za(e))}async function Bn(e,t){if(te(e))try{return{success:!0,data:await $a(e,t)}}catch(r){return{success:!1,error:r}}if(oe(e))return await e.safeParseAsync(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}async function At(e,t){if(te(e))return await $a(e,t);if(oe(e))return await e.parseAsync(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function Yi(e,t){if(te(e))try{return{success:!0,data:jn(e,t)}}catch(r){return{success:!1,error:r}}if(oe(e))return e.safeParse(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function Xi(e,t){if(te(e))return jn(e,t);if(oe(e))return e.parse(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function Tr(e){if(te(e))return Te.get(e)?.description;if(oe(e)||"description"in e&&typeof e.description=="string")return e.description}function Qi(e){if(!Se(e))return!1;if(oe(e)){let t=e._def;if(t.typeName==="ZodObject"){let r=e;return!r.shape||Object.keys(r.shape).length===0}if(t.typeName==="ZodRecord")return!0}if(te(e)){let t=e._zod.def;if(t.type==="object"){let r=e;return!r.shape||Object.keys(r.shape).length===0}if(t.type==="record")return!0}return typeof e=="object"&&e!==null&&!("shape"in e)}function Sr(e){return Se(e)?oe(e)?e._def.typeName==="ZodString":te(e)?e._zod.def.type==="string":!1:!1}function rn(e){return typeof e=="object"&&e!==null&&"_def"in e&&typeof e._def=="object"&&e._def!==null&&"typeName"in e._def&&e._def.typeName==="ZodObject"}function $e(e){return te(e)?typeof e=="object"&&e!==null&&"_zod"in e&&typeof e._zod=="object"&&e._zod!==null&&"def"in e._zod&&typeof e._zod.def=="object"&&e._zod.def!==null&&"type"in e._zod.def&&e._zod.def.type==="object":!1}function nn(e){return te(e)?typeof e=="object"&&e!==null&&"_zod"in e&&typeof e._zod=="object"&&e._zod!==null&&"def"in e._zod&&typeof e._zod.def=="object"&&e._zod.def!==null&&"type"in e._zod.def&&e._zod.def.type==="array":!1}function Ba(e){return te(e)?typeof e=="object"&&e!==null&&"_zod"in e&&typeof e._zod=="object"&&e._zod!==null&&"def"in e._zod&&typeof e._zod.def=="object"&&e._zod.def!==null&&"type"in e._zod.def&&e._zod.def.type==="optional":!1}function Za(e){return te(e)?typeof e=="object"&&e!==null&&"_zod"in e&&typeof e._zod=="object"&&e._zod!==null&&"def"in e._zod&&typeof e._zod.def=="object"&&e._zod.def!==null&&"type"in e._zod.def&&e._zod.def.type==="nullable":!1}function eo(e){return!!(rn(e)||$e(e))}function Fn(e){if(oe(e))return e.shape;if(te(e))return e._zod.def.shape;throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function to(e,t){if(oe(e))return e.extend(t);if(te(e))return Ma.extend(e,t);throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function ro(e){if(oe(e))return e.partial();if(te(e))return Ma.partial(Da,e,void 0);throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function xr(e,t=!1){if(rn(e))return e.strict();if($e(e)){let r=e._zod.def.shape;if(t)for(let[s,i]of Object.entries(e._zod.def.shape)){if($e(i))r[s]=xr(i,t);else if(nn(i)){let c=i._zod.def.element;$e(c)&&(c=xr(c,t)),r[s]=rt(i,{...i._zod.def,element:c})}else r[s]=i;let o=Te.get(i);o&&Te.add(r[s],o)}let n=rt(e,{...e._zod.def,shape:r,catchall:qi(Gi)}),a=Te.get(e);return a&&Te.add(n,a),n}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function zn(e,t=!1){if(rn(e))return e.passthrough();if($e(e)){let r=e._zod.def.shape;if(t)for(let[s,i]of Object.entries(e._zod.def.shape)){if($e(i))r[s]=zn(i,t);else if(nn(i)){let c=i._zod.def.element;$e(c)&&(c=zn(c,t)),r[s]=rt(i,{...i._zod.def,element:c})}else r[s]=i;let o=Te.get(i);o&&Te.add(r[s],o)}let n=rt(e,{...e._zod.def,shape:r,catchall:Ji(Wi)}),a=Te.get(e);return a&&Te.add(n,a),n}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function no(e){if(oe(e))try{let t=e.parse(void 0);return()=>t}catch{return}if(te(e))try{let t=jn(e,void 0);return()=>t}catch{return}}function ou(e){return oe(e)&&"typeName"in e._def&&e._def.typeName==="ZodEffects"}function cu(e){return te(e)&&e._zod.def.type==="pipe"}function Wt(e,t,r){let n=r.get(e);if(n!==void 0)return n;if(oe(e))return ou(e)?Wt(e._def.schema,t,r):e;if(te(e)){let a=e;if(cu(e)&&(a=Wt(e._zod.def.in,t,r)),t){if($e(a)){let i={};for(let[o,c]of Object.entries(a._zod.def.shape))i[o]=Wt(c,t,r);a=rt(a,{...a._zod.def,shape:i})}else if(nn(a)){let i=Wt(a._zod.def.element,t,r);a=rt(a,{...a._zod.def,element:i})}else if(Ba(a)){let i=Wt(a._zod.def.innerType,t,r);a=rt(a,{...a._zod.def,innerType:i})}else if(Za(a)){let i=Wt(a._zod.def.innerType,t,r);a=rt(a,{...a._zod.def,innerType:i})}}let s=Te.get(e);return s&&Te.add(a,s),r.set(e,a),a}throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function Zn(e,t=!1){return Wt(e,t,new WeakMap)}function ao(e,t){if(oe(e)){let r=Fn(e),n={};for(let[a,s]of Object.entries(r))t(a,s)?n[a]=s.optional():n[a]=s;return e.extend(n)}if(te(e)){let r=Fn(e),n={...e._zod.def.shape};for(let[i,o]of Object.entries(r))t(i,o)&&(n[i]=new Da({type:"optional",innerType:o}));let a=rt(e,{...e._zod.def,shape:n}),s=Te.get(e);return s&&Te.add(a,s),a}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Un(e){return e instanceof Error&&(e.constructor.name==="ZodError"||e.constructor.name==="$ZodError")}var Va=Symbol("Let zodToJsonSchema decide on which parser to use"),Ua={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"},Wa=e=>typeof e=="string"?{...Ua,name:e}:{...Ua,...e};var Ga=e=>{let t=Wa(e),r=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([n,a])=>[a._def,{def:a._def,path:[...t.basePath,t.definitionPath,n],jsonSchema:void 0}]))}};var an=(e,t)=>{let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];r++);return[(e.length-r).toString(),...t.slice(r)].join("/")};function ne(e){if(e.target!=="openAi")return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy==="relative"?an(t,e.currentPath):t.join("/")}}function Vn(e,t,r,n){n?.errorMessages&&r&&(e.errorMessage={...e.errorMessage,[t]:r})}function H(e,t,r,n,a){e[t]=r,Vn(e,t,n,a)}var ve={};su(ve,{BRAND:()=>Mu,DIRTY:()=>Gt,EMPTY_PATH:()=>fu,INVALID:()=>D,NEVER:()=>_l,OK:()=>ge,ParseStatus:()=>pe,Schema:()=>W,ZodAny:()=>It,ZodArray:()=>gt,ZodBigInt:()=>qt,ZodBoolean:()=>Ht,ZodBranded:()=>on,ZodCatch:()=>ir,ZodDate:()=>Kt,ZodDefault:()=>sr,ZodDiscriminatedUnion:()=>Jn,ZodEffects:()=>je,ZodEnum:()=>nr,ZodError:()=>Ee,ZodFirstPartyTypeKind:()=>T,ZodFunction:()=>Hn,ZodIntersection:()=>er,ZodIssueCode:()=>x,ZodLazy:()=>tr,ZodLiteral:()=>rr,ZodMap:()=>Nr,ZodNaN:()=>Rr,ZodNativeEnum:()=>ar,ZodNever:()=>Je,ZodNull:()=>Xt,ZodNullable:()=>st,ZodNumber:()=>Jt,ZodObject:()=>Ae,ZodOptional:()=>De,ZodParsedType:()=>O,ZodPipeline:()=>cn,ZodPromise:()=>Nt,ZodReadonly:()=>or,ZodRecord:()=>qn,ZodSchema:()=>W,ZodSet:()=>Pr,ZodString:()=>Ot,ZodSymbol:()=>Or,ZodTransformer:()=>je,ZodTuple:()=>at,ZodType:()=>W,ZodUndefined:()=>Yt,ZodUnion:()=>Qt,ZodUnknown:()=>ht,ZodVoid:()=>Ir,addIssueToContext:()=>E,any:()=>Uu,array:()=>Ju,bigint:()=>ju,boolean:()=>go,coerce:()=>yl,custom:()=>po,date:()=>Fu,datetimeRegex:()=>lo,defaultErrorMap:()=>pt,discriminatedUnion:()=>Yu,effect:()=>ul,enum:()=>il,function:()=>nl,getErrorMap:()=>Er,getParsedType:()=>nt,instanceof:()=>Du,intersection:()=>Xu,isAborted:()=>Wn,isAsync:()=>Ar,isDirty:()=>Gn,isValid:()=>Ct,late:()=>$u,lazy:()=>al,literal:()=>sl,makeIssue:()=>sn,map:()=>tl,nan:()=>Lu,nativeEnum:()=>ol,never:()=>Wu,null:()=>Zu,nullable:()=>dl,number:()=>ho,object:()=>qu,objectUtil:()=>Ja,oboolean:()=>gl,onumber:()=>hl,optional:()=>ll,ostring:()=>ml,pipeline:()=>pl,preprocess:()=>fl,promise:()=>cl,quotelessJson:()=>uu,record:()=>el,set:()=>rl,setErrorMap:()=>du,strictObject:()=>Hu,string:()=>mo,symbol:()=>zu,transformer:()=>ul,tuple:()=>Qu,undefined:()=>Bu,union:()=>Ku,unknown:()=>Vu,util:()=>J,void:()=>Gu});var J;(function(e){e.assertEqual=a=>{};function t(a){}e.assertIs=t;function r(a){throw new Error}e.assertNever=r,e.arrayToEnum=a=>{let s={};for(let i of a)s[i]=i;return s},e.getValidEnumValues=a=>{let s=e.objectKeys(a).filter(o=>typeof a[a[o]]!="number"),i={};for(let o of s)i[o]=a[o];return e.objectValues(i)},e.objectValues=a=>e.objectKeys(a).map(function(s){return a[s]}),e.objectKeys=typeof Object.keys=="function"?a=>Object.keys(a):a=>{let s=[];for(let i in a)Object.prototype.hasOwnProperty.call(a,i)&&s.push(i);return s},e.find=(a,s)=>{for(let i of a)if(s(i))return i},e.isInteger=typeof Number.isInteger=="function"?a=>Number.isInteger(a):a=>typeof a=="number"&&Number.isFinite(a)&&Math.floor(a)===a;function n(a,s=" | "){return a.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}e.joinValues=n,e.jsonStringifyReplacer=(a,s)=>typeof s=="bigint"?s.toString():s})(J||(J={}));var Ja;(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(Ja||(Ja={}));var O=J.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),nt=e=>{switch(typeof e){case"undefined":return O.undefined;case"string":return O.string;case"number":return Number.isNaN(e)?O.nan:O.number;case"boolean":return O.boolean;case"function":return O.function;case"bigint":return O.bigint;case"symbol":return O.symbol;case"object":return Array.isArray(e)?O.array:e===null?O.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?O.promise:typeof Map<"u"&&e instanceof Map?O.map:typeof Set<"u"&&e instanceof Set?O.set:typeof Date<"u"&&e instanceof Date?O.date:O.object;default:return O.unknown}};var x=J.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"]),uu=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),Ee=class e extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=t}format(t){let r=t||function(s){return s.message},n={_errors:[]},a=s=>{for(let i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(a);else if(i.code==="invalid_return_type")a(i.returnTypeError);else if(i.code==="invalid_arguments")a(i.argumentsError);else if(i.path.length===0)n._errors.push(r(i));else{let o=n,c=0;for(;c<i.path.length;){let l=i.path[c];c===i.path.length-1?(o[l]=o[l]||{_errors:[]},o[l]._errors.push(r(i))):o[l]=o[l]||{_errors:[]},o=o[l],c++}}};return a(this),n}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,J.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=r=>r.message){let r=Object.create(null),n=[];for(let a of this.issues)if(a.path.length>0){let s=a.path[0];r[s]=r[s]||[],r[s].push(t(a))}else n.push(t(a));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};Ee.create=e=>new Ee(e);var lu=(e,t)=>{let r;switch(e.code){case x.invalid_type:e.received===O.undefined?r="Required":r=`Expected ${e.expected}, received ${e.received}`;break;case x.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,J.jsonStringifyReplacer)}`;break;case x.unrecognized_keys:r=`Unrecognized key(s) in object: ${J.joinValues(e.keys,", ")}`;break;case x.invalid_union:r="Invalid input";break;case x.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${J.joinValues(e.options)}`;break;case x.invalid_enum_value:r=`Invalid enum value. Expected ${J.joinValues(e.options)}, received '${e.received}'`;break;case x.invalid_arguments:r="Invalid function arguments";break;case x.invalid_return_type:r="Invalid function return type";break;case x.invalid_date:r="Invalid date";break;case x.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:J.assertNever(e.validation):e.validation!=="regex"?r=`Invalid ${e.validation}`:r="Invalid";break;case x.too_small:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:r="Invalid input";break;case x.too_big:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?r=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:r="Invalid input";break;case x.custom:r="Invalid input";break;case x.invalid_intersection_types:r="Intersection results could not be merged";break;case x.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case x.not_finite:r="Number must be finite";break;default:r=t.defaultError,J.assertNever(e)}return{message:r}},pt=lu;var so=pt;function du(e){so=e}function Er(){return so}var sn=e=>{let{data:t,path:r,errorMaps:n,issueData:a}=e,s=[...r,...a.path||[]],i={...a,path:s};if(a.message!==void 0)return{...a,path:s,message:a.message};let o="",c=n.filter(l=>!!l).slice().reverse();for(let l of c)o=l(i,{data:t,defaultError:o}).message;return{...a,path:s,message:o}},fu=[];function E(e,t){let r=Er(),n=sn({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===pt?void 0:pt].filter(a=>!!a)});e.common.issues.push(n)}var pe=class e{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,r){let n=[];for(let a of r){if(a.status==="aborted")return D;a.status==="dirty"&&t.dirty(),n.push(a.value)}return{status:t.value,value:n}}static async mergeObjectAsync(t,r){let n=[];for(let a of r){let s=await a.key,i=await a.value;n.push({key:s,value:i})}return e.mergeObjectSync(t,n)}static mergeObjectSync(t,r){let n={};for(let a of r){let{key:s,value:i}=a;if(s.status==="aborted"||i.status==="aborted")return D;s.status==="dirty"&&t.dirty(),i.status==="dirty"&&t.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||a.alwaysSet)&&(n[s.value]=i.value)}return{status:t.value,value:n}}},D=Object.freeze({status:"aborted"}),Gt=e=>({status:"dirty",value:e}),ge=e=>({status:"valid",value:e}),Wn=e=>e.status==="aborted",Gn=e=>e.status==="dirty",Ct=e=>e.status==="valid",Ar=e=>typeof Promise<"u"&&e instanceof Promise;var R;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(R||(R={}));var Le=class{constructor(t,r,n,a){this._cachedPath=[],this.parent=t,this.data=r,this._path=n,this._key=a}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},io=(e,t)=>{if(Ct(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new Ee(e.common.issues);return this._error=r,this._error}}};function U(e){if(!e)return{};let{errorMap:t,invalid_type_error:r,required_error:n,description:a}=e;if(t&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:a}:{errorMap:(i,o)=>{let{message:c}=e;return i.code==="invalid_enum_value"?{message:c??o.defaultError}:typeof o.data>"u"?{message:c??n??o.defaultError}:i.code!=="invalid_type"?{message:o.defaultError}:{message:c??r??o.defaultError}},description:a}}var W=class{get description(){return this._def.description}_getType(t){return nt(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:nt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new pe,ctx:{common:t.parent.common,data:t.data,parsedType:nt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let r=this._parse(t);if(Ar(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(t){let r=this._parse(t);return Promise.resolve(r)}parse(t,r){let n=this.safeParse(t,r);if(n.success)return n.data;throw n.error}safeParse(t,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:nt(t)},a=this._parseSync({data:t,path:n.path,parent:n});return io(n,a)}"~validate"(t){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:nt(t)};if(!this["~standard"].async)try{let n=this._parseSync({data:t,path:[],parent:r});return Ct(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:r}).then(n=>Ct(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(t,r){let n=await this.safeParseAsync(t,r);if(n.success)return n.data;throw n.error}async safeParseAsync(t,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:nt(t)},a=this._parse({data:t,path:n.path,parent:n}),s=await(Ar(a)?a:Promise.resolve(a));return io(n,s)}refine(t,r){let n=a=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(a):r;return this._refinement((a,s)=>{let i=t(a),o=()=>s.addIssue({code:x.custom,...n(a)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(o(),!1)):i?!0:(o(),!1)})}refinement(t,r){return this._refinement((n,a)=>t(n)?!0:(a.addIssue(typeof r=="function"?r(n,a):r),!1))}_refinement(t){return new je({schema:this,typeName:T.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return De.create(this,this._def)}nullable(){return st.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return gt.create(this)}promise(){return Nt.create(this,this._def)}or(t){return Qt.create([this,t],this._def)}and(t){return er.create(this,t,this._def)}transform(t){return new je({...U(this._def),schema:this,typeName:T.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let r=typeof t=="function"?t:()=>t;return new sr({...U(this._def),innerType:this,defaultValue:r,typeName:T.ZodDefault})}brand(){return new on({typeName:T.ZodBranded,type:this,...U(this._def)})}catch(t){let r=typeof t=="function"?t:()=>t;return new ir({...U(this._def),innerType:this,catchValue:r,typeName:T.ZodCatch})}describe(t){let r=this.constructor;return new r({...this._def,description:t})}pipe(t){return cn.create(this,t)}readonly(){return or.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},pu=/^c[^\s-]{8,}$/i,mu=/^[0-9a-z]+$/,hu=/^[0-9A-HJKMNP-TV-Z]{26}$/i,gu=/^[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,yu=/^[a-z0-9_-]{21}$/i,_u=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,vu=/^[-+]?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)?)??$/,bu=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,wu="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",qa,ku=/^(?:(?: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])$/,xu=/^(?:(?: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])$/,Tu=/^(([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]))$/,Su=/^(([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])$/,Eu=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Au=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,co="((\\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])))",Cu=new RegExp(`^${co}$`);function uo(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);let r=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${r}`}function Ou(e){return new RegExp(`^${uo(e)}$`)}function lo(e){let t=`${co}T${uo(e)}`,r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function Iu(e,t){return!!((t==="v4"||!t)&&ku.test(e)||(t==="v6"||!t)&&Tu.test(e))}function Nu(e,t){if(!_u.test(e))return!1;try{let[r]=e.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),a=JSON.parse(atob(n));return!(typeof a!="object"||a===null||"typ"in a&&a?.typ!=="JWT"||!a.alg||t&&a.alg!==t)}catch{return!1}}function Pu(e,t){return!!((t==="v4"||!t)&&xu.test(e)||(t==="v6"||!t)&&Su.test(e))}var Ot=class e extends W{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==O.string){let s=this._getOrReturnCtx(t);return E(s,{code:x.invalid_type,expected:O.string,received:s.parsedType}),D}let n=new pe,a;for(let s of this._def.checks)if(s.kind==="min")t.data.length<s.value&&(a=this._getOrReturnCtx(t,a),E(a,{code:x.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")t.data.length>s.value&&(a=this._getOrReturnCtx(t,a),E(a,{code:x.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){let i=t.data.length>s.value,o=t.data.length<s.value;(i||o)&&(a=this._getOrReturnCtx(t,a),i?E(a,{code:x.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):o&&E(a,{code:x.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")bu.test(t.data)||(a=this._getOrReturnCtx(t,a),E(a,{validation:"email",code:x.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")qa||(qa=new RegExp(wu,"u")),qa.test(t.data)||(a=this._getOrReturnCtx(t,a),E(a,{validation:"emoji",code:x.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")gu.test(t.data)||(a=this._getOrReturnCtx(t,a),E(a,{validation:"uuid",code:x.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")yu.test(t.data)||(a=this._getOrReturnCtx(t,a),E(a,{validation:"nanoid",code:x.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")pu.test(t.data)||(a=this._getOrReturnCtx(t,a),E(a,{validation:"cuid",code:x.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")mu.test(t.data)||(a=this._getOrReturnCtx(t,a),E(a,{validation:"cuid2",code:x.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")hu.test(t.data)||(a=this._getOrReturnCtx(t,a),E(a,{validation:"ulid",code:x.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(t.data)}catch{a=this._getOrReturnCtx(t,a),E(a,{validation:"url",code:x.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(t.data)||(a=this._getOrReturnCtx(t,a),E(a,{validation:"regex",code:x.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?t.data=t.data.trim():s.kind==="includes"?t.data.includes(s.value,s.position)||(a=this._getOrReturnCtx(t,a),E(a,{code:x.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.dirty()):s.kind==="toLowerCase"?t.data=t.data.toLowerCase():s.kind==="toUpperCase"?t.data=t.data.toUpperCase():s.kind==="startsWith"?t.data.startsWith(s.value)||(a=this._getOrReturnCtx(t,a),E(a,{code:x.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?t.data.endsWith(s.value)||(a=this._getOrReturnCtx(t,a),E(a,{code:x.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?lo(s).test(t.data)||(a=this._getOrReturnCtx(t,a),E(a,{code:x.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?Cu.test(t.data)||(a=this._getOrReturnCtx(t,a),E(a,{code:x.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?Ou(s).test(t.data)||(a=this._getOrReturnCtx(t,a),E(a,{code:x.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?vu.test(t.data)||(a=this._getOrReturnCtx(t,a),E(a,{validation:"duration",code:x.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?Iu(t.data,s.version)||(a=this._getOrReturnCtx(t,a),E(a,{validation:"ip",code:x.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?Nu(t.data,s.alg)||(a=this._getOrReturnCtx(t,a),E(a,{validation:"jwt",code:x.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?Pu(t.data,s.version)||(a=this._getOrReturnCtx(t,a),E(a,{validation:"cidr",code:x.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?Eu.test(t.data)||(a=this._getOrReturnCtx(t,a),E(a,{validation:"base64",code:x.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?Au.test(t.data)||(a=this._getOrReturnCtx(t,a),E(a,{validation:"base64url",code:x.invalid_string,message:s.message}),n.dirty()):J.assertNever(s);return{status:n.value,value:t.data}}_regex(t,r,n){return this.refinement(a=>t.test(a),{validation:r,code:x.invalid_string,...R.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...R.errToObj(t)})}url(t){return this._addCheck({kind:"url",...R.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...R.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...R.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...R.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...R.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...R.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...R.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...R.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...R.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...R.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...R.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...R.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...R.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...R.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...R.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...R.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,...R.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...R.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...R.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...R.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...R.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...R.errToObj(r)})}nonempty(t){return this.min(1,R.errToObj(t))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxLength(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}};Ot.create=e=>new Ot({checks:[],typeName:T.ZodString,coerce:e?.coerce??!1,...U(e)});function Ru(e,t){let r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,a=r>n?r:n,s=Number.parseInt(e.toFixed(a).replace(".","")),i=Number.parseInt(t.toFixed(a).replace(".",""));return s%i/10**a}var Jt=class e extends W{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==O.number){let s=this._getOrReturnCtx(t);return E(s,{code:x.invalid_type,expected:O.number,received:s.parsedType}),D}let n,a=new pe;for(let s of this._def.checks)s.kind==="int"?J.isInteger(t.data)||(n=this._getOrReturnCtx(t,n),E(n,{code:x.invalid_type,expected:"integer",received:"float",message:s.message}),a.dirty()):s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(n=this._getOrReturnCtx(t,n),E(n,{code:x.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),a.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(n=this._getOrReturnCtx(t,n),E(n,{code:x.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),a.dirty()):s.kind==="multipleOf"?Ru(t.data,s.value)!==0&&(n=this._getOrReturnCtx(t,n),E(n,{code:x.not_multiple_of,multipleOf:s.value,message:s.message}),a.dirty()):s.kind==="finite"?Number.isFinite(t.data)||(n=this._getOrReturnCtx(t,n),E(n,{code:x.not_finite,message:s.message}),a.dirty()):J.assertNever(s);return{status:a.value,value:t.data}}gte(t,r){return this.setLimit("min",t,!0,R.toString(r))}gt(t,r){return this.setLimit("min",t,!1,R.toString(r))}lte(t,r){return this.setLimit("max",t,!0,R.toString(r))}lt(t,r){return this.setLimit("max",t,!1,R.toString(r))}setLimit(t,r,n,a){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:R.toString(a)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:R.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:R.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:R.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:R.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:R.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:R.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:R.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:R.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:R.toString(t)})}get minValue(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&J.isInteger(t.value))}get isFinite(){let t=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(t===null||n.value<t)&&(t=n.value)}return Number.isFinite(r)&&Number.isFinite(t)}};Jt.create=e=>new Jt({checks:[],typeName:T.ZodNumber,coerce:e?.coerce||!1,...U(e)});var qt=class e extends W{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==O.bigint)return this._getInvalidInput(t);let n,a=new pe;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(n=this._getOrReturnCtx(t,n),E(n,{code:x.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),a.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(n=this._getOrReturnCtx(t,n),E(n,{code:x.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),a.dirty()):s.kind==="multipleOf"?t.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(t,n),E(n,{code:x.not_multiple_of,multipleOf:s.value,message:s.message}),a.dirty()):J.assertNever(s);return{status:a.value,value:t.data}}_getInvalidInput(t){let r=this._getOrReturnCtx(t);return E(r,{code:x.invalid_type,expected:O.bigint,received:r.parsedType}),D}gte(t,r){return this.setLimit("min",t,!0,R.toString(r))}gt(t,r){return this.setLimit("min",t,!1,R.toString(r))}lte(t,r){return this.setLimit("max",t,!0,R.toString(r))}lt(t,r){return this.setLimit("max",t,!1,R.toString(r))}setLimit(t,r,n,a){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:R.toString(a)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:R.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:R.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:R.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:R.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:R.toString(r)})}get minValue(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}};qt.create=e=>new qt({checks:[],typeName:T.ZodBigInt,coerce:e?.coerce??!1,...U(e)});var Ht=class extends W{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==O.boolean){let n=this._getOrReturnCtx(t);return E(n,{code:x.invalid_type,expected:O.boolean,received:n.parsedType}),D}return ge(t.data)}};Ht.create=e=>new Ht({typeName:T.ZodBoolean,coerce:e?.coerce||!1,...U(e)});var Kt=class e extends W{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==O.date){let s=this._getOrReturnCtx(t);return E(s,{code:x.invalid_type,expected:O.date,received:s.parsedType}),D}if(Number.isNaN(t.data.getTime())){let s=this._getOrReturnCtx(t);return E(s,{code:x.invalid_date}),D}let n=new pe,a;for(let s of this._def.checks)s.kind==="min"?t.data.getTime()<s.value&&(a=this._getOrReturnCtx(t,a),E(a,{code:x.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?t.data.getTime()>s.value&&(a=this._getOrReturnCtx(t,a),E(a,{code:x.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):J.assertNever(s);return{status:n.value,value:new Date(t.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(t,r){return this._addCheck({kind:"min",value:t.getTime(),message:R.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:R.toString(r)})}get minDate(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t!=null?new Date(t):null}};Kt.create=e=>new Kt({checks:[],coerce:e?.coerce||!1,typeName:T.ZodDate,...U(e)});var Or=class extends W{_parse(t){if(this._getType(t)!==O.symbol){let n=this._getOrReturnCtx(t);return E(n,{code:x.invalid_type,expected:O.symbol,received:n.parsedType}),D}return ge(t.data)}};Or.create=e=>new Or({typeName:T.ZodSymbol,...U(e)});var Yt=class extends W{_parse(t){if(this._getType(t)!==O.undefined){let n=this._getOrReturnCtx(t);return E(n,{code:x.invalid_type,expected:O.undefined,received:n.parsedType}),D}return ge(t.data)}};Yt.create=e=>new Yt({typeName:T.ZodUndefined,...U(e)});var Xt=class extends W{_parse(t){if(this._getType(t)!==O.null){let n=this._getOrReturnCtx(t);return E(n,{code:x.invalid_type,expected:O.null,received:n.parsedType}),D}return ge(t.data)}};Xt.create=e=>new Xt({typeName:T.ZodNull,...U(e)});var It=class extends W{constructor(){super(...arguments),this._any=!0}_parse(t){return ge(t.data)}};It.create=e=>new It({typeName:T.ZodAny,...U(e)});var ht=class extends W{constructor(){super(...arguments),this._unknown=!0}_parse(t){return ge(t.data)}};ht.create=e=>new ht({typeName:T.ZodUnknown,...U(e)});var Je=class extends W{_parse(t){let r=this._getOrReturnCtx(t);return E(r,{code:x.invalid_type,expected:O.never,received:r.parsedType}),D}};Je.create=e=>new Je({typeName:T.ZodNever,...U(e)});var Ir=class extends W{_parse(t){if(this._getType(t)!==O.undefined){let n=this._getOrReturnCtx(t);return E(n,{code:x.invalid_type,expected:O.void,received:n.parsedType}),D}return ge(t.data)}};Ir.create=e=>new Ir({typeName:T.ZodVoid,...U(e)});var gt=class e extends W{_parse(t){let{ctx:r,status:n}=this._processInputParams(t),a=this._def;if(r.parsedType!==O.array)return E(r,{code:x.invalid_type,expected:O.array,received:r.parsedType}),D;if(a.exactLength!==null){let i=r.data.length>a.exactLength.value,o=r.data.length<a.exactLength.value;(i||o)&&(E(r,{code:i?x.too_big:x.too_small,minimum:o?a.exactLength.value:void 0,maximum:i?a.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:a.exactLength.message}),n.dirty())}if(a.minLength!==null&&r.data.length<a.minLength.value&&(E(r,{code:x.too_small,minimum:a.minLength.value,type:"array",inclusive:!0,exact:!1,message:a.minLength.message}),n.dirty()),a.maxLength!==null&&r.data.length>a.maxLength.value&&(E(r,{code:x.too_big,maximum:a.maxLength.value,type:"array",inclusive:!0,exact:!1,message:a.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,o)=>a.type._parseAsync(new Le(r,i,r.path,o)))).then(i=>pe.mergeArray(n,i));let s=[...r.data].map((i,o)=>a.type._parseSync(new Le(r,i,r.path,o)));return pe.mergeArray(n,s)}get element(){return this._def.type}min(t,r){return new e({...this._def,minLength:{value:t,message:R.toString(r)}})}max(t,r){return new e({...this._def,maxLength:{value:t,message:R.toString(r)}})}length(t,r){return new e({...this._def,exactLength:{value:t,message:R.toString(r)}})}nonempty(t){return this.min(1,t)}};gt.create=(e,t)=>new gt({type:e,minLength:null,maxLength:null,exactLength:null,typeName:T.ZodArray,...U(t)});function Cr(e){if(e instanceof Ae){let t={};for(let r in e.shape){let n=e.shape[r];t[r]=De.create(Cr(n))}return new Ae({...e._def,shape:()=>t})}else return e instanceof gt?new gt({...e._def,type:Cr(e.element)}):e instanceof De?De.create(Cr(e.unwrap())):e instanceof st?st.create(Cr(e.unwrap())):e instanceof at?at.create(e.items.map(t=>Cr(t))):e}var Ae=class e extends W{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),r=J.objectKeys(t);return this._cached={shape:t,keys:r},this._cached}_parse(t){if(this._getType(t)!==O.object){let l=this._getOrReturnCtx(t);return E(l,{code:x.invalid_type,expected:O.object,received:l.parsedType}),D}let{status:n,ctx:a}=this._processInputParams(t),{shape:s,keys:i}=this._getCached(),o=[];if(!(this._def.catchall instanceof Je&&this._def.unknownKeys==="strip"))for(let l in a.data)i.includes(l)||o.push(l);let c=[];for(let l of i){let f=s[l],p=a.data[l];c.push({key:{status:"valid",value:l},value:f._parse(new Le(a,p,a.path,l)),alwaysSet:l in a.data})}if(this._def.catchall instanceof Je){let l=this._def.unknownKeys;if(l==="passthrough")for(let f of o)c.push({key:{status:"valid",value:f},value:{status:"valid",value:a.data[f]}});else if(l==="strict")o.length>0&&(E(a,{code:x.unrecognized_keys,keys:o}),n.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let f of o){let p=a.data[f];c.push({key:{status:"valid",value:f},value:l._parse(new Le(a,p,a.path,f)),alwaysSet:f in a.data})}}return a.common.async?Promise.resolve().then(async()=>{let l=[];for(let f of c){let p=await f.key,y=await f.value;l.push({key:p,value:y,alwaysSet:f.alwaysSet})}return l}).then(l=>pe.mergeObjectSync(n,l)):pe.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(t){return R.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(r,n)=>{let a=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:R.errToObj(t).message??a}:{message:a}}}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:T.ZodObject})}setKey(t,r){return this.augment({[t]:r})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let r={};for(let n of J.objectKeys(t))t[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new e({...this._def,shape:()=>r})}omit(t){let r={};for(let n of J.objectKeys(this.shape))t[n]||(r[n]=this.shape[n]);return new e({...this._def,shape:()=>r})}deepPartial(){return Cr(this)}partial(t){let r={};for(let n of J.objectKeys(this.shape)){let a=this.shape[n];t&&!t[n]?r[n]=a:r[n]=a.optional()}return new e({...this._def,shape:()=>r})}required(t){let r={};for(let n of J.objectKeys(this.shape))if(t&&!t[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof De;)s=s._def.innerType;r[n]=s}return new e({...this._def,shape:()=>r})}keyof(){return fo(J.objectKeys(this.shape))}};Ae.create=(e,t)=>new Ae({shape:()=>e,unknownKeys:"strip",catchall:Je.create(),typeName:T.ZodObject,...U(t)});Ae.strictCreate=(e,t)=>new Ae({shape:()=>e,unknownKeys:"strict",catchall:Je.create(),typeName:T.ZodObject,...U(t)});Ae.lazycreate=(e,t)=>new Ae({shape:e,unknownKeys:"strip",catchall:Je.create(),typeName:T.ZodObject,...U(t)});var Qt=class extends W{_parse(t){let{ctx:r}=this._processInputParams(t),n=this._def.options;function a(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 r.common.issues.push(...o.ctx.common.issues),o.result;let i=s.map(o=>new Ee(o.ctx.common.issues));return E(r,{code:x.invalid_union,unionErrors:i}),D}if(r.common.async)return Promise.all(n.map(async s=>{let i={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(a);{let s,i=[];for(let c of n){let l={...r,common:{...r.common,issues:[]},parent:null},f=c._parseSync({data:r.data,path:r.path,parent:l});if(f.status==="valid")return f;f.status==="dirty"&&!s&&(s={result:f,ctx:l}),l.common.issues.length&&i.push(l.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;let o=i.map(c=>new Ee(c));return E(r,{code:x.invalid_union,unionErrors:o}),D}}get options(){return this._def.options}};Qt.create=(e,t)=>new Qt({options:e,typeName:T.ZodUnion,...U(t)});var mt=e=>e instanceof tr?mt(e.schema):e instanceof je?mt(e.innerType()):e instanceof rr?[e.value]:e instanceof nr?e.options:e instanceof ar?J.objectValues(e.enum):e instanceof sr?mt(e._def.innerType):e instanceof Yt?[void 0]:e instanceof Xt?[null]:e instanceof De?[void 0,...mt(e.unwrap())]:e instanceof st?[null,...mt(e.unwrap())]:e instanceof on||e instanceof or?mt(e.unwrap()):e instanceof ir?mt(e._def.innerType):[],Jn=class e extends W{_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==O.object)return E(r,{code:x.invalid_type,expected:O.object,received:r.parsedType}),D;let n=this.discriminator,a=r.data[n],s=this.optionsMap.get(a);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(E(r,{code:x.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),D)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,r,n){let a=new Map;for(let s of r){let i=mt(s.shape[t]);if(!i.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let o of i){if(a.has(o))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(o)}`);a.set(o,s)}}return new e({typeName:T.ZodDiscriminatedUnion,discriminator:t,options:r,optionsMap:a,...U(n)})}};function Ha(e,t){let r=nt(e),n=nt(t);if(e===t)return{valid:!0,data:e};if(r===O.object&&n===O.object){let a=J.objectKeys(t),s=J.objectKeys(e).filter(o=>a.indexOf(o)!==-1),i={...e,...t};for(let o of s){let c=Ha(e[o],t[o]);if(!c.valid)return{valid:!1};i[o]=c.data}return{valid:!0,data:i}}else if(r===O.array&&n===O.array){if(e.length!==t.length)return{valid:!1};let a=[];for(let s=0;s<e.length;s++){let i=e[s],o=t[s],c=Ha(i,o);if(!c.valid)return{valid:!1};a.push(c.data)}return{valid:!0,data:a}}else return r===O.date&&n===O.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var er=class extends W{_parse(t){let{status:r,ctx:n}=this._processInputParams(t),a=(s,i)=>{if(Wn(s)||Wn(i))return D;let o=Ha(s.value,i.value);return o.valid?((Gn(s)||Gn(i))&&r.dirty(),{status:r.value,value:o.data}):(E(n,{code:x.invalid_intersection_types}),D)};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,i])=>a(s,i)):a(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=(e,t,r)=>new er({left:e,right:t,typeName:T.ZodIntersection,...U(r)});var at=class e extends W{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==O.array)return E(n,{code:x.invalid_type,expected:O.array,received:n.parsedType}),D;if(n.data.length<this._def.items.length)return E(n,{code:x.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),D;!this._def.rest&&n.data.length>this._def.items.length&&(E(n,{code:x.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let s=[...n.data].map((i,o)=>{let c=this._def.items[o]||this._def.rest;return c?c._parse(new Le(n,i,n.path,o)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>pe.mergeArray(r,i)):pe.mergeArray(r,s)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};at.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new at({items:e,typeName:T.ZodTuple,rest:null,...U(t)})};var qn=class e extends W{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==O.object)return E(n,{code:x.invalid_type,expected:O.object,received:n.parsedType}),D;let a=[],s=this._def.keyType,i=this._def.valueType;for(let o in n.data)a.push({key:s._parse(new Le(n,o,n.path,o)),value:i._parse(new Le(n,n.data[o],n.path,o)),alwaysSet:o in n.data});return n.common.async?pe.mergeObjectAsync(r,a):pe.mergeObjectSync(r,a)}get element(){return this._def.valueType}static create(t,r,n){return r instanceof W?new e({keyType:t,valueType:r,typeName:T.ZodRecord,...U(n)}):new e({keyType:Ot.create(),valueType:t,typeName:T.ZodRecord,...U(r)})}},Nr=class extends W{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==O.map)return E(n,{code:x.invalid_type,expected:O.map,received:n.parsedType}),D;let a=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([o,c],l)=>({key:a._parse(new Le(n,o,n.path,[l,"key"])),value:s._parse(new Le(n,c,n.path,[l,"value"]))}));if(n.common.async){let o=new Map;return Promise.resolve().then(async()=>{for(let c of i){let l=await c.key,f=await c.value;if(l.status==="aborted"||f.status==="aborted")return D;(l.status==="dirty"||f.status==="dirty")&&r.dirty(),o.set(l.value,f.value)}return{status:r.value,value:o}})}else{let o=new Map;for(let c of i){let l=c.key,f=c.value;if(l.status==="aborted"||f.status==="aborted")return D;(l.status==="dirty"||f.status==="dirty")&&r.dirty(),o.set(l.value,f.value)}return{status:r.value,value:o}}}};Nr.create=(e,t,r)=>new Nr({valueType:t,keyType:e,typeName:T.ZodMap,...U(r)});var Pr=class e extends W{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==O.set)return E(n,{code:x.invalid_type,expected:O.set,received:n.parsedType}),D;let a=this._def;a.minSize!==null&&n.data.size<a.minSize.value&&(E(n,{code:x.too_small,minimum:a.minSize.value,type:"set",inclusive:!0,exact:!1,message:a.minSize.message}),r.dirty()),a.maxSize!==null&&n.data.size>a.maxSize.value&&(E(n,{code:x.too_big,maximum:a.maxSize.value,type:"set",inclusive:!0,exact:!1,message:a.maxSize.message}),r.dirty());let s=this._def.valueType;function i(c){let l=new Set;for(let f of c){if(f.status==="aborted")return D;f.status==="dirty"&&r.dirty(),l.add(f.value)}return{status:r.value,value:l}}let o=[...n.data.values()].map((c,l)=>s._parse(new Le(n,c,n.path,l)));return n.common.async?Promise.all(o).then(c=>i(c)):i(o)}min(t,r){return new e({...this._def,minSize:{value:t,message:R.toString(r)}})}max(t,r){return new e({...this._def,maxSize:{value:t,message:R.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}};Pr.create=(e,t)=>new Pr({valueType:e,minSize:null,maxSize:null,typeName:T.ZodSet,...U(t)});var Hn=class e extends W{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==O.function)return E(r,{code:x.invalid_type,expected:O.function,received:r.parsedType}),D;function n(o,c){return sn({data:o,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Er(),pt].filter(l=>!!l),issueData:{code:x.invalid_arguments,argumentsError:c}})}function a(o,c){return sn({data:o,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Er(),pt].filter(l=>!!l),issueData:{code:x.invalid_return_type,returnTypeError:c}})}let s={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof Nt){let o=this;return ge(async function(...c){let l=new Ee([]),f=await o._def.args.parseAsync(c,s).catch(h=>{throw l.addIssue(n(c,h)),l}),p=await Reflect.apply(i,this,f);return await o._def.returns._def.type.parseAsync(p,s).catch(h=>{throw l.addIssue(a(p,h)),l})})}else{let o=this;return ge(function(...c){let l=o._def.args.safeParse(c,s);if(!l.success)throw new Ee([n(c,l.error)]);let f=Reflect.apply(i,this,l.data),p=o._def.returns.safeParse(f,s);if(!p.success)throw new Ee([a(f,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:at.create(t).rest(ht.create())})}returns(t){return new e({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,r,n){return new e({args:t||at.create([]).rest(ht.create()),returns:r||ht.create(),typeName:T.ZodFunction,...U(n)})}},tr=class extends W{get schema(){return this._def.getter()}_parse(t){let{ctx:r}=this._processInputParams(t);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};tr.create=(e,t)=>new tr({getter:e,typeName:T.ZodLazy,...U(t)});var rr=class extends W{_parse(t){if(t.data!==this._def.value){let r=this._getOrReturnCtx(t);return E(r,{received:r.data,code:x.invalid_literal,expected:this._def.value}),D}return{status:"valid",value:t.data}}get value(){return this._def.value}};rr.create=(e,t)=>new rr({value:e,typeName:T.ZodLiteral,...U(t)});function fo(e,t){return new nr({values:e,typeName:T.ZodEnum,...U(t)})}var nr=class e extends W{_parse(t){if(typeof t.data!="string"){let r=this._getOrReturnCtx(t),n=this._def.values;return E(r,{expected:J.joinValues(n),received:r.parsedType,code:x.invalid_type}),D}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){let r=this._getOrReturnCtx(t),n=this._def.values;return E(r,{received:r.data,code:x.invalid_enum_value,options:n}),D}return ge(t.data)}get options(){return this._def.values}get enum(){let t={};for(let r of this._def.values)t[r]=r;return t}get Values(){let t={};for(let r of this._def.values)t[r]=r;return t}get Enum(){let t={};for(let r of this._def.values)t[r]=r;return t}extract(t,r=this._def){return e.create(t,{...this._def,...r})}exclude(t,r=this._def){return e.create(this.options.filter(n=>!t.includes(n)),{...this._def,...r})}};nr.create=fo;var ar=class extends W{_parse(t){let r=J.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(t);if(n.parsedType!==O.string&&n.parsedType!==O.number){let a=J.objectValues(r);return E(n,{expected:J.joinValues(a),received:n.parsedType,code:x.invalid_type}),D}if(this._cache||(this._cache=new Set(J.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let a=J.objectValues(r);return E(n,{received:n.data,code:x.invalid_enum_value,options:a}),D}return ge(t.data)}get enum(){return this._def.values}};ar.create=(e,t)=>new ar({values:e,typeName:T.ZodNativeEnum,...U(t)});var Nt=class extends W{unwrap(){return this._def.type}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==O.promise&&r.common.async===!1)return E(r,{code:x.invalid_type,expected:O.promise,received:r.parsedType}),D;let n=r.parsedType===O.promise?r.data:Promise.resolve(r.data);return ge(n.then(a=>this._def.type.parseAsync(a,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Nt.create=(e,t)=>new Nt({type:e,typeName:T.ZodPromise,...U(t)});var je=class extends W{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===T.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:r,ctx:n}=this._processInputParams(t),a=this._def.effect||null,s={addIssue:i=>{E(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),a.type==="preprocess"){let i=a.transform(n.data,s);if(n.common.async)return Promise.resolve(i).then(async o=>{if(r.value==="aborted")return D;let c=await this._def.schema._parseAsync({data:o,path:n.path,parent:n});return c.status==="aborted"?D:c.status==="dirty"?Gt(c.value):r.value==="dirty"?Gt(c.value):c});{if(r.value==="aborted")return D;let o=this._def.schema._parseSync({data:i,path:n.path,parent:n});return o.status==="aborted"?D:o.status==="dirty"?Gt(o.value):r.value==="dirty"?Gt(o.value):o}}if(a.type==="refinement"){let i=o=>{let c=a.refinement(o,s);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(n.common.async===!1){let o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?D:(o.status==="dirty"&&r.dirty(),i(o.value),{status:r.value,value:o.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>o.status==="aborted"?D:(o.status==="dirty"&&r.dirty(),i(o.value).then(()=>({status:r.value,value:o.value}))))}if(a.type==="transform")if(n.common.async===!1){let i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Ct(i))return D;let o=a.transform(i.value,s);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:o}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>Ct(i)?Promise.resolve(a.transform(i.value,s)).then(o=>({status:r.value,value:o})):D);J.assertNever(a)}};je.create=(e,t,r)=>new je({schema:e,typeName:T.ZodEffects,effect:t,...U(r)});je.createWithPreprocess=(e,t,r)=>new je({schema:t,effect:{type:"preprocess",transform:e},typeName:T.ZodEffects,...U(r)});var De=class extends W{_parse(t){return this._getType(t)===O.undefined?ge(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};De.create=(e,t)=>new De({innerType:e,typeName:T.ZodOptional,...U(t)});var st=class extends W{_parse(t){return this._getType(t)===O.null?ge(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};st.create=(e,t)=>new st({innerType:e,typeName:T.ZodNullable,...U(t)});var sr=class extends W{_parse(t){let{ctx:r}=this._processInputParams(t),n=r.data;return r.parsedType===O.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};sr.create=(e,t)=>new sr({innerType:e,typeName:T.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...U(t)});var ir=class extends W{_parse(t){let{ctx:r}=this._processInputParams(t),n={...r,common:{...r.common,issues:[]}},a=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Ar(a)?a.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Ee(n.common.issues)},input:n.data})})):{status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new Ee(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};ir.create=(e,t)=>new ir({innerType:e,typeName:T.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...U(t)});var Rr=class extends W{_parse(t){if(this._getType(t)!==O.nan){let n=this._getOrReturnCtx(t);return E(n,{code:x.invalid_type,expected:O.nan,received:n.parsedType}),D}return{status:"valid",value:t.data}}};Rr.create=e=>new Rr({typeName:T.ZodNaN,...U(e)});var Mu=Symbol("zod_brand"),on=class extends W{_parse(t){let{ctx:r}=this._processInputParams(t),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},cn=class e extends W{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?D:s.status==="dirty"?(r.dirty(),Gt(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{let a=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?D:a.status==="dirty"?(r.dirty(),{status:"dirty",value:a.value}):this._def.out._parseSync({data:a.value,path:n.path,parent:n})}}static create(t,r){return new e({in:t,out:r,typeName:T.ZodPipeline})}},or=class extends W{_parse(t){let r=this._def.innerType._parse(t),n=a=>(Ct(a)&&(a.value=Object.freeze(a.value)),a);return Ar(r)?r.then(a=>n(a)):n(r)}unwrap(){return this._def.innerType}};or.create=(e,t)=>new or({innerType:e,typeName:T.ZodReadonly,...U(t)});function oo(e,t){let r=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof r=="string"?{message:r}:r}function po(e,t={},r){return e?It.create().superRefine((n,a)=>{let s=e(n);if(s instanceof Promise)return s.then(i=>{if(!i){let o=oo(t,n),c=o.fatal??r??!0;a.addIssue({code:"custom",...o,fatal:c})}});if(!s){let i=oo(t,n),o=i.fatal??r??!0;a.addIssue({code:"custom",...i,fatal:o})}}):It.create()}var $u={object:Ae.lazycreate},T;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(T||(T={}));var Du=(e,t={message:`Input not instance of ${e.name}`})=>po(r=>r instanceof e,t),mo=Ot.create,ho=Jt.create,Lu=Rr.create,ju=qt.create,go=Ht.create,Fu=Kt.create,zu=Or.create,Bu=Yt.create,Zu=Xt.create,Uu=It.create,Vu=ht.create,Wu=Je.create,Gu=Ir.create,Ju=gt.create,qu=Ae.create,Hu=Ae.strictCreate,Ku=Qt.create,Yu=Jn.create,Xu=er.create,Qu=at.create,el=qn.create,tl=Nr.create,rl=Pr.create,nl=Hn.create,al=tr.create,sl=rr.create,il=nr.create,ol=ar.create,cl=Nt.create,ul=je.create,ll=De.create,dl=st.create,fl=je.createWithPreprocess,pl=cn.create,ml=()=>mo().optional(),hl=()=>ho().optional(),gl=()=>go().optional(),yl={string:(e=>Ot.create({...e,coerce:!0})),number:(e=>Jt.create({...e,coerce:!0})),boolean:(e=>Ht.create({...e,coerce:!0})),bigint:(e=>qt.create({...e,coerce:!0})),date:(e=>Kt.create({...e,coerce:!0}))};var _l=D;function Ka(e,t){let r={type:"array"};return e.type?._def&&e.type?._def?.typeName!==T.ZodAny&&(r.items=j(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&H(r,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&H(r,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(H(r,"minItems",e.exactLength.value,e.exactLength.message,t),H(r,"maxItems",e.exactLength.value,e.exactLength.message,t)),r}function Ya(e,t){let r={type:"integer",format:"int64"};if(!e.checks)return r;for(let n of e.checks)switch(n.kind){case"min":t.target==="jsonSchema7"?n.inclusive?H(r,"minimum",n.value,n.message,t):H(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),H(r,"minimum",n.value,n.message,t));break;case"max":t.target==="jsonSchema7"?n.inclusive?H(r,"maximum",n.value,n.message,t):H(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),H(r,"maximum",n.value,n.message,t));break;case"multipleOf":H(r,"multipleOf",n.value,n.message,t);break}return r}function Xa(){return{type:"boolean"}}function un(e,t){return j(e.type._def,t)}var Qa=(e,t)=>j(e.innerType._def,t);function Kn(e,t,r){let n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map(a=>Kn(e,t,a))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return vl(e,t)}}var vl=(e,t)=>{let r={type:"integer",format:"unix-time"};if(t.target==="openApi3")return r;for(let n of e.checks)switch(n.kind){case"min":H(r,"minimum",n.value,n.message,t);break;case"max":H(r,"maximum",n.value,n.message,t);break}return r};function es(e,t){return{...j(e.innerType._def,t),default:e.defaultValue()}}function ts(e,t){return t.effectStrategy==="input"?j(e.schema._def,t):ne(t)}function rs(e){return{type:"string",enum:Array.from(e.values)}}var bl=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function ns(e,t){let r=[j(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),j(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(s=>!!s),n=t.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,a=[];return r.forEach(s=>{if(bl(s))a.push(...s.allOf),s.unevaluatedProperties===void 0&&(n=void 0);else{let i=s;if("additionalProperties"in s&&s.additionalProperties===!1){let{additionalProperties:o,...c}=s;i=c}else n=void 0;a.push(i)}}),a.length?{allOf:a,...n}:void 0}function as(e,t){let r=typeof e.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(e.value)?"array":"object"}:t.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[e.value]}:{type:r==="bigint"?"integer":r,const:e.value}}var ss,Fe={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:()=>(ss===void 0&&(ss=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),ss),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 ln(e,t){let r={type:"string"};if(e.checks)for(let n of e.checks)switch(n.kind){case"min":H(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,t);break;case"max":H(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"email":switch(t.emailStrategy){case"format:email":qe(r,"email",n.message,t);break;case"format:idn-email":qe(r,"idn-email",n.message,t);break;case"pattern:zod":be(r,Fe.email,n.message,t);break}break;case"url":qe(r,"uri",n.message,t);break;case"uuid":qe(r,"uuid",n.message,t);break;case"regex":be(r,n.regex,n.message,t);break;case"cuid":be(r,Fe.cuid,n.message,t);break;case"cuid2":be(r,Fe.cuid2,n.message,t);break;case"startsWith":be(r,RegExp(`^${is(n.value,t)}`),n.message,t);break;case"endsWith":be(r,RegExp(`${is(n.value,t)}$`),n.message,t);break;case"datetime":qe(r,"date-time",n.message,t);break;case"date":qe(r,"date",n.message,t);break;case"time":qe(r,"time",n.message,t);break;case"duration":qe(r,"duration",n.message,t);break;case"length":H(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,t),H(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"includes":be(r,RegExp(is(n.value,t)),n.message,t);break;case"ip":n.version!=="v6"&&qe(r,"ipv4",n.message,t),n.version!=="v4"&&qe(r,"ipv6",n.message,t);break;case"base64url":be(r,Fe.base64url,n.message,t);break;case"jwt":be(r,Fe.jwt,n.message,t);break;case"cidr":n.version!=="v6"&&be(r,Fe.ipv4Cidr,n.message,t),n.version!=="v4"&&be(r,Fe.ipv6Cidr,n.message,t);break;case"emoji":be(r,Fe.emoji(),n.message,t);break;case"ulid":be(r,Fe.ulid,n.message,t);break;case"base64":switch(t.base64Strategy){case"format:binary":qe(r,"binary",n.message,t);break;case"contentEncoding:base64":H(r,"contentEncoding","base64",n.message,t);break;case"pattern:zod":be(r,Fe.base64,n.message,t);break}break;case"nanoid":be(r,Fe.nanoid,n.message,t);break;case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function is(e,t){return t.patternStrategy==="escape"?kl(e):e}var wl=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function kl(e){let t="";for(let r=0;r<e.length;r++)wl.has(e[r])||(t+="\\"),t+=e[r];return t}function qe(e,t,r,n){e.format||e.anyOf?.some(a=>a.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&n.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...r&&n.errorMessages&&{errorMessage:{format:r}}})):H(e,"format",t,r,n)}function be(e,t,r,n){e.pattern||e.allOf?.some(a=>a.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&n.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:yo(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):H(e,"pattern",yo(t,n),r,n)}function yo(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let r={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},n=r.i?e.source.toLowerCase():e.source,a="",s=!1,i=!1,o=!1;for(let c=0;c<n.length;c++){if(s){a+=n[c],s=!1;continue}if(r.i){if(i){if(n[c].match(/[a-z]/)){o?(a+=n[c],a+=`${n[c-2]}-${n[c]}`.toUpperCase(),o=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(a+=n[c],o=!0):a+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){a+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){a+=`(^|(?<=[\r
3
+ ]))`;continue}else if(n[c]==="$"){a+=`($|(?=[\r
4
+ ]))`;continue}}if(r.s&&n[c]==="."){a+=i?`${n[c]}\r
5
+ `:`[${n[c]}\r
6
+ ]`;continue}a+=n[c],n[c]==="\\"?s=!0:i&&n[c]==="]"?i=!1:!i&&n[c]==="["&&(i=!0)}try{new RegExp(a)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return a}function dn(e,t){if(t.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),t.target==="openApi3"&&e.keyType?._def.typeName===T.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,a)=>({...n,[a]:j(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",a]})??ne(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let r={type:"object",additionalProperties:j(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if(t.target==="openApi3")return r;if(e.keyType?._def.typeName===T.ZodString&&e.keyType._def.checks?.length){let{type:n,...a}=ln(e.keyType._def,t);return{...r,propertyNames:a}}else{if(e.keyType?._def.typeName===T.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===T.ZodBranded&&e.keyType._def.type._def.typeName===T.ZodString&&e.keyType._def.type._def.checks?.length){let{type:n,...a}=un(e.keyType._def,t);return{...r,propertyNames:a}}}return r}function os(e,t){return t.mapStrategy==="record"?dn(e,t):{type:"array",maxItems:125,items:{type:"array",items:[j(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||ne(t),j(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||ne(t)],minItems:2,maxItems:2}}}function cs(e){let t=e.values,r=Object.keys(e.values).filter(a=>typeof t[t[a]]!="number").map(a=>t[a]),n=Array.from(new Set(r.map(a=>typeof a)));return{type:n.length===1?n[0]==="string"?"string":"number":["string","number"],enum:r}}function us(e){return e.target==="openAi"?void 0:{not:ne({...e,currentPath:[...e.currentPath,"not"]})}}function ls(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Mr={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function ds(e,t){if(t.target==="openApi3")return _o(e,t);let r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(n=>n._def.typeName in Mr&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((a,s)=>{let i=Mr[s._def.typeName];return i&&!a.includes(i)?[...a,i]:a},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((a,s)=>{let i=typeof s._def.value;switch(i){case"string":case"number":case"boolean":return[...a,i];case"bigint":return[...a,"integer"];case"object":return s._def.value===null?[...a,"null"]:a;default:return a}},[]);if(n.length===r.length){let a=n.filter((s,i,o)=>o.indexOf(s)===i);return{type:a.length>1?a:a[0],enum:r.reduce((s,i)=>s.includes(i._def.value)?s:[...s,i._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,a)=>[...n,...a._def.values.filter(s=>!n.includes(s))],[])};return _o(e,t)}var _o=(e,t)=>{let r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((n,a)=>j(n._def,{...t,currentPath:[...t.currentPath,"anyOf",`${a}`]})).filter(n=>!!n&&(!t.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function fs(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target==="openApi3"?{type:Mr[e.innerType._def.typeName],nullable:!0}:{type:[Mr[e.innerType._def.typeName],"null"]};if(t.target==="openApi3"){let n=j(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=j(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function ps(e,t){let r={type:"number"};if(!e.checks)return r;for(let n of e.checks)switch(n.kind){case"int":r.type="integer",Vn(r,"type",n.message,t);break;case"min":t.target==="jsonSchema7"?n.inclusive?H(r,"minimum",n.value,n.message,t):H(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),H(r,"minimum",n.value,n.message,t));break;case"max":t.target==="jsonSchema7"?n.inclusive?H(r,"maximum",n.value,n.message,t):H(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),H(r,"maximum",n.value,n.message,t));break;case"multipleOf":H(r,"multipleOf",n.value,n.message,t);break}return r}function ms(e,t){let r=t.target==="openAi",n={type:"object",properties:{}},a=[],s=e.shape();for(let o in s){let c=s[o];if(c===void 0||c._def===void 0)continue;let l=Tl(c);l&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),l=!1);let f=j(c._def,{...t,currentPath:[...t.currentPath,"properties",o],propertyPath:[...t.currentPath,"properties",o]});f!==void 0&&(n.properties[o]=f,l||a.push(o))}a.length&&(n.required=a);let i=xl(e,t);return i!==void 0&&(n.additionalProperties=i),n}function xl(e,t){if(e.catchall._def.typeName!=="ZodNever")return j(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return t.removeAdditionalStrategy==="strict"?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function Tl(e){try{return e.isOptional()}catch{return!0}}var hs=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return j(e.innerType._def,t);let r=j(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:ne(t)},r]}:ne(t)};var gs=(e,t)=>{if(t.pipeStrategy==="input")return j(e.in._def,t);if(t.pipeStrategy==="output")return j(e.out._def,t);let r=j(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]});return{allOf:[r,j(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]})].filter(n=>n!==void 0)}};function ys(e,t){return j(e.type._def,t)}function _s(e,t){let r={type:"array",uniqueItems:!0,items:j(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&H(r,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&H(r,"maxItems",e.maxSize.value,e.maxSize.message,t),r}function vs(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((r,n)=>j(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:j(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,n)=>j(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function bs(e){return{not:ne(e)}}function ws(e){return ne(e)}var ks=(e,t)=>j(e.innerType._def,t);var xs=(e,t,r)=>{switch(t){case T.ZodString:return ln(e,r);case T.ZodNumber:return ps(e,r);case T.ZodObject:return ms(e,r);case T.ZodBigInt:return Ya(e,r);case T.ZodBoolean:return Xa();case T.ZodDate:return Kn(e,r);case T.ZodUndefined:return bs(r);case T.ZodNull:return ls(r);case T.ZodArray:return Ka(e,r);case T.ZodUnion:case T.ZodDiscriminatedUnion:return ds(e,r);case T.ZodIntersection:return ns(e,r);case T.ZodTuple:return vs(e,r);case T.ZodRecord:return dn(e,r);case T.ZodLiteral:return as(e,r);case T.ZodEnum:return rs(e);case T.ZodNativeEnum:return cs(e);case T.ZodNullable:return fs(e,r);case T.ZodOptional:return hs(e,r);case T.ZodMap:return os(e,r);case T.ZodSet:return _s(e,r);case T.ZodLazy:return()=>e.getter()._def;case T.ZodPromise:return ys(e,r);case T.ZodNaN:case T.ZodNever:return us(r);case T.ZodEffects:return ts(e,r);case T.ZodAny:return ne(r);case T.ZodUnknown:return ws(r);case T.ZodDefault:return es(e,r);case T.ZodBranded:return un(e,r);case T.ZodReadonly:return ks(e,r);case T.ZodCatch:return Qa(e,r);case T.ZodPipeline:return gs(e,r);case T.ZodFunction:case T.ZodVoid:case T.ZodSymbol:return;default:return(n=>{})(t)}};function j(e,t,r=!1){let n=t.seen.get(e);if(t.override){let o=t.override?.(e,t,n,r);if(o!==Va)return o}if(n&&!r){let o=Sl(n,t);if(o!==void 0)return o}let a={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,a);let s=xs(e,e.typeName,t),i=typeof s=="function"?j(s(),t):s;if(i&&El(e,t,i),t.postProcess){let o=t.postProcess(i,e,t);return a.jsonSchema=i,o}return a.jsonSchema=i,i}var Sl=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:an(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((r,n)=>t.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),ne(t)):t.$refStrategy==="seen"?ne(t):void 0}},El=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r);var Ts=(e,t)=>{let r=Ga(t),n=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[l,f])=>({...c,[l]:j(f._def,{...r,currentPath:[...r.basePath,r.definitionPath,l]},!0)??ne(r)}),{}):void 0,a=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,s=j(e._def,a===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,a]},!1)??ne(r),i=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;i!==void 0&&(s.title=i),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let o=a===void 0?n?{...s,[r.definitionPath]:n}:s:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,a].join("/"),[r.definitionPath]:{...n,[a]:s}};return r.target==="jsonSchema7"?o.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(o.$schema="https://json-schema.org/draft/2019-09/schema#"),r.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};var eg=M({isSerializableSchema:()=>cr,isStandardJsonSchema:()=>Yn,isStandardSchema:()=>vo});function vo(e){return(typeof e=="object"||typeof e=="function")&&e!==null&&"~standard"in e&&typeof e["~standard"]=="object"&&e["~standard"]!==null&&"validate"in e["~standard"]}function Yn(e){return(typeof e=="object"||typeof e=="function")&&e!==null&&"~standard"in e&&typeof e["~standard"]=="object"&&e["~standard"]!==null&&"jsonSchema"in e["~standard"]}function cr(e){return vo(e)&&Yn(e)}function it(e,t){let r=typeof e;if(r!==typeof t)return!1;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let n=e.length;if(n!==t.length)return!1;for(let a=0;a<n;a++)if(!it(e[a],t[a]))return!1;return!0}if(r==="object"){if(!e||!t)return e===t;let n=Object.keys(e),a=Object.keys(t);if(n.length!==a.length)return!1;for(let i of n)if(!it(e[i],t[i]))return!1;return!0}return e===t}function Ie(e){return encodeURI(Al(e))}function Al(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}var Cl={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},Ol={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},Il={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},Nl=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 He(e,t=Object.create(null),r=Nl,n=""){if(e&&typeof e=="object"&&!Array.isArray(e)){let s=e.$id||e.id;if(s){let i=new URL(s,r.href);i.hash.length>1?t[i.href]=e:(i.hash="",n===""?r=i:He(e,t,r))}}else if(e!==!0&&e!==!1)return t;let a=r.href+(n?"#"+n:"");if(t[a]!==void 0)throw new Error(`Duplicate schema URI "${a}".`);if(t[a]=e,e===!0||e===!1)return t;if(e.__absolute_uri__===void 0&&Object.defineProperty(e,"__absolute_uri__",{enumerable:!1,value:a}),e.$ref&&e.__absolute_ref__===void 0){let s=new URL(e.$ref,r.href);s.hash=s.hash,Object.defineProperty(e,"__absolute_ref__",{enumerable:!1,value:s.href})}if(e.$recursiveRef&&e.__absolute_recursive_ref__===void 0){let s=new URL(e.$recursiveRef,r.href);s.hash=s.hash,Object.defineProperty(e,"__absolute_recursive_ref__",{enumerable:!1,value:s.href})}if(e.$anchor){let s=new URL("#"+e.$anchor,r.href);t[s.href]=e}for(let s in e){if(Il[s])continue;let i=`${n}/${Ie(s)}`,o=e[s];if(Array.isArray(o)){if(Cl[s]){let c=o.length;for(let l=0;l<c;l++)He(o[l],t,r,`${i}/${l}`)}}else if(Ol[s])for(let c in o)He(o[c],t,r,`${i}/${Ie(c)}`);else He(o,t,r,i)}return t}var Pl=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Rl=[0,31,28,31,30,31,30,31,31,30,31,30,31],Ml=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,$l=/^(?=.{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,Dl=/^(?:[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,Ll=/^(?:(?:[^\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,jl=/^(?:(?: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,Fl=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,zl=/^(?:\/(?:[^~/]|~0|~1)*)*$/,Bl=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,Zl=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,Ul=e=>{if(e[0]==='"')return!1;let[t,r,...n]=e.split("@");return!t||!r||n.length!==0||t.length>64||r.length>253||t[0]==="."||t.endsWith(".")||t.includes("..")||!/^[a-z0-9.-]+$/i.test(r)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t)?!1:r.split(".").every(a=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(a))},Vl=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,Wl=/^((([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,Gl=e=>e.length>1&&e.length<80&&(/^P\d+([.,]\d+)?W$/.test(e)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(e)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(e));function ot(e){return e.test.bind(e)}var Ss={date:bo,time:wo.bind(void 0,!1),"date-time":Hl,duration:Gl,uri:Xl,"uri-reference":ot(Dl),"uri-template":ot(Ll),url:ot(jl),email:Ul,hostname:ot($l),ipv4:ot(Vl),ipv6:ot(Wl),regex:ed,uuid:ot(Fl),"json-pointer":ot(zl),"json-pointer-uri-fragment":ot(Bl),"relative-json-pointer":ot(Zl)};function Jl(e){return e%4===0&&(e%100!==0||e%400===0)}function bo(e){let t=e.match(Pl);if(!t)return!1;let r=+t[1],n=+t[2],a=+t[3];return n>=1&&n<=12&&a>=1&&a<=(n==2&&Jl(r)?29:Rl[n])}function wo(e,t){let r=t.match(Ml);if(!r)return!1;let n=+r[1],a=+r[2],s=+r[3],i=!!r[5];return(n<=23&&a<=59&&s<=59||n==23&&a==59&&s==60)&&(!e||i)}var ql=/t|\s/i;function Hl(e){let t=e.split(ql);return t.length==2&&bo(t[0])&&wo(!0,t[1])}var Kl=/\/|:/,Yl=/^(?:[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 Xl(e){return Kl.test(e)&&Yl.test(e)}var Ql=/[^\\]\\Z/;function ed(e){if(Ql.test(e))return!1;try{return new RegExp(e,"u"),!0}catch{return!1}}var ko;(function(e){e[e.Flag=1]="Flag",e[e.Basic=2]="Basic",e[e.Detailed=4]="Detailed"})(ko||(ko={}));function xo(e){let t=0,r=e.length,n=0,a;for(;n<r;)t++,a=e.charCodeAt(n++),a>=55296&&a<=56319&&n<r&&(a=e.charCodeAt(n),(a&64512)==56320&&n++);return t}function re(e,t,r="2019-09",n=He(t),a=!0,s=null,i="#",o="#",c=Object.create(null)){if(t===!0)return{valid:!0,errors:[]};if(t===!1)return{valid:!1,errors:[{instanceLocation:i,keyword:"false",keywordLocation:i,error:"False boolean schema."}]};let l=typeof e,f;switch(l){case"boolean":case"number":case"string":f=l;break;case"object":e===null?f="null":Array.isArray(e)?f="array":f="object";break;default:throw new Error(`Instances of "${l}" type are not supported.`)}let{$ref:p,$recursiveRef:y,$recursiveAnchor:h,type:m,const:v,enum:b,required:k,not:I,anyOf:S,allOf:L,oneOf:V,if:ue,then:de,else:_,format:Ze,properties:Xe,patternProperties:ee,additionalProperties:kt,unevaluatedProperties:Br,minProperties:xt,maxProperties:mr,propertyNames:K,dependentRequired:Zr,dependentSchemas:Lt,dependencies:jt,prefixItems:Ue,items:ft,additionalItems:Ur,unevaluatedItems:Vr,contains:Wr,minContains:Ve,maxContains:d,minItems:u,maxItems:w,uniqueItems:g,minimum:G,maximum:X,exclusiveMinimum:le,exclusiveMaximum:se,multipleOf:me,minLength:Me,maxLength:ie,pattern:Qe,__absolute_ref__:hr,__absolute_recursive_ref__:An}=t,C=[];if(h===!0&&s===null&&(s=t),y==="#"){let F=s===null?n[An]:s,$=`${o}/$recursiveRef`,Z=re(e,s===null?t:s,r,n,a,F,i,$,c);Z.valid||C.push({instanceLocation:i,keyword:"$recursiveRef",keywordLocation:$,error:"A subschema had errors."},...Z.errors)}if(p!==void 0){let $=n[hr||p];if($===void 0){let A=`Unresolved $ref "${p}".`;throw hr&&hr!==p&&(A+=` Absolute URI "${hr}".`),A+=`
7
+ Known schemas:
8
+ - ${Object.keys(n).join(`
9
+ - `)}`,new Error(A)}let Z=`${o}/$ref`,N=re(e,$,r,n,a,s,i,Z,c);if(N.valid||C.push({instanceLocation:i,keyword:"$ref",keywordLocation:Z,error:"A subschema had errors."},...N.errors),r==="4"||r==="7")return{valid:C.length===0,errors:C}}if(Array.isArray(m)){let F=m.length,$=!1;for(let Z=0;Z<F;Z++)if(f===m[Z]||m[Z]==="integer"&&f==="number"&&e%1===0&&e===e){$=!0;break}$||C.push({instanceLocation:i,keyword:"type",keywordLocation:`${o}/type`,error:`Instance type "${f}" is invalid. Expected "${m.join('", "')}".`})}else m==="integer"?(f!=="number"||e%1||e!==e)&&C.push({instanceLocation:i,keyword:"type",keywordLocation:`${o}/type`,error:`Instance type "${f}" is invalid. Expected "${m}".`}):m!==void 0&&f!==m&&C.push({instanceLocation:i,keyword:"type",keywordLocation:`${o}/type`,error:`Instance type "${f}" is invalid. Expected "${m}".`});if(v!==void 0&&(f==="object"||f==="array"?it(e,v)||C.push({instanceLocation:i,keyword:"const",keywordLocation:`${o}/const`,error:`Instance does not match ${JSON.stringify(v)}.`}):e!==v&&C.push({instanceLocation:i,keyword:"const",keywordLocation:`${o}/const`,error:`Instance does not match ${JSON.stringify(v)}.`})),b!==void 0&&(f==="object"||f==="array"?b.some(F=>it(e,F))||C.push({instanceLocation:i,keyword:"enum",keywordLocation:`${o}/enum`,error:`Instance does not match any of ${JSON.stringify(b)}.`}):b.some(F=>e===F)||C.push({instanceLocation:i,keyword:"enum",keywordLocation:`${o}/enum`,error:`Instance does not match any of ${JSON.stringify(b)}.`})),I!==void 0){let F=`${o}/not`;re(e,I,r,n,a,s,i,F).valid&&C.push({instanceLocation:i,keyword:"not",keywordLocation:F,error:'Instance matched "not" schema.'})}let Ft=[];if(S!==void 0){let F=`${o}/anyOf`,$=C.length,Z=!1;for(let N=0;N<S.length;N++){let A=S[N],B=Object.create(c),z=re(e,A,r,n,a,h===!0?s:null,i,`${F}/${N}`,B);C.push(...z.errors),Z=Z||z.valid,z.valid&&Ft.push(B)}Z?C.length=$:C.splice($,0,{instanceLocation:i,keyword:"anyOf",keywordLocation:F,error:"Instance does not match any subschemas."})}if(L!==void 0){let F=`${o}/allOf`,$=C.length,Z=!0;for(let N=0;N<L.length;N++){let A=L[N],B=Object.create(c),z=re(e,A,r,n,a,h===!0?s:null,i,`${F}/${N}`,B);C.push(...z.errors),Z=Z&&z.valid,z.valid&&Ft.push(B)}Z?C.length=$:C.splice($,0,{instanceLocation:i,keyword:"allOf",keywordLocation:F,error:"Instance does not match every subschema."})}if(V!==void 0){let F=`${o}/oneOf`,$=C.length,Z=V.filter((N,A)=>{let B=Object.create(c),z=re(e,N,r,n,a,h===!0?s:null,i,`${F}/${A}`,B);return C.push(...z.errors),z.valid&&Ft.push(B),z.valid}).length;Z===1?C.length=$:C.splice($,0,{instanceLocation:i,keyword:"oneOf",keywordLocation:F,error:`Instance does not match exactly one subschema (${Z} matches).`})}if((f==="object"||f==="array")&&Object.assign(c,...Ft),ue!==void 0){let F=`${o}/if`;if(re(e,ue,r,n,a,s,i,F,c).valid){if(de!==void 0){let Z=re(e,de,r,n,a,s,i,`${o}/then`,c);Z.valid||C.push({instanceLocation:i,keyword:"if",keywordLocation:F,error:'Instance does not match "then" schema.'},...Z.errors)}}else if(_!==void 0){let Z=re(e,_,r,n,a,s,i,`${o}/else`,c);Z.valid||C.push({instanceLocation:i,keyword:"if",keywordLocation:F,error:'Instance does not match "else" schema.'},...Z.errors)}}if(f==="object"){if(k!==void 0)for(let N of k)N in e||C.push({instanceLocation:i,keyword:"required",keywordLocation:`${o}/required`,error:`Instance does not have required property "${N}".`});let F=Object.keys(e);if(xt!==void 0&&F.length<xt&&C.push({instanceLocation:i,keyword:"minProperties",keywordLocation:`${o}/minProperties`,error:`Instance does not have at least ${xt} properties.`}),mr!==void 0&&F.length>mr&&C.push({instanceLocation:i,keyword:"maxProperties",keywordLocation:`${o}/maxProperties`,error:`Instance does not have at least ${mr} properties.`}),K!==void 0){let N=`${o}/propertyNames`;for(let A in e){let B=`${i}/${Ie(A)}`,z=re(A,K,r,n,a,s,B,N);z.valid||C.push({instanceLocation:i,keyword:"propertyNames",keywordLocation:N,error:`Property name "${A}" does not match schema.`},...z.errors)}}if(Zr!==void 0){let N=`${o}/dependantRequired`;for(let A in Zr)if(A in e){let B=Zr[A];for(let z of B)z in e||C.push({instanceLocation:i,keyword:"dependentRequired",keywordLocation:N,error:`Instance has "${A}" but does not have "${z}".`})}}if(Lt!==void 0)for(let N in Lt){let A=`${o}/dependentSchemas`;if(N in e){let B=re(e,Lt[N],r,n,a,s,i,`${A}/${Ie(N)}`,c);B.valid||C.push({instanceLocation:i,keyword:"dependentSchemas",keywordLocation:A,error:`Instance has "${N}" but does not match dependant schema.`},...B.errors)}}if(jt!==void 0){let N=`${o}/dependencies`;for(let A in jt)if(A in e){let B=jt[A];if(Array.isArray(B))for(let z of B)z in e||C.push({instanceLocation:i,keyword:"dependencies",keywordLocation:N,error:`Instance has "${A}" but does not have "${z}".`});else{let z=re(e,B,r,n,a,s,i,`${N}/${Ie(A)}`);z.valid||C.push({instanceLocation:i,keyword:"dependencies",keywordLocation:N,error:`Instance has "${A}" but does not match dependant schema.`},...z.errors)}}}let $=Object.create(null),Z=!1;if(Xe!==void 0){let N=`${o}/properties`;for(let A in Xe){if(!(A in e))continue;let B=`${i}/${Ie(A)}`,z=re(e[A],Xe[A],r,n,a,s,B,`${N}/${Ie(A)}`);if(z.valid)c[A]=$[A]=!0;else if(Z=a,C.push({instanceLocation:i,keyword:"properties",keywordLocation:N,error:`Property "${A}" does not match schema.`},...z.errors),Z)break}}if(!Z&&ee!==void 0){let N=`${o}/patternProperties`;for(let A in ee){let B=new RegExp(A,"u"),z=ee[A];for(let ke in e){if(!B.test(ke))continue;let ri=`${i}/${Ie(ke)}`,ni=re(e[ke],z,r,n,a,s,ri,`${N}/${Ie(A)}`);ni.valid?c[ke]=$[ke]=!0:(Z=a,C.push({instanceLocation:i,keyword:"patternProperties",keywordLocation:N,error:`Property "${ke}" matches pattern "${A}" but does not match associated schema.`},...ni.errors))}}}if(!Z&&kt!==void 0){let N=`${o}/additionalProperties`;for(let A in e){if($[A])continue;let B=`${i}/${Ie(A)}`,z=re(e[A],kt,r,n,a,s,B,N);z.valid?c[A]=!0:(Z=a,C.push({instanceLocation:i,keyword:"additionalProperties",keywordLocation:N,error:`Property "${A}" does not match additional properties schema.`},...z.errors))}}else if(!Z&&Br!==void 0){let N=`${o}/unevaluatedProperties`;for(let A in e)if(!c[A]){let B=`${i}/${Ie(A)}`,z=re(e[A],Br,r,n,a,s,B,N);z.valid?c[A]=!0:C.push({instanceLocation:i,keyword:"unevaluatedProperties",keywordLocation:N,error:`Property "${A}" does not match unevaluated properties schema.`},...z.errors)}}}else if(f==="array"){w!==void 0&&e.length>w&&C.push({instanceLocation:i,keyword:"maxItems",keywordLocation:`${o}/maxItems`,error:`Array has too many items (${e.length} > ${w}).`}),u!==void 0&&e.length<u&&C.push({instanceLocation:i,keyword:"minItems",keywordLocation:`${o}/minItems`,error:`Array has too few items (${e.length} < ${u}).`});let F=e.length,$=0,Z=!1;if(Ue!==void 0){let N=`${o}/prefixItems`,A=Math.min(Ue.length,F);for(;$<A;$++){let B=re(e[$],Ue[$],r,n,a,s,`${i}/${$}`,`${N}/${$}`);if(c[$]=!0,!B.valid&&(Z=a,C.push({instanceLocation:i,keyword:"prefixItems",keywordLocation:N,error:"Items did not match schema."},...B.errors),Z))break}}if(ft!==void 0){let N=`${o}/items`;if(Array.isArray(ft)){let A=Math.min(ft.length,F);for(;$<A;$++){let B=re(e[$],ft[$],r,n,a,s,`${i}/${$}`,`${N}/${$}`);if(c[$]=!0,!B.valid&&(Z=a,C.push({instanceLocation:i,keyword:"items",keywordLocation:N,error:"Items did not match schema."},...B.errors),Z))break}}else for(;$<F;$++){let A=re(e[$],ft,r,n,a,s,`${i}/${$}`,N);if(c[$]=!0,!A.valid&&(Z=a,C.push({instanceLocation:i,keyword:"items",keywordLocation:N,error:"Items did not match schema."},...A.errors),Z))break}if(!Z&&Ur!==void 0){let A=`${o}/additionalItems`;for(;$<F;$++){let B=re(e[$],Ur,r,n,a,s,`${i}/${$}`,A);c[$]=!0,B.valid||(Z=a,C.push({instanceLocation:i,keyword:"additionalItems",keywordLocation:A,error:"Items did not match additional items schema."},...B.errors))}}}if(Wr!==void 0)if(F===0&&Ve===void 0)C.push({instanceLocation:i,keyword:"contains",keywordLocation:`${o}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(Ve!==void 0&&F<Ve)C.push({instanceLocation:i,keyword:"minContains",keywordLocation:`${o}/minContains`,error:`Array has less items (${F}) than minContains (${Ve}).`});else{let N=`${o}/contains`,A=C.length,B=0;for(let z=0;z<F;z++){let ke=re(e[z],Wr,r,n,a,s,`${i}/${z}`,N);ke.valid?(c[z]=!0,B++):C.push(...ke.errors)}B>=(Ve||0)&&(C.length=A),Ve===void 0&&d===void 0&&B===0?C.splice(A,0,{instanceLocation:i,keyword:"contains",keywordLocation:N,error:"Array does not contain item matching schema."}):Ve!==void 0&&B<Ve?C.push({instanceLocation:i,keyword:"minContains",keywordLocation:`${o}/minContains`,error:`Array must contain at least ${Ve} items matching schema. Only ${B} items were found.`}):d!==void 0&&B>d&&C.push({instanceLocation:i,keyword:"maxContains",keywordLocation:`${o}/maxContains`,error:`Array may contain at most ${d} items matching schema. ${B} items were found.`})}if(!Z&&Vr!==void 0){let N=`${o}/unevaluatedItems`;for($;$<F;$++){if(c[$])continue;let A=re(e[$],Vr,r,n,a,s,`${i}/${$}`,N);c[$]=!0,A.valid||C.push({instanceLocation:i,keyword:"unevaluatedItems",keywordLocation:N,error:"Items did not match unevaluated items schema."},...A.errors)}}if(g)for(let N=0;N<F;N++){let A=e[N],B=typeof A=="object"&&A!==null;for(let z=0;z<F;z++){if(N===z)continue;let ke=e[z];(A===ke||B&&(typeof ke=="object"&&ke!==null)&&it(A,ke))&&(C.push({instanceLocation:i,keyword:"uniqueItems",keywordLocation:`${o}/uniqueItems`,error:`Duplicate items at indexes ${N} and ${z}.`}),N=Number.MAX_SAFE_INTEGER,z=Number.MAX_SAFE_INTEGER)}}}else if(f==="number"){if(r==="4"?(G!==void 0&&(le===!0&&e<=G||e<G)&&C.push({instanceLocation:i,keyword:"minimum",keywordLocation:`${o}/minimum`,error:`${e} is less than ${le?"or equal to ":""} ${G}.`}),X!==void 0&&(se===!0&&e>=X||e>X)&&C.push({instanceLocation:i,keyword:"maximum",keywordLocation:`${o}/maximum`,error:`${e} is greater than ${se?"or equal to ":""} ${X}.`})):(G!==void 0&&e<G&&C.push({instanceLocation:i,keyword:"minimum",keywordLocation:`${o}/minimum`,error:`${e} is less than ${G}.`}),X!==void 0&&e>X&&C.push({instanceLocation:i,keyword:"maximum",keywordLocation:`${o}/maximum`,error:`${e} is greater than ${X}.`}),le!==void 0&&e<=le&&C.push({instanceLocation:i,keyword:"exclusiveMinimum",keywordLocation:`${o}/exclusiveMinimum`,error:`${e} is less than ${le}.`}),se!==void 0&&e>=se&&C.push({instanceLocation:i,keyword:"exclusiveMaximum",keywordLocation:`${o}/exclusiveMaximum`,error:`${e} is greater than or equal to ${se}.`})),me!==void 0){let F=e%me;Math.abs(0-F)>=11920929e-14&&Math.abs(me-F)>=11920929e-14&&C.push({instanceLocation:i,keyword:"multipleOf",keywordLocation:`${o}/multipleOf`,error:`${e} is not a multiple of ${me}.`})}}else if(f==="string"){let F=Me===void 0&&ie===void 0?0:xo(e);Me!==void 0&&F<Me&&C.push({instanceLocation:i,keyword:"minLength",keywordLocation:`${o}/minLength`,error:`String is too short (${F} < ${Me}).`}),ie!==void 0&&F>ie&&C.push({instanceLocation:i,keyword:"maxLength",keywordLocation:`${o}/maxLength`,error:`String is too long (${F} > ${ie}).`}),Qe!==void 0&&!new RegExp(Qe,"u").test(e)&&C.push({instanceLocation:i,keyword:"pattern",keywordLocation:`${o}/pattern`,error:"String does not match pattern."}),Ze!==void 0&&Ss[Ze]&&!Ss[Ze](e)&&C.push({instanceLocation:i,keyword:"format",keywordLocation:`${o}/format`,error:`String does not match format "${Ze}".`})}return{valid:C.length===0,errors:C}}var Xn=class{schema;draft;shortCircuit;lookup;constructor(t,r="2019-09",n=!0){this.schema=t,this.draft=r,this.shortCircuit=n,this.lookup=He(t)}validate(t){return re(t,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(t,r){r&&(t={...t,$id:r}),He(t,this.lookup)}};var Mg=M({Validator:()=>Xn,deepCompareStrict:()=>it,toJsonSchema:()=>ct,validatesOnlyStrings:()=>$r}),To=new WeakMap;function ct(e,t){let r=!t&&e!=null&&typeof e=="object";if(r){let a=To.get(e);if(a)return a}let n;if(Yn(e)&&!te(e))n=e["~standard"].jsonSchema.input({target:"draft-07"});else if(te(e)){let a=Zn(e,!0);$e(a)?n=La(xr(a,!0),t):n=La(e,t)}else oe(e)?n=Ts(e):n=e;return r&&n!=null&&typeof n=="object"&&To.set(e,n),n}function $r(e){if(!e||typeof e!="object"||Object.keys(e).length===0||Array.isArray(e))return!1;if("type"in e)return typeof e.type=="string"?e.type==="string":Array.isArray(e.type)?e.type.every(t=>t==="string"):!1;if("enum"in e)return Array.isArray(e.enum)&&e.enum.length>0&&e.enum.every(t=>typeof t=="string");if("const"in e)return typeof e.const=="string";if("allOf"in e&&Array.isArray(e.allOf))return e.allOf.some(t=>$r(t));if("anyOf"in e&&Array.isArray(e.anyOf)||"oneOf"in e&&Array.isArray(e.oneOf)){let t="anyOf"in e?e.anyOf:e.oneOf;return t.length>0&&t.every(r=>$r(r))}if("not"in e)return!1;if("$ref"in e&&typeof e.$ref=="string"){let t=e.$ref,r=He(e);return r[t]?$r(r[t]):!1}return!1}function Es(e){return typeof e=="object"&&e!==null&&typeof e[Symbol.iterator]=="function"&&typeof e.next=="function"}var So=e=>e!=null&&typeof e=="object"&&"next"in e&&typeof e.next=="function";function Qn(e){return typeof e=="object"&&e!==null&&typeof e[Symbol.asyncIterator]=="function"}function As(e){return e!=null&&typeof e=="object"&&typeof e.next=="function"}async function Eo(e,t){try{let r=await e.next();for(;!r.done;)await t?.(r.value),r=await e.next();return r.value}finally{await e.return?.(void 0)}}function*Cs(e,t){for(;;){let{value:r,done:n}=Ce.runWithConfig(xe(e),t.next.bind(t),!0);if(n)break;yield r}}async function*ea(e,t){let r=t[Symbol.asyncIterator]();for(;;){let{value:n,done:a}=await Ce.runWithConfig(xe(e),r.next.bind(t),!0);if(a)break;yield n}}var P="0123456789abcdef".split(""),td=[-2147483648,8388608,32768,128],Ke=[24,16,8,0],ta=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],fe=[];function Ye(e,t){t?(fe[0]=fe[16]=fe[1]=fe[2]=fe[3]=fe[4]=fe[5]=fe[6]=fe[7]=fe[8]=fe[9]=fe[10]=fe[11]=fe[12]=fe[13]=fe[14]=fe[15]=0,this.blocks=fe):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],e?(this.h0=3238371032,this.h1=914150663,this.h2=812702999,this.h3=4144912697,this.h4=4290775857,this.h5=1750603025,this.h6=1694076839,this.h7=3204075428):(this.h0=1779033703,this.h1=3144134277,this.h2=1013904242,this.h3=2773480762,this.h4=1359893119,this.h5=2600822924,this.h6=528734635,this.h7=1541459225),this.block=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0,this.is224=e}Ye.prototype.update=function(e){if(!this.finalized){var t,r=typeof e;if(r!=="string"){if(r==="object"){if(e===null)throw new Error(ERROR);if(ARRAY_BUFFER&&e.constructor===ArrayBuffer)e=new Uint8Array(e);else if(!Array.isArray(e)&&(!ARRAY_BUFFER||!ArrayBuffer.isView(e)))throw new Error(ERROR)}else throw new Error(ERROR);t=!0}for(var n,a=0,s,i=e.length,o=this.blocks;a<i;){if(this.hashed&&(this.hashed=!1,o[0]=this.block,this.block=o[16]=o[1]=o[2]=o[3]=o[4]=o[5]=o[6]=o[7]=o[8]=o[9]=o[10]=o[11]=o[12]=o[13]=o[14]=o[15]=0),t)for(s=this.start;a<i&&s<64;++a)o[s>>>2]|=e[a]<<Ke[s++&3];else for(s=this.start;a<i&&s<64;++a)n=e.charCodeAt(a),n<128?o[s>>>2]|=n<<Ke[s++&3]:n<2048?(o[s>>>2]|=(192|n>>>6)<<Ke[s++&3],o[s>>>2]|=(128|n&63)<<Ke[s++&3]):n<55296||n>=57344?(o[s>>>2]|=(224|n>>>12)<<Ke[s++&3],o[s>>>2]|=(128|n>>>6&63)<<Ke[s++&3],o[s>>>2]|=(128|n&63)<<Ke[s++&3]):(n=65536+((n&1023)<<10|e.charCodeAt(++a)&1023),o[s>>>2]|=(240|n>>>18)<<Ke[s++&3],o[s>>>2]|=(128|n>>>12&63)<<Ke[s++&3],o[s>>>2]|=(128|n>>>6&63)<<Ke[s++&3],o[s>>>2]|=(128|n&63)<<Ke[s++&3]);this.lastByteIndex=s,this.bytes+=s-this.start,s>=64?(this.block=o[16],this.start=s-64,this.hash(),this.hashed=!0):this.start=s}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this}};Ye.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var e=this.blocks,t=this.lastByteIndex;e[16]=this.block,e[t>>>2]|=td[t&3],this.block=e[16],t>=56&&(this.hashed||this.hash(),e[0]=this.block,e[16]=e[1]=e[2]=e[3]=e[4]=e[5]=e[6]=e[7]=e[8]=e[9]=e[10]=e[11]=e[12]=e[13]=e[14]=e[15]=0),e[14]=this.hBytes<<3|this.bytes>>>29,e[15]=this.bytes<<3,this.hash()}};Ye.prototype.hash=function(){var e=this.h0,t=this.h1,r=this.h2,n=this.h3,a=this.h4,s=this.h5,i=this.h6,o=this.h7,c=this.blocks,l,f,p,y,h,m,v,b,k,I,S;for(l=16;l<64;++l)h=c[l-15],f=(h>>>7|h<<25)^(h>>>18|h<<14)^h>>>3,h=c[l-2],p=(h>>>17|h<<15)^(h>>>19|h<<13)^h>>>10,c[l]=c[l-16]+f+c[l-7]+p<<0;for(S=t&r,l=0;l<64;l+=4)this.first?(this.is224?(b=300032,h=c[0]-1413257819,o=h-150054599<<0,n=h+24177077<<0):(b=704751109,h=c[0]-210244248,o=h-1521486534<<0,n=h+143694565<<0),this.first=!1):(f=(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10),p=(a>>>6|a<<26)^(a>>>11|a<<21)^(a>>>25|a<<7),b=e&t,y=b^e&r^S,v=a&s^~a&i,h=o+p+v+ta[l]+c[l],m=f+y,o=n+h<<0,n=h+m<<0),f=(n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10),p=(o>>>6|o<<26)^(o>>>11|o<<21)^(o>>>25|o<<7),k=n&e,y=k^n&t^b,v=i&o^~i&a,h=s+p+v+ta[l+1]+c[l+1],m=f+y,i=r+h<<0,r=h+m<<0,f=(r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10),p=(i>>>6|i<<26)^(i>>>11|i<<21)^(i>>>25|i<<7),I=r&n,y=I^r&e^k,v=s&i^~s&o,h=a+p+v+ta[l+2]+c[l+2],m=f+y,s=t+h<<0,t=h+m<<0,f=(t>>>2|t<<30)^(t>>>13|t<<19)^(t>>>22|t<<10),p=(s>>>6|s<<26)^(s>>>11|s<<21)^(s>>>25|s<<7),S=t&r,y=S^t&n^I,v=s&i^~s&o,h=a+p+v+ta[l+3]+c[l+3],m=f+y,a=e+h<<0,e=h+m<<0,this.chromeBugWorkAround=!0;this.h0=this.h0+e<<0,this.h1=this.h1+t<<0,this.h2=this.h2+r<<0,this.h3=this.h3+n<<0,this.h4=this.h4+a<<0,this.h5=this.h5+s<<0,this.h6=this.h6+i<<0,this.h7=this.h7+o<<0};Ye.prototype.hex=function(){this.finalize();var e=this.h0,t=this.h1,r=this.h2,n=this.h3,a=this.h4,s=this.h5,i=this.h6,o=this.h7,c=P[e>>>28&15]+P[e>>>24&15]+P[e>>>20&15]+P[e>>>16&15]+P[e>>>12&15]+P[e>>>8&15]+P[e>>>4&15]+P[e&15]+P[t>>>28&15]+P[t>>>24&15]+P[t>>>20&15]+P[t>>>16&15]+P[t>>>12&15]+P[t>>>8&15]+P[t>>>4&15]+P[t&15]+P[r>>>28&15]+P[r>>>24&15]+P[r>>>20&15]+P[r>>>16&15]+P[r>>>12&15]+P[r>>>8&15]+P[r>>>4&15]+P[r&15]+P[n>>>28&15]+P[n>>>24&15]+P[n>>>20&15]+P[n>>>16&15]+P[n>>>12&15]+P[n>>>8&15]+P[n>>>4&15]+P[n&15]+P[a>>>28&15]+P[a>>>24&15]+P[a>>>20&15]+P[a>>>16&15]+P[a>>>12&15]+P[a>>>8&15]+P[a>>>4&15]+P[a&15]+P[s>>>28&15]+P[s>>>24&15]+P[s>>>20&15]+P[s>>>16&15]+P[s>>>12&15]+P[s>>>8&15]+P[s>>>4&15]+P[s&15]+P[i>>>28&15]+P[i>>>24&15]+P[i>>>20&15]+P[i>>>16&15]+P[i>>>12&15]+P[i>>>8&15]+P[i>>>4&15]+P[i&15];return this.is224||(c+=P[o>>>28&15]+P[o>>>24&15]+P[o>>>20&15]+P[o>>>16&15]+P[o>>>12&15]+P[o>>>8&15]+P[o>>>4&15]+P[o&15]),c};Ye.prototype.toString=Ye.prototype.hex;Ye.prototype.digest=function(){this.finalize();var e=this.h0,t=this.h1,r=this.h2,n=this.h3,a=this.h4,s=this.h5,i=this.h6,o=this.h7,c=[e>>>24&255,e>>>16&255,e>>>8&255,e&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255,r>>>24&255,r>>>16&255,r>>>8&255,r&255,n>>>24&255,n>>>16&255,n>>>8&255,n&255,a>>>24&255,a>>>16&255,a>>>8&255,a&255,s>>>24&255,s>>>16&255,s>>>8&255,s&255,i>>>24&255,i>>>16&255,i>>>8&255,i&255];return this.is224||c.push(o>>>24&255,o>>>16&255,o>>>8&255,o&255),c};Ye.prototype.array=Ye.prototype.digest;Ye.prototype.arrayBuffer=function(){this.finalize();var e=new ArrayBuffer(this.is224?28:32),t=new DataView(e);return t.setUint32(0,this.h0),t.setUint32(4,this.h1),t.setUint32(8,this.h2),t.setUint32(12,this.h3),t.setUint32(16,this.h4),t.setUint32(20,this.h5),t.setUint32(24,this.h6),this.is224||t.setUint32(28,this.h7),e};var ra=(...e)=>new Ye(!1,!0).update(e.join("")).hex();var Ug=M({sha256:()=>ra});var Hg=M({BaseCache:()=>Co,InMemoryCache:()=>Os,defaultHashKeyEncoder:()=>Ao,deserializeStoredGeneration:()=>rd,serializeGeneration:()=>nd}),Ao=(...e)=>ra(e.join("_"));function rd(e){return e.message!==void 0?{text:e.text,message:Mn(e.message)}:{text:e.text}}function nd(e){let t={text:e.text};return e.message!==void 0&&(t.message=e.message.toDict()),t}var Co=class{keyEncoder=Ao;makeDefaultKeyEncoder(e){this.keyEncoder=e}},ad=new Map,Os=class Oo extends Co{cache;constructor(t){super(),this.cache=t??new Map}lookup(t,r){return Promise.resolve(this.cache.get(this.keyEncoder(t,r))??null)}async update(t,r,n){this.cache.set(this.keyEncoder(t,r),n)}static global(){return new Oo(ad)}};var sd=Object.prototype.toString,id=e=>sd.call(e)==="[object Error]",od=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"]);function Io(e){if(!(e&&id(e)&&e.name==="TypeError"&&typeof e.message=="string"))return!1;let{message:t,stack:r}=e;return t==="Load failed"?r===void 0||"__sentry_captured__"in e:t.startsWith("error sending request for url")?!0:od.has(t)}function cd(e){if(typeof e=="number"){if(e<0)throw new TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(e))throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(e!==void 0)throw new TypeError("Expected `retries` to be a number or Infinity.")}function na(e,t,{min:r=0,allowInfinity:n=!1}={}){if(t!==void 0){if(typeof t!="number"||Number.isNaN(t))throw new TypeError(`Expected \`${e}\` to be a number${n?" or Infinity":""}.`);if(!n&&!Number.isFinite(t))throw new TypeError(`Expected \`${e}\` to be a finite number.`);if(t<r)throw new TypeError(`Expected \`${e}\` to be \u2265 ${r}.`)}}var ud=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}};function ld(e,t){let r=Math.max(1,e+1),n=t.randomize?Math.random()+1:1,a=Math.round(n*t.minTimeout*t.factor**(r-1));return a=Math.min(a,t.maxTimeout),a}function No(e,t){return Number.isFinite(t)?t-(performance.now()-e):t}async function dd({error:e,attemptNumber:t,retriesConsumed:r,startTime:n,options:a}){let s=e instanceof Error?e:new TypeError(`Non-error was thrown: "${e}". You should only throw errors.`);if(s instanceof ud)throw s.originalError;let i=Number.isFinite(a.retries)?Math.max(0,a.retries-r):a.retries,o=a.maxRetryTime??Number.POSITIVE_INFINITY,c=Object.freeze({error:s,attemptNumber:t,retriesLeft:i,retriesConsumed:r});if(await a.onFailedAttempt(c),No(n,o)<=0)throw s;let l=await a.shouldConsumeRetry(c),f=No(n,o);if(f<=0||i<=0)throw s;if(s instanceof TypeError&&!Io(s)){if(l)throw s;return a.signal?.throwIfAborted(),!1}if(!await a.shouldRetry(c))throw s;if(!l)return a.signal?.throwIfAborted(),!1;let p=ld(r,a),y=typeof s.retryAfterMs=="number"&&s.retryAfterMs>=0?s.retryAfterMs:void 0;y!==void 0&&(p=Math.max(p,y));let h=Math.min(p,f);return h>0&&await new Promise((m,v)=>{let b=()=>{clearTimeout(k),a.signal?.removeEventListener("abort",b),v(a.signal.reason)},k=setTimeout(()=>{a.signal?.removeEventListener("abort",b),m()},h);a.unref&&k.unref?.(),a.signal?.addEventListener("abort",b,{once:!0})}),a.signal?.throwIfAborted(),!0}async function fn(e,t={}){if(t={...t},cd(t.retries),Object.hasOwn(t,"forever"))throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");t.retries??=10,t.factor??=2,t.minTimeout??=1e3,t.maxTimeout??=Number.POSITIVE_INFINITY,t.maxRetryTime??=Number.POSITIVE_INFINITY,t.randomize??=!1,t.onFailedAttempt??=()=>{},t.shouldRetry??=()=>!0,t.shouldConsumeRetry??=()=>!0,na("factor",t.factor,{min:0,allowInfinity:!1}),na("minTimeout",t.minTimeout,{min:0,allowInfinity:!1}),na("maxTimeout",t.maxTimeout,{min:0,allowInfinity:!0}),na("maxRetryTime",t.maxRetryTime,{min:0,allowInfinity:!0}),t.factor>0||(t.factor=1),t.signal?.throwIfAborted();let r=0,n=0,a=performance.now();for(;!Number.isFinite(t.retries)||n<=t.retries;){r++;try{t.signal?.throwIfAborted();let s=await e(r);return t.signal?.throwIfAborted(),s}catch(s){await dd({error:s,attemptNumber:r,retriesConsumed:n,startTime:a,options:t})&&n++}}throw new Error("Retry attempts exhausted without throwing an error.")}var aa=ai(iu(),1),iy=M({AsyncCaller:()=>yt,classifyRateLimitError:()=>Lo,parseRetryAfterMs:()=>Do}),fd=[400,401,402,403,404,405,406,407,409,413],pd=6e4,md=[/insufficient[_ -]?quota/i,/exceeded (?:your|the current|the available).+quota/i,/usage quota/i,/quota (?:has been )?exhausted/i,/billing/i,/credit balance/i,/out of credits/i,/will reset at/i],hd=/(?:try again in|retry after)\s+(\d+(?:\.\d+)?)\s*(milliseconds?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h)\b/i;function Ro(e){return typeof e=="object"&&e!==null&&"response"in e&&typeof e.response=="object"&&e.response!==null&&"status"in e.response&&typeof e.response.status=="number"?e.response.status:void 0}function Mo(e){if(!(typeof e!="object"||e===null)){if("status"in e&&typeof e.status=="number")return e.status;if("statusCode"in e&&typeof e.statusCode=="number")return e.statusCode}}function Ns(e){return typeof e=="object"&&e!==null&&"message"in e&&typeof e.message=="string"?e.message:void 0}function $o(e){if(!(typeof e!="object"||e===null))return"code"in e&&typeof e.code=="string"?e.code:"error"in e&&typeof e.error=="object"&&e.error!==null&&"code"in e.error&&typeof e.error.code=="string"?e.error.code:void 0}function gd(e){if(e?.headers)return typeof e.headers.get=="function"?e.headers.get("retry-after"):e.headers["retry-after"]??e.headers["Retry-After"];if(e?.response?.headers)return typeof e.response.headers.get=="function"?e.response.headers.get("retry-after"):e.response.headers["retry-after"]??e.response.headers["Retry-After"]}function yd(e){if(e==null)return;let t=hd.exec(e);if(!t)return;let r=Number(t[1]),n=t[2]?.toLowerCase();if(!(Number.isNaN(r)||!n))return n==="ms"||n.startsWith("millisecond")?r:n==="m"||n.startsWith("min")?r*6e4:n==="h"||n.startsWith("hr")||n.startsWith("hour")?r*36e5:r*1e3}function Po(e,t){if(e instanceof Error)return e;let r=new Error(t);return typeof e=="object"&&e!==null&&Object.assign(r,e),r}function Is(e,t){if(typeof e!="object"||e===null)return;let r=e;r.rateLimitType=t.action,r.rateLimitReason=t.reason,t.retryAfterMs!==void 0&&(r.retryAfterMs=t.retryAfterMs)}function Do(e){if(e==null)return;let t=e.trim();if(!t)return;let r=Number(t);if(!Number.isNaN(r)&&r>=0)return r*1e3;let n=Date.parse(t);if(!Number.isNaN(n)){let a=n-Date.now();return a>0?a:0}}function Lo(e){if((Ro(e)??Mo(e))!==429)return;if($o(e)==="insufficient_quota")return{action:"stop",reason:"insufficient_quota"};let t=Ns(e);if(t&&md.some(n=>n.test(t)))return{action:"stop",reason:"quota_message"};let r=Do(gd(e))??yd(t);return r!==void 0?r<=pd?{action:"wait",retryAfterMs:r,reason:"retry_after_hint"}:{action:"capacity",retryAfterMs:r,reason:"retry_after_too_large"}:{action:"capacity",reason:"headerless_429"}}var _d=e=>{if(typeof e!="object"||e===null)return;if(Ai(e)===!1)throw e;if("message"in e&&typeof e.message=="string"&&(e.message.startsWith("Cancel")||e.message.startsWith("AbortError"))||"name"in e&&typeof e.name=="string"&&e.name==="AbortError")throw vr(e,!1);if("code"in e&&typeof e.code=="string"&&e.code==="ECONNABORTED")throw e;let t=Ro(e)??Mo(e);if(t&&fd.includes(+t))throw vr(e,!1);if($o(e)==="insufficient_quota"){let n=Po(e,Ns(e)??"Insufficient quota");throw n.name="InsufficientQuotaError",Is(n,{action:"stop",reason:"insufficient_quota"}),vr(n,!1)}let r=Lo(e);if(r){if(r.action==="wait"){Is(e,r),vr(e,!0);return}let n=Po(e,Ns(e)??"Rate limit exceeded");throw n.name==="Error"&&(n.name=r.action==="stop"?"RateLimitQuotaExhaustedError":"RateLimitCapacityError"),Is(n,r),vr(n,r.action!=="stop")}},yt=class{maxConcurrency;maxRetries;onFailedAttempt;queue;constructor(e){this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,this.onFailedAttempt=e.onFailedAttempt??_d;let t="default"in aa.default?aa.default.default:aa.default;this.queue=new t({concurrency:this.maxConcurrency})}async call(e,...t){return this.callWithRetries(this.maxRetries,e,t)}callWithRetries(e,t,r){return this.queue.add(()=>fn(()=>t(...r).catch(n=>{throw n instanceof Error?n:new Error(n)}),{onFailedAttempt:({error:n})=>this.onFailedAttempt?.(n),retries:e,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(e,t,...r){let n=e.maxRetries??this.maxRetries;if(e.signal){let a;return Promise.race([this.callWithRetries(n,t,r),new Promise((s,i)=>{a=()=>{i(Et(e.signal))},e.signal?.addEventListener("abort",a,{once:!0})})]).finally(()=>{e.signal&&a&&e.signal.removeEventListener("abort",a)})}return this.callWithRetries(n,t,r)}fetch(...e){return this.call(()=>fetch(...e).then(t=>t.ok?t:Promise.reject(t)))}};var my=M({AsyncGeneratorWithSetup:()=>Pt,IterableReadableStream:()=>we,atee:()=>sa,concat:()=>Ne,pipeGeneratorWithSetup:()=>Rs}),we=class Ps extends ReadableStream{reader;ensureReader(){this.reader||(this.reader=this.getReader())}async next(){this.ensureReader();try{let t=await this.reader.read();return t.done?(this.reader.releaseLock(),{done:!0,value:void 0}):{done:!1,value:t.value}}catch(t){throw this.reader.releaseLock(),t}}async return(){if(this.ensureReader(),this.locked){let t=this.reader.cancel();this.reader.releaseLock(),await t}return{done:!0,value:void 0}}async throw(t){if(this.ensureReader(),this.locked){let r=this.reader.cancel();this.reader.releaseLock(),await r}throw t}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}static fromReadableStream(t){let r=t.getReader();return new Ps({start(n){return a();function a(){return r.read().then(({done:s,value:i})=>{if(s){n.close();return}return n.enqueue(i),a()})}},cancel(){r.releaseLock()}})}static fromAsyncGenerator(t){return new Ps({async pull(r){let{value:n,done:a}=await t.next();a&&r.close(),r.enqueue(n)},async cancel(r){await t.return(r)}})}};function sa(e,t=2){let r=Array.from({length:t},()=>[]);return r.map(async function*(a){for(;;)if(a.length===0){let s=await e.next();for(let i of r)i.push(s)}else{if(a[0].done)return;yield a.shift().value}})}function Ne(e,t){if(Array.isArray(e)&&Array.isArray(t))return e.concat(t);if(typeof e=="string"&&typeof t=="string")return e+t;if(typeof e=="number"&&typeof t=="number")return e+t;if("concat"in e&&typeof e.concat=="function")return e.concat(t);if(typeof e=="object"&&typeof t=="object"){let r={...e};for(let[n,a]of Object.entries(t))n in r&&!Array.isArray(r[n])?r[n]=Ne(r[n],a):r[n]=a;return r}else throw new Error(`Cannot concat ${typeof e} and ${typeof t}`)}var Pt=class{generator;setup;config;signal;firstResult;firstResultUsed=!1;constructor(e){this.generator=e.generator,this.config=e.config,this.signal=e.signal??this.config?.signal,this.setup=new Promise((t,r)=>{Ce.runWithConfig(xe(e.config),async()=>{this.firstResult=this.signal?Oe(e.generator.next(),this.signal):e.generator.next(),e.startSetup?this.firstResult.then(e.startSetup).then(t,r):this.firstResult.then(n=>t(void 0),r)},!0)})}async next(...e){return this.signal?.throwIfAborted(),this.firstResultUsed?Ce.runWithConfig(xe(this.config),this.signal?async()=>Oe(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 Rs(e,t,r,n,...a){let s=new Pt({generator:t,startSetup:r,signal:n}),i=await s.setup;return{output:e(s,i,...a),setup:i}}var vd=Object.prototype.hasOwnProperty;function oa(e,t){return vd.call(e,t)}function ca(e){if(Array.isArray(e)){let r=new Array(e.length);for(let n=0;n<r.length;n++)r[n]=""+n;return r}if(Object.keys)return Object.keys(e);let t=[];for(let r in e)oa(e,r)&&t.push(r);return t}function Pe(e){switch(typeof e){case"object":return JSON.parse(JSON.stringify(e));case"undefined":return null;default:return e}}function ua(e){let t=0,r=e.length,n;for(;t<r;){if(n=e.charCodeAt(t),n>=48&&n<=57){t++;continue}return!1}return!0}function ur(e){return e.indexOf("/")===-1&&e.indexOf("~")===-1?e:e.replace(/~/g,"~0").replace(/\//g,"~1")}function Fo(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function ia(e){if(e===void 0)return!0;if(e){if(Array.isArray(e)){for(let r=0,n=e.length;r<n;r++)if(ia(e[r]))return!0}else if(typeof e=="object"){let r=ca(e),n=r.length;for(var t=0;t<n;t++)if(ia(e[r[t]]))return!0}}return!1}function jo(e,t){let r=[e];for(let n in t){let a=typeof t[n]=="object"?JSON.stringify(t[n],null,2):t[n];typeof a<"u"&&r.push(`${n}: ${a}`)}return r.join(`
10
+ `)}var zo=class extends Error{name;index;operation;tree;constructor(e,t,r,n,a){super(jo(e,{name:t,index:r,operation:n,tree:a})),this.name=t,this.index=r,this.operation=n,this.tree=a,Object.setPrototypeOf(this,new.target.prototype),this.message=jo(e,{name:t,index:r,operation:n,tree:a})}};var Bo=M({JsonPatchError:()=>ae,_areEquals:()=>Lr,applyOperation:()=>Rt,applyPatch:()=>_t,applyReducer:()=>Zo,deepClone:()=>bd,getValueByPointer:()=>pn,validate:()=>Ms,validator:()=>mn});var ae=zo,bd=Pe,Dr={add:function(e,t,r){if(t==="__proto__"||t==="constructor")throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");return e[t]=this.value,{newDocument:r}},remove:function(e,t,r){if(t==="__proto__"||t==="constructor")throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");var n=e[t];return delete e[t],{newDocument:r,removed:n}},replace:function(e,t,r){if(t==="__proto__"||t==="constructor")throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");var n=e[t];return e[t]=this.value,{newDocument:r,removed:n}},move:function(e,t,r){let n=pn(r,this.path);n&&(n=Pe(n));let a=Rt(r,{op:"remove",path:this.from}).removed;return Rt(r,{op:"add",path:this.path,value:a}),{newDocument:r,removed:n}},copy:function(e,t,r){let n=pn(r,this.from);return Rt(r,{op:"add",path:this.path,value:Pe(n)}),{newDocument:r}},test:function(e,t,r){return{newDocument:r,test:Lr(e[t],this.value)}},_get:function(e,t,r){return this.value=e[t],{newDocument:r}}},wd={add:function(e,t,r){return ua(t)?e.splice(t,0,this.value):e[t]=this.value,{newDocument:r,index:t}},remove:function(e,t,r){return{newDocument:r,removed:e.splice(t,1)[0]}},replace:function(e,t,r){var n=e[t];return e[t]=this.value,{newDocument:r,removed:n}},move:Dr.move,copy:Dr.copy,test:Dr.test,_get:Dr._get};function pn(e,t){if(t=="")return e;var r={op:"_get",path:t};return Rt(e,r),r.value}function Rt(e,t,r=!1,n=!0,a=!0,s=0){if(r&&(typeof r=="function"?r(t,0,e,t.path):mn(t,0)),t.path===""){let i={newDocument:e};if(t.op==="add")return i.newDocument=t.value,i;if(t.op==="replace")return i.newDocument=t.value,i.removed=e,i;if(t.op==="move"||t.op==="copy")return i.newDocument=pn(e,t.from),t.op==="move"&&(i.removed=e),i;if(t.op==="test"){if(i.test=Lr(e,t.value),i.test===!1)throw new ae("Test operation failed","TEST_OPERATION_FAILED",s,t,e);return i.newDocument=e,i}else{if(t.op==="remove")return i.removed=e,i.newDocument=null,i;if(t.op==="_get")return t.value=e,i;if(r)throw new ae("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",s,t,e);return i}}else{n||(e=Pe(e));let i=(t.path||"").split("/"),o=e,c=1,l=i.length,f,p,y;for(typeof r=="function"?y=r:y=mn;;){if(p=i[c],p&&p.indexOf("~")!=-1&&(p=Fo(p)),a&&(p=="__proto__"||p=="prototype"&&c>0&&i[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(r&&f===void 0&&(o[p]===void 0?f=i.slice(0,c).join("/"):c==l-1&&(f=t.path),f!==void 0&&y(t,0,e,f)),c++,Array.isArray(o)){if(p==="-")p=o.length;else{if(r&&!ua(p))throw new ae("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",s,t,e);ua(p)&&(p=~~p)}if(c>=l){if(r&&t.op==="add"&&p>o.length)throw new ae("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",s,t,e);let h=wd[t.op].call(t,o,p,e);if(h.test===!1)throw new ae("Test operation failed","TEST_OPERATION_FAILED",s,t,e);return h}}else if(c>=l){let h=Dr[t.op].call(t,o,p,e);if(h.test===!1)throw new ae("Test operation failed","TEST_OPERATION_FAILED",s,t,e);return h}if(o=o[p],r&&c<l&&(!o||typeof o!="object"))throw new ae("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",s,t,e)}}}function _t(e,t,r,n=!0,a=!0){if(r&&!Array.isArray(t))throw new ae("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");n||(e=Pe(e));let s=new Array(t.length);for(let i=0,o=t.length;i<o;i++)s[i]=Rt(e,t[i],r,!0,a,i),e=s[i].newDocument;return s.newDocument=e,s}function Zo(e,t,r){let n=Rt(e,t);if(n.test===!1)throw new ae("Test operation failed","TEST_OPERATION_FAILED",r,t,e);return n.newDocument}function mn(e,t,r,n){if(typeof e!="object"||e===null||Array.isArray(e))throw new ae("Operation is not an object","OPERATION_NOT_AN_OBJECT",t,e,r);if(Dr[e.op]){if(typeof e.path!="string")throw new ae("Operation `path` property is not a string","OPERATION_PATH_INVALID",t,e,r);if(e.path.indexOf("/")!==0&&e.path.length>0)throw new ae('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",t,e,r);if((e.op==="move"||e.op==="copy")&&typeof e.from!="string")throw new ae("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",t,e,r);if((e.op==="add"||e.op==="replace"||e.op==="test")&&e.value===void 0)throw new ae("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",t,e,r);if((e.op==="add"||e.op==="replace"||e.op==="test")&&ia(e.value))throw new ae("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",t,e,r);if(r){if(e.op=="add"){var a=e.path.split("/").length,s=n.split("/").length;if(a!==s+1&&a!==s)throw new ae("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",t,e,r)}else if(e.op==="replace"||e.op==="remove"||e.op==="_get"){if(e.path!==n)throw new ae("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",t,e,r)}else if(e.op==="move"||e.op==="copy"){var i=Ms([{op:"_get",path:e.from,value:void 0}],r);if(i&&i.name==="OPERATION_PATH_UNRESOLVABLE")throw new ae("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",t,e,r)}}}else throw new ae("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",t,e,r)}function Ms(e,t,r){try{if(!Array.isArray(e))throw new ae("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(t)_t(Pe(t),Pe(e),r||!0);else{r=r||mn;for(var n=0;n<e.length;n++)r(e[n],n,t,void 0)}}catch(a){if(a instanceof ae)return a;throw a}}function Lr(e,t){if(e===t)return!0;if(e&&t&&typeof e=="object"&&typeof t=="object"){var r=Array.isArray(e),n=Array.isArray(t),a,s,i;if(r&&n){if(s=e.length,s!=t.length)return!1;for(a=s;a--!==0;)if(!Lr(e[a],t[a]))return!1;return!0}if(r!=n)return!1;var o=Object.keys(e);if(s=o.length,s!==Object.keys(t).length)return!1;for(a=s;a--!==0;)if(!t.hasOwnProperty(o[a]))return!1;for(a=s;a--!==0;)if(i=o[a],!Lr(e[i],t[i]))return!1;return!0}return e!==e&&t!==t}function Uo(e,t,r,n,a){if(t!==e){typeof t.toJSON=="function"&&(t=t.toJSON());for(var s=ca(t),i=ca(e),o=!1,c=i.length-1;c>=0;c--){var l=i[c],f=e[l];if(oa(t,l)&&!(t[l]===void 0&&f!==void 0&&Array.isArray(t)===!1)){var p=t[l];typeof f=="object"&&f!=null&&typeof p=="object"&&p!=null&&Array.isArray(f)===Array.isArray(p)?Uo(f,p,r,n+"/"+ur(l),a):f!==p&&(a&&r.push({op:"test",path:n+"/"+ur(l),value:Pe(f)}),r.push({op:"replace",path:n+"/"+ur(l),value:Pe(p)}))}else Array.isArray(e)===Array.isArray(t)?(a&&r.push({op:"test",path:n+"/"+ur(l),value:Pe(f)}),r.push({op:"remove",path:n+"/"+ur(l)}),o=!0):(a&&r.push({op:"test",path:n,value:e}),r.push({op:"replace",path:n,value:t}))}if(!(!o&&s.length==i.length))for(var c=0;c<s.length;c++){var l=s[c];!oa(e,l)&&t[l]!==void 0&&r.push({op:"add",path:n+"/"+ur(l),value:Pe(t[l])})}}}function lr(e,t,r=!1){var n=[];return Uo(e,t,n,"",r),n}({...Bo});var $y=M({LogStreamCallbackHandler:()=>da,RunLog:()=>la,RunLogPatch:()=>ut,isLogStreamHandler:()=>Ds}),ut=class{ops;constructor(e){this.ops=e.ops??[]}concat(e){let t=this.ops.concat(e.ops),r=_t({},t);return new la({ops:t,state:r[r.length-1].newDocument})}},la=class $s extends ut{state;constructor(t){super(t),this.state=t.state}concat(t){let r=this.ops.concat(t.ops),n=_t(this.state,t.ops);return new $s({ops:r,state:n[n.length-1].newDocument})}static fromRunLogPatch(t){let r=_t({},t.ops);return new $s({ops:t.ops,state:r[r.length-1].newDocument})}},Ds=e=>e.name==="log_stream_tracer";async function Vo(e,t){if(t==="original")throw new Error("Do not assign inputs with original schema drop the key for now. When inputs are added to streamLog they should be added with standardized schema for streaming events.");let{inputs:r}=e;if(["retriever","llm","prompt"].includes(e.run_type))return r;if(!(Object.keys(r).length===1&&r?.input===""))return r.input}async function Wo(e,t){let{outputs:r}=e;return t==="original"||["retriever","llm","prompt"].includes(e.run_type)?r:r!==void 0&&Object.keys(r).length===1&&r?.output!==void 0?r.output:r}function kd(e){return e!==void 0&&e.message!==void 0}var da=class extends kr{autoClose=!0;includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;_schemaFormat="original";rootId;keyMapByRunId={};counterMapByRunName={};transformStream;writer;receiveStream;name="log_stream_tracer";lc_prefer_streaming=!0;constructor(e){super({_awaitHandler:!0,...e}),this.autoClose=e?.autoClose??!0,this.includeNames=e?.includeNames,this.includeTypes=e?.includeTypes,this.includeTags=e?.includeTags,this.excludeNames=e?.excludeNames,this.excludeTypes=e?.excludeTypes,this.excludeTags=e?.excludeTags,this._schemaFormat=e?._schemaFormat??this._schemaFormat,this.transformStream=new TransformStream,this.writer=this.transformStream.writable.getWriter(),this.receiveStream=we.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){if(e.id===this.rootId)return!1;let t=e.tags??[],r=this.includeNames===void 0&&this.includeTags===void 0&&this.includeTypes===void 0;return this.includeNames!==void 0&&(r=r||this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(r=r||this.includeTypes.includes(e.run_type)),this.includeTags!==void 0&&(r=r||t.find(n=>this.includeTags?.includes(n))!==void 0),this.excludeNames!==void 0&&(r=r&&!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(r=r&&!this.excludeTypes.includes(e.run_type)),this.excludeTags!==void 0&&(r=r&&t.every(n=>!this.excludeTags?.includes(n))),r}async*tapOutputIterable(e,t){for await(let r of t){if(e!==this.rootId){let n=this.keyMapByRunId[e];n&&await this.writer.write(new ut({ops:[{op:"add",path:`/logs/${n}/streamed_output/-`,value:r}]}))}yield r}}async onRunCreate(e){if(this.rootId===void 0&&(this.rootId=e.id,await this.writer.write(new ut({ops:[{op:"replace",path:"",value:{id:e.id,name:e.name,type:e.run_type,streamed_output:[],final_output:void 0,logs:{}}}]}))),!this._includeRun(e))return;this.counterMapByRunName[e.name]===void 0&&(this.counterMapByRunName[e.name]=0),this.counterMapByRunName[e.name]+=1;let t=this.counterMapByRunName[e.name];this.keyMapByRunId[e.id]=t===1?e.name:`${e.name}:${t}`;let r={id:e.id,name:e.name,type:e.run_type,tags:e.tags??[],metadata:e.extra?.metadata??{},start_time:new Date(e.start_time).toISOString(),streamed_output:[],streamed_output_str:[],final_output:void 0,end_time:void 0};this._schemaFormat==="streaming_events"&&(r.inputs=await Vo(e,this._schemaFormat)),await this.writer.write(new ut({ops:[{op:"add",path:`/logs/${this.keyMapByRunId[e.id]}`,value:r}]}))}async onRunUpdate(e){try{let t=this.keyMapByRunId[e.id];if(t===void 0)return;let r=[];this._schemaFormat==="streaming_events"&&r.push({op:"replace",path:`/logs/${t}/inputs`,value:await Vo(e,this._schemaFormat)}),r.push({op:"add",path:`/logs/${t}/final_output`,value:await Wo(e,this._schemaFormat)}),e.end_time!==void 0&&r.push({op:"add",path:`/logs/${t}/end_time`,value:new Date(e.end_time).toISOString()});let n=new ut({ops:r});await this.writer.write(n)}finally{if(e.id===this.rootId){let t=new ut({ops:[{op:"replace",path:"/final_output",value:await Wo(e,this._schemaFormat)}]});await this.writer.write(t),this.autoClose&&await this.writer.close()}}}async onLLMNewToken(e,t,r){let n=this.keyMapByRunId[e.id];if(n===void 0)return;let a=e.inputs.messages!==void 0,s;a?kd(r?.chunk)?s=r?.chunk:s=new _e({id:`run-${e.id}`,content:t}):s=t;let i=new ut({ops:[{op:"add",path:`/logs/${n}/streamed_output_str/-`,value:t},{op:"add",path:`/logs/${n}/streamed_output/-`,value:s}]});await this.writer.write(i)}};var zy=M({ChatGenerationChunk:()=>fa,GenerationChunk:()=>vt,RUN_KEY:()=>dr}),dr="__run",vt=class Go{text;generationInfo;constructor(t){this.text=t.text,this.generationInfo=t.generationInfo}concat(t){return new Go({text:this.text+t.text,generationInfo:{...this.generationInfo,...t.generationInfo}})}},fa=class Jo extends vt{message;constructor(t){super(t),this.message=t.message}concat(t){return new Jo({text:this.text+t.text,generationInfo:{...this.generationInfo,...t.generationInfo},message:this.message.concat(t.message)})}};function pa({name:e,serialized:t}){return e!==void 0?e:t?.name!==void 0?t.name:t?.id!==void 0&&Array.isArray(t?.id)?t.id[t.id.length-1]:"Unnamed"}var qo=e=>e.name==="event_stream_tracer",Ho=class extends kr{autoClose=!0;includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;runInfoMap=new Map;tappedPromises=new Map;transformStream;writer;receiveStream;readableStreamClosed=!1;name="event_stream_tracer";lc_prefer_streaming=!0;constructor(e){super({_awaitHandler:!0,...e}),this.autoClose=e?.autoClose??!0,this.includeNames=e?.includeNames,this.includeTypes=e?.includeTypes,this.includeTags=e?.includeTags,this.excludeNames=e?.excludeNames,this.excludeTypes=e?.excludeTypes,this.excludeTags=e?.excludeTags,this.transformStream=new TransformStream({flush:()=>{this.readableStreamClosed=!0}}),this.writer=this.transformStream.writable.getWriter(),this.receiveStream=we.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){let t=e.tags??[],r=this.includeNames===void 0&&this.includeTags===void 0&&this.includeTypes===void 0;return this.includeNames!==void 0&&(r=r||this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(r=r||this.includeTypes.includes(e.runType)),this.includeTags!==void 0&&(r=r||t.find(n=>this.includeTags?.includes(n))!==void 0),this.excludeNames!==void 0&&(r=r&&!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(r=r&&!this.excludeTypes.includes(e.runType)),this.excludeTags!==void 0&&(r=r&&t.every(n=>!this.excludeTags?.includes(n))),r}async*tapOutputIterable(e,t){let r=await t.next();if(r.done)return;let n=this.runInfoMap.get(e);if(n===void 0){yield r.value;return}function a(i,o){return i==="llm"&&typeof o=="string"?new vt({text:o}):o}let s=this.tappedPromises.get(e);if(s===void 0){let i;s=new Promise(o=>{i=o}),this.tappedPromises.set(e,s);try{let o={event:`on_${n.runType}_stream`,run_id:e,name:n.name,tags:n.tags,metadata:n.metadata,data:{}};await this.send({...o,data:{chunk:a(n.runType,r.value)}},n),yield r.value;for await(let c of t)n.runType!=="tool"&&n.runType!=="retriever"&&await this.send({...o,data:{chunk:a(n.runType,c)}},n),yield c}finally{i?.()}}else{yield r.value;for await(let i of t)yield i}}async send(e,t){this.readableStreamClosed||this._includeRun(t)&&await this.writer.write(e)}async sendEndEvent(e,t){let r=this.tappedPromises.get(e.run_id);r!==void 0?r.then(()=>{this.send(e,t)}):await this.send(e,t)}async onLLMStart(e){let t=pa(e),r=e.inputs.messages!==void 0?"chat_model":"llm",n={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:r,inputs:e.inputs};this.runInfoMap.set(e.id,n);let a=`on_${r}_start`;await this.send({event:a,data:{input:e.inputs},name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},n)}async onLLMNewToken(e,t,r){let n=this.runInfoMap.get(e.id),a,s;if(n===void 0)throw new Error(`onLLMNewToken: Run ID ${e.id} not found in run map.`);if(this.runInfoMap.size!==1){if(n.runType==="chat_model")s="on_chat_model_stream",r?.chunk===void 0?a=new _e({content:t,id:`run-${e.id}`}):a=r.chunk.message;else if(n.runType==="llm")s="on_llm_stream",r?.chunk===void 0?a=new vt({text:t}):a=r.chunk;else throw new Error(`Unexpected run type ${n.runType}`);await this.send({event:s,data:{chunk:a},run_id:e.id,name:n.name,tags:n.tags,metadata:n.metadata},n)}}async onLLMEnd(e){let t=this.runInfoMap.get(e.id);this.runInfoMap.delete(e.id);let r;if(t===void 0)throw new Error(`onLLMEnd: Run ID ${e.id} not found in run map.`);let n=e.outputs?.generations,a;if(t.runType==="chat_model"){for(let s of n??[]){if(a!==void 0)break;a=s[0]?.message}r="on_chat_model_end"}else if(t.runType==="llm")a={generations:n?.map(s=>s.map(i=>({text:i.text,generationInfo:i.generationInfo}))),llmOutput:e.outputs?.llmOutput??{}},r="on_llm_end";else throw new Error(`onLLMEnd: Unexpected run type: ${t.runType}`);await this.sendEndEvent({event:r,data:{output:a,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onChainStart(e){let t=pa(e),r=e.run_type??"chain",n={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:e.run_type},a={};e.inputs.input===""&&Object.keys(e.inputs).length===1?(a={},n.inputs={}):e.inputs.input!==void 0?(a.input=e.inputs.input,n.inputs=e.inputs.input):(a.input=e.inputs,n.inputs=e.inputs),this.runInfoMap.set(e.id,n),await this.send({event:`on_${r}_start`,data:a,name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},n)}async onChainEnd(e){let t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw new Error(`onChainEnd: Run ID ${e.id} not found in run map.`);let r=`on_${e.run_type}_end`,n=e.inputs??t.inputs??{},a={output:e.outputs?.output??e.outputs,input:n};n.input&&Object.keys(n).length===1&&(a.input=n.input,t.inputs=n.input),await this.sendEndEvent({event:r,data:a,run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata??{}},t)}async onToolStart(e){let t=pa(e),r={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:"tool",inputs:e.inputs??{}};this.runInfoMap.set(e.id,r),await this.send({event:"on_tool_start",data:{input:e.inputs??{}},name:t,run_id:e.id,tags:e.tags??[],metadata:e.extra?.metadata??{}},r)}async onToolEnd(e){let t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw new Error(`onToolEnd: Run ID ${e.id} not found in run map.`);if(t.inputs===void 0)throw new Error(`onToolEnd: Run ID ${e.id} is a tool call, and is expected to have traced inputs.`);let r=e.outputs?.output===void 0?e.outputs:e.outputs.output;await this.sendEndEvent({event:"on_tool_end",data:{output:r,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onToolError(e){let t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw new Error(`onToolEnd: Run ID ${e.id} not found in run map.`);if(t.inputs===void 0)throw new Error(`onToolEnd: Run ID ${e.id} is a tool call, and is expected to have traced inputs.`);await this.sendEndEvent({event:"on_tool_error",data:{input:t.inputs,error:e.error},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onRetrieverStart(e){let t=pa(e),r={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:"retriever",inputs:{query:e.inputs.query}};this.runInfoMap.set(e.id,r),await this.send({event:"on_retriever_start",data:{input:{query:e.inputs.query}},name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},r)}async onRetrieverEnd(e){let t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw new Error(`onRetrieverEnd: Run ID ${e.id} not found in run map.`);await this.sendEndEvent({event:"on_retriever_end",data:{output:e.outputs?.documents??e.outputs,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async handleCustomEvent(e,t,r){let n=this.runInfoMap.get(r);if(n===void 0)throw new Error(`handleCustomEvent: Run ID ${r} not found in run map.`);await this.send({event:"on_custom_event",run_id:r,name:e,tags:n.tags,metadata:n.metadata,data:t},n)}async finish(){let e=[...this.tappedPromises.values()];Promise.all(e).finally(()=>{this.writer.close()})}};var Ls=class extends kr{name="RootListenersTracer";rootId;config;argOnStart;argOnEnd;argOnError;constructor({config:e,onStart:t,onEnd:r,onError:n}){super({_awaitHandler:!0}),this.config=e,this.argOnStart=t,this.argOnEnd=r,this.argOnError=n}persistRun(e){return Promise.resolve()}async onRunCreate(e){this.rootId||(this.rootId=e.id,this.argOnStart&&await this.argOnStart(e,this.config))}async onRunUpdate(e){e.id===this.rootId&&(e.error?this.argOnError&&await this.argOnError(e,this.config):this.argOnEnd&&await this.argOnEnd(e,this.config))}};function hn(e){return e?e.lc_runnable:!1}var Ko=class{includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;constructor(e){this.includeNames=e.includeNames,this.includeTypes=e.includeTypes,this.includeTags=e.includeTags,this.excludeNames=e.excludeNames,this.excludeTypes=e.excludeTypes,this.excludeTags=e.excludeTags}includeEvent(e,t){let r=this.includeNames===void 0&&this.includeTypes===void 0&&this.includeTags===void 0,n=e.tags??[];return this.includeNames!==void 0&&(r=r||this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(r=r||this.includeTypes.includes(t)),this.includeTags!==void 0&&(r=r||n.some(a=>this.includeTags?.includes(a))),this.excludeNames!==void 0&&(r=r&&!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(r=r&&!this.excludeTypes.includes(t)),this.excludeTags!==void 0&&(r=r&&n.every(a=>!this.excludeTags?.includes(a))),r}},Yo=e=>btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");function js(e){return e.replace(/[^a-zA-Z-_0-9]/g,"_")}var xd=["*","_","`"];function Td(e){let t="";for(let[r,n]of Object.entries(e))t+=` classDef ${r} ${n};
11
+ `;return t}function Xo(e,t,r){let{firstNode:n,lastNode:a,nodeColors:s,withStyles:i=!0,curveStyle:o="linear",wrapLabelNWords:c=9}=r??{},l=i?`%%{init: {'flowchart': {'curve': '${o}'}}}%%
12
+ graph TD;
13
+ `:`graph TD;
14
+ `;if(i){let m="default",v={[m]:"{0}({1})"};n!==void 0&&(v[n]="{0}([{1}]):::first"),a!==void 0&&(v[a]="{0}([{1}]):::last");for(let[b,k]of Object.entries(e)){let I=k.name.split(":").pop()??"",S=xd.some(V=>I.startsWith(V)&&I.endsWith(V))?`<p>${I}</p>`:I;Object.keys(k.metadata??{}).length&&(S+=`<hr/><small><em>${Object.entries(k.metadata??{}).map(([V,ue])=>`${V} = ${ue}`).join(`
15
+ `)}</em></small>`);let L=(v[b]??v[m]).replace("{0}",js(b)).replace("{1}",S);l+=` ${L}
16
+ `}}let f={};for(let m of t){let v=m.source.split(":"),b=m.target.split(":"),k=v.filter((I,S)=>I===b[S]).join(":");f[k]||(f[k]=[]),f[k].push(m)}let p=new Set;function y(m){return[...m].sort((v,b)=>v.split(":").length-b.split(":").length)}function h(m,v){let b=m.length===1&&m[0].source===m[0].target;if(v&&!b){let I=v.split(":").pop();if(p.has(v))throw new Error(`Found duplicate subgraph '${I}' at '${v} -- this likely means that you're reusing a subgraph node with the same name. Please adjust your graph to have subgraph nodes with unique names.`);p.add(v),l+=` subgraph ${I}
17
+ `}let k=y(Object.keys(f).filter(I=>I.startsWith(`${v}:`)&&I!==v&&I.split(":").length===v.split(":").length+1));for(let I of k)h(f[I],I);for(let I of m){let{source:S,target:L,data:V,conditional:ue}=I,de="";if(V!==void 0){let _=V,Ze=_.split(" ");Ze.length>c&&(_=Array.from({length:Math.ceil(Ze.length/c)},(Xe,ee)=>Ze.slice(ee*c,(ee+1)*c).join(" ")).join("&nbsp;<br>&nbsp;")),de=ue?` -. &nbsp;${_}&nbsp; .-> `:` -- &nbsp;${_}&nbsp; --> `}else de=ue?" -.-> ":" --> ";l+=` ${js(S)}${de}${js(L)};
18
+ `}v&&!b&&(l+=` end
19
+ `)}h(f[""]??[],"");for(let m in f)!m.includes(":")&&m!==""&&h(f[m],m);return i&&(l+=Td(s??{})),l}async function Qo(e,t){let r=t?.backgroundColor??"white",n=t?.imageType??"png",a=Yo(e);r!==void 0&&(/^#(?:[0-9a-fA-F]{3}){1,2}$/.test(r)||(r=`!${r}`));let s=`https://mermaid.ink/img/${a}?bgColor=${r}&type=${n}`,i=await fetch(s);if(!i.ok)throw new Error(["Failed to render the graph using the Mermaid.INK API.",`Status code: ${i.status}`,`Status text: ${i.statusText}`].join(`
20
+ `));return await i.blob()}var i_=M({Graph:()=>ma});function Sd(e,t){if(e!==void 0&&!tn(e))return e;if(hn(t))try{let r=t.getName();return r=r.startsWith("Runnable")?r.slice(8):r,r}catch{return t.getName()}else return t.name??"UnknownSchema"}function Ed(e){return hn(e.data)?{type:"runnable",data:{id:e.data.lc_id,name:e.data.getName()}}:{type:"schema",data:{...ct(e.data.schema),title:e.data.name}}}var ma=class rc{nodes={};edges=[];constructor(t){this.nodes=t?.nodes??this.nodes,this.edges=t?.edges??this.edges}toJSON(){let t={};return Object.values(this.nodes).forEach((r,n)=>{t[r.id]=tn(r.id)?n:r.id}),{nodes:Object.values(this.nodes).map(r=>({id:t[r.id],...Ed(r)})),edges:this.edges.map(r=>{let n={source:t[r.source],target:t[r.target]};return typeof r.data<"u"&&(n.data=r.data),typeof r.conditional<"u"&&(n.conditional=r.conditional),n})}}addNode(t,r,n){if(r!==void 0&&this.nodes[r]!==void 0)throw new Error(`Node with id ${r} already exists`);let a=r??Zi(),s={id:a,data:t,name:Sd(r,t),metadata:n};return this.nodes[a]=s,s}removeNode(t){delete this.nodes[t.id],this.edges=this.edges.filter(r=>r.source!==t.id&&r.target!==t.id)}addEdge(t,r,n,a){if(this.nodes[t.id]===void 0)throw new Error(`Source node ${t.id} not in graph`);if(this.nodes[r.id]===void 0)throw new Error(`Target node ${r.id} not in graph`);let s={source:t.id,target:r.id,data:n,conditional:a};return this.edges.push(s),s}firstNode(){return ec(this)}lastNode(){return tc(this)}extend(t,r=""){let n=r;Object.values(t.nodes).map(c=>c.id).every(tn)&&(n="");let a=c=>n?`${n}:${c}`:c;Object.entries(t.nodes).forEach(([c,l])=>{this.nodes[a(c)]={...l,id:a(c)}});let s=t.edges.map(c=>({...c,source:a(c.source),target:a(c.target)}));this.edges=[...this.edges,...s];let i=t.firstNode(),o=t.lastNode();return[i?{id:a(i.id),data:i.data}:void 0,o?{id:a(o.id),data:o.data}:void 0]}trimFirstNode(){let t=this.firstNode();t&&ec(this,[t.id])&&this.removeNode(t)}trimLastNode(){let t=this.lastNode();t&&tc(this,[t.id])&&this.removeNode(t)}reid(){let t=Object.fromEntries(Object.values(this.nodes).map(a=>[a.id,a.name])),r=new Map;Object.values(t).forEach(a=>{r.set(a,(r.get(a)||0)+1)});let n=a=>{let s=t[a];return tn(a)&&r.get(s)===1?s:a};return new rc({nodes:Object.fromEntries(Object.entries(this.nodes).map(([a,s])=>[n(a),{...s,id:n(a)}])),edges:this.edges.map(a=>({...a,source:n(a.source),target:n(a.target)}))})}drawMermaid(t){let{withStyles:r,curveStyle:n,nodeColors:a={default:"fill:#f2f0ff,line-height:1.2",first:"fill-opacity:0",last:"fill:#bfb6fc"},wrapLabelNWords:s}=t??{},i=this.reid(),o=i.firstNode(),c=i.lastNode();return Xo(i.nodes,i.edges,{firstNode:o?.id,lastNode:c?.id,withStyles:r,curveStyle:n,nodeColors:a,wrapLabelNWords:s})}async drawMermaidPng(t){return Qo(this.drawMermaid(t),{backgroundColor:t?.backgroundColor})}};function ec(e,t=[]){let r=new Set(e.edges.filter(a=>!t.includes(a.source)).map(a=>a.target)),n=[];for(let a of Object.values(e.nodes))!t.includes(a.id)&&!r.has(a.id)&&n.push(a);return n.length===1?n[0]:void 0}function tc(e,t=[]){let r=new Set(e.edges.filter(a=>!t.includes(a.target)).map(a=>a.source)),n=[];for(let a of Object.values(e.nodes))!t.includes(a.id)&&!r.has(a.id)&&n.push(a);return n.length===1?n[0]:void 0}function nc(e){let t=new TextEncoder,r=new ReadableStream({async start(n){for await(let a of e)n.enqueue(t.encode(`event: data
21
+ data: ${JSON.stringify(a)}
22
+
23
+ `));n.enqueue(t.encode(`event: end
24
+
25
+ `)),n.close()}});return we.fromReadableStream(r)}function ce(e,t){return e&&!Array.isArray(e)&&!(e instanceof Date)&&typeof e=="object"?e:{[t]:e}}var Q=class extends Cn{lc_runnable=!0;name;getName(e){let t=this.name??this.constructor.lc_name()??this.constructor.name;return e?`${t}${e}`:t}withRetry(e){return new ga({bound:this,kwargs:{},config:{},maxAttemptNumber:e?.stopAfterAttempt,...e})}withConfig(e){return new Mt({bound:this,config:e,kwargs:{}})}withFallbacks(e){let t=Array.isArray(e)?e:e.fallbacks;return new Fs({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(q);if(t>1&&!Array.isArray(e)&&e.runId){console.warn("Provided runId will be used only for the first element of the batch.");let r=Object.fromEntries(Object.entries(e).filter(([n])=>n!=="runId"));return Array.from({length:t},(n,a)=>q(a===0?e:r))}return Array.from({length:t},()=>q(e))}async batch(e,t,r){let n=this._getOptionsList(t??{},e.length),a=new yt({maxConcurrency:n[0]?.maxConcurrency??r?.maxConcurrency,onFailedAttempt:i=>{throw i}}),s=e.map((i,o)=>a.call(async()=>{try{return await this.invoke(i,n[o])}catch(c){if(r?.returnExceptions)return c;throw c}}));return Promise.all(s)}async*_streamIterator(e,t){yield this.invoke(e,t)}async stream(e,t){let r=q(t),n=new Pt({generator:this._streamIterator(e,r),config:r});return await n.setup,we.fromAsyncGenerator(n)}_separateRunnableConfigFromCallOptions(e){let t;e===void 0?t=q(e):t=q({callbacks:e.callbacks,tags:e.tags,metadata:e.metadata,runName:e.runName,configurable:e.configurable,recursionLimit:e.recursionLimit,maxConcurrency:e.maxConcurrency,runId:e.runId,timeout:e.timeout,signal:e.signal});let r={...e};return delete r.callbacks,delete r.tags,delete r.metadata,delete r.runName,delete r.configurable,delete r.recursionLimit,delete r.maxConcurrency,delete r.runId,delete r.timeout,delete r.signal,[t,r]}async _callWithConfig(e,t,r){let n=q(r),a=await(await he(n))?.handleChainStart(this.toJSON(),ce(t,"input"),n.runId,n?.runType,void 0,void 0,n?.runName??this.getName());delete n.runId;let s;try{s=await Oe(e.call(this,t,n,a),n.signal)}catch(i){throw await a?.handleChainError(i),i}return await a?.handleChainEnd(ce(s,"output")),s}async _batchWithConfig(e,t,r,n){let a=this._getOptionsList(r??{},t.length),s=await Promise.all(a.map(he)),i=await Promise.all(s.map(async(c,l)=>{let f=await c?.handleChainStart(this.toJSON(),ce(t[l],"input"),a[l].runId,a[l].runType,void 0,void 0,a[l].runName??this.getName());return delete a[l].runId,f})),o;try{o=await Oe(e.call(this,t,a,i,n),a?.[0]?.signal)}catch(c){throw await Promise.all(i.map(l=>l?.handleChainError(c))),c}return await Promise.all(i.map(c=>c?.handleChainEnd(ce(o,"output")))),o}_concatOutputChunks(e,t){return Ne(e,t)}async*_transformStreamWithConfig(e,t,r){let n,a=!0,s,i=!0,o=q(r),c=await he(o),l=this;async function*f(){for await(let y of e){if(a)if(n===void 0)n=y;else try{n=l._concatOutputChunks(n,y)}catch{n=void 0,a=!1}yield y}}let p;try{let y=await Rs(t.bind(this),f(),async()=>c?.handleChainStart(this.toJSON(),{input:""},o.runId,o.runType,void 0,void 0,o.runName??this.getName(),void 0,{lc_defers_inputs:!0}),o.signal,o);delete o.runId,p=y.setup;let h=p?.handlers.find(qo),m=y.output;h!==void 0&&p!==void 0&&(m=h.tapOutputIterable(p.runId,m));let v=p?.handlers.find(Ds);v!==void 0&&p!==void 0&&(m=v.tapOutputIterable(p.runId,m));for await(let b of m)if(yield b,i)if(s===void 0)s=b;else try{s=this._concatOutputChunks(s,b)}catch{s=void 0,i=!1}}catch(y){throw await p?.handleChainError(y,void 0,void 0,void 0,{inputs:ce(n,"input")}),y}await p?.handleChainEnd(s??{},void 0,void 0,void 0,{inputs:ce(n,"input")})}getGraph(e){let t=new ma,r=t.addNode({name:`${this.getName()}Input`,schema:ve.any()}),n=t.addNode(this),a=t.addNode({name:`${this.getName()}Output`,schema:ve.any()});return t.addEdge(r,n),t.addEdge(n,a),t}pipe(e){return new jr({first:this,last:Re(e)})}pick(e){return this.pipe(new zs(e))}assign(e){return this.pipe(new yn(new $t({steps:e})))}async*transform(e,t){let r;for await(let n of e)r===void 0?r=n:r=this._concatOutputChunks(r,n);yield*this._streamIterator(r,q(t))}async*streamLog(e,t,r){let n=new da({...r,autoClose:!1,_schemaFormat:"original"}),a=q(t);yield*this._streamLog(e,n,a)}async*_streamLog(e,t,r){let{callbacks:n}=r;if(n===void 0)r.callbacks=[t];else if(Array.isArray(n))r.callbacks=n.concat([t]);else{let o=n.copy();o.addHandler(t,!0),r.callbacks=o}let a=this.stream(e,r);async function s(){try{let o=await a;for await(let c of o){let l=new ut({ops:[{op:"add",path:"/streamed_output/-",value:c}]});await t.writer.write(l)}}finally{await t.writer.close()}}let i=s();try{for await(let o of t)yield o}finally{await i}}streamEvents(e,t,r){let n;if(t.version==="v1")n=this._streamEventsV1(e,t,r);else if(t.version==="v2")n=this._streamEventsV2(e,t,r);else throw new Error('Only versions "v1" and "v2" of the schema are currently supported.');return t.encoding==="text/event-stream"?nc(n):we.fromAsyncGenerator(n)}async*_streamEventsV2(e,t,r){let n=new Ho({...r,autoClose:!1}),a=q(t),s=a.runId??Ui();a.runId=s;let i=a.callbacks;if(i===void 0)a.callbacks=[n];else if(Array.isArray(i))a.callbacks=i.concat(n);else{let h=i.copy();h.addHandler(n,!0),a.callbacks=h}let o=new AbortController,c=this;async function l(){let h;try{if(a.signal)if("any"in AbortSignal)h=AbortSignal.any([o.signal,a.signal]);else{let b=new AbortController;a.signal.addEventListener("abort",()=>b.abort(),{once:!0}),o.signal.addEventListener("abort",()=>b.abort(),{once:!0}),h=b.signal}else h=o.signal;let m=await c.stream(e,{...a,signal:h}),v=n.tapOutputIterable(s,m);for await(let b of v)if(o.signal.aborted)break}finally{await n.finish()}}let f=l(),p=!1,y;try{for await(let h of n){if(!p){h.data.input=e,p=!0,y=h.run_id,yield h;continue}h.run_id===y&&h.event.endsWith("_end")&&h.data?.input&&delete h.data.input,yield h}}finally{o.abort(),await f}}async*_streamEventsV1(e,t,r){let n,a=!1,s=q(t),i=s.tags??[],o=s.metadata??{},c=s.runName??this.getName(),l=new da({...r,autoClose:!1,_schemaFormat:"streaming_events"}),f=new Ko({...r}),p=this._streamLog(e,l,s);for await(let h of p){if(n?n=n.concat(h):n=la.fromRunLogPatch(h),n.state===void 0)throw new Error('Internal error: "streamEvents" state is missing. Please open a bug report.');if(!a){a=!0;let k={...n.state},I={run_id:k.id,event:`on_${k.type}_start`,name:c,tags:i,metadata:o,data:{input:e}};f.includeEvent(I,k.type)&&(yield I)}let m=h.ops.filter(k=>k.path.startsWith("/logs/")).map(k=>k.path.split("/")[2]),v=[...new Set(m)];for(let k of v){let I,S={},L=n.state.logs[k];if(L.end_time===void 0?L.streamed_output.length>0?I="stream":I="start":I="end",I==="start")L.inputs!==void 0&&(S.input=L.inputs);else if(I==="end")L.inputs!==void 0&&(S.input=L.inputs),S.output=L.final_output;else if(I==="stream"){let V=L.streamed_output.length;if(V!==1)throw new Error(`Expected exactly one chunk of streamed output, got ${V} instead. Encountered in: "${L.name}"`);S={chunk:L.streamed_output[0]},L.streamed_output=[]}yield{event:`on_${L.type}_${I}`,name:L.name,run_id:L.id,tags:L.tags,metadata:L.metadata,data:S}}let{state:b}=n;if(b.streamed_output.length>0){let k=b.streamed_output.length;if(k!==1)throw new Error(`Expected exactly one chunk of streamed output, got ${k} instead. Encountered in: "${b.name}"`);let I={chunk:b.streamed_output[0]};b.streamed_output=[];let S={event:`on_${b.type}_stream`,run_id:b.id,tags:i,metadata:o,name:c,data:I};f.includeEvent(S,b.type)&&(yield S)}}let y=n?.state;if(y!==void 0){let h={event:`on_${y.type}_end`,name:c,run_id:y.id,tags:i,metadata:o,data:{output:y.final_output}};f.includeEvent(h,y.type)&&(yield h)}}static isRunnable(e){return hn(e)}withListeners({onStart:e,onEnd:t,onError:r}){return new Mt({bound:this,config:{},configFactories:[n=>({callbacks:[new Ls({config:n,onStart:e,onEnd:t,onError:r})]})]})}asTool(e){return Od(this,e)}},Mt=class ac extends Q{static lc_name(){return"RunnableBinding"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;bound;config;kwargs;configFactories;constructor(t){super(t),this.bound=t.bound,this.kwargs=t.kwargs,this.config=t.config,this.configFactories=t.configFactories}getName(t){return this.bound.getName(t)}async _mergeConfig(...t){let r=Vt(this.config,...t);return Vt(r,...this.configFactories?await Promise.all(this.configFactories.map(async n=>await n(r))):[])}withConfig(t){return new this.constructor({bound:this.bound,kwargs:this.kwargs,config:{...this.config,...t}})}withRetry(t){return new ga({bound:this.bound,kwargs:this.kwargs,config:this.config,maxAttemptNumber:t?.stopAfterAttempt,...t})}async invoke(t,r){return this.bound.invoke(t,await this._mergeConfig(r,this.kwargs))}async batch(t,r,n){let a=Array.isArray(r)?await Promise.all(r.map(async s=>this._mergeConfig(q(s),this.kwargs))):await this._mergeConfig(q(r),this.kwargs);return this.bound.batch(t,a,n)}_concatOutputChunks(t,r){return this.bound._concatOutputChunks(t,r)}async*_streamIterator(t,r){yield*this.bound._streamIterator(t,await this._mergeConfig(q(r),this.kwargs))}async stream(t,r){return this.bound.stream(t,await this._mergeConfig(q(r),this.kwargs))}async*transform(t,r){yield*this.bound.transform(t,await this._mergeConfig(q(r),this.kwargs))}streamEvents(t,r,n){let a=this,s=async function*(){yield*a.bound.streamEvents(t,{...await a._mergeConfig(q(r),a.kwargs),version:r.version},n)};return we.fromAsyncGenerator(s())}static isRunnableBinding(t){return t.bound&&Q.isRunnable(t.bound)}withListeners({onStart:t,onEnd:r,onError:n}){return new ac({bound:this.bound,kwargs:this.kwargs,config:this.config,configFactories:[a=>({callbacks:[new Ls({config:a,onStart:t,onEnd:r,onError:n})]})]})}},sc=class ic extends Q{static lc_name(){return"RunnableEach"}lc_serializable=!0;lc_namespace=["langchain_core","runnables"];bound;constructor(t){super(t),this.bound=t.bound}async invoke(t,r){return this._callWithConfig(this._invoke.bind(this),t,r)}async _invoke(t,r,n){return this.bound.batch(t,Y(r,{callbacks:n?.getChild()}))}withListeners({onStart:t,onEnd:r,onError:n}){return new ic({bound:this.bound.withListeners({onStart:t,onEnd:r,onError:n})})}},ga=class extends Mt{static lc_name(){return"RunnableRetry"}lc_namespace=["langchain_core","runnables"];maxAttemptNumber=3;onFailedAttempt=()=>{};constructor(e){super(e),this.maxAttemptNumber=e.maxAttemptNumber??this.maxAttemptNumber,this.onFailedAttempt=e.onFailedAttempt??this.onFailedAttempt}_patchConfigForRetry(e,t,r){let n=e>1?`retry:attempt:${e}`:void 0;return Y(t,{callbacks:r?.getChild(n)})}async _invoke(e,t,r){return fn(n=>super.invoke(e,this._patchConfigForRetry(n,t,r)),{onFailedAttempt:({error:n})=>this.onFailedAttempt(n,e),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}async invoke(e,t){return this._callWithConfig(this._invoke.bind(this),e,t)}async _batch(e,t,r,n){let a={};try{await fn(async s=>{let i=e.map((p,y)=>y).filter(p=>a[p.toString()]===void 0||a[p.toString()]instanceof Error),o=i.map(p=>e[p]),c=i.map(p=>this._patchConfigForRetry(s,t?.[p],r?.[p])),l=await super.batch(o,c,{...n,returnExceptions:!0}),f;for(let p=0;p<l.length;p+=1){let y=l[p],h=i[p];y instanceof Error&&f===void 0&&(f=y,f.input=o[p]),a[h.toString()]=y}if(f)throw f;return l},{onFailedAttempt:({error:s})=>this.onFailedAttempt(s,s.input),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}catch(s){if(n?.returnExceptions!==!0)throw s}return Object.keys(a).sort((s,i)=>parseInt(s,10)-parseInt(i,10)).map(s=>a[parseInt(s,10)])}async batch(e,t,r){return this._batchWithConfig(this._batch.bind(this),e,t,r)}},jr=class gn extends Q{static lc_name(){return"RunnableSequence"}first;middle=[];last;omitSequenceTags=!1;lc_serializable=!0;lc_namespace=["langchain_core","runnables"];constructor(t){super(t),this.first=t.first,this.middle=t.middle??this.middle,this.last=t.last,this.name=t.name,this.omitSequenceTags=t.omitSequenceTags??this.omitSequenceTags}get steps(){return[this.first,...this.middle,this.last]}async invoke(t,r){let n=q(r),a=await(await he(n))?.handleChainStart(this.toJSON(),ce(t,"input"),n.runId,void 0,void 0,void 0,n?.runName);delete n.runId;let s=t,i;try{let o=[this.first,...this.middle];for(let c=0;c<o.length;c+=1)s=await Oe(o[c].invoke(s,Y(n,{callbacks:a?.getChild(this.omitSequenceTags?void 0:`seq:step:${c+1}`)})),n.signal);if(n.signal?.aborted)throw Et(n.signal);i=await this.last.invoke(s,Y(n,{callbacks:a?.getChild(this.omitSequenceTags?void 0:`seq:step:${this.steps.length}`)}))}catch(o){throw await a?.handleChainError(o),o}return await a?.handleChainEnd(ce(i,"output")),i}async batch(t,r,n){let a=this._getOptionsList(r??{},t.length),s=await Promise.all(a.map(he)),i=await Promise.all(s.map(async(c,l)=>{let f=await c?.handleChainStart(this.toJSON(),ce(t[l],"input"),a[l].runId,void 0,void 0,void 0,a[l].runName);return delete a[l].runId,f})),o=t;try{for(let c=0;c<this.steps.length;c+=1)o=await Oe(this.steps[c].batch(o,i.map((l,f)=>{let p=l?.getChild(this.omitSequenceTags?void 0:`seq:step:${c+1}`);return Y(a[f],{callbacks:p})}),n),a[0]?.signal)}catch(c){throw await Promise.all(i.map(l=>l?.handleChainError(c))),c}return await Promise.all(i.map(c=>c?.handleChainEnd(ce(o,"output")))),o}_concatOutputChunks(t,r){return this.last._concatOutputChunks(t,r)}async*_streamIterator(t,r){let n=await he(r),{runId:a,...s}=r??{},i=await n?.handleChainStart(this.toJSON(),ce(t,"input"),a,void 0,void 0,void 0,s?.runName),o=[this.first,...this.middle,this.last],c=!0,l;async function*f(){yield t}try{let p=o[0].transform(f(),Y(s,{callbacks:i?.getChild(this.omitSequenceTags?void 0:"seq:step:1")}));for(let y=1;y<o.length;y+=1)p=await o[y].transform(p,Y(s,{callbacks:i?.getChild(this.omitSequenceTags?void 0:`seq:step:${y+1}`)}));for await(let y of p)if(r?.signal?.throwIfAborted(),yield y,c)if(l===void 0)l=y;else try{l=this._concatOutputChunks(l,y)}catch{l=void 0,c=!1}}catch(p){throw await i?.handleChainError(p),p}await i?.handleChainEnd(ce(l,"output"))}getGraph(t){let r=new ma,n=null;return this.steps.forEach((a,s)=>{let i=a.getGraph(t);s!==0&&i.trimFirstNode(),s!==this.steps.length-1&&i.trimLastNode(),r.extend(i);let o=i.firstNode();if(!o)throw new Error(`Runnable ${a} has no first node`);n&&r.addEdge(n,o),n=i.lastNode()}),r}pipe(t){return gn.isRunnableSequence(t)?new gn({first:this.first,middle:this.middle.concat([this.last,t.first,...t.middle]),last:t.last,name:this.name??t.name}):new gn({first:this.first,middle:[...this.middle,this.last],last:Re(t),name:this.name})}static isRunnableSequence(t){return Array.isArray(t.middle)&&Q.isRunnable(t)}static from([t,...r],n){let a={};return typeof n=="string"?a.name=n:n!==void 0&&(a=n),new gn({...a,first:Re(t),middle:r.slice(0,-1).map(Re),last:Re(r[r.length-1])})}},$t=class oc extends Q{static lc_name(){return"RunnableMap"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;steps;getStepsKeys(){return Object.keys(this.steps)}constructor(t){super(t),this.steps={};for(let[r,n]of Object.entries(t.steps))this.steps[r]=Re(n)}static from(t){return new oc({steps:t})}async invoke(t,r){let n=q(r),a=await(await he(n))?.handleChainStart(this.toJSON(),{input:t},n.runId,void 0,void 0,void 0,n?.runName);delete n.runId;let s={};try{let i=Object.entries(this.steps).map(async([o,c])=>{s[o]=await c.invoke(t,Y(n,{callbacks:a?.getChild(`map:key:${o}`)}))});await Oe(Promise.all(i),n.signal)}catch(i){throw await a?.handleChainError(i),i}return await a?.handleChainEnd(s),s}async*_transform(t,r,n){let a={...this.steps},s=sa(t,Object.keys(a).length),i=new Map(Object.entries(a).map(([o,c],l)=>{let f=c.transform(s[l],Y(n,{callbacks:r?.getChild(`map:key:${o}`)}));return[o,f.next().then(p=>({key:o,gen:f,result:p}))]}));for(;i.size;){let{key:o,result:c,gen:l}=await Oe(Promise.race(i.values()),n?.signal);i.delete(o),c.done||(yield{[o]:c.value},i.set(o,l.next().then(f=>({key:o,gen:l,result:f}))))}}transform(t,r){return this._transformStreamWithConfig(t,this._transform.bind(this),r)}async stream(t,r){async function*n(){yield t}let a=q(r),s=new Pt({generator:this.transform(n(),a),config:a});return await s.setup,we.fromAsyncGenerator(s)}},Ad=class cc extends Q{lc_serializable=!1;lc_namespace=["langchain_core","runnables"];func;constructor(t){if(super(t),!Dn(t.func))throw new Error("RunnableTraceable requires a function that is wrapped in traceable higher-order function");this.func=t.func}async invoke(t,r){let[n]=this._getOptionsList(r??{},1),a=await he(n);return Oe(this.func(Y(n,{callbacks:a}),t),n?.signal)}async*_streamIterator(t,r){let[n]=this._getOptionsList(r??{},1),a=await this.invoke(t,r);if(Qn(a)){for await(let s of a)n?.signal?.throwIfAborted(),yield s;return}if(So(a)){for(;;){n?.signal?.throwIfAborted();let s=a.next();if(s.done)break;yield s.value}return}yield a}static from(t){return new cc({func:t})}};function Cd(e){if(Dn(e))throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.")}var ze=class uc extends Q{static lc_name(){return"RunnableLambda"}lc_namespace=["langchain_core","runnables"];func;constructor(t){if(Dn(t.func))return Ad.from(t.func);super(t),Cd(t.func),this.func=t.func}static from(t){return new uc({func:t})}async _invoke(t,r,n){return new Promise((a,s)=>{let i=Y(r,{callbacks:n?.getChild(),recursionLimit:(r?.recursionLimit??25)-1});Ce.runWithConfig(xe(i),async()=>{try{let o=await this.func(t,{...i});if(o&&Q.isRunnable(o)){if(r?.recursionLimit===0)throw new Error("Recursion limit reached.");o=await o.invoke(t,{...i,recursionLimit:(i.recursionLimit??25)-1})}else if(Qn(o)){let c;for await(let l of ea(i,o))if(r?.signal?.throwIfAborted(),c===void 0)c=l;else try{c=this._concatOutputChunks(c,l)}catch{c=l}o=c}else if(Es(o)){let c;for(let l of Cs(i,o))if(r?.signal?.throwIfAborted(),c===void 0)c=l;else try{c=this._concatOutputChunks(c,l)}catch{c=l}o=c}a(o)}catch(o){s(o)}})})}async invoke(t,r){return this._callWithConfig(this._invoke.bind(this),t,r)}async*_transform(t,r,n){let a;for await(let o of t)if(a===void 0)a=o;else try{a=this._concatOutputChunks(a,o)}catch{a=o}let s=Y(n,{callbacks:r?.getChild(),recursionLimit:(n?.recursionLimit??25)-1}),i=await new Promise((o,c)=>{Ce.runWithConfig(xe(s),async()=>{try{o(await this.func(a,{...s,config:s}))}catch(l){c(l)}})});if(i&&Q.isRunnable(i)){if(n?.recursionLimit===0)throw new Error("Recursion limit reached.");let o=await i.stream(a,s);for await(let c of o)yield c}else if(Qn(i))for await(let o of ea(s,i))n?.signal?.throwIfAborted(),yield o;else if(Es(i))for(let o of Cs(s,i))n?.signal?.throwIfAborted(),yield o;else yield i}transform(t,r){return this._transformStreamWithConfig(t,this._transform.bind(this),r)}async stream(t,r){async function*n(){yield t}let a=q(r),s=new Pt({generator:this.transform(n(),a),config:a});return await s.setup,we.fromAsyncGenerator(s)}},lc=class extends $t{},Fs=class extends Q{static lc_name(){return"RunnableWithFallbacks"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;runnable;fallbacks;constructor(e){super(e),this.runnable=e.runnable,this.fallbacks=e.fallbacks}*runnables(){yield this.runnable;for(let e of this.fallbacks)yield e}async invoke(e,t){let r=q(t),n=await he(r),{runId:a,...s}=r,i=await n?.handleChainStart(this.toJSON(),ce(e,"input"),a,void 0,void 0,void 0,s?.runName),o=Y(s,{callbacks:i?.getChild()});return await Ce.runWithConfig(o,async()=>{let c;for(let l of this.runnables()){r?.signal?.throwIfAborted();try{let f=await l.invoke(e,o);return await i?.handleChainEnd(ce(f,"output")),f}catch(f){c===void 0&&(c=f)}}throw c===void 0?new Error("No error stored at end of fallback."):(await i?.handleChainError(c),c)})}async*_streamIterator(e,t){let r=q(t),n=await he(r),{runId:a,...s}=r,i=await n?.handleChainStart(this.toJSON(),ce(e,"input"),a,void 0,void 0,void 0,s?.runName),o,c;for(let f of this.runnables()){r?.signal?.throwIfAborted();let p=Y(s,{callbacks:i?.getChild()});try{c=ea(p,await f.stream(e,p));break}catch(y){o===void 0&&(o=y)}}if(c===void 0){let f=o??new Error("No error stored at end of fallback.");throw await i?.handleChainError(f),f}let l;try{for await(let f of c){yield f;try{l=l===void 0?l:this._concatOutputChunks(l,f)}catch{l=void 0}}}catch(f){throw await i?.handleChainError(f),f}await i?.handleChainEnd(ce(l,"output"))}async batch(e,t,r){if(r?.returnExceptions)throw new Error("Not implemented.");let n=this._getOptionsList(t??{},e.length),a=await Promise.all(n.map(o=>he(o))),s=await Promise.all(a.map(async(o,c)=>{let l=await o?.handleChainStart(this.toJSON(),ce(e[c],"input"),n[c].runId,void 0,void 0,void 0,n[c].runName);return delete n[c].runId,l})),i;for(let o of this.runnables()){n[0].signal?.throwIfAborted();try{let c=await o.batch(e,s.map((l,f)=>Y(n[f],{callbacks:l?.getChild()})),r);return await Promise.all(s.map((l,f)=>l?.handleChainEnd(ce(c[f],"output")))),c}catch(c){i===void 0&&(i=c)}}throw i?(await Promise.all(s.map(o=>o?.handleChainError(i))),i):new Error("No error stored at end of fallbacks.")}};function Re(e){if(typeof e=="function")return new ze({func:e});if(Q.isRunnable(e))return e;if(!Array.isArray(e)&&typeof e=="object"){let t={};for(let[r,n]of Object.entries(e))t[r]=Re(n);return new $t({steps:t})}else throw new Error(`Expected a Runnable, function or object.
26
+ Instead got an unsupported type.`)}var yn=class extends Q{static lc_name(){return"RunnableAssign"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;mapper;constructor(e){e instanceof $t&&(e={mapper:e}),super(e),this.mapper=e.mapper}async invoke(e,t){let r=await this.mapper.invoke(e,t);return{...e,...r}}async*_transform(e,t,r){let n=this.mapper.getStepsKeys(),[a,s]=sa(e),i=this.mapper.transform(s,Y(r,{callbacks:t?.getChild()})),o=i.next();for await(let c of a){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(([f])=>!n.includes(f)));Object.keys(l).length>0&&(yield l)}yield(await o).value;for await(let c of i)yield c}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*r(){yield e}let n=q(t),a=new Pt({generator:this.transform(r(),n),config:n});return await a.setup,we.fromAsyncGenerator(a)}},zs=class extends Q{static lc_name(){return"RunnablePick"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;keys;constructor(e){(typeof e=="string"||Array.isArray(e))&&(e={keys:e}),super(e),this.keys=e.keys}async _pick(e){if(typeof this.keys=="string")return e[this.keys];{let t=this.keys.map(r=>[r,e[r]]).filter(r=>r[1]!==void 0);return t.length===0?void 0:Object.fromEntries(t)}}async invoke(e,t){return this._callWithConfig(this._pick.bind(this),e,t)}async*_transform(e){for await(let t of e){let r=await this._pick(t);r!==void 0&&(yield r)}}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*r(){yield e}let n=q(t),a=new Pt({generator:this.transform(r(),n),config:n});return await a.setup,we.fromAsyncGenerator(a)}},ha=class extends Mt{name;description;schema;constructor(e){let t=jr.from([ze.from(async r=>{let n;if(gr(r))try{n=await At(this.schema,r.args)}catch{throw new yr("Received tool input did not match expected schema",JSON.stringify(r.args))}else n=r;return n}).withConfig({runName:`${e.name}:parse_input`}),e.bound]).withConfig({runName:e.name});super({bound:t,config:e.config??{}}),this.name=e.name,this.description=e.description,this.schema=e.schema}static lc_name(){return"RunnableToolLike"}};function Od(e,t){let r=t.name??e.getName(),n=t.description??Tr(t.schema);return Sr(t.schema)?new ha({name:r,description:n,schema:ve.object({input:ve.string()}).transform(a=>a.input),bound:e}):new ha({name:r,description:n,schema:t.schema,bound:e})}var Z_=M({BasePromptValue:()=>ya,ChatPromptValue:()=>Zs,ImagePromptValue:()=>Id,StringPromptValue:()=>Bs}),ya=class extends Cn{},Bs=class extends ya{static lc_name(){return"StringPromptValue"}lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;value;constructor(e){super({value:e}),this.value=e}toString(){return this.value}toChatMessages(){return[new et(this.value)]}},Zs=class extends ya{lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;static lc_name(){return"ChatPromptValue"}messages;constructor(e){Array.isArray(e)&&(e={messages:e}),super(e),this.messages=e.messages}toString(){return Rn(this.messages)}toChatMessages(){return this.messages}},Id=class extends ya{lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;static lc_name(){return"ImagePromptValue"}imageUrl;value;constructor(e){"imageUrl"in e||(e={imageUrl:e}),super(e),this.imageUrl=e.imageUrl}toString(){return this.imageUrl.url}toChatMessages(){return[new et({content:[{type:"image_url",image_url:{detail:this.imageUrl.detail,url:this.imageUrl.url}}]})]}};var mc=ai(pc(),1),jd=Object.defineProperty,Fd=(e,t,r)=>t in e?jd(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,zd=(e,t,r)=>(Fd(e,typeof t!="symbol"?t+"":t,r),r);function Bd(e,t){let r=Array.from({length:e.length},(n,a)=>({start:a,end:a+1}));for(;r.length>1;){let n=null;for(let a=0;a<r.length-1;a++){let s=e.slice(r[a].start,r[a+1].end),i=t.get(s.join(","));i!=null&&(n==null||i<n[0])&&(n=[i,a])}if(n!=null){let a=n[1];r[a]={start:r[a].start,end:r[a+1].end},r.splice(a+1,1)}else break}return r}function Zd(e,t){return e.length===1?[t.get(e.join(","))]:Bd(e,t).map(r=>t.get(e.slice(r.start,r.end).join(","))).filter(r=>r!=null)}function Ud(e){return e.replace(/[\\^$*+?.()|[\]{}]/g,"\\$&")}var Vs=class{specialTokens;inverseSpecialTokens;patStr;textEncoder=new TextEncoder;textDecoder=new TextDecoder("utf-8");rankMap=new Map;textMap=new Map;constructor(e,t){this.patStr=e.pat_str;let r=e.bpe_ranks.split(`
27
+ `).filter(Boolean).reduce((n,a)=>{let[s,i,...o]=a.split(" "),c=Number.parseInt(i,10);return o.forEach((l,f)=>n[l]=c+f),n},{});for(let[n,a]of Object.entries(r)){let s=mc.default.toByteArray(n);this.rankMap.set(s.join(","),a),this.textMap.set(a,s)}this.specialTokens={...e.special_tokens,...t},this.inverseSpecialTokens=Object.entries(this.specialTokens).reduce((n,[a,s])=>(n[s]=this.textEncoder.encode(a),n),{})}encode(e,t=[],r="all"){let n=new RegExp(this.patStr,"ug"),a=Vs.specialTokenRegex(Object.keys(this.specialTokens)),s=[],i=new Set(t==="all"?Object.keys(this.specialTokens):t),o=new Set(r==="all"?Object.keys(this.specialTokens).filter(l=>!i.has(l)):r);if(o.size>0){let l=Vs.specialTokenRegex([...o]),f=e.match(l);if(f!=null)throw new Error(`The text contains a special token that is not allowed: ${f[0]}`)}let c=0;for(;;){let l=null,f=c;for(;a.lastIndex=f,l=a.exec(e),!(l==null||i.has(l[0]));)f=l.index+1;let p=l?.index??e.length;for(let h of e.substring(c,p).matchAll(n)){let m=this.textEncoder.encode(h[0]),v=this.rankMap.get(m.join(","));if(v!=null){s.push(v);continue}s.push(...Zd(m,this.rankMap))}if(l==null)break;let y=this.specialTokens[l[0]];s.push(y),c=l.index+l[0].length}return s}decode(e){let t=[],r=0;for(let s=0;s<e.length;++s){let i=e[s],o=this.textMap.get(i)??this.inverseSpecialTokens[i];o!=null&&(t.push(o),r+=o.length)}let n=new Uint8Array(r),a=0;for(let s of t)n.set(s,a),a+=s.length;return this.textDecoder.decode(n)}},va=Vs;zd(va,"specialTokenRegex",e=>new RegExp(e.map(t=>Ud(t)).join("|"),"g"));function Ws(e){switch(e){case"gpt2":return"gpt2";case"code-cushman-001":case"code-cushman-002":case"code-davinci-001":case"code-davinci-002":case"cushman-codex":case"davinci-codex":case"davinci-002":case"text-davinci-002":case"text-davinci-003":return"p50k_base";case"code-davinci-edit-001":case"text-davinci-edit-001":return"p50k_edit";case"ada":case"babbage":case"babbage-002":case"code-search-ada-code-001":case"code-search-babbage-code-001":case"curie":case"davinci":case"text-ada-001":case"text-babbage-001":case"text-curie-001":case"text-davinci-001":case"text-search-ada-doc-001":case"text-search-babbage-doc-001":case"text-search-curie-doc-001":case"text-search-davinci-doc-001":case"text-similarity-ada-001":case"text-similarity-babbage-001":case"text-similarity-curie-001":case"text-similarity-davinci-001":return"r50k_base";case"gpt-3.5-turbo-instruct-0914":case"gpt-3.5-turbo-instruct":case"gpt-3.5-turbo-16k-0613":case"gpt-3.5-turbo-16k":case"gpt-3.5-turbo-0613":case"gpt-3.5-turbo-0301":case"gpt-3.5-turbo":case"gpt-4-32k-0613":case"gpt-4-32k-0314":case"gpt-4-32k":case"gpt-4-0613":case"gpt-4-0314":case"gpt-4":case"gpt-3.5-turbo-1106":case"gpt-35-turbo":case"gpt-4-1106-preview":case"gpt-4-vision-preview":case"gpt-3.5-turbo-0125":case"gpt-4-turbo":case"gpt-4-turbo-2024-04-09":case"gpt-4-turbo-preview":case"gpt-4-0125-preview":case"text-embedding-ada-002":case"text-embedding-3-small":case"text-embedding-3-large":return"cl100k_base";case"gpt-4o":case"gpt-4o-2024-05-13":case"gpt-4o-2024-08-06":case"gpt-4o-2024-11-20":case"gpt-4o-mini-2024-07-18":case"gpt-4o-mini":case"gpt-4o-search-preview":case"gpt-4o-search-preview-2025-03-11":case"gpt-4o-mini-search-preview":case"gpt-4o-mini-search-preview-2025-03-11":case"gpt-4o-audio-preview":case"gpt-4o-audio-preview-2024-12-17":case"gpt-4o-audio-preview-2024-10-01":case"gpt-4o-mini-audio-preview":case"gpt-4o-mini-audio-preview-2024-12-17":case"o1":case"o1-2024-12-17":case"o1-mini":case"o1-mini-2024-09-12":case"o1-preview":case"o1-preview-2024-09-12":case"o1-pro":case"o1-pro-2025-03-19":case"o3":case"o3-2025-04-16":case"o3-mini":case"o3-mini-2025-01-31":case"o4-mini":case"o4-mini-2025-04-16":case"chatgpt-4o-latest":case"gpt-4o-realtime":case"gpt-4o-realtime-preview-2024-10-01":case"gpt-4o-realtime-preview-2024-12-17":case"gpt-4o-mini-realtime-preview":case"gpt-4o-mini-realtime-preview-2024-12-17":case"gpt-4.1":case"gpt-4.1-2025-04-14":case"gpt-4.1-mini":case"gpt-4.1-mini-2025-04-14":case"gpt-4.1-nano":case"gpt-4.1-nano-2025-04-14":case"gpt-4.5-preview":case"gpt-4.5-preview-2025-02-27":case"gpt-5":case"gpt-5-2025-08-07":case"gpt-5-nano":case"gpt-5-nano-2025-08-07":case"gpt-5-mini":case"gpt-5-mini-2025-08-07":case"gpt-5-chat-latest":return"o200k_base";default:throw new Error("Unknown model")}}var rv=M({encodingForModel:()=>wa,getEncoding:()=>hc}),ba={},Vd=new yt({});async function hc(e){return e in ba||(ba[e]=Vd.fetch(`https://tiktoken.pages.dev/js/${e}.json`).then(t=>t.json()).then(t=>new va(t)).catch(t=>{throw delete ba[e],t})),await ba[e]}async function wa(e){return hc(Ws(e))}var dv=M({BaseLangChain:()=>xa,BaseLanguageModel:()=>_n,calculateMaxTokens:()=>Jd,getEmbeddingContextSize:()=>Wd,getModelContextSize:()=>gc,getModelNameForTiktoken:()=>ka,isOpenAITool:()=>Gd}),ka=e=>e.startsWith("gpt-5")?"gpt-5":e.startsWith("gpt-3.5-turbo-16k")?"gpt-3.5-turbo-16k":e.startsWith("gpt-3.5-turbo-")?"gpt-3.5-turbo":e.startsWith("gpt-4-32k")?"gpt-4-32k":e.startsWith("gpt-4-")?"gpt-4":e.startsWith("gpt-4o")?"gpt-4o":e,Wd=e=>e==="text-embedding-ada-002"?8191:2046,gc=e=>{switch(ka(e)){case"gpt-5":case"gpt-5-turbo":case"gpt-5-turbo-preview":return 4e5;case"gpt-4o":case"gpt-4o-mini":case"gpt-4o-2024-05-13":case"gpt-4o-2024-08-06":return 128e3;case"gpt-4-turbo":case"gpt-4-turbo-preview":case"gpt-4-turbo-2024-04-09":case"gpt-4-0125-preview":case"gpt-4-1106-preview":return 128e3;case"gpt-4-32k":case"gpt-4-32k-0314":case"gpt-4-32k-0613":return 32768;case"gpt-4":case"gpt-4-0314":case"gpt-4-0613":return 8192;case"gpt-3.5-turbo-16k":case"gpt-3.5-turbo-16k-0613":return 16384;case"gpt-3.5-turbo":case"gpt-3.5-turbo-0301":case"gpt-3.5-turbo-0613":case"gpt-3.5-turbo-1106":case"gpt-3.5-turbo-0125":return 4096;case"text-davinci-003":case"text-davinci-002":return 4097;case"text-davinci-001":return 2049;case"text-curie-001":case"text-babbage-001":case"text-ada-001":return 2048;case"code-davinci-002":case"code-davinci-001":return 8e3;case"code-cushman-001":return 2048;case"claude-3-5-sonnet-20241022":case"claude-3-5-sonnet-20240620":case"claude-3-opus-20240229":case"claude-3-sonnet-20240229":case"claude-3-haiku-20240307":case"claude-2.1":return 2e5;case"claude-2.0":case"claude-instant-1.2":return 1e5;case"gemini-1.5-pro":case"gemini-1.5-pro-latest":case"gemini-1.5-flash":case"gemini-1.5-flash-latest":return 1e6;case"gemini-pro":case"gemini-pro-vision":return 32768;default:return 4097}};function Gd(e){return typeof e!="object"||!e?!1:!!("type"in e&&e.type==="function"&&"function"in e&&typeof e.function=="object"&&e.function&&"name"in e.function&&"parameters"in e.function)}var Jd=async({prompt:e,modelName:t})=>{let r;try{r=(await wa(ka(t))).encode(e).length}catch{console.warn("Failed to calculate number of tokens, falling back to approximate count"),r=Math.ceil(e.length/4)}return gc(t)-r},qd=()=>!1,xa=class extends Q{verbose;callbacks;tags;metadata;get lc_attributes(){return{callbacks:void 0,verbose:void 0}}constructor(e){super(e),this.verbose=e.verbose??qd(),this.callbacks=e.callbacks,this.tags=e.tags??[],this.metadata=e.metadata??{},this._addVersion("@langchain/core","1.2.9")}_addVersion(e,t){let r=this.metadata?.versions;this.metadata={...this.metadata,versions:{...typeof r=="object"&&r!==null?r:{},[e]:t}}}},_n=class extends xa{get callKeys(){return["stop","timeout","signal","tags","metadata","callbacks"]}caller;cache;constructor({callbacks:e,callbackManager:t,...r}){let{cache:n,...a}=r;super({callbacks:e??t,...a}),typeof n=="object"?this.cache=n:n?this.cache=Os.global():this.cache=void 0,this.caller=new yt(r??{})}_encoding;async getNumTokens(e){let t;typeof e=="string"?t=e:t=e.map(n=>typeof n=="string"?n:n.type==="text"&&"text"in n?n.text:"").join("");let r=Math.ceil(t.length/4);if(!this._encoding)try{this._encoding=await wa("modelName"in this?ka(this.modelName):"gpt2")}catch(n){console.warn("Failed to calculate number of tokens, falling back to approximate count",n)}if(this._encoding)try{r=this._encoding.encode(t).length}catch(n){console.warn("Failed to calculate number of tokens, falling back to approximate count",n)}return r}static _convertInputToPromptValue(e){return typeof e=="string"?new Bs(e):Array.isArray(e)?new Zs(e.map(St)):e}_identifyingParams(){return{}}_getSerializedCacheKeyParametersForCall({config:e,...t}){let r={...this._identifyingParams(),...t,_type:this._llmType(),_model:this._modelType()};return Object.entries(r).filter(([n,a])=>a!==void 0).map(([n,a])=>`${n}:${JSON.stringify(a)}`).sort().join(",")}serialize(){return{...this._identifyingParams(),_type:this._llmType(),_model:this._modelType()}}static async deserialize(e){throw new Error("Use .toJSON() instead")}get profile(){return{}}_filterInvocationParamsForTracing(e){let{tools:t,functions:r,messages:n,response_format:a,...s}=e;return s}};function vn(e){return e!==void 0&&Array.isArray(e.lc_namespace)}function bn(e){return e!==void 0&&Q.isRunnable(e)&&"lc_name"in e.constructor&&typeof e.constructor.lc_name=="function"&&e.constructor.lc_name()==="RunnableToolLike"}function wn(e){return!!e&&typeof e=="object"&&"name"in e&&"schema"in e&&(Se(e.schema)||e.schema!=null&&typeof e.schema=="object"&&"type"in e.schema&&typeof e.schema.type=="string"&&["null","boolean","object","array","number","string"].includes(e.schema.type))}function kn(e){return wn(e)||bn(e)||vn(e)}var Dv=M({BaseToolkit:()=>Hd,DynamicStructuredTool:()=>vc,DynamicTool:()=>_c,StructuredTool:()=>Gs,Tool:()=>yc,ToolInputParsingException:()=>yr,isLangChainTool:()=>kn,isRunnableToolLike:()=>bn,isStructuredTool:()=>vn,isStructuredToolParams:()=>wn,tool:()=>Kd}),Gs=class extends xa{extras;returnDirect=!1;verboseParsingErrors=!1;get lc_namespace(){return["langchain","tools"]}responseFormat="content";defaultConfig;constructor(e){super(e??{}),this.verboseParsingErrors=e?.verboseParsingErrors??this.verboseParsingErrors,this.responseFormat=e?.responseFormat??this.responseFormat,this.defaultConfig=e?.defaultConfig??this.defaultConfig,this.metadata=e?.metadata??this.metadata,this.extras=e?.extras??this.extras}async invoke(e,t){let r,n=q(Vt(this.defaultConfig,t));return gr(e)?(r=e.args,n={...n,toolCall:e}):r=e,this.call(r,n)}async call(e,t,r){let n=gr(e)?e.args:e,a;if(Se(this.schema))try{a=await At(this.schema,n)}catch(h){let m="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(m=`${m}
28
+ Details: ${h.message}`),Un(h)&&(m=`${m}
29
+
30
+ ${ja.prettifyError(h)}`),new yr(m,JSON.stringify(e))}else{let h=re(n,this.schema);if(!h.valid){let m="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(m=`${m}
31
+ Details: ${h.errors.map(v=>`${v.keywordLocation}: ${v.error}`).join(`
32
+ `)}`),new yr(m,JSON.stringify(e))}a=n}let s=Ln(t),i=tt.configure(s.callbacks,this.callbacks,s.tags||r,this.tags,s.metadata,this.metadata,{verbose:this.verbose}),o;gr(e)&&(o=e.id),!o&&si(s)&&(o=s.toolCall.id);let c=await i?.handleToolStart(this.toJSON(),typeof e=="string"?e:JSON.stringify(e),s.runId,void 0,void 0,void 0,s.runName,o);delete s.runId;let l;try{let h=await this._call(a,c,s);l=As(h)?await Eo(h,async m=>{try{await c?.handleToolEvent(m)}catch(v){await c?.handleToolError(v)}}):h}catch(h){throw await c?.handleToolError(h),h}let f,p;if(this.responseFormat==="content_and_artifact")if(Array.isArray(l)&&l.length===2)[f,p]=l;else throw new Error(`Tool response format is "content_and_artifact" but the output was not a two-tuple.
33
+ Result: ${JSON.stringify(l)}`);else f=l;let y=Xd({content:f,artifact:p,toolCallId:o,name:this.name,metadata:this.metadata});return await c?.handleToolEnd(y),y}},yc=class extends Gs{schema=ve.object({input:ve.string().optional()}).transform(e=>e.input);constructor(e){super(e)}call(e,t){let r=typeof e=="string"||e==null?{input:e}:e;return super.call(r,t)}},_c=class extends yc{static lc_name(){return"DynamicTool"}name;description;func;constructor(e){super(e),this.name=e.name,this.description=e.description,this.func=e.func,this.returnDirect=e.returnDirect??this.returnDirect}async call(e,t){let r=Ln(t);return r.runName===void 0&&(r.runName=this.name),super.call(e,r)}_call(e,t,r){return this.func(e,t,r)}},vc=class extends Gs{static lc_name(){return"DynamicStructuredTool"}description;func;schema;constructor(e){super(e),this.name=e.name,this.description=e.description,this.func=e.func,this.returnDirect=e.returnDirect??this.returnDirect,this.schema=e.schema}async call(e,t,r){let n=Ln(t);return n.runName===void 0&&(n.runName=this.name),super.call(e,n,r)}_call(e,t,r){return this.func(e,t,r)}},Hd=class{getTools(){return this.tools}};function Kd(e,t){let r=Sr(t.schema),n=$r(t.schema);if(!t.schema||r||n)return new _c({...t,description:t.description??t.schema?.description??`${t.name} tool`,func:async(i,o,c)=>new Promise((l,f)=>{let p=Y(c,{callbacks:o?.getChild()});Ce.runWithConfig(xe(p),async()=>{try{l(e(i,p))}catch(y){f(y)}})})});let a=t.schema,s=t.description??t.schema.description??`${t.name} tool`;return new vc({...t,description:s,schema:a,func:async(i,o,c)=>new Promise((l,f)=>{let p,y=()=>{c?.signal&&p&&c.signal.removeEventListener("abort",p)};c?.signal&&(p=()=>{y(),f(Et(c.signal))},c.signal.addEventListener("abort",p,{once:!0}));let h=Y(c,{callbacks:o?.getChild()});Ce.runWithConfig(xe(h),async()=>{try{let m=await e(i,h);if(As(m)){l(m);return}if(c?.signal?.aborted){y();return}y(),l(m)}catch(m){y(),f(m)}})})})}function Yd(e){return typeof e=="object"&&e!==null&&"type"in e}function Xd(e){let{content:t,artifact:r,toolCallId:n,metadata:a}=e;return n&&!Pn(t)?typeof t=="string"||Array.isArray(t)&&t.every(Yd)?new Tt({status:"success",content:t,artifact:r,tool_call_id:n,name:e.name,metadata:a}):new Tt({status:"success",content:Qd(t),artifact:r,tool_call_id:n,name:e.name,metadata:a}):t}function Qd(e){try{return JSON.stringify(e)??""}catch{return`${e}`}}var Ta=(e,t)=>{let r=[...new Set(t?.map(a=>{if(typeof a=="string")return a;let s=new a({});if(!("getType"in s)||typeof s.getType!="function")throw new Error("Invalid type provided.");return s.getType()}))],n=e.getType();return r.some(a=>a===n)};function Tc(e,t){return Array.isArray(e)?bc(e,t):ze.from(r=>bc(r,e))}function bc(e,t={}){let{includeNames:r,excludeNames:n,includeTypes:a,excludeTypes:s,includeIds:i,excludeIds:o}=t,c=[];for(let l of e)if(!(n&&l.name&&n.includes(l.name))){{if(s&&Ta(l,s))continue;if(o&&l.id&&o.includes(l.id))continue}a||i||r?(r&&l.name&&r.some(f=>f===l.name)||a&&Ta(l,a)||i&&l.id&&i.some(f=>f===l.id))&&c.push(l):c.push(l)}return c}function Sc(e){return Array.isArray(e)?wc(e):ze.from(wc)}function wc(e){if(!e.length)return[];let t=[];for(let r of e){let n=r,a=t.pop();if(!a)t.push(n);else if(n.getType()==="tool"||n.getType()!==a.getType())t.push(a,n);else{let s=Ut(a),i=Ut(n),o=s.concat(i);typeof s.content=="string"&&typeof i.content=="string"&&(o.content=`${s.content}
34
+ ${i.content}`),t.push(tf(o))}}return t}function Ec(e,t){if(Array.isArray(e)){let r=e;if(!t)throw new Error("Options parameter is required when providing messages.");return kc(r,t)}else{let r=e;return ze.from(n=>kc(n,r)).withConfig({runName:"trim_messages"})}}async function kc(e,t){let{maxTokens:r,tokenCounter:n,strategy:a="last",allowPartial:s=!1,endOn:i,startOn:o,includeSystem:c=!1,textSplitter:l}=t;if(o&&a==="first")throw new Error("`startOn` should only be specified if `strategy` is 'last'.");if(c&&a==="first")throw new Error("`includeSystem` should only be specified if `strategy` is 'last'.");let f;"getNumTokens"in n?f=async y=>(await Promise.all(y.map(h=>n.getNumTokens(h.content)))).reduce((h,m)=>h+m,0):f=async y=>n(y);let p=qs;if(l&&("splitText"in l?p=l.splitText.bind(l):p=async y=>l(y)),a==="first")return Ac(e,{maxTokens:r,tokenCounter:f,textSplitter:p,partialStrategy:s?"first":void 0,endOn:i});if(a==="last")return ef(e,{maxTokens:r,tokenCounter:f,textSplitter:p,allowPartial:s,includeSystem:c,startOn:o,endOn:i});throw new Error(`Unrecognized strategy: '${a}'. Must be one of 'first' or 'last'.`)}async function Ac(e,t){let{maxTokens:r,tokenCounter:n,textSplitter:a,partialStrategy:s,endOn:i}=t,o=[...e],c=0;for(let l=0;l<o.length;l+=1)if(await n(l>0?o.slice(0,-l):o)<=r){c=o.length-l;break}if(c<o.length&&s){let l=!1;if(Array.isArray(o[c].content)){let f=o[c];if(typeof f.content=="string")throw new Error("Expected content to be an array.");let p=f.content.length,y=s==="last"?[...f.content].reverse():f.content;for(let h=1;h<=p;h+=1){let m=s==="first"?y.slice(0,h):y.slice(-h),v=Object.fromEntries(Object.entries(f).filter(([I])=>I!=="type"&&!I.startsWith("lc_"))),b=Js(f.getType(),{...v,content:m}),k=[...o.slice(0,c),b];if(await n(k)<=r)o=k,c+=1,l=!0;else break}l&&s==="last"&&(f.content=[...y].reverse())}if(!l){let f=o[c],p;if(Array.isArray(f.content)&&f.content.some(y=>typeof y=="string"||y.type==="text")?p=f.content.find(y=>y.type==="text"&&y.text)?.text:typeof f.content=="string"&&(p=f.content),p){let y=await a(p),h=y.length;s==="last"&&y.reverse();for(let m=0;m<h-1;m+=1)if(y.pop(),f.content=y.join(""),await n([...o.slice(0,c),f])<=r){s==="last"&&(f.content=[...y].reverse().join("")),o=[...o.slice(0,c),f],c+=1;break}}}}if(i){let l=Array.isArray(i)?i:[i];for(;c>0&&!Ta(o[c-1],l);)c-=1}return o.slice(0,c)}async function ef(e,t){let{allowPartial:r=!1,includeSystem:n=!1,endOn:a,startOn:s,...i}=t,o=e.map(f=>{let p=Object.fromEntries(Object.entries(f).filter(([y])=>y!=="type"&&!y.startsWith("lc_")));return Js(f.getType(),p,_r(f))});if(a){let f=Array.isArray(a)?a:[a];for(;o.length>0&&!Ta(o[o.length-1],f);)o=o.slice(0,-1)}let c=n&&o[0]?.getType()==="system",l=c?o.slice(0,1).concat(o.slice(1).reverse()):o.reverse();return l=await Ac(l,{...i,partialStrategy:r?"last":void 0,endOn:s}),c?[l[0],...l.slice(1).reverse()]:l.reverse()}var xc={human:{message:et,messageChunk:Qr},ai:{message:Ge,messageChunk:_e},system:{message:Bt,messageChunk:Zt},developer:{message:Bt,messageChunk:Zt},tool:{message:Tt,messageChunk:Gr},function:{message:Yr,messageChunk:Xr},generic:{message:Hr,messageChunk:Kr},remove:{message:en,messageChunk:en}};function Js(e,t,r){let n,a;switch(e){case"human":r?n=new Qr(t):a=new et(t);break;case"ai":if(r){let s={...t};"tool_calls"in s&&(s={...s,tool_call_chunks:s.tool_calls?.map(i=>({...i,type:"tool_call_chunk",index:void 0,args:JSON.stringify(i.args)}))}),n=new _e(s)}else a=new Ge(t);break;case"system":r?n=new Zt(t):a=new Bt(t);break;case"developer":r?n=new Zt({...t,additional_kwargs:{...t.additional_kwargs,__openai_role__:"developer"}}):a=new Bt({...t,additional_kwargs:{...t.additional_kwargs,__openai_role__:"developer"}});break;case"tool":if("tool_call_id"in t)r?n=new Gr(t):a=new Tt(t);else throw new Error("Can not convert ToolMessage to ToolMessageChunk if 'tool_call_id' field is not defined.");break;case"function":if(r)n=new Xr(t);else{if(!t.name)throw new Error("FunctionMessage must have a 'name' field");a=new Yr(t)}break;case"generic":if("role"in t)r?n=new Kr(t):a=new Hr(t);else throw new Error("Can not convert ChatMessage to ChatMessageChunk if 'role' field is not defined.");break;default:throw new Error(`Unrecognized message type ${e}`)}if(r&&n)return n;if(a)return a;throw new Error(`Unrecognized message type ${e}`)}function tf(e){let t=e.getType(),r,n=Object.fromEntries(Object.entries(e).filter(([a])=>!["type","tool_call_chunks"].includes(a)&&!a.startsWith("lc_")));if(t in xc&&(r=Js(t,n)),!r)throw new Error(`Unrecognized message chunk class ${t}. Supported classes are ${Object.keys(xc)}`);return r}function qs(e){let t=e.split(`
35
+ `);return Promise.resolve([...t.slice(0,-1).map(r=>`${r}
36
+ `),t[t.length-1]])}var Cc=["tool_call","tool_call_chunk","invalid_tool_call","server_tool_call","server_tool_call_chunk","server_tool_call_result"];var Oc=["image","video","audio","text-plain","file"];var Ic=["text","reasoning",...Cc,...Oc];var b0=M({AIMessage:()=>Ge,AIMessageChunk:()=>_e,BaseMessage:()=>hi,BaseMessageChunk:()=>wi,ChatMessage:()=>Hr,ChatMessageChunk:()=>Kr,DEFAULT_MERGE_IGNORE_KEYS:()=>yi,FunctionMessage:()=>Yr,FunctionMessageChunk:()=>Xr,HumanMessage:()=>et,HumanMessageChunk:()=>Qr,KNOWN_BLOCK_TYPES:()=>Ic,RemoveMessage:()=>en,SystemMessage:()=>Bt,SystemMessageChunk:()=>Zt,ToolMessage:()=>Tt,ToolMessageChunk:()=>Gr,_isMessageFieldWithRole:()=>ki,_mergeDicts:()=>_i,_mergeLists:()=>vi,_mergeObj:()=>bi,_mergeStatus:()=>mi,coerceMessageLikeToMessage:()=>St,collapseToolCallChunks:()=>Bi,convertToChunk:()=>Ut,convertToOpenAIImageBlock:()=>Nn,convertToProviderContentBlock:()=>di,defaultTextSplitter:()=>qs,defaultToolCallParser:()=>xi,filterMessages:()=>Tc,getBufferString:()=>Rn,iife:()=>ji,isAIMessage:()=>br,isAIMessageChunk:()=>qr,isBase64ContentBlock:()=>In,isBaseMessage:()=>We,isBaseMessageChunk:()=>_r,isChatMessage:()=>Ii,isChatMessageChunk:()=>Ni,isDataContentBlock:()=>ii,isDirectToolOutput:()=>Pn,isFunctionMessage:()=>Pi,isFunctionMessageChunk:()=>Ri,isHumanMessage:()=>Mi,isHumanMessageChunk:()=>$i,isIDContentBlock:()=>ci,isMessage:()=>fi,isOpenAIToolCallArray:()=>gi,isPlainTextContentBlock:()=>oi,isSystemMessage:()=>Di,isSystemMessageChunk:()=>Li,isToolMessage:()=>Ti,isToolMessageChunk:()=>Si,isURLContentBlock:()=>On,mapChatMessagesToStoredMessages:()=>zi,mapStoredMessageToChatMessage:()=>Mn,mapStoredMessagesToChatMessages:()=>Fi,mergeContent:()=>pi,mergeMessageRuns:()=>Sc,mergeResponseMetadata:()=>Ci,mergeUsageMetadata:()=>Oi,parseBase64DataUrl:()=>li,parseMimeType:()=>ui,trimMessages:()=>Ec});var T0=M({ChatModelStream:()=>Ea,ReasoningContentStream:()=>Mc,TextContentStream:()=>Pc,ToolCallsStream:()=>Rc,UsageMetadataStream:()=>$c}),rf=class{events=[];finished=!1;waiters=[];error=null;push(e){this.events.push(e);let t=this.waiters.splice(0);for(let r of t)r()}finish(){this.finished=!0;let e=this.waiters.splice(0);for(let t of e)t()}setError(e){this.error=e,this.finished=!0;let t=this.waiters.splice(0);for(let r of t)r()}async*iterate(){if(this.finished){if(this.error)throw this.error;yield*this.events;return}let e=0;for(;;){for(;e<this.events.length;)yield this.events[e],e++;if(this.finished){if(this.error)throw this.error;return}await new Promise(t=>{if(e<this.events.length||this.finished){t();return}this.waiters.push(t)})}}};function nf(e,t){switch(t.type){case"text-delta":return e.type==="text"?{...e,text:(e.text??"")+t.text}:e;case"reasoning-delta":return e.type==="thinking"?{...e,thinking:(e.thinking??"")+t.reasoning}:e.type==="reasoning"?{...e,reasoning:(e.reasoning??"")+t.reasoning}:e;case"data-delta":return{...e,data:(e.data??"")+t.data};case"block-delta":return{...e,...t.fields};default:throw new Error(`Unknown delta type: ${JSON.stringify(t)}`)}}function xn(e){if(e.event!=="content-block-delta")return;if("delta"in e&&e.delta)return e.delta;let t=e.content;if(t==null||typeof t!="object")return;let r=t;if(r.type==="text"&&typeof r.text=="string")return{type:"text-delta",text:r.text};if(r.type==="reasoning"&&typeof r.reasoning=="string")return{type:"reasoning-delta",reasoning:r.reasoning};if(r.type==="thinking"&&typeof r.thinking=="string")return{type:"reasoning-delta",reasoning:r.thinking};if(typeof r.data=="string")return{type:"data-delta",data:r.data,encoding:"base64"};if(typeof r.type=="string")return{type:"block-delta",fields:{...r,type:r.type}}}function Nc(e){if(e==null||typeof e!="object")return;let t=e;if(t.type==="reasoning"&&typeof t.reasoning=="string")return t.reasoning;if(t.type==="thinking"&&typeof t.thinking=="string")return t.thinking}function Sa(e){if(e==null||typeof e!="object")return!1;let t=e.type;return t==="reasoning"||t==="thinking"}function Fr(e){if(e)return{...e,input_tokens:e.input_tokens??0,output_tokens:e.output_tokens??0,total_tokens:e.total_tokens??0}}function af(e){if(e!=null&&typeof e=="object"&&!Array.isArray(e))return e;if(typeof e!="string"||e.length===0)return{};try{let t=JSON.parse(e);return t!=null&&typeof t=="object"&&!Array.isArray(t)?t:{}}catch{return{}}}function sf(e){let t=e;if(e.type==="tool_call"||e.type!=="tool_call_chunk"&&e.type!=="tool_use"&&e.type!=="input_json_delta")return e;let r=typeof t.name=="string"?t.name:void 0;if(r==null)return e;let n=t.args??t.input;return{...t,type:"tool_call",name:r,args:af(n)}}var Pc=class{_buffer;constructor(e){this._buffer=e}get full(){let e=this._buffer;return{async*[Symbol.asyncIterator](){let t="";for await(let r of e.iterate()){let n=xn(r);n?.type==="text-delta"&&(t+=n.text,yield t)}}}}[Symbol.asyncIterator](){let e=this._buffer;async function*t(){for await(let r of e.iterate()){let n=xn(r);n?.type==="text-delta"&&(yield n.text)}}return t()}then(e,t){return(async()=>{let r="";for await(let n of this)r+=n;return r})().then(e,t)}},Rc=class{_buffer;constructor(e){this._buffer=e}get full(){let e=this._buffer;return{async*[Symbol.asyncIterator](){let t=[];for await(let r of e.iterate())r.event==="content-block-finish"&&r.content.type==="tool_call"&&(t.push(r.content),yield[...t])}}}[Symbol.asyncIterator](){let e=this._buffer;async function*t(){for await(let r of e.iterate())r.event==="content-block-finish"&&r.content.type==="tool_call"&&(yield r.content)}return t()}then(e,t){return(async()=>{let r=[];for await(let n of this)r.push(n);return r})().then(e,t)}},Mc=class{_buffer;constructor(e){this._buffer=e}get full(){let e=this._buffer;return{async*[Symbol.asyncIterator](){let t="",r=!1;for await(let n of e.iterate())if(n.event==="content-block-start"){if(!Sa(n.content)){if(r)return;continue}r=!0;let a=Nc(n.content);if(a==null||a.length===0)continue;t+=a,yield t}else if(n.event==="content-block-delta"){let a=xn(n);if(a?.type!=="reasoning-delta")continue;r=!0;let s=a.reasoning;if(s==null||s.length===0)continue;t+=s,yield t}else{if(n.event==="content-block-finish"&&Sa(n.content))return;if(n.event==="message-finish")return}}}}[Symbol.asyncIterator](){let e=this._buffer;async function*t(){let r=!1;for await(let n of e.iterate())if(n.event==="content-block-start"){if(!Sa(n.content)){if(r)return;continue}r=!0;let a=Nc(n.content);a!=null&&a.length>0&&(yield a)}else if(n.event==="content-block-delta"){let a=xn(n);if(a?.type!=="reasoning-delta")continue;r=!0;let s=a.reasoning;s!=null&&s.length>0&&(yield s)}else{if(n.event==="content-block-finish"&&Sa(n.content))return;if(n.event==="message-finish")return}}return t()}then(e,t){return(async()=>{let r="";for await(let n of this)r+=n;return r})().then(e,t)}},$c=class{_buffer;constructor(e){this._buffer=e}[Symbol.asyncIterator](){let e=this._buffer;async function*t(){for await(let r of e.iterate())if(r.event==="usage"){let n=Fr(r.usage);n&&(yield n)}else if(r.event==="message-start"&&r.usage){let n=Fr(r.usage);n&&(yield n)}else if(r.event==="message-finish"&&r.usage){let n=Fr(r.usage);n&&(yield n)}}return t()}then(e,t){return(async()=>{let r;for await(let n of this)r=n;return r})().then(e,t)}},Ea=class{_buffer;constructor(e){this._buffer=new rf,this._consume(e)}async _consume(e){try{for await(let t of e)this._buffer.push(t);this._buffer.finish()}catch(t){this._buffer.setError(t instanceof Error?t:new Error(String(t)))}}[Symbol.asyncIterator](){return this._buffer.iterate()}get text(){return new Pc(this._buffer)}get toolCalls(){return new Rc(this._buffer)}get reasoning(){return new Mc(this._buffer)}get usage(){return new $c(this._buffer)}get output(){return this._assembleMessage()}then(e,t){return this._assembleMessage().then(e,t)}async _assembleMessage(){let e=[],t,r,n={},a;for await(let i of this._buffer.iterate())switch(i.event){case"message-start":t=i.id??t,i.usage&&(r=Fr(i.usage));break;case"content-block-start":e[i.index]=i.content;break;case"content-block-delta":{let o=e[i.index],c=xn(i);o&&c&&(e[i.index]=nf(o,c));break}case"content-block-finish":e[i.index]=i.content;break;case"usage":r=Fr(i.usage);break;case"message-finish":a=i.reason,i.usage&&(r=Fr(i.usage)),i.responseMetadata&&(n={...n,...i.responseMetadata});break;default:break}let s=e.filter(i=>i!=null).map(sf);return new Ge({id:t,content:s,usage_metadata:r,response_metadata:{...n,...a?{finish_reason:a}:{},output_version:"v1"}})}};var M0=M({Embeddings:()=>of}),of=class{caller;constructor(e){this.caller=new yt(e??{})}};var pr=class extends Q{static lc_name(){return"RunnablePassthrough"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;func;constructor(e){super(e),e&&(this.func=e.func)}async invoke(e,t){let r=q(t);return this.func&&await this.func(e,r),this._callWithConfig(n=>Promise.resolve(n),e,r)}async*transform(e,t){let r=q(t),n,a=!0;for await(let s of this._transformStreamWithConfig(e,i=>i,r))if(yield s,a)if(n===void 0)n=s;else try{n=Ne(n,s)}catch{n=void 0,a=!1}this.func&&n!==void 0&&await this.func(n,r)}static assign(e){return new yn(new $t({steps:e}))}};var Dc=class extends Q{static lc_name(){return"RouterRunnable"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;runnables;constructor(e){super(e),this.runnables=e.runnables}async invoke(e,t){let{key:r,input:n}=e,a=this.runnables[r];if(a===void 0)throw new Error(`No runnable associated with key "${r}".`);return a.invoke(n,q(t))}async batch(e,t,r){let n=e.map(f=>f.key),a=e.map(f=>f.input);if(n.find(f=>this.runnables[f]===void 0)!==void 0)throw new Error("One or more keys do not have a corresponding runnable.");let s=n.map(f=>this.runnables[f]),i=this._getOptionsList(t??{},e.length),o=i[0]?.maxConcurrency??r?.maxConcurrency,c=o&&o>0?o:e.length,l=[];for(let f=0;f<a.length;f+=c){let p=a.slice(f,f+c).map((h,m)=>s[m].invoke(h,i[m])),y=await Promise.all(p);l.push(y)}return l.flat()}async stream(e,t){let{key:r,input:n}=e,a=this.runnables[r];if(a===void 0)throw new Error(`No runnable associated with key "${r}".`);return a.stream(n,t)}};var Lc=class extends Q{static lc_name(){return"RunnableBranch"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;default;branches;constructor(e){super(e),this.branches=e.branches,this.default=e.default}static from(e){if(e.length<1)throw new Error("RunnableBranch requires at least one branch");let t=e.slice(0,-1).map(([n,a])=>[Re(n),Re(a)]),r=Re(e[e.length-1]);return new this({branches:t,default:r})}async _invoke(e,t,r){let n;for(let a=0;a<this.branches.length;a+=1){let[s,i]=this.branches[a];if(await s.invoke(e,Y(t,{callbacks:r?.getChild(`condition:${a+1}`)}))){n=await i.invoke(e,Y(t,{callbacks:r?.getChild(`branch:${a+1}`)}));break}}return n||(n=await this.default.invoke(e,Y(t,{callbacks:r?.getChild("branch:default")}))),n}async invoke(e,t={}){return this._callWithConfig(this._invoke,e,t)}async*_streamIterator(e,t){let r=await(await he(t))?.handleChainStart(this.toJSON(),ce(e,"input"),t?.runId,void 0,void 0,void 0,t?.runName),n,a=!0,s;try{for(let i=0;i<this.branches.length;i+=1){let[o,c]=this.branches[i];if(await o.invoke(e,Y(t,{callbacks:r?.getChild(`condition:${i+1}`)}))){s=await c.stream(e,Y(t,{callbacks:r?.getChild(`branch:${i+1}`)}));for await(let l of s)if(yield l,a)if(n===void 0)n=l;else try{n=Ne(n,l)}catch{n=void 0,a=!1}break}}if(s===void 0){s=await this.default.stream(e,Y(t,{callbacks:r?.getChild("branch:default")}));for await(let i of s)if(yield i,a)if(n===void 0)n=i;else try{n=Ne(n,i)}catch{n=void 0,a=!1}}}catch(i){throw await r?.handleChainError(i),i}await r?.handleChainEnd(n??{})}};var jc=class extends Mt{runnable;inputMessagesKey;outputMessagesKey;historyMessagesKey;getMessageHistory;constructor(e){let t=ze.from((s,i)=>this._enterHistory(s,i??{})).withConfig({runName:"loadHistory"}),r=e.historyMessagesKey??e.inputMessagesKey;r&&(t=pr.assign({[r]:t}).withConfig({runName:"insertHistory"}));let n=t.pipe(e.runnable.withListeners({onEnd:(s,i)=>this._exitHistory(s,i??{})})).withConfig({runName:"RunnableWithMessageHistory"}),a=e.config??{};super({...e,config:a,bound:n}),this.runnable=e.runnable,this.getMessageHistory=e.getMessageHistory,this.inputMessagesKey=e.inputMessagesKey,this.outputMessagesKey=e.outputMessagesKey,this.historyMessagesKey=e.historyMessagesKey}_getInputMessages(e){let t;if(typeof e=="object"&&!Array.isArray(e)&&!We(e)){let r;this.inputMessagesKey?r=this.inputMessagesKey:Object.keys(e).length===1?r=Object.keys(e)[0]:r="input",Array.isArray(e[r])&&Array.isArray(e[r][0])?t=e[r][0]:t=e[r]}else t=e;if(typeof t=="string")return[new et(t)];if(Array.isArray(t))return t;if(We(t))return[t];throw new Error(`Expected a string, BaseMessage, or array of BaseMessages.
37
+ Got ${JSON.stringify(t,null,2)}`)}_getOutputMessages(e){let t;if(!Array.isArray(e)&&!We(e)&&typeof e!="string"){let r;this.outputMessagesKey!==void 0?r=this.outputMessagesKey:Object.keys(e).length===1?r=Object.keys(e)[0]:r="output",e.generations!==void 0?t=e.generations[0][0].message:t=e[r]}else t=e;if(typeof t=="string")return[new Ge(t)];if(Array.isArray(t))return t;if(We(t))return[t];throw new Error(`Expected a string, BaseMessage, or array of BaseMessages. Received: ${JSON.stringify(t,null,2)}`)}async _enterHistory(e,t){let r=await(t?.configurable?.messageHistory).getMessages();return this.historyMessagesKey===void 0?r.concat(this._getInputMessages(e)):r}async _exitHistory(e,t){let r=t.configurable?.messageHistory,n;Array.isArray(e.inputs)&&Array.isArray(e.inputs[0])?n=e.inputs[0]:n=e.inputs;let a=this._getInputMessages(n);if(this.historyMessagesKey===void 0){let o=await r.getMessages();a=a.slice(o.length)}let s=e.outputs;if(!s)throw new Error(`Output values from 'Run' undefined. Run: ${JSON.stringify(e,null,2)}`);let i=this._getOutputMessages(s);await r.addMessages([...a,...i])}async _mergeConfig(...e){let t=await super._mergeConfig(...e);if(!t.configurable||!t.configurable.sessionId){let n={[this.inputMessagesKey??"input"]:"foo"};throw new Error(`sessionId is required. Pass it in as part of the config argument to .invoke() or .stream()
38
+ eg. chain.invoke(${JSON.stringify(n)}, ${JSON.stringify({configurable:{sessionId:"123"}})})`)}let{sessionId:r}=t.configurable;return t.configurable.messageHistory=await this.getMessageHistory(r),t}};var pb=M({RouterRunnable:()=>Dc,Runnable:()=>Q,RunnableAssign:()=>yn,RunnableBinding:()=>Mt,RunnableBranch:()=>Lc,RunnableEach:()=>sc,RunnableLambda:()=>ze,RunnableMap:()=>$t,RunnableParallel:()=>lc,RunnablePassthrough:()=>pr,RunnablePick:()=>zs,RunnableRetry:()=>ga,RunnableSequence:()=>jr,RunnableToolLike:()=>ha,RunnableWithFallbacks:()=>Fs,RunnableWithMessageHistory:()=>jc,_coerceToRunnable:()=>Re,ensureConfig:()=>q,getCallbackManagerForConfig:()=>he,mergeConfigs:()=>Vt,patchConfig:()=>Y,pickRunnableConfigKeys:()=>xe,raceWithSignal:()=>Oe});var yb=M({extendInteropZodObject:()=>to,getInteropZodDefaultGetter:()=>no,getInteropZodObjectShape:()=>Fn,getSchemaDescription:()=>Tr,interopParse:()=>Xi,interopParseAsync:()=>At,interopSafeParse:()=>Yi,interopSafeParseAsync:()=>Bn,interopZodObjectMakeFieldsOptional:()=>ao,interopZodObjectPartial:()=>ro,interopZodObjectPassthrough:()=>zn,interopZodObjectStrict:()=>xr,interopZodTransformInputSchema:()=>Zn,isInteropZodError:()=>Un,isInteropZodLiteral:()=>Ki,isInteropZodObject:()=>eo,isInteropZodSchema:()=>Se,isShapelessZodSchema:()=>Qi,isSimpleStringZodSchema:()=>Sr,isZodArrayV4:()=>nn,isZodLiteralV3:()=>Fa,isZodLiteralV4:()=>za,isZodNullableV4:()=>Za,isZodObjectV3:()=>rn,isZodObjectV4:()=>$e,isZodOptionalV4:()=>Ba,isZodSchema:()=>Hi,isZodSchemaV3:()=>oe,isZodSchemaV4:()=>te});var wb=M({convertChunksToEvents:()=>Hs,finalizeContentBlock:()=>Aa}),cf={wav:"audio/wav",mp3:"audio/mpeg",flac:"audio/flac",opus:"audio/opus",aac:"audio/aac",pcm16:"audio/pcm"},uf={png:"image/png",jpeg:"image/jpeg",jpg:"image/jpeg",webp:"image/webp",gif:"image/gif"};function Fc(e){let t=0;for(let r of e.keys())r>=t&&(t=r+1);return t}function zc(e){let t=e.additional_kwargs;return t!=null&&typeof t=="object"?t:{}}function lf(e){let t=zc(e).tool_outputs;if(!Array.isArray(t))return[];let r=[];for(let n of t){if(n==null||typeof n!="object")continue;let a=n;if(a.type!=="image_generation_call")continue;let s=typeof a.result=="string"?a.result:void 0,i=typeof a.url=="string"?a.url:void 0;if(s==null&&i==null)continue;let o=typeof a.output_format=="string"?a.output_format.toLowerCase():void 0,c=(o!=null?uf[o]:void 0)??"image/png";r.push({type:"image",...typeof a.id=="string"?{id:a.id}:{},...i!=null?{url:i}:{},...s!=null?{data:s}:{},mimeType:c})}return r}function df(e){let t=zc(e).audio;if(t==null||typeof t!="object")return;let r=t,n=typeof r.data=="string"?r.data:void 0,a=typeof r.url=="string"?r.url:void 0,s=typeof r.transcript=="string"?r.transcript:void 0;if(n==null&&a==null&&s==null)return;let i=typeof r.mime_type=="string"?r.mime_type:typeof r.mimeType=="string"?r.mimeType:void 0,o=typeof r.format=="string"?r.format.toLowerCase():void 0,c=i??(o!=null?cf[o]:void 0)??(n!=null?"audio/wav":"audio/pcm");return{...typeof r.id=="string"?{id:r.id}:{},...n!=null?{data:n}:{},...a!=null?{url:a}:{},...s!=null?{transcript:s}:{},mimeType:c}}async function*Hs(e,t){let r=new Map,n=!1,a,s,i=new Set;for await(let o of e){t?.signal?.throwIfAborted();let c=o.message,l=!1;if(!n){n=!0;let y={event:"message-start",id:c.id??void 0};_e.isInstance(c)&&c.usage_metadata&&(y.usage=c.usage_metadata,a={...c.usage_metadata},l=!0),yield y}let f=c.content;if(typeof f=="string"){if(f!==""){if(!r.has(0)){let m={type:"text",text:""};r.set(0,{type:"text",accumulated:m}),yield{event:"content-block-start",index:0,content:m}}let h=r.get(0);h.accumulated={...h.accumulated,text:(h.accumulated.text??"")+f},yield{event:"content-block-delta",index:0,delta:{type:"text-delta",text:f}}}}else if(Array.isArray(f))for(let y of f){let h=typeof y.index=="number"?y.index:r.size;if(!r.has(h))r.set(h,{type:y.type,accumulated:{...y}}),yield{event:"content-block-start",index:h,content:{...y}};else{let m=r.get(h),v=pf(y);m.accumulated=ff(m.accumulated,v),yield{event:"content-block-delta",index:h,delta:v}}}if(_e.isInstance(c)&&c.tool_call_chunks&&c.tool_call_chunks.length>0)for(let y of c.tool_call_chunks){let h=typeof y.index=="number"?y.index:r.size;if(!r.has(h)){let v={type:"tool_call_chunk",id:y.id,name:y.name,args:"",index:h};r.set(h,{type:"tool_call_chunk",accumulated:v}),yield{event:"content-block-start",index:h,content:v}}let m=r.get(h).accumulated;y.id!=null&&(m.id=y.id),y.name!=null&&(m.name=y.name),m.args=(m.args??"")+(y.args??""),yield{event:"content-block-delta",index:h,delta:{type:"block-delta",fields:{type:"tool_call_chunk",..."id"in m&&m.id!=null?{id:m.id}:{},..."name"in m&&m.name!=null?{name:m.name}:{},args:m.args}}}}let p=df(c);if(p!=null){if(s==null){let h=Fc(r);s={index:h,id:p.id,mimeType:p.mimeType,transcript:""};let m={type:"audio",...p.id!=null?{id:p.id}:{},...p.url!=null?{url:p.url}:{},data:"",mimeType:p.mimeType};r.set(h,{type:"audio",accumulated:m}),yield{event:"content-block-start",index:h,content:m}}let y=r.get(s.index);if(y!=null){let h=y.accumulated;p.id!=null&&s.id==null&&(s.id=p.id,h.id=p.id),p.transcript!=null&&(s.transcript+=p.transcript,h.transcript=s.transcript,yield{event:"content-block-delta",index:s.index,delta:{type:"block-delta",fields:{type:"audio",transcript:s.transcript}}}),p.data!=null&&p.data.length>0&&(h.data=(h.data??"")+p.data,yield{event:"content-block-delta",index:s.index,delta:{type:"data-delta",data:p.data,encoding:"base64"}})}}for(let y of lf(c)){let h=y,m=h.id??h.url??(h.data!=null?`${h.data.length}:${h.data.slice(0,32)}`:void 0);if(m!=null&&i.has(m))continue;m!=null&&i.add(m);let v=Fc(r);r.set(v,{type:"image",accumulated:y}),yield{event:"content-block-start",index:v,content:y}}if(!l&&_e.isInstance(c)&&c.usage_metadata){let y=c.usage_metadata;a?a={input_tokens:a.input_tokens+y.input_tokens,output_tokens:a.output_tokens+y.output_tokens,total_tokens:a.total_tokens+y.total_tokens}:a={...y},yield{event:"usage",usage:{...a}}}}for(let[o,c]of r)yield{event:"content-block-finish",index:o,content:Aa(c.accumulated)};yield{event:"message-finish",reason:"stop",...a?{usage:a}:{}}}function ff(e,t){switch(t.type){case"text-delta":return e.type==="text"?{...e,text:(e.text??"")+t.text}:e;case"reasoning-delta":return e.type==="thinking"?{...e,thinking:(e.thinking??"")+t.reasoning}:e.type==="reasoning"?{...e,reasoning:(e.reasoning??"")+t.reasoning}:e;case"data-delta":return{...e,data:(e.data??"")+t.data};case"block-delta":return{...e,...t.fields};default:throw new Error(`Unknown delta type: ${JSON.stringify(t)}`)}}function pf(e){if(e.type==="text")return{type:"text-delta",text:e.text};if(e.type==="reasoning")return{type:"reasoning-delta",reasoning:e.reasoning};if(e.type==="thinking"&&typeof e.thinking=="string")return{type:"reasoning-delta",reasoning:e.thinking};if(typeof e.data=="string")return{type:"data-delta",data:e.data,encoding:"base64"};if(typeof e.type=="string")return{type:"block-delta",fields:{...e}};throw new Error(`Unsupported content block delta: ${JSON.stringify(e)}`)}function Aa(e){if(e.type==="tool_call_chunk"){let t=e,r;try{r=JSON.parse(t.args??"{}")}catch{return{type:"invalid_tool_call",id:t.id,name:t.name,args:t.args,error:"Failed to parse tool call arguments as JSON"}}return{type:"tool_call",id:t.id,name:t.name,args:r}}return e}var Sb=M({convertOpenAICompletionsStream:()=>mf});async function*mf(e,t={}){let r=t.streamUsage??!0,n=t.provider??"openai",a=t.mapChunk,s=new Map,i=new Map,o=0,c=!1,l,f,p,y=!1,h=(m,v)=>{let b=i.get(m);if(b!==void 0)return{index:b,isNew:!1};let k=o++;return i.set(m,k),s.set(k,{...v}),{index:k,isNew:!0}};for await(let m of e){a&&(m=a(m)),c||(c=!0,yield{event:"message-start",id:m.id}),!y&&(m.model||m.service_tier)&&(y=!0,yield{event:"provider",provider:n,name:"stream_metadata",payload:{model:m.model,service_tier:m.service_tier}}),m.usage&&r&&(l=_f(m.usage),yield{event:"usage",usage:l});let v=m.x_groq?.usage;v&&r&&(l=gf(v),yield{event:"usage",usage:l});let b=m.choices?.[0];if(!b)continue;b.finish_reason!=null&&(f=yf(b.finish_reason),p=vf(m,b));let{delta:k}=b;if(!k)continue;let I=hf(k);if(I){let{index:S,isNew:L}=h("reasoning",{type:"reasoning",reasoning:""});L&&(yield{event:"content-block-start",index:S,content:{type:"reasoning",reasoning:""}});let V=s.get(S);V.reasoning=(V.reasoning??"")+I,yield{event:"content-block-delta",index:S,delta:{type:"reasoning-delta",reasoning:I}}}if(k.content){let{index:S,isNew:L}=h("text",{type:"text",text:""});L&&(yield{event:"content-block-start",index:S,content:{type:"text",text:""}});let V=s.get(S);V.text=(V.text??"")+k.content,yield{event:"content-block-delta",index:S,delta:{type:"text-delta",text:k.content}}}if(Array.isArray(k.tool_calls))for(let S of k.tool_calls){let L=S.index??0,{index:V,isNew:ue}=h(`tool:${L}`,{type:"tool_call_chunk",id:S.id,name:S.function?.name,args:"",index:L});ue&&(yield{event:"content-block-start",index:V,content:{type:"tool_call_chunk",id:S.id,name:S.function?.name,args:"",index:L}});let de=s.get(V);S.id!=null&&(de.id=S.id),S.function?.name!=null&&(de.name=S.function.name);let _=S.function?.arguments??"";de.args=(de.args??"")+_,yield{event:"content-block-delta",index:V,delta:{type:"block-delta",fields:{type:"tool_call_chunk",...de.id!=null?{id:de.id}:{},...de.name!=null?{name:de.name}:{},args:de.args}}}}if(k.audio){let{index:S,isNew:L}=h("audio",{type:"audio",id:k.audio.id,data:"",mimeType:"audio/pcm",transcript:k.audio.transcript??""});L&&(yield{event:"content-block-start",index:S,content:{type:"audio",id:k.audio.id,data:"",mimeType:"audio/pcm",transcript:k.audio.transcript??""}});let V=s.get(S);k.audio.transcript&&(V.transcript=(V.transcript??"")+k.audio.transcript,yield{event:"content-block-delta",index:S,delta:{type:"block-delta",fields:{type:"audio",transcript:V.transcript}}}),k.audio.data&&(V.data=(V.data??"")+k.audio.data,yield{event:"content-block-delta",index:S,delta:{type:"data-delta",data:k.audio.data,encoding:"base64"}})}k.function_call&&(yield{event:"provider",provider:n,name:"function_call",payload:k.function_call}),b.logprobs&&(yield{event:"provider",provider:n,name:"logprobs",payload:b.logprobs})}for(let[m,v]of s)yield{event:"content-block-finish",index:m,content:Aa(v)};yield{event:"message-finish",reason:f,...l?{usage:l}:{},...p?{responseMetadata:p}:{}}}function hf(e){let t=e.reasoning_content??e.reasoning;return typeof t=="string"&&t.length>0?t:void 0}function gf(e){return{input_tokens:e.prompt_tokens??0,output_tokens:e.completion_tokens??0,total_tokens:e.total_tokens??0}}function yf(e){switch(e){case"stop":return"stop";case"length":case"max_tokens":return"length";case"tool_calls":case"function_call":return"tool_use";case"content_filter":return"content_filter";default:return"stop"}}function _f(e){let t={...e.prompt_tokens_details?.audio_tokens!=null&&{audio:e.prompt_tokens_details.audio_tokens},...e.prompt_tokens_details?.cached_tokens!=null&&{cache_read:e.prompt_tokens_details.cached_tokens}},r={...e.completion_tokens_details?.audio_tokens!=null&&{audio:e.completion_tokens_details.audio_tokens},...e.completion_tokens_details?.reasoning_tokens!=null&&{reasoning:e.completion_tokens_details.reasoning_tokens}};return{input_tokens:e.prompt_tokens??0,output_tokens:e.completion_tokens??0,total_tokens:e.total_tokens??0,...Object.keys(t).length>0&&{input_token_details:t},...Object.keys(r).length>0&&{output_token_details:r}}}function vf(e,t){return{model_provider:"openai",model_name:e.model,system_fingerprint:e.system_fingerprint,service_tier:e.service_tier,finish_reason:t.finish_reason,...e.usage?{usage:e.usage}:{}}}var Cb=M({chunkArray:()=>bf}),bf=(e,t)=>e.reduce((r,n,a)=>{let s=Math.floor(a/t);return r[s]=(r[s]||[]).concat([n]),r},[]);var Ks=class extends Q{parseResultWithPrompt(e,t,r){return this.parseResult(e,r)}_baseMessageToString(e){return typeof e.content=="string"?e.content:this._baseMessageContentToString(e.content)}_baseMessageContentToString(e){return JSON.stringify(e)}async invoke(e,t){return typeof e=="string"?this._callWithConfig(async(r,n)=>this.parseResult([{text:r}],n?.callbacks),e,{...t,runType:"parser"}):this._callWithConfig(async(r,n)=>this.parseResult([{message:r,text:this._baseMessageToString(r)}],n?.callbacks),e,{...t,runType:"parser"})}},bt=class extends Ks{parseResult(e,t){return this.parse(e[0].text,t)}async parseWithPrompt(e,t,r){return this.parse(e,r)}_type(){throw new Error("_type not implemented")}},ye=class extends Error{llmOutput;observation;sendToLLM;constructor(e,t,r,n=!1){if(super(e),this.llmOutput=t,this.observation=r,this.sendToLLM=n,n&&(r===void 0||t===void 0))throw new Error("Arguments 'observation' & 'llmOutput' are required if 'sendToLlm' is true");Ei(this,"OUTPUT_PARSING_FAILURE")}};var wt=class extends bt{async*_transform(e){for await(let t of e)typeof t=="string"?yield this.parseResult([{text:t}]):yield this.parseResult([{message:t,text:this._baseMessageToString(t)}])}async*transform(e,t){yield*this._transformStreamWithConfig(e,this._transform.bind(this),{...t,runType:"parser"})}},Dt=class extends wt{diff=!1;constructor(e){super(e),this.diff=e?.diff??this.diff}async*_transform(e){let t,r;for await(let n of e){if(typeof n!="string"&&typeof n.content!="string")throw new Error("Cannot handle non-string output.");let a;if(_r(n)){if(typeof n.content!="string")throw new Error("Cannot handle non-string message output.");a=new fa({message:n,text:n.content})}else if(We(n)){if(typeof n.content!="string")throw new Error("Cannot handle non-string message output.");a=new fa({message:Ut(n),text:n.content})}else a=new vt({text:n});r===void 0?r=a:r=r.concat(a);let s=await this.parsePartialResult([r]);s!=null&&!it(s,t)&&(this.diff?yield this._diff(t,s):yield s,t=s)}}getFormatInstructions(){return""}};var Hb=M({applyPatch:()=>_t,compare:()=>lr});var Ca=class extends Dt{static lc_name(){return"JsonOutputParser"}lc_namespace=["langchain_core","output_parsers"];lc_serializable=!0;_concatOutputChunks(e,t){return this.diff?super._concatOutputChunks(e,t):t}_diff(e,t){if(t)return e?lr(e,t):[{op:"replace",path:"",value:t}]}async parsePartialResult(e){return zt(e[0].text)}async parse(e){return zt(e,JSON.parse)}getFormatInstructions(){return""}_baseMessageToString(e){return e.text}};var Bc=class extends wt{static lc_name(){return"BytesOutputParser"}lc_namespace=["langchain_core","output_parsers","bytes"];lc_serializable=!0;textEncoder=new TextEncoder;parse(e){return Promise.resolve(this.textEncoder.encode(e))}getFormatInstructions(){return""}};var zr=class extends wt{re;async*_transform(e){let t="";for await(let r of e)if(typeof r=="string"?t+=r:t+=r.content,this.re){let n=[...t.matchAll(this.re)];if(n.length>1){let a=0;for(let s of n.slice(0,-1))yield[s[1]],a+=(s.index??0)+s[0].length;t=t.slice(a)}}else{let n=await this.parse(t);if(n.length>1){for(let a of n.slice(0,-1))yield[a];t=n[n.length-1]}}for(let r of await this.parse(t))yield[r]}},Zc=class extends zr{static lc_name(){return"CommaSeparatedListOutputParser"}lc_namespace=["langchain_core","output_parsers","list"];lc_serializable=!0;async parse(e){try{return e.trim().split(",").map(t=>t.trim())}catch{throw new ye(`Could not parse output: ${e}`,e)}}getFormatInstructions(){return"Your response should be a list of comma separated values, eg: `foo, bar, baz`"}},Uc=class extends zr{lc_namespace=["langchain_core","output_parsers","list"];length;separator;constructor({length:e,separator:t}){super(...arguments),this.length=e,this.separator=t||","}async parse(e){try{let t=e.trim().split(this.separator).map(r=>r.trim());if(this.length!==void 0&&t.length!==this.length)throw new ye(`Incorrect number of items. Expected ${this.length}, got ${t.length}.`);return t}catch(t){throw Object.getPrototypeOf(t)===ye.prototype?t:new ye(`Could not parse output: ${e}`)}}getFormatInstructions(){return`Your response should be a list of ${this.length===void 0?"":`${this.length} `}items separated by "${this.separator}" (eg: \`foo${this.separator} bar${this.separator} baz\`)`}},Vc=class extends zr{static lc_name(){return"NumberedListOutputParser"}lc_namespace=["langchain_core","output_parsers","list"];lc_serializable=!0;getFormatInstructions(){return`Your response should be a numbered list with each item on a new line. For example:
39
+
40
+ 1. foo
41
+
42
+ 2. bar
43
+
44
+ 3. baz`}re=/\d+\.\s([^\n]+)/g;async parse(e){return[...e.matchAll(this.re)??[]].map(t=>t[1])}},Wc=class extends zr{static lc_name(){return"NumberedListOutputParser"}lc_namespace=["langchain_core","output_parsers","list"];lc_serializable=!0;getFormatInstructions(){return`Your response should be a numbered list with each item on a new line. For example:
45
+
46
+ 1. foo
47
+
48
+ 2. bar
49
+
50
+ 3. baz`}re=/^\s*[-*]\s([^\n]+)$/gm;async parse(e){return[...e.matchAll(this.re)??[]].map(t=>t[1])}};var Gc=class extends wt{static lc_name(){return"StrOutputParser"}lc_namespace=["langchain_core","output_parsers","string"];lc_serializable=!0;parse(e){return Promise.resolve(e)}getFormatInstructions(){return""}_textContentToString(e){return e.text}_imageUrlContentToString(e){throw new Error('Cannot coerce a multimodal "image_url" message part into a string.')}_messageContentToString(e){switch(e.type){case"text":case"text_delta":if("text"in e)return this._textContentToString(e);break;case"image_url":if("image_url"in e)return this._imageUrlContentToString(e);break;case"reasoning":case"thinking":case"redacted_thinking":return"";default:throw new Error(`Cannot coerce "${e.type}" message part into a string.`)}throw new Error(`Invalid content type: ${e.type}`)}_baseMessageContentToString(e){return e.reduce((t,r)=>t+this._messageContentToString(r),"")}};var Oa=class extends bt{static lc_name(){return"StandardSchemaOutputParser"}lc_namespace=["langchain","output_parsers","standard_schema"];schema;constructor(e){super(),this.schema=e}static fromSerializableSchema(e){return new this(e)}async parse(e){try{let t=zt(e,JSON.parse),r=await this.schema["~standard"].validate(t);if(r.issues)throw new Error(`Validation failed: ${JSON.stringify(r.issues)}`);return r.value}catch(t){throw new ye(`Failed to parse. Text: "${e}". Error: ${t}`,e)}}_baseMessageToString(e){return e.text}getFormatInstructions(){return""}};var Tn=class extends bt{schema;static lc_name(){return"StructuredOutputParser"}lc_namespace=["langchain","output_parsers","structured"];toJSON(){return this.toJSONNotImplemented()}constructor(e){super(e),this.schema=e}static fromZodSchema(e){return new this(e)}static fromNamesAndDescriptions(e){let t=ve.object(Object.fromEntries(Object.entries(e).map(([r,n])=>[r,ve.string().describe(n)])));return new this(t)}getFormatInstructions(){return`You must format your output as a JSON value that adheres to a given "JSON Schema" instance.
51
+
52
+ "JSON Schema" is a declarative language that allows you to annotate and validate JSON documents.
53
+
54
+ For example, the example "JSON Schema" instance {{"properties": {{"foo": {{"description": "a list of test words", "type": "array", "items": {{"type": "string"}}}}}}, "required": ["foo"]}}
55
+ would match an object with one required property, "foo". The "type" property specifies "foo" must be an "array", and the "description" property semantically describes it as "a list of test words". The items within "foo" must be strings.
56
+ Thus, the object {{"foo": ["bar", "baz"]}} is a well-formatted instance of this example "JSON Schema". The object {{"properties": {{"foo": ["bar", "baz"]}}}} is not well-formatted.
57
+
58
+ Your output will be parsed and type-checked according to the provided schema instance, so make sure all fields in your output match the schema exactly and there are no trailing commas!
59
+
60
+ Here is the JSON Schema instance your output must adhere to. Include the enclosing markdown codeblock:
61
+ \`\`\`json
62
+ ${JSON.stringify(ct(this.schema))}
63
+ \`\`\`
64
+ `}async parse(e){try{let t=e.trim(),r=(t.match(/^```(?:json)?\s*([\s\S]*?)```/)?.[1]||t.match(/```json\s*([\s\S]*?)```/)?.[1]||t).replace(/"([^"\\]*(\\.[^"\\]*)*)"/g,(n,a)=>`"${a.replace(/\n/g,"\\n")}"`).replace(/\n/g,"");return await At(this.schema,JSON.parse(r))}catch(t){throw new ye(`Failed to parse. Text: "${e}". Error: ${t}`,e)}}_baseMessageToString(e){return e.text}},Ys=class extends Tn{static lc_name(){return"JsonMarkdownStructuredOutputParser"}getFormatInstructions(e){let t=e?.interpolationDepth??1;if(t<1)throw new Error("f string interpolation depth must be at least 1");return`Return a markdown code snippet with a JSON object formatted to look like:
65
+ \`\`\`json
66
+ ${this._schemaToInstruction(ct(this.schema)).replaceAll("{","{".repeat(t)).replaceAll("}","}".repeat(t))}
67
+ \`\`\``}_schemaToInstruction(e,t=2){let r=e;if("type"in r){let n=!1,a;if(Array.isArray(r.type)){let o=r.type.findIndex(c=>c==="null");o!==-1&&(n=!0,r.type.splice(o,1)),a=r.type.join(" | ")}else a=r.type;if(r.type==="object"&&r.properties){let o=r.description?` // ${r.description}`:"";return`{
68
+ ${Object.entries(r.properties).map(([c,l])=>{let f=r.required?.includes(c)?"":" (optional)";return`${" ".repeat(t)}"${c}": ${this._schemaToInstruction(l,t+2)}${f}`}).join(`
69
+ `)}
70
+ ${" ".repeat(t-2)}}${o}`}if(r.type==="array"&&r.items){let o=r.description?` // ${r.description}`:"";return`array[
71
+ ${" ".repeat(t)}${this._schemaToInstruction(r.items,t+2)}
72
+ ${" ".repeat(t-2)}] ${o}`}let s=n?" (nullable)":"",i=r.description?` // ${r.description}`:"";return`${a}${i}${s}`}if("anyOf"in r)return r.anyOf.map(n=>this._schemaToInstruction(n,t)).join(`
73
+ ${" ".repeat(t-2)}`);throw new Error("unsupported schema type")}static fromZodSchema(e){return new this(e)}static fromNamesAndDescriptions(e){let t=ve.object(Object.fromEntries(Object.entries(e).map(([r,n])=>[r,ve.string().describe(n)])));return new this(t)}},Jc=class extends bt{structuredInputParser;constructor({inputSchema:e}){super(...arguments),this.structuredInputParser=new Ys(e)}async parse(e){let t;try{t=await this.structuredInputParser.parse(e)}catch(r){throw new ye(`Failed to parse. Text: "${e}". Error: ${r}`,e)}return this.outputProcessor(t)}getFormatInstructions(){return this.structuredInputParser.getFormatInstructions()}};var wf=function(){let e={};e.parser=function(d,u){return new r(d,u)},e.SAXParser=r,e.SAXStream=l,e.createStream=c,e.MAX_BUFFER_LENGTH=65536;let t=["comment","sgmlDecl","textNode","tagName","doctype","procInstName","procInstBody","entity","attribName","attribValue","cdata","script"];e.EVENTS=["text","processinginstruction","sgmldeclaration","doctype","comment","opentagstart","attribute","opentag","closetag","opencdata","cdata","closecdata","error","end","ready","script","opennamespace","closenamespace"];function r(d,u){if(!(this instanceof r))return new r(d,u);var w=this;a(w),w.q=w.c="",w.bufferCheckPosition=e.MAX_BUFFER_LENGTH,w.opt=u||{},w.opt.lowercase=w.opt.lowercase||w.opt.lowercasetags,w.looseCase=w.opt.lowercase?"toLowerCase":"toUpperCase",w.tags=[],w.closed=w.closedRoot=w.sawRoot=!1,w.tag=w.error=null,w.strict=!!d,w.noscript=!!(d||w.opt.noscript),w.state=_.BEGIN,w.strictEntities=w.opt.strictEntities,w.ENTITIES=w.strictEntities?Object.create(e.XML_ENTITIES):Object.create(e.ENTITIES),w.attribList=[],w.opt.xmlns&&(w.ns=Object.create(m)),w.trackPosition=w.opt.position!==!1,w.trackPosition&&(w.position=w.line=w.column=0),Xe(w,"onready")}Object.create||(Object.create=function(d){function u(){}return u.prototype=d,new u}),Object.keys||(Object.keys=function(d){var u=[];for(var w in d)d.hasOwnProperty(w)&&u.push(w);return u});function n(d){for(var u=Math.max(e.MAX_BUFFER_LENGTH,10),w=0,g=0,G=t.length;g<G;g++){var X=d[t[g]].length;if(X>u)switch(t[g]){case"textNode":kt(d);break;case"cdata":ee(d,"oncdata",d.cdata),d.cdata="";break;case"script":ee(d,"onscript",d.script),d.script="";break;default:xt(d,"Max buffer length exceeded: "+t[g])}w=Math.max(w,X)}d.bufferCheckPosition=e.MAX_BUFFER_LENGTH-w+d.position}function a(d){for(var u=0,w=t.length;u<w;u++)d[t[u]]=""}function s(d){kt(d),d.cdata!==""&&(ee(d,"oncdata",d.cdata),d.cdata=""),d.script!==""&&(ee(d,"onscript",d.script),d.script="")}r.prototype={end:function(){mr(this)},write:Ve,resume:function(){return this.error=null,this},close:function(){return this.write(null)},flush:function(){s(this)}};var i=ReadableStream;i||(i=function(){});var o=e.EVENTS.filter(function(d){return d!=="error"&&d!=="end"});function c(d,u){return new l(d,u)}function l(d,u){if(!(this instanceof l))return new l(d,u);i.apply(this),this._parser=new r(d,u),this.writable=!0,this.readable=!0;var w=this;this._parser.onend=function(){w.emit("end")},this._parser.onerror=function(g){w.emit("error",g),w._parser.error=null},this._decoder=null,o.forEach(function(g){Object.defineProperty(w,"on"+g,{get:function(){return w._parser["on"+g]},set:function(G){if(!G)return w.removeAllListeners(g),w._parser["on"+g]=G,G;w.on(g,G)},enumerable:!0,configurable:!1})})}l.prototype=Object.create(i.prototype,{constructor:{value:l}}),l.prototype.write=function(d){return this._parser.write(d.toString()),this.emit("data",d),!0},l.prototype.end=function(d){return d&&d.length&&this.write(d),this._parser.end(),!0},l.prototype.on=function(d,u){var w=this;return!w._parser["on"+d]&&o.indexOf(d)!==-1&&(w._parser["on"+d]=function(){var g=arguments.length===1?[arguments[0]]:Array.apply(null,arguments);g.splice(0,0,d),w.emit.apply(w,g)}),i.prototype.on.call(w,d,u)};var f="[CDATA[",p="DOCTYPE",y="http://www.w3.org/XML/1998/namespace",h="http://www.w3.org/2000/xmlns/",m={xml:y,xmlns:h},v=/[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,b=/[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/,k=/[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,I=/[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/;function S(d){return d===" "||d===`
74
+ `||d==="\r"||d===" "}function L(d){return d==='"'||d==="'"}function V(d){return d===">"||S(d)}function ue(d,u){return d.test(u)}function de(d,u){return!ue(d,u)}var _=0;e.STATE={BEGIN:_++,BEGIN_WHITESPACE:_++,TEXT:_++,TEXT_ENTITY:_++,OPEN_WAKA:_++,SGML_DECL:_++,SGML_DECL_QUOTED:_++,DOCTYPE:_++,DOCTYPE_QUOTED:_++,DOCTYPE_DTD:_++,DOCTYPE_DTD_QUOTED:_++,COMMENT_STARTING:_++,COMMENT:_++,COMMENT_ENDING:_++,COMMENT_ENDED:_++,CDATA:_++,CDATA_ENDING:_++,CDATA_ENDING_2:_++,PROC_INST:_++,PROC_INST_BODY:_++,PROC_INST_ENDING:_++,OPEN_TAG:_++,OPEN_TAG_SLASH:_++,ATTRIB:_++,ATTRIB_NAME:_++,ATTRIB_NAME_SAW_WHITE:_++,ATTRIB_VALUE:_++,ATTRIB_VALUE_QUOTED:_++,ATTRIB_VALUE_CLOSED:_++,ATTRIB_VALUE_UNQUOTED:_++,ATTRIB_VALUE_ENTITY_Q:_++,ATTRIB_VALUE_ENTITY_U:_++,CLOSE_TAG:_++,CLOSE_TAG_SAW_WHITE:_++,SCRIPT:_++,SCRIPT_ENDING:_++},e.XML_ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'"},e.ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'",AElig:198,Aacute:193,Acirc:194,Agrave:192,Aring:197,Atilde:195,Auml:196,Ccedil:199,ETH:208,Eacute:201,Ecirc:202,Egrave:200,Euml:203,Iacute:205,Icirc:206,Igrave:204,Iuml:207,Ntilde:209,Oacute:211,Ocirc:212,Ograve:210,Oslash:216,Otilde:213,Ouml:214,THORN:222,Uacute:218,Ucirc:219,Ugrave:217,Uuml:220,Yacute:221,aacute:225,acirc:226,aelig:230,agrave:224,aring:229,atilde:227,auml:228,ccedil:231,eacute:233,ecirc:234,egrave:232,eth:240,euml:235,iacute:237,icirc:238,igrave:236,iuml:239,ntilde:241,oacute:243,ocirc:244,ograve:242,oslash:248,otilde:245,ouml:246,szlig:223,thorn:254,uacute:250,ucirc:251,ugrave:249,uuml:252,yacute:253,yuml:255,copy:169,reg:174,nbsp:160,iexcl:161,cent:162,pound:163,curren:164,yen:165,brvbar:166,sect:167,uml:168,ordf:170,laquo:171,not:172,shy:173,macr:175,deg:176,plusmn:177,sup1:185,sup2:178,sup3:179,acute:180,micro:181,para:182,middot:183,cedil:184,ordm:186,raquo:187,frac14:188,frac12:189,frac34:190,iquest:191,times:215,divide:247,OElig:338,oelig:339,Scaron:352,scaron:353,Yuml:376,fnof:402,circ:710,tilde:732,Alpha:913,Beta:914,Gamma:915,Delta:916,Epsilon:917,Zeta:918,Eta:919,Theta:920,Iota:921,Kappa:922,Lambda:923,Mu:924,Nu:925,Xi:926,Omicron:927,Pi:928,Rho:929,Sigma:931,Tau:932,Upsilon:933,Phi:934,Chi:935,Psi:936,Omega:937,alpha:945,beta:946,gamma:947,delta:948,epsilon:949,zeta:950,eta:951,theta:952,iota:953,kappa:954,lambda:955,mu:956,nu:957,xi:958,omicron:959,pi:960,rho:961,sigmaf:962,sigma:963,tau:964,upsilon:965,phi:966,chi:967,psi:968,omega:969,thetasym:977,upsih:978,piv:982,ensp:8194,emsp:8195,thinsp:8201,zwnj:8204,zwj:8205,lrm:8206,rlm:8207,ndash:8211,mdash:8212,lsquo:8216,rsquo:8217,sbquo:8218,ldquo:8220,rdquo:8221,bdquo:8222,dagger:8224,Dagger:8225,bull:8226,hellip:8230,permil:8240,prime:8242,Prime:8243,lsaquo:8249,rsaquo:8250,oline:8254,frasl:8260,euro:8364,image:8465,weierp:8472,real:8476,trade:8482,alefsym:8501,larr:8592,uarr:8593,rarr:8594,darr:8595,harr:8596,crarr:8629,lArr:8656,uArr:8657,rArr:8658,dArr:8659,hArr:8660,forall:8704,part:8706,exist:8707,empty:8709,nabla:8711,isin:8712,notin:8713,ni:8715,prod:8719,sum:8721,minus:8722,lowast:8727,radic:8730,prop:8733,infin:8734,ang:8736,and:8743,or:8744,cap:8745,cup:8746,int:8747,there4:8756,sim:8764,cong:8773,asymp:8776,ne:8800,equiv:8801,le:8804,ge:8805,sub:8834,sup:8835,nsub:8836,sube:8838,supe:8839,oplus:8853,otimes:8855,perp:8869,sdot:8901,lceil:8968,rceil:8969,lfloor:8970,rfloor:8971,lang:9001,rang:9002,loz:9674,spades:9824,clubs:9827,hearts:9829,diams:9830},Object.keys(e.ENTITIES).forEach(function(d){var u=e.ENTITIES[d],w=typeof u=="number"?String.fromCharCode(u):u;e.ENTITIES[d]=w});for(var Ze in e.STATE)e.STATE[e.STATE[Ze]]=Ze;_=e.STATE;function Xe(d,u,w){d[u]&&d[u](w)}function ee(d,u,w){d.textNode&&kt(d),Xe(d,u,w)}function kt(d){d.textNode=Br(d.opt,d.textNode),d.textNode&&Xe(d,"ontext",d.textNode),d.textNode=""}function Br(d,u){return d.trim&&(u=u.trim()),d.normalize&&(u=u.replace(/\s+/g," ")),u}function xt(d,u){return kt(d),d.trackPosition&&(u+=`
75
+ Line: `+d.line+`
76
+ Column: `+d.column+`
77
+ Char: `+d.c),u=new Error(u),d.error=u,Xe(d,"onerror",u),d}function mr(d){return d.sawRoot&&!d.closedRoot&&K(d,"Unclosed root tag"),d.state!==_.BEGIN&&d.state!==_.BEGIN_WHITESPACE&&d.state!==_.TEXT&&xt(d,"Unexpected end"),kt(d),d.c="",d.closed=!0,Xe(d,"onend"),r.call(d,d.strict,d.opt),d}function K(d,u){if(typeof d!="object"||!(d instanceof r))throw new Error("bad call to strictFail");d.strict&&xt(d,u)}function Zr(d){d.strict||(d.tagName=d.tagName[d.looseCase]());var u=d.tags[d.tags.length-1]||d,w=d.tag={name:d.tagName,attributes:{}};d.opt.xmlns&&(w.ns=u.ns),d.attribList.length=0,ee(d,"onopentagstart",w)}function Lt(d,u){var w=d.indexOf(":")<0?["",d]:d.split(":"),g=w[0],G=w[1];return u&&d==="xmlns"&&(g="xmlns",G=""),{prefix:g,local:G}}function jt(d){if(d.strict||(d.attribName=d.attribName[d.looseCase]()),d.attribList.indexOf(d.attribName)!==-1||d.tag.attributes.hasOwnProperty(d.attribName)){d.attribName=d.attribValue="";return}if(d.opt.xmlns){var u=Lt(d.attribName,!0),w=u.prefix,g=u.local;if(w==="xmlns")if(g==="xml"&&d.attribValue!==y)K(d,"xml: prefix must be bound to "+y+`
78
+ Actual: `+d.attribValue);else if(g==="xmlns"&&d.attribValue!==h)K(d,"xmlns: prefix must be bound to "+h+`
79
+ Actual: `+d.attribValue);else{var G=d.tag,X=d.tags[d.tags.length-1]||d;G.ns===X.ns&&(G.ns=Object.create(X.ns)),G.ns[g]=d.attribValue}d.attribList.push([d.attribName,d.attribValue])}else d.tag.attributes[d.attribName]=d.attribValue,ee(d,"onattribute",{name:d.attribName,value:d.attribValue});d.attribName=d.attribValue=""}function Ue(d,u){if(d.opt.xmlns){var w=d.tag,g=Lt(d.tagName);w.prefix=g.prefix,w.local=g.local,w.uri=w.ns[g.prefix]||"",w.prefix&&!w.uri&&(K(d,"Unbound namespace prefix: "+JSON.stringify(d.tagName)),w.uri=g.prefix);var G=d.tags[d.tags.length-1]||d;w.ns&&G.ns!==w.ns&&Object.keys(w.ns).forEach(function(Ft){ee(d,"onopennamespace",{prefix:Ft,uri:w.ns[Ft]})});for(var X=0,le=d.attribList.length;X<le;X++){var se=d.attribList[X],me=se[0],Me=se[1],ie=Lt(me,!0),Qe=ie.prefix,hr=ie.local,An=Qe===""?"":w.ns[Qe]||"",C={name:me,value:Me,prefix:Qe,local:hr,uri:An};Qe&&Qe!=="xmlns"&&!An&&(K(d,"Unbound namespace prefix: "+JSON.stringify(Qe)),C.uri=Qe),d.tag.attributes[me]=C,ee(d,"onattribute",C)}d.attribList.length=0}d.tag.isSelfClosing=!!u,d.sawRoot=!0,d.tags.push(d.tag),ee(d,"onopentag",d.tag),u||(!d.noscript&&d.tagName.toLowerCase()==="script"?d.state=_.SCRIPT:d.state=_.TEXT,d.tag=null,d.tagName=""),d.attribName=d.attribValue="",d.attribList.length=0}function ft(d){if(!d.tagName){K(d,"Weird empty close tag."),d.textNode+="</>",d.state=_.TEXT;return}if(d.script){if(d.tagName!=="script"){d.script+="</"+d.tagName+">",d.tagName="",d.state=_.SCRIPT;return}ee(d,"onscript",d.script),d.script=""}var u=d.tags.length,w=d.tagName;d.strict||(w=w[d.looseCase]());for(var g=w;u--&&d.tags[u].name!==g;)K(d,"Unexpected close tag");if(u<0){K(d,"Unmatched closing tag: "+d.tagName),d.textNode+="</"+d.tagName+">",d.state=_.TEXT;return}d.tagName=w;for(var G=d.tags.length;G-- >u;){var X=d.tag=d.tags.pop();d.tagName=d.tag.name,ee(d,"onclosetag",d.tagName);var le={};for(var se in X.ns)le[se]=X.ns[se];var me=d.tags[d.tags.length-1]||d;d.opt.xmlns&&X.ns!==me.ns&&Object.keys(X.ns).forEach(function(Me){var ie=X.ns[Me];ee(d,"onclosenamespace",{prefix:Me,uri:ie})})}u===0&&(d.closedRoot=!0),d.tagName=d.attribValue=d.attribName="",d.attribList.length=0,d.state=_.TEXT}function Ur(d){var u=d.entity,w=u.toLowerCase(),g,G="";return d.ENTITIES[u]?d.ENTITIES[u]:d.ENTITIES[w]?d.ENTITIES[w]:(u=w,u.charAt(0)==="#"&&(u.charAt(1)==="x"?(u=u.slice(2),g=parseInt(u,16),G=g.toString(16)):(u=u.slice(1),g=parseInt(u,10),G=g.toString(10))),u=u.replace(/^0+/,""),isNaN(g)||G.toLowerCase()!==u?(K(d,"Invalid character entity"),"&"+d.entity+";"):String.fromCodePoint(g))}function Vr(d,u){u==="<"?(d.state=_.OPEN_WAKA,d.startTagPosition=d.position):S(u)||(K(d,"Non-whitespace before first tag."),d.textNode=u,d.state=_.TEXT)}function Wr(d,u){var w="";return u<d.length&&(w=d.charAt(u)),w}function Ve(d){var u=this;if(this.error)throw this.error;if(u.closed)return xt(u,"Cannot write after close. Assign an onready handler.");if(d===null)return mr(u);typeof d=="object"&&(d=d.toString());for(var w=0,g="";g=Wr(d,w++),u.c=g,!!g;)switch(u.trackPosition&&(u.position++,g===`
80
+ `?(u.line++,u.column=0):u.column++),u.state){case _.BEGIN:if(u.state=_.BEGIN_WHITESPACE,g==="\uFEFF")continue;Vr(u,g);continue;case _.BEGIN_WHITESPACE:Vr(u,g);continue;case _.TEXT:if(u.sawRoot&&!u.closedRoot){for(var G=w-1;g&&g!=="<"&&g!=="&";)g=Wr(d,w++),g&&u.trackPosition&&(u.position++,g===`
81
+ `?(u.line++,u.column=0):u.column++);u.textNode+=d.substring(G,w-1)}g==="<"&&!(u.sawRoot&&u.closedRoot&&!u.strict)?(u.state=_.OPEN_WAKA,u.startTagPosition=u.position):(!S(g)&&(!u.sawRoot||u.closedRoot)&&K(u,"Text data outside of root node."),g==="&"?u.state=_.TEXT_ENTITY:u.textNode+=g);continue;case _.SCRIPT:g==="<"?u.state=_.SCRIPT_ENDING:u.script+=g;continue;case _.SCRIPT_ENDING:g==="/"?u.state=_.CLOSE_TAG:(u.script+="<"+g,u.state=_.SCRIPT);continue;case _.OPEN_WAKA:if(g==="!")u.state=_.SGML_DECL,u.sgmlDecl="";else if(!S(g))if(ue(v,g))u.state=_.OPEN_TAG,u.tagName=g;else if(g==="/")u.state=_.CLOSE_TAG,u.tagName="";else if(g==="?")u.state=_.PROC_INST,u.procInstName=u.procInstBody="";else{if(K(u,"Unencoded <"),u.startTagPosition+1<u.position){var X=u.position-u.startTagPosition;g=new Array(X).join(" ")+g}u.textNode+="<"+g,u.state=_.TEXT}continue;case _.SGML_DECL:(u.sgmlDecl+g).toUpperCase()===f?(ee(u,"onopencdata"),u.state=_.CDATA,u.sgmlDecl="",u.cdata=""):u.sgmlDecl+g==="--"?(u.state=_.COMMENT,u.comment="",u.sgmlDecl=""):(u.sgmlDecl+g).toUpperCase()===p?(u.state=_.DOCTYPE,(u.doctype||u.sawRoot)&&K(u,"Inappropriately located doctype declaration"),u.doctype="",u.sgmlDecl=""):g===">"?(ee(u,"onsgmldeclaration",u.sgmlDecl),u.sgmlDecl="",u.state=_.TEXT):(L(g)&&(u.state=_.SGML_DECL_QUOTED),u.sgmlDecl+=g);continue;case _.SGML_DECL_QUOTED:g===u.q&&(u.state=_.SGML_DECL,u.q=""),u.sgmlDecl+=g;continue;case _.DOCTYPE:g===">"?(u.state=_.TEXT,ee(u,"ondoctype",u.doctype),u.doctype=!0):(u.doctype+=g,g==="["?u.state=_.DOCTYPE_DTD:L(g)&&(u.state=_.DOCTYPE_QUOTED,u.q=g));continue;case _.DOCTYPE_QUOTED:u.doctype+=g,g===u.q&&(u.q="",u.state=_.DOCTYPE);continue;case _.DOCTYPE_DTD:u.doctype+=g,g==="]"?u.state=_.DOCTYPE:L(g)&&(u.state=_.DOCTYPE_DTD_QUOTED,u.q=g);continue;case _.DOCTYPE_DTD_QUOTED:u.doctype+=g,g===u.q&&(u.state=_.DOCTYPE_DTD,u.q="");continue;case _.COMMENT:g==="-"?u.state=_.COMMENT_ENDING:u.comment+=g;continue;case _.COMMENT_ENDING:g==="-"?(u.state=_.COMMENT_ENDED,u.comment=Br(u.opt,u.comment),u.comment&&ee(u,"oncomment",u.comment),u.comment=""):(u.comment+="-"+g,u.state=_.COMMENT);continue;case _.COMMENT_ENDED:g!==">"?(K(u,"Malformed comment"),u.comment+="--"+g,u.state=_.COMMENT):u.state=_.TEXT;continue;case _.CDATA:g==="]"?u.state=_.CDATA_ENDING:u.cdata+=g;continue;case _.CDATA_ENDING:g==="]"?u.state=_.CDATA_ENDING_2:(u.cdata+="]"+g,u.state=_.CDATA);continue;case _.CDATA_ENDING_2:g===">"?(u.cdata&&ee(u,"oncdata",u.cdata),ee(u,"onclosecdata"),u.cdata="",u.state=_.TEXT):g==="]"?u.cdata+="]":(u.cdata+="]]"+g,u.state=_.CDATA);continue;case _.PROC_INST:g==="?"?u.state=_.PROC_INST_ENDING:S(g)?u.state=_.PROC_INST_BODY:u.procInstName+=g;continue;case _.PROC_INST_BODY:if(!u.procInstBody&&S(g))continue;g==="?"?u.state=_.PROC_INST_ENDING:u.procInstBody+=g;continue;case _.PROC_INST_ENDING:g===">"?(ee(u,"onprocessinginstruction",{name:u.procInstName,body:u.procInstBody}),u.procInstName=u.procInstBody="",u.state=_.TEXT):(u.procInstBody+="?"+g,u.state=_.PROC_INST_BODY);continue;case _.OPEN_TAG:ue(b,g)?u.tagName+=g:(Zr(u),g===">"?Ue(u):g==="/"?u.state=_.OPEN_TAG_SLASH:(S(g)||K(u,"Invalid character in tag name"),u.state=_.ATTRIB));continue;case _.OPEN_TAG_SLASH:g===">"?(Ue(u,!0),ft(u)):(K(u,"Forward-slash in opening tag not followed by >"),u.state=_.ATTRIB);continue;case _.ATTRIB:if(S(g))continue;g===">"?Ue(u):g==="/"?u.state=_.OPEN_TAG_SLASH:ue(v,g)?(u.attribName=g,u.attribValue="",u.state=_.ATTRIB_NAME):K(u,"Invalid attribute name");continue;case _.ATTRIB_NAME:g==="="?u.state=_.ATTRIB_VALUE:g===">"?(K(u,"Attribute without value"),u.attribValue=u.attribName,jt(u),Ue(u)):S(g)?u.state=_.ATTRIB_NAME_SAW_WHITE:ue(b,g)?u.attribName+=g:K(u,"Invalid attribute name");continue;case _.ATTRIB_NAME_SAW_WHITE:if(g==="=")u.state=_.ATTRIB_VALUE;else{if(S(g))continue;K(u,"Attribute without value"),u.tag.attributes[u.attribName]="",u.attribValue="",ee(u,"onattribute",{name:u.attribName,value:""}),u.attribName="",g===">"?Ue(u):ue(v,g)?(u.attribName=g,u.state=_.ATTRIB_NAME):(K(u,"Invalid attribute name"),u.state=_.ATTRIB)}continue;case _.ATTRIB_VALUE:if(S(g))continue;L(g)?(u.q=g,u.state=_.ATTRIB_VALUE_QUOTED):(K(u,"Unquoted attribute value"),u.state=_.ATTRIB_VALUE_UNQUOTED,u.attribValue=g);continue;case _.ATTRIB_VALUE_QUOTED:if(g!==u.q){g==="&"?u.state=_.ATTRIB_VALUE_ENTITY_Q:u.attribValue+=g;continue}jt(u),u.q="",u.state=_.ATTRIB_VALUE_CLOSED;continue;case _.ATTRIB_VALUE_CLOSED:S(g)?u.state=_.ATTRIB:g===">"?Ue(u):g==="/"?u.state=_.OPEN_TAG_SLASH:ue(v,g)?(K(u,"No whitespace between attributes"),u.attribName=g,u.attribValue="",u.state=_.ATTRIB_NAME):K(u,"Invalid attribute name");continue;case _.ATTRIB_VALUE_UNQUOTED:if(!V(g)){g==="&"?u.state=_.ATTRIB_VALUE_ENTITY_U:u.attribValue+=g;continue}jt(u),g===">"?Ue(u):u.state=_.ATTRIB;continue;case _.CLOSE_TAG:if(u.tagName)g===">"?ft(u):ue(b,g)?u.tagName+=g:u.script?(u.script+="</"+u.tagName,u.tagName="",u.state=_.SCRIPT):(S(g)||K(u,"Invalid tagname in closing tag"),u.state=_.CLOSE_TAG_SAW_WHITE);else{if(S(g))continue;de(v,g)?u.script?(u.script+="</"+g,u.state=_.SCRIPT):K(u,"Invalid tagname in closing tag."):u.tagName=g}continue;case _.CLOSE_TAG_SAW_WHITE:if(S(g))continue;g===">"?ft(u):K(u,"Invalid characters in closing tag");continue;case _.TEXT_ENTITY:case _.ATTRIB_VALUE_ENTITY_Q:case _.ATTRIB_VALUE_ENTITY_U:var le,se;switch(u.state){case _.TEXT_ENTITY:le=_.TEXT,se="textNode";break;case _.ATTRIB_VALUE_ENTITY_Q:le=_.ATTRIB_VALUE_QUOTED,se="attribValue";break;case _.ATTRIB_VALUE_ENTITY_U:le=_.ATTRIB_VALUE_UNQUOTED,se="attribValue";break}if(g===";")if(u.opt.unparsedEntities){var me=Ur(u);u.entity="",u.state=le,u.write(me)}else u[se]+=Ur(u),u.entity="",u.state=le;else ue(u.entity.length?I:k,g)?u.entity+=g:(K(u,"Invalid character in entity name"),u[se]+="&"+u.entity+g,u.entity="",u.state=le);continue;default:throw new Error(u,"Unknown state: "+u.state)}return u.position>=u.bufferCheckPosition&&n(u),u}return String.fromCodePoint||(function(){var d=String.fromCharCode,u=Math.floor,w=function(){var g=16384,G=[],X,le,se=-1,me=arguments.length;if(!me)return"";for(var Me="";++se<me;){var ie=Number(arguments[se]);if(!isFinite(ie)||ie<0||ie>1114111||u(ie)!==ie)throw RangeError("Invalid code point: "+ie);ie<=65535?G.push(ie):(ie-=65536,X=(ie>>10)+55296,le=ie%1024+56320,G.push(X,le)),(se+1===me||G.length>g)&&(Me+=d.apply(null,G),G.length=0)}return Me};Object.defineProperty?Object.defineProperty(String,"fromCodePoint",{value:w,configurable:!0,writable:!0}):String.fromCodePoint=w})(),e},qc=wf();var Ia=`The output should be formatted as a XML file.
82
+ 1. Output should conform to the tags below.
83
+ 2. If tags are not given, make them on your own.
84
+ 3. Remember to always open and close all the tags.
85
+
86
+ As an example, for the tags ["foo", "bar", "baz"]:
87
+ 1. String "<foo>
88
+ <bar>
89
+ <baz></baz>
90
+ </bar>
91
+ </foo>" is a well-formatted instance of the schema.
92
+ 2. String "<foo>
93
+ <bar>
94
+ </foo>" is a badly-formatted instance.
95
+ 3. String "<foo>
96
+ <tag>
97
+ </tag>
98
+ </foo>" is a badly-formatted instance.
99
+
100
+ Here are the output tags:
101
+ \`\`\`
102
+ {tags}
103
+ \`\`\``,Hc=class extends Dt{tags;constructor(e){super(e),this.tags=e?.tags}static lc_name(){return"XMLOutputParser"}lc_namespace=["langchain_core","output_parsers"];lc_serializable=!0;_diff(e,t){if(t)return e?lr(e,t):[{op:"replace",path:"",value:t}]}async parsePartialResult(e){return Na(e[0].text)}async parse(e){return Na(e)}getFormatInstructions(){return this.tags&&this.tags.length>0?Ia.replace("{tags}",this.tags?.join(", ")??""):Ia}},kf=e=>e.split(`
104
+ `).map(t=>t.replace(/^\s+/,"")).join(`
105
+ `).trim(),Kc=e=>{if(Object.keys(e).length===0)return{};let t={};return e.children.length>0?(t[e.name]=e.children.map(Kc),t):(t[e.name]=e.text??void 0,t)};function Na(e){let t=kf(e),r=qc.parser(!0),n={},a=[];r.onopentag=o=>{let c={name:o.name,attributes:o.attributes,children:[],text:"",isSelfClosing:o.isSelfClosing};a.length>0?a[a.length-1].children.push(c):n=c,o.isSelfClosing||a.push(c)},r.onclosetag=()=>{if(a.length>0){let o=a.pop();a.length===0&&o&&(n=o)}},r.ontext=o=>{if(a.length>0){let c=a[a.length-1];c.text+=o}},r.onattribute=o=>{if(a.length>0){let c=a[a.length-1];c.attributes[o.name]=o.value}};let s=/```(xml)?(.*)```/s.exec(t),i=s?s[2]:t;return r.write(i).close(),n&&n.name==="?xml"&&(n=n.children[0]),Kc(n)}var qw=M({AsymmetricStructuredOutputParser:()=>Jc,BaseCumulativeTransformOutputParser:()=>Dt,BaseLLMOutputParser:()=>Ks,BaseOutputParser:()=>bt,BaseTransformOutputParser:()=>wt,BytesOutputParser:()=>Bc,CommaSeparatedListOutputParser:()=>Zc,CustomListOutputParser:()=>Uc,JsonMarkdownStructuredOutputParser:()=>Ys,JsonOutputParser:()=>Ca,ListOutputParser:()=>zr,MarkdownListOutputParser:()=>Wc,NumberedListOutputParser:()=>Vc,OutputParserException:()=>ye,StandardSchemaOutputParser:()=>Oa,StringOutputParser:()=>Gc,StructuredOutputParser:()=>Tn,XMLOutputParser:()=>Hc,XML_FORMAT_INSTRUCTIONS:()=>Ia,parseJsonMarkdown:()=>zt,parsePartialJson:()=>Jr,parseXMLMarkdown:()=>Na});function Xs(e,t){if(e.function===void 0)return;let r;if(t?.partial)try{r=Jr(e.function.arguments??"{}")}catch{return}else try{r=JSON.parse(e.function.arguments)}catch(a){throw new ye([`Function "${e.function.name}" arguments:`,"",e.function.arguments,"","are not valid JSON.",`Error: ${a.message}`].join(`
106
+ `))}let n={name:e.function.name,args:r,type:"tool_call"};return t?.returnId&&(n.id=e.id),n}function Yc(e){if(e.id===void 0)throw new Error('All OpenAI tool calls must have an "id" field.');return{id:e.id,type:"function",function:{name:e.name,arguments:JSON.stringify(e.args)}}}function Xc(e,t){return{name:e.function?.name,args:e.function?.arguments,id:e.id,error:t,type:"invalid_tool_call"}}var Qs=class extends Dt{static lc_name(){return"JsonOutputToolsParser"}returnId=!1;lc_namespace=["langchain","output_parsers","openai_tools"];lc_serializable=!0;constructor(e){super(e),this.returnId=e?.returnId??this.returnId}_diff(){throw new Error("Not supported.")}async parse(){throw new Error("Not implemented.")}async parseResult(e){return await this.parsePartialResult(e,!1)}async parsePartialResult(e,t=!0){let r=e[0].message,n;if(br(r)&&r.tool_calls?.length?n=r.tool_calls.map(s=>{let{id:i,...o}=s;return this.returnId?{id:i,...o}:o}):r.additional_kwargs.tool_calls!==void 0&&(n=JSON.parse(JSON.stringify(r.additional_kwargs.tool_calls)).map(s=>Xs(s,{returnId:this.returnId,partial:t}))),!n)return[];let a=[];for(let s of n)if(s!==void 0){let i={type:s.name,args:s.args,id:s.id};a.push(i)}return a}},Pa=class extends Qs{static lc_name(){return"JsonOutputKeyToolsParser"}lc_namespace=["langchain","output_parsers","openai_tools"];lc_serializable=!0;returnId=!1;keyName;returnSingle=!1;zodSchema;serializableSchema;constructor(e){super(e),this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,"zodSchema"in e&&(this.zodSchema=e.zodSchema),"serializableSchema"in e&&(this.serializableSchema=e.serializableSchema)}async _validateResult(e){if(this.serializableSchema!==void 0){let r=await this.serializableSchema["~standard"].validate(e);if(r.issues)throw new ye(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(r.issues)}`,JSON.stringify(e,null,2));return r.value}if(this.zodSchema===void 0)return e;let t=await Bn(this.zodSchema,e);if(t.success)return t.data;throw new ye(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(t.error?.issues)}`,JSON.stringify(e,null,2))}async parsePartialResult(e){let t=(await super.parsePartialResult(e)).filter(n=>n.type===this.keyName),r=t;if(t.length)return this.returnId||(r=t.map(n=>n.args)),this.returnSingle?r[0]:r}async parseResult(e){let t=(await super.parsePartialResult(e,!1)).filter(n=>n.type===this.keyName),r=t;if(t.length)return this.returnId||(r=t.map(n=>n.args)),this.returnSingle?this._validateResult(r[0]):await Promise.all(r.map(n=>this._validateResult(n)))}};var yk=M({assembleStructuredOutputPipeline:()=>ei,createContentParser:()=>xf,createFunctionCallingParser:()=>Tf});function xf(e){return Se(e)?Tn.fromZodSchema(e):cr(e)?Oa.fromSerializableSchema(e):new Ca}function Tf(e,t,r){let n=r??Pa;return Se(e)?new n({returnSingle:!0,keyName:t,zodSchema:e}):cr(e)?new n({returnSingle:!0,keyName:t,serializableSchema:e}):new n({returnSingle:!0,keyName:t})}function ei(e,t,r,n){if(!r){let c=e.pipe(t);return n?c.withConfig({runName:n}):c}let a=pr.assign({parsed:(c,l)=>t.invoke(c.raw,l)}),s=pr.assign({parsed:()=>null}),i=a.withFallbacks({fallbacks:[s]}),o=jr.from([{raw:e},i]);return n?o.withConfig({runName:n}):o}var Qc=e=>e();function Sn(e){let t=e.constructor;return new t({...e,content:e.contentBlocks,response_metadata:{...e.response_metadata,output_version:"v1"}})}var Bk=M({BaseChatModel:()=>eu,SimpleChatModel:()=>Sf});function ti(e){let t=[];for(let r of e){let n=r;if(Array.isArray(r.content))for(let a=0;a<r.content.length;a++){let s=r.content[a];(On(s)||In(s))&&n===r&&(n=new r.constructor({...n,content:[...r.content.slice(0,a),Nn(s),...r.content.slice(a+1)]}))}t.push(n)}return t}var eu=class dt extends _n{lc_namespace=["langchain","chat_models",this._llmType()];disableStreaming=!1;outputVersion;get callKeys(){return[...super.callKeys,"outputVersion"]}constructor(t){super(t),this.outputVersion=Qc(()=>{let r=t.outputVersion??wr("LC_OUTPUT_VERSION");return r&&["v0","v1"].includes(r)?r:"v0"})}_separateRunnableConfigFromCallOptionsCompat(t){let[r,n]=super._separateRunnableConfigFromCallOptions(t);return n.signal=r.signal,[r,n]}async invoke(t,r){let n=dt._convertInputToPromptValue(t);return(await this.generatePrompt([n],r,r?.callbacks)).generations[0][0].message}async*_streamResponseChunks(t,r,n){throw new Error("Not implemented.")}async*_streamChatModelEvents(t,r,n){yield*Hs(this._streamResponseChunks(t,r,n),{signal:r.signal})}streamEvents(t,r,n){if(r?.version==="v1"||r?.version==="v2")return super.streamEvents(t,r,n);let a=dt._convertInputToPromptValue(t).toChatMessages(),[,s]=this._separateRunnableConfigFromCallOptionsCompat(r);return new Ea(this._streamChatModelEvents(a,s))}streamV2(t,r){return this.streamEvents(t,r)}async*_streamIterator(t,r){if(this._streamResponseChunks===dt.prototype._streamResponseChunks||this.disableStreaming)yield this.invoke(t,r);else{let n=dt._convertInputToPromptValue(t).toChatMessages(),[a,s]=this._separateRunnableConfigFromCallOptionsCompat(r),i={...a.metadata,...this.getLsParamsWithDefaults(s)},o=this._getInvocationParamsForTracing(s),c=await tt.configure(a.callbacks,this.callbacks,a.tags,this.tags,i,this.metadata,{verbose:this.verbose,tracerInheritableMetadata:this._filterInvocationParamsForTracing(o)}),l={options:this._getCallOptionsForTracing(s,o),invocation_params:o,batch_size:1},f=s.outputVersion??this.outputVersion,p=await c?.handleChatModelStart(this.toJSON(),[ti(n)],a.runId,void 0,l,void 0,void 0,a.runName),y,h;try{for await(let m of this._streamResponseChunks(n,s,p?.[0])){if(s.signal?.throwIfAborted(),m.message.id==null){let v=p?.at(0)?.runId;v!=null&&m.message._updateId(`run-${v}`)}m.message.response_metadata={...m.generationInfo,...m.message.response_metadata},f==="v1"?yield Sn(m.message):yield m.message,y?y=y.concat(m):y=m,qr(m.message)&&m.message.usage_metadata!==void 0&&(h={tokenUsage:{promptTokens:m.message.usage_metadata.input_tokens,completionTokens:m.message.usage_metadata.output_tokens,totalTokens:m.message.usage_metadata.total_tokens}})}s.signal?.throwIfAborted()}catch(m){throw await Promise.all((p??[]).map(v=>v?.handleLLMError(m))),m}await Promise.all((p??[]).map(m=>m?.handleLLMEnd({generations:[[y]],llmOutput:h})))}}getLsParams(t){let r=this.getName().startsWith("Chat")?this.getName().replace("Chat",""):this.getName();return{ls_model_type:"chat",ls_stop:t.stop,ls_provider:r}}getLsParamsWithDefaults(t){return{...this.getLsParams(t),ls_integration:"langchain_chat_model"}}async _generateUncached(t,r,n,a){let s=t.map(h=>h.map(St)),i;if(a!==void 0&&a.length===s.length)i=a;else{let h={...n.metadata,...this.getLsParamsWithDefaults(r)},m=this._getInvocationParamsForTracing(r),v=await tt.configure(n.callbacks,this.callbacks,n.tags,this.tags,h,this.metadata,{verbose:this.verbose,tracerInheritableMetadata:this._filterInvocationParamsForTracing(m)}),b={options:this._getCallOptionsForTracing(r,m),invocation_params:m,batch_size:1};i=await v?.handleChatModelStart(this.toJSON(),s.map(ti),n.runId,void 0,b,void 0,void 0,n.runName)}let o=r.outputVersion??this.outputVersion,c=[],l=[],f=!!i?.[0].handlers.find(Vi),p=!!i?.[0].handlers.find($n);if(f&&!this.disableStreaming&&s.length===1&&(this._streamChatModelEvents!==dt.prototype._streamChatModelEvents||this._streamResponseChunks!==dt.prototype._streamResponseChunks))try{let h=!1,m=i?.[0],v=this._streamChatModelEvents(s[0],r),b=await new Ea({async*[Symbol.asyncIterator](){for await(let S of v){r.signal?.throwIfAborted(),h=!0;let L=S.event==="message-start"&&S.id==null&&m?.runId!=null?{...S,id:`run-${m.runId}`}:S;await m?.handleChatModelStreamEvent(L),yield L}}});if(r.signal?.throwIfAborted(),!h)throw new Error("Received empty response from chat model call.");if(b.id==null){let S=i?.at(0)?.runId;S!=null&&b._updateId(`run-${S}`)}let k={text:b.text,message:b};c.push([k]);let I=b.usage_metadata!==void 0?{tokenUsage:{promptTokens:b.usage_metadata.input_tokens,completionTokens:b.usage_metadata.output_tokens,totalTokens:b.usage_metadata.total_tokens}}:void 0;await i?.[0].handleLLMEnd({generations:c,llmOutput:I})}catch(h){throw await i?.[0].handleLLMError(h),h}else if(p&&!this.disableStreaming&&s.length===1&&this._streamResponseChunks!==dt.prototype._streamResponseChunks)try{let h=await this._streamResponseChunks(s[0],r,i?.[0]),m,v;for await(let b of h){if(r.signal?.aborted){let k=m?.message;throw new Ra("Model invocation was aborted.",k)}if(b.message.id==null){let k=i?.at(0)?.runId;k!=null&&b.message._updateId(`run-${k}`)}m===void 0?m=b:m=Ne(m,b),qr(b.message)&&b.message.usage_metadata!==void 0&&(v={tokenUsage:{promptTokens:b.message.usage_metadata.input_tokens,completionTokens:b.message.usage_metadata.output_tokens,totalTokens:b.message.usage_metadata.total_tokens}})}if(r.signal?.aborted){let b=m?.message;throw new Ra("Model invocation was aborted.",b)}if(m===void 0)throw new Error("Received empty response from chat model call.");o==="v1"&&(m.message=Sn(m.message)),c.push([m]),await i?.[0].handleLLMEnd({generations:c,llmOutput:v})}catch(h){throw await i?.[0].handleLLMError(h),h}else{let h=await Promise.allSettled(s.map(async(m,v)=>{let b=await this._generate(m,{...r,promptIndex:v},i?.[v]);if(o==="v1")for(let k of b.generations)k.message=Sn(k.message);return b}));await Promise.all(h.map(async(m,v)=>{if(m.status==="fulfilled"){let b=m.value;for(let k of b.generations){if(k.message.id==null){let I=i?.at(0)?.runId;I!=null&&k.message._updateId(`run-${I}`)}k.message.response_metadata={...k.generationInfo,...k.message.response_metadata}}return b.generations.length===1&&(b.generations[0].message.response_metadata={...b.llmOutput,...b.generations[0].message.response_metadata}),c[v]=b.generations,l[v]=b.llmOutput,i?.[v]?.handleLLMEnd({generations:[b.generations],llmOutput:b.llmOutput})}else return await i?.[v]?.handleLLMError(m.reason),Promise.reject(m.reason)}))}let y={generations:c,llmOutput:l.length?this._combineLLMOutput?.(...l):void 0};return Object.defineProperty(y,dr,{value:i?{runIds:i?.map(h=>h.runId)}:void 0,configurable:!0}),y}async _generateCached({messages:t,cache:r,llmStringKey:n,parsedOptions:a,handledOptions:s}){let i=t.map(k=>k.map(St)),o={...s.metadata,...this.getLsParamsWithDefaults(a)},c=this._getInvocationParamsForTracing(a),l=await tt.configure(s.callbacks,this.callbacks,s.tags,this.tags,o,this.metadata,{verbose:this.verbose,tracerInheritableMetadata:this._filterInvocationParamsForTracing(c)}),f={options:this._getCallOptionsForTracing(a,c),invocation_params:c,batch_size:1},p=await l?.handleChatModelStart(this.toJSON(),i.map(ti),s.runId,void 0,f,void 0,void 0,s.runName),y=[],h=(await Promise.allSettled(i.map(async(k,I)=>{let S=dt._convertInputToPromptValue(k).toString(),L=await r.lookup(S,n);return L==null&&y.push(I),L}))).map((k,I)=>({result:k,runManager:p?.[I]})).filter(({result:k})=>k.status==="fulfilled"&&k.value!=null||k.status==="rejected"),m=a.outputVersion??this.outputVersion,v=[];await Promise.all(h.map(async({result:k,runManager:I},S)=>{if(k.status==="fulfilled"){let L=k.value;return v[S]=L.map(V=>("message"in V&&We(V.message)&&br(V.message)&&(V.message.usage_metadata={input_tokens:0,output_tokens:0,total_tokens:0},m==="v1"&&(V.message=Sn(V.message))),V.generationInfo={...V.generationInfo,tokenUsage:{}},V)),L.length&&await I?.handleLLMNewToken(L[0].text),I?.handleLLMEnd({generations:[L]},void 0,void 0,void 0,{cached:!0})}else return await I?.handleLLMError(k.reason,void 0,void 0,void 0,{cached:!0}),Promise.reject(k.reason)}));let b={generations:v,missingPromptIndices:y,startedRunManagers:p};return Object.defineProperty(b,dr,{value:p?{runIds:p?.map(k=>k.runId)}:void 0,configurable:!0}),b}async generate(t,r,n){let a;Array.isArray(r)?a={stop:r}:a=r;let s=t.map(m=>m.map(St)),[i,o]=this._separateRunnableConfigFromCallOptionsCompat(a);if(i.callbacks=i.callbacks??n,!this.cache)return this._generateUncached(s,o,i);let{cache:c}=this,l=this._getSerializedCacheKeyParametersForCall(o),{generations:f,missingPromptIndices:p,startedRunManagers:y}=await this._generateCached({messages:s,cache:c,llmStringKey:l,parsedOptions:o,handledOptions:i}),h={};if(p.length>0){let m=await this._generateUncached(p.map(v=>s[v]),o,i,y!==void 0?p.map(v=>y?.[v]):void 0);await Promise.all(m.generations.map(async(v,b)=>{let k=p[b];f[k]=v;let I=dt._convertInputToPromptValue(s[k]).toString();return c.update(I,l,v)})),h=m.llmOutput??{}}return{generations:f,llmOutput:h}}_getInvocationParamsForTracing(t){return this.invocationParams(t)}_getCallOptionsForTracing(t,r){return t}invocationParams(t){return{}}_modelType(){return"base_chat_model"}async generatePrompt(t,r,n){let a=t.map(s=>s.toChatMessages());return this.generate(a,r,n)}withStructuredOutput(t,r){if(typeof this.bindTools!="function")throw new Error('Chat model must implement ".bindTools()" to use withStructuredOutput.');if(r?.strict)throw new Error('"strict" mode is not supported for this model by default.');let n=t,a=r?.name,s=Tr(n)??"A function available to call.",i=r?.method,o=r?.includeRaw;if(i==="jsonMode")throw new Error('Base withStructuredOutput implementation only supports "functionCalling" as a method.');let c=a??"extract";!Se(n)&&!cr(n)&&"name"in n&&(c=n.name);let l=Se(n)||cr(n)?ct(n):n,f=[{type:"function",function:{name:c,description:s,parameters:l}}];return ei(this.bindTools(f),ze.from(p=>{if(!_e.isInstance(p))throw new Error("Input is not an AIMessageChunk.");if(!p.tool_calls||p.tool_calls.length===0)throw new Error("No tool calls found in the response.");let y=p.tool_calls.find(h=>h.name===c);if(!y)throw new Error(`No tool call found with name ${c}.`);return y.args}),o,o?"StructuredOutputRunnable":"StructuredOutput")}},Sf=class extends eu{async _generate(e,t,r){let n=new Ge(await this._call(e,t,r));if(typeof n.content!="string")throw new Error("Cannot generate with a simple chat model when output is not a string.");return{generations:[{text:n.content,message:n}]}}};var Kk=M({BaseLLM:()=>tu,LLM:()=>Ef}),tu=class En extends _n{lc_namespace=["langchain","llms",this._llmType()];async invoke(t,r){let n=En._convertInputToPromptValue(t);return(await this.generatePrompt([n],r,r?.callbacks)).generations[0][0].text}async*_streamResponseChunks(t,r,n){throw new Error("Not implemented.")}_separateRunnableConfigFromCallOptionsCompat(t){let[r,n]=super._separateRunnableConfigFromCallOptions(t);return n.signal=r.signal,[r,n]}async*_streamIterator(t,r){if(this._streamResponseChunks===En.prototype._streamResponseChunks)yield this.invoke(t,r);else{let n=En._convertInputToPromptValue(t),[a,s]=this._separateRunnableConfigFromCallOptionsCompat(r),i=this.invocationParams(s),o=await tt.configure(a.callbacks,this.callbacks,a.tags,this.tags,a.metadata,this.metadata,{verbose:this.verbose,tracerInheritableMetadata:this._filterInvocationParamsForTracing(i)}),c={options:s,invocation_params:i,batch_size:1},l=await o?.handleLLMStart(this.toJSON(),[n.toString()],a.runId,void 0,c,void 0,void 0,a.runName),f=new vt({text:""});try{for await(let p of this._streamResponseChunks(n.toString(),s,l?.[0]))f?f=f.concat(p):f=p,typeof p.text=="string"&&(yield p.text)}catch(p){throw await Promise.all((l??[]).map(y=>y?.handleLLMError(p))),p}await Promise.all((l??[]).map(p=>p?.handleLLMEnd({generations:[[f]]})))}}async generatePrompt(t,r,n){let a=t.map(s=>s.toString());return this.generate(a,r,n)}invocationParams(t){return{}}_flattenLLMResult(t){let r=[];for(let n=0;n<t.generations.length;n+=1){let a=t.generations[n];if(n===0)r.push({generations:[a],llmOutput:t.llmOutput});else{let s=t.llmOutput?{...t.llmOutput,tokenUsage:{}}:void 0;r.push({generations:[a],llmOutput:s})}}return r}async _generateUncached(t,r,n,a){let s;if(a!==void 0&&a.length===t.length)s=a;else{let l=this.invocationParams(r),f=await tt.configure(n.callbacks,this.callbacks,n.tags,this.tags,n.metadata,this.metadata,{verbose:this.verbose,tracerInheritableMetadata:this._filterInvocationParamsForTracing(l)}),p={options:r,invocation_params:l,batch_size:t.length};s=await f?.handleLLMStart(this.toJSON(),t,n.runId,void 0,p,void 0,void 0,n?.runName)}let i=!!s?.[0].handlers.find($n),o;if(i&&t.length===1&&this._streamResponseChunks!==En.prototype._streamResponseChunks)try{let l=await this._streamResponseChunks(t[0],r,s?.[0]),f;for await(let p of l)f===void 0?f=p:f=Ne(f,p);if(f===void 0)throw new Error("Received empty response from chat model call.");o={generations:[[f]],llmOutput:{}},await s?.[0].handleLLMEnd(o)}catch(l){throw await s?.[0].handleLLMError(l),l}else{try{o=await this._generate(t,r,s?.[0])}catch(f){throw await Promise.all((s??[]).map(p=>p?.handleLLMError(f))),f}let l=this._flattenLLMResult(o);await Promise.all((s??[]).map((f,p)=>f?.handleLLMEnd(l[p])))}let c=s?.map(l=>l.runId)||void 0;return Object.defineProperty(o,dr,{value:c?{runIds:c}:void 0,configurable:!0}),o}async _generateCached({prompts:t,cache:r,llmStringKey:n,parsedOptions:a,handledOptions:s,runId:i}){let o=this.invocationParams(a),c=await tt.configure(s.callbacks,this.callbacks,s.tags,this.tags,s.metadata,this.metadata,{verbose:this.verbose,tracerInheritableMetadata:this._filterInvocationParamsForTracing(o)}),l={options:a,invocation_params:o,batch_size:t.length},f=await c?.handleLLMStart(this.toJSON(),t,i,void 0,l,void 0,void 0,s?.runName),p=[],y=(await Promise.allSettled(t.map(async(v,b)=>{let k=await r.lookup(v,n);return k==null&&p.push(b),k}))).map((v,b)=>({result:v,runManager:f?.[b]})).filter(({result:v})=>v.status==="fulfilled"&&v.value!=null||v.status==="rejected"),h=[];await Promise.all(y.map(async({result:v,runManager:b},k)=>{if(v.status==="fulfilled"){let I=v.value;return h[k]=I.map(S=>(S.generationInfo={...S.generationInfo,tokenUsage:{}},S)),I.length&&await b?.handleLLMNewToken(I[0].text),b?.handleLLMEnd({generations:[I]},void 0,void 0,void 0,{cached:!0})}else return await b?.handleLLMError(v.reason,void 0,void 0,void 0,{cached:!0}),Promise.reject(v.reason)}));let m={generations:h,missingPromptIndices:p,startedRunManagers:f};return Object.defineProperty(m,dr,{value:f?{runIds:f?.map(v=>v.runId)}:void 0,configurable:!0}),m}async generate(t,r,n){if(!Array.isArray(t))throw new Error("Argument 'prompts' is expected to be a string[]");let a;Array.isArray(r)?a={stop:r}:a=r;let[s,i]=this._separateRunnableConfigFromCallOptionsCompat(a);if(s.callbacks=s.callbacks??n,!this.cache)return this._generateUncached(t,i,s);let{cache:o}=this,c=this._getSerializedCacheKeyParametersForCall(i),{generations:l,missingPromptIndices:f,startedRunManagers:p}=await this._generateCached({prompts:t,cache:o,llmStringKey:c,parsedOptions:i,handledOptions:s,runId:s.runId}),y={};if(f.length>0){let h=await this._generateUncached(f.map(m=>t[m]),i,s,p!==void 0?f.map(m=>p?.[m]):void 0);await Promise.all(h.generations.map(async(m,v)=>{let b=f[v];return l[b]=m,o.update(t[b],c,m)})),y=h.llmOutput??{}}return{generations:l,llmOutput:y}}_identifyingParams(){return{}}_modelType(){return"base_llm"}},Ef=class extends tu{async _generate(e,t,r){return{generations:await Promise.all(e.map((n,a)=>this._call(n,{...t,promptIndex:a},r).then(s=>[{text:s}])))}}};var tx=M({JsonOutputKeyToolsParser:()=>Pa,JsonOutputToolsParser:()=>Qs,convertLangChainToolCallToOpenAI:()=>Yc,makeInvalidToolCall:()=>Xc,parseToolCall:()=>Xs});var ix=M({convertToOpenAIFunction:()=>ru,convertToOpenAITool:()=>Af,isLangChainTool:()=>kn,isRunnableToolLike:()=>bn,isStructuredTool:()=>vn,isStructuredToolParams:()=>wn});function ru(e,t){let r=typeof t=="number"?void 0:t;return{name:e.name,description:e.description,parameters:ct(e.schema),...r?.strict!==void 0?{strict:r.strict}:{}}}function Af(e,t){let r=typeof t=="number"?void 0:t,n;return kn(e)?n={type:"function",function:ru(e)}:n=e,r?.strict!==void 0&&(n.function.strict=r.strict),n}var lx=M({DEFAULT_LANGSMITH_GATEWAY:()=>nu,resolveLangSmithGatewayConfig:()=>Mf}),Cf="LANGSMITH_GATEWAY",Of="LANGSMITH_GATEWAY_API_KEY",If="LANGSMITH_API_KEY",nu="https://gateway.smith.langchain.com",Nf=["true","1","yes"],Pf=["false","0","no"];function Rf(e){let t=wr(Cf);if(!(!t||Pf.includes(t.toLowerCase())))return`${Nf.includes(t.toLowerCase())?nu:t.replace(/\/+$/,"")}/${e}`}function Mf({baseURL:e,providerPath:t}){if(e!==void 0)return{baseURL:e};let r=Rf(t);return r===void 0?{}:{baseURL:r,apiKey:wr(Of)||wr(If)}}export{Oe as a,te as b,oe as c,Se as d,Bn as e,Xi as f,Tr as g,eo as h,Fn as i,to as j,ro as k,no as l,ao as m,T as n,ve as o,eg as p,cr as q,Xn as r,Mg as s,ct as t,ra as u,Ug as v,Hg as w,iy as x,my as y,we as z,Pt as A,lr as B,$y as C,zy as D,fa as E,i_ as F,ma as G,Q as H,Mt as I,jr as J,ze as K,Re as L,Z_ as M,Bs as N,Zs as O,Id as P,rv as Q,dv as R,Gd as S,_n as T,kn as U,Dv as V,Gs as W,Kd as X,b0 as Y,M0 as Z,of as _,pr as $,pb as aa,Hb as ba,Ks as ca,bt as da,Dt as ea,Ca as fa,qw as ga,yb as ha,Xs as ia,Yc as ja,Xc as ka,yk as la,xf as ma,Tf as na,ei as oa,T0 as pa,Ea as qa,wb as ra,Aa as sa,Bk as ta,eu as ua,Sb as va,mf as wa,Kk as xa,Ef as ya,tx as za,Cb as Aa,bf as Ba,ix as Ca,Af as Da,lx as Ea,nu as Fa,Mf as Ga};