@opentiny/next-sdk 0.1.13 → 0.1.14-alpha.0

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 (62) hide show
  1. package/agent/AgentModelProvider.ts +49 -20
  2. package/agent/type.ts +4 -4
  3. package/dist/McpSdk.d.ts +14 -0
  4. package/dist/WebAgent.d.ts +5 -0
  5. package/dist/WebMcp.d.ts +20 -0
  6. package/dist/WebMcpClient.d.ts +250 -1488
  7. package/dist/WebMcpServer.d.ts +190 -78
  8. package/dist/Zod.d.ts +1 -0
  9. package/dist/agent/AgentModelProvider.d.ts +6 -4
  10. package/dist/agent/type.d.ts +6 -2
  11. package/dist/agent/utils/getAISDKTools.d.ts +1 -0
  12. package/dist/index.d.ts +2 -1
  13. package/dist/index.es.dev.js +23743 -25868
  14. package/dist/index.es.js +24524 -24312
  15. package/dist/index.js +1789 -25
  16. package/dist/index.umd.dev.js +23845 -25970
  17. package/dist/index.umd.js +185 -129
  18. package/dist/{mcpsdk@1.20.1.dev.js → mcpsdk@1.23.0.dev.js} +13535 -14184
  19. package/dist/{mcpsdk@1.20.1.es.dev.js → mcpsdk@1.23.0.es.dev.js} +13563 -14212
  20. package/dist/mcpsdk@1.23.0.es.js +15584 -0
  21. package/dist/mcpsdk@1.23.0.js +43 -0
  22. package/dist/remoter/createRemoter.d.ts +9 -0
  23. package/dist/remoter/tooltips.d.ts +36 -0
  24. package/dist/script/utils.d.ts +1 -0
  25. package/dist/transport/ExtensionClientTransport.d.ts +3 -2
  26. package/dist/transport/ExtensionContentServerTransport.d.ts +3 -2
  27. package/dist/transport/ExtensionPageServerTransport.d.ts +3 -2
  28. package/dist/vite-build-tsc.d.ts +2 -0
  29. package/dist/vite.config.d.ts +2 -0
  30. package/dist/vite.config.mcpSdk.d.ts +2 -0
  31. package/dist/vite.config.webAgent.d.ts +2 -0
  32. package/dist/vite.config.webMcp.d.ts +2 -0
  33. package/dist/vite.config.webMcpFull.d.ts +2 -0
  34. package/dist/vite.config.zod.d.ts +2 -0
  35. package/dist/webagent.dev.js +18803 -18836
  36. package/dist/webagent.es.dev.js +17726 -17759
  37. package/dist/webagent.es.js +22571 -20829
  38. package/dist/webagent.js +172 -109
  39. package/dist/webmcp-full.dev.js +14463 -15009
  40. package/dist/webmcp-full.es.dev.js +14471 -15017
  41. package/dist/webmcp-full.es.js +13391 -12365
  42. package/dist/webmcp-full.js +43 -16
  43. package/package.json +3 -2
  44. package/remoter/createRemoter.ts +126 -71
  45. package/remoter/tooltips.ts +260 -0
  46. package/tsconfig.json +5 -3
  47. package/vite-build-tsc.ts +60 -0
  48. package/vite-env.d.ts +5 -0
  49. package/dist/WebMcpClient.js +0 -363
  50. package/dist/WebMcpServer.js +0 -283
  51. package/dist/agent/AgentModelProvider.js +0 -293
  52. package/dist/agent/type.js +0 -1
  53. package/dist/agent/utils/getAISDKTools.js +0 -36
  54. package/dist/mcpsdk@1.20.1.es.js +0 -14600
  55. package/dist/mcpsdk@1.20.1.js +0 -16
  56. package/dist/remoter/QrCode.js +0 -55
  57. package/dist/remoter/createRemoter.js +0 -743
  58. package/dist/transport/ExtensionClientTransport.js +0 -81
  59. package/dist/transport/ExtensionContentServerTransport.js +0 -128
  60. package/dist/transport/ExtensionPageServerTransport.js +0 -118
  61. package/dist/transport/messages.js +0 -51
  62. package/dist/utils/uuid.js +0 -10
package/dist/webagent.js CHANGED
@@ -1,122 +1,160 @@
1
- (function(Ir,xn){typeof exports=="object"&&typeof module<"u"?xn(exports):typeof define=="function"&&define.amd?define(["exports"],xn):(Ir=typeof globalThis<"u"?globalThis:Ir||self,xn(Ir.WebAgent={}))})(this,function(Ir){"use strict";var xn="vercel.ai.error",Lm=Symbol.for(xn),Kl,Um=class Dm extends Error{constructor({name:e,message:r,cause:a}){super(r),this[Kl]=!0,this.name=e,this.cause=a}static isInstance(e){return Dm.hasMarker(e,xn)}static hasMarker(e,r){const a=Symbol.for(r);return e!=null&&typeof e=="object"&&a in e&&typeof e[a]=="boolean"&&e[a]===!0}};Kl=Lm;var ve=Um,Ql="AI_APICallError",Yl=`vercel.ai.error.${Ql}`,Fm=Symbol.for(Yl),Xl,ft=class extends ve{constructor({message:t,url:e,requestBodyValues:r,statusCode:a,responseHeaders:n,responseBody:s,cause:o,isRetryable:i=a!=null&&(a===408||a===409||a===429||a>=500),data:l}){super({name:Ql,message:t,cause:o}),this[Xl]=!0,this.url=e,this.requestBodyValues=r,this.statusCode=a,this.responseHeaders=n,this.responseBody=s,this.isRetryable=i,this.data=l}static isInstance(t){return ve.hasMarker(t,Yl)}};Xl=Fm;var eu="AI_EmptyResponseBodyError",tu=`vercel.ai.error.${eu}`,qm=Symbol.for(tu),ru,Zm=class extends ve{constructor({message:t="Empty response body"}={}){super({name:eu,message:t}),this[ru]=!0}static isInstance(t){return ve.hasMarker(t,tu)}};ru=qm;function En(t){return t==null?"unknown error":typeof t=="string"?t:t instanceof Error?t.message:JSON.stringify(t)}var nu="AI_InvalidArgumentError",au=`vercel.ai.error.${nu}`,Vm=Symbol.for(au),su,ou=class extends ve{constructor({message:e,cause:r,argument:a}){super({name:nu,message:e,cause:r}),this[su]=!0,this.argument=a}static isInstance(e){return ve.hasMarker(e,au)}};su=Vm;var iu="AI_InvalidPromptError",lu=`vercel.ai.error.${iu}`,Bm=Symbol.for(lu),uu,Kr=class extends ve{constructor({prompt:t,message:e,cause:r}){super({name:iu,message:`Invalid prompt: ${e}`,cause:r}),this[uu]=!0,this.prompt=t}static isInstance(t){return ve.hasMarker(t,lu)}};uu=Bm;var cu="AI_InvalidResponseDataError",du=`vercel.ai.error.${cu}`,Hm=Symbol.for(du),pu,Wn=class extends ve{constructor({data:t,message:e=`Invalid response data: ${JSON.stringify(t)}.`}){super({name:cu,message:e}),this[pu]=!0,this.data=t}static isInstance(t){return ve.hasMarker(t,du)}};pu=Hm;var hu="AI_JSONParseError",fu=`vercel.ai.error.${hu}`,Jm=Symbol.for(fu),mu,qa=class extends ve{constructor({text:t,cause:e}){super({name:hu,message:`JSON parsing failed: Text: ${t}.
2
- Error message: ${En(e)}`,cause:e}),this[mu]=!0,this.text=t}static isInstance(t){return ve.hasMarker(t,fu)}};mu=Jm;var vu="AI_LoadAPIKeyError",gu=`vercel.ai.error.${vu}`,Wm=Symbol.for(gu),yu,Za=class extends ve{constructor({message:t}){super({name:vu,message:t}),this[yu]=!0}static isInstance(t){return ve.hasMarker(t,gu)}};yu=Wm;var _u="AI_NoSuchModelError",wu=`vercel.ai.error.${_u}`,Gm=Symbol.for(wu),bu,bo=class extends ve{constructor({errorName:t=_u,modelId:e,modelType:r,message:a=`No such ${r}: ${e}`}){super({name:t,message:a}),this[bu]=!0,this.modelId=e,this.modelType=r}static isInstance(t){return ve.hasMarker(t,wu)}};bu=Gm;var xu="AI_TooManyEmbeddingValuesForCallError",Eu=`vercel.ai.error.${xu}`,Km=Symbol.for(Eu),Su,Qm=class extends ve{constructor(t){super({name:xu,message:`Too many values for a single embedding call. The ${t.provider} model "${t.modelId}" can only embed up to ${t.maxEmbeddingsPerCall} values per call, but ${t.values.length} values were provided.`}),this[Su]=!0,this.provider=t.provider,this.modelId=t.modelId,this.maxEmbeddingsPerCall=t.maxEmbeddingsPerCall,this.values=t.values}static isInstance(t){return ve.hasMarker(t,Eu)}};Su=Km;var Iu="AI_TypeValidationError",ku=`vercel.ai.error.${Iu}`,Ym=Symbol.for(ku),Tu,Xm=class Gl extends ve{constructor({value:e,cause:r}){super({name:Iu,message:`Type validation failed: Value: ${JSON.stringify(e)}.
3
- Error message: ${En(r)}`,cause:r}),this[Tu]=!0,this.value=e}static isInstance(e){return ve.hasMarker(e,ku)}static wrap({value:e,cause:r}){return Gl.isInstance(r)&&r.value===e?r:new Gl({value:e,cause:r})}};Tu=Ym;var Gn=Xm,Pu="AI_UnsupportedFunctionalityError",Cu=`vercel.ai.error.${Pu}`,ev=Symbol.for(Cu),Ru,Yt=class extends ve{constructor({functionality:t,message:e=`'${t}' functionality not supported.`}){super({name:Pu,message:e}),this[Ru]=!0,this.functionality=t}static isInstance(t){return ve.hasMarker(t,Cu)}};Ru=ev;class Ou extends Error{constructor(e,r){super(e),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}}function xo(t){}function $u(t){if(typeof t=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:e=xo,onError:r=xo,onRetry:a=xo,onComment:n}=t;let s="",o=!0,i,l="",u="";function d(g){const f=o?g.replace(/^\xEF\xBB\xBF/,""):g,[p,b]=tv(`${s}${f}`);for(const y of p)v(y);s=b,o=!1}function v(g){if(g===""){c();return}if(g.startsWith(":")){n&&n(g.slice(g.startsWith(": ")?2:1));return}const f=g.indexOf(":");if(f!==-1){const p=g.slice(0,f),b=g[f+1]===" "?2:1,y=g.slice(f+b);m(p,y,g);return}m(g,"",g)}function m(g,f,p){switch(g){case"event":u=f;break;case"data":l=`${l}${f}
4
- `;break;case"id":i=f.includes("\0")?void 0:f;break;case"retry":/^\d+$/.test(f)?a(parseInt(f,10)):r(new Ou(`Invalid \`retry\` value: "${f}"`,{type:"invalid-retry",value:f,line:p}));break;default:r(new Ou(`Unknown field "${g.length>20?`${g.slice(0,20)}…`:g}"`,{type:"unknown-field",field:g,value:f,line:p}));break}}function c(){l.length>0&&e({id:i,event:u||void 0,data:l.endsWith(`
5
- `)?l.slice(0,-1):l}),i=void 0,l="",u=""}function h(g={}){s&&g.consume&&v(s),o=!0,i=void 0,l="",u="",s=""}return{feed:d,reset:h}}function tv(t){const e=[];let r="",a=0;for(;a<t.length;){const n=t.indexOf("\r",a),s=t.indexOf(`
6
- `,a);let o=-1;if(n!==-1&&s!==-1?o=Math.min(n,s):n!==-1?n===t.length-1?o=-1:o=n:s!==-1&&(o=s),o===-1){r=t.slice(a);break}else{const i=t.slice(a,o);e.push(i),a=o+1,t[a-1]==="\r"&&t[a]===`
7
- `&&a++}}return[e,r]}class Au extends TransformStream{constructor({onError:e,onRetry:r,onComment:a}={}){let n;super({start(s){n=$u({onEvent:o=>{s.enqueue(o)},onError(o){e==="terminate"?s.error(o):typeof e=="function"&&e(o)},onRetry:r,onComment:a})},transform(s){n.feed(s)}})}}function z(t,e,r){function a(i,l){var u;Object.defineProperty(i,"_zod",{value:i._zod??{},enumerable:!1}),(u=i._zod).traits??(u.traits=new Set),i._zod.traits.add(t),e(i,l);for(const d in o.prototype)d in i||Object.defineProperty(i,d,{value:o.prototype[d].bind(i)});i._zod.constr=o,i._zod.def=l}const n=(r==null?void 0:r.Parent)??Object;class s extends n{}Object.defineProperty(s,"name",{value:t});function o(i){var l;const u=r!=null&&r.Parent?new s:this;a(u,i),(l=u._zod).deferred??(l.deferred=[]);for(const d of u._zod.deferred)d();return u}return Object.defineProperty(o,"init",{value:a}),Object.defineProperty(o,Symbol.hasInstance,{value:i=>{var l,u;return r!=null&&r.Parent&&i instanceof r.Parent?!0:(u=(l=i==null?void 0:i._zod)==null?void 0:l.traits)==null?void 0:u.has(t)}}),Object.defineProperty(o,"name",{value:t}),o}class Kn extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const Nu={};function Nr(t){return Nu}function Mu(t){const e=Object.values(t).filter(a=>typeof a=="number");return Object.entries(t).filter(([a,n])=>e.indexOf(+a)===-1).map(([a,n])=>n)}function rv(t,e){return typeof e=="bigint"?e.toString():e}function Eo(t){return{get value(){{const e=t();return Object.defineProperty(this,"value",{value:e}),e}}}}function So(t){return t==null}function Io(t){const e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function nv(t,e){const r=(t.toString().split(".")[1]||"").length,a=(e.toString().split(".")[1]||"").length,n=r>a?r:a,s=Number.parseInt(t.toFixed(n).replace(".","")),o=Number.parseInt(e.toFixed(n).replace(".",""));return s%o/10**n}function je(t,e,r){Object.defineProperty(t,e,{get(){{const a=r();return t[e]=a,a}},set(a){Object.defineProperty(t,e,{value:a})},configurable:!0})}function Va(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Qn(t){return JSON.stringify(t)}const Du=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};function Ba(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}const av=Eo(()=>{var t;if(typeof navigator<"u"&&((t=navigator==null?void 0:navigator.userAgent)!=null&&t.includes("Cloudflare")))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function Ha(t){if(Ba(t)===!1)return!1;const e=t.constructor;if(e===void 0)return!0;const r=e.prototype;return!(Ba(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}const sv=new Set(["string","number","symbol"]);function Yn(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Qr(t,e,r){const a=new t._zod.constr(e??t._zod.def);return(!e||r!=null&&r.parent)&&(a._zod.parent=t),a}function ne(t){const e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if((e==null?void 0:e.message)!==void 0){if((e==null?void 0:e.error)!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function ov(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}const iv={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function lv(t,e){const r={},a=t._zod.def;for(const n in e){if(!(n in a.shape))throw new Error(`Unrecognized key: "${n}"`);e[n]&&(r[n]=a.shape[n])}return Qr(t,{...t._zod.def,shape:r,checks:[]})}function uv(t,e){const r={...t._zod.def.shape},a=t._zod.def;for(const n in e){if(!(n in a.shape))throw new Error(`Unrecognized key: "${n}"`);e[n]&&delete r[n]}return Qr(t,{...t._zod.def,shape:r,checks:[]})}function cv(t,e){if(!Ha(e))throw new Error("Invalid input to extend: expected a plain object");const r={...t._zod.def,get shape(){const a={...t._zod.def.shape,...e};return Va(this,"shape",a),a},checks:[]};return Qr(t,r)}function dv(t,e){return Qr(t,{...t._zod.def,get shape(){const r={...t._zod.def.shape,...e._zod.def.shape};return Va(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function pv(t,e,r){const a=e._zod.def.shape,n={...a};if(r)for(const s in r){if(!(s in a))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(n[s]=t?new t({type:"optional",innerType:a[s]}):a[s])}else for(const s in a)n[s]=t?new t({type:"optional",innerType:a[s]}):a[s];return Qr(e,{...e._zod.def,shape:n,checks:[]})}function hv(t,e,r){const a=e._zod.def.shape,n={...a};if(r)for(const s in r){if(!(s in n))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(n[s]=new t({type:"nonoptional",innerType:a[s]}))}else for(const s in a)n[s]=new t({type:"nonoptional",innerType:a[s]});return Qr(e,{...e._zod.def,shape:n,checks:[]})}function Xn(t,e=0){var r;for(let a=e;a<t.issues.length;a++)if(((r=t.issues[a])==null?void 0:r.continue)!==!0)return!0;return!1}function Yr(t,e){return e.map(r=>{var a;return(a=r).path??(a.path=[]),r.path.unshift(t),r})}function Ja(t){return typeof t=="string"?t:t==null?void 0:t.message}function Mr(t,e,r){var n,s,o,i,l,u;const a={...t,path:t.path??[]};if(!t.message){const d=Ja((o=(s=(n=t.inst)==null?void 0:n._zod.def)==null?void 0:s.error)==null?void 0:o.call(s,t))??Ja((i=e==null?void 0:e.error)==null?void 0:i.call(e,t))??Ja((l=r.customError)==null?void 0:l.call(r,t))??Ja((u=r.localeError)==null?void 0:u.call(r,t))??"Invalid input";a.message=d}return delete a.inst,delete a.continue,e!=null&&e.reportInput||delete a.input,a}function ko(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function ea(...t){const[e,r,a]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:a}:{...e}}const ju=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),Object.defineProperty(t,"message",{get(){return JSON.stringify(e,rv,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},zu=z("$ZodError",ju),Lu=z("$ZodError",ju,{Parent:Error});function fv(t,e=r=>r.message){const r={},a=[];for(const n of t.issues)n.path.length>0?(r[n.path[0]]=r[n.path[0]]||[],r[n.path[0]].push(e(n))):a.push(e(n));return{formErrors:a,fieldErrors:r}}function mv(t,e){const r=e||function(s){return s.message},a={_errors:[]},n=s=>{for(const o of s.issues)if(o.code==="invalid_union"&&o.errors.length)o.errors.map(i=>n({issues:i}));else if(o.code==="invalid_key")n({issues:o.issues});else if(o.code==="invalid_element")n({issues:o.issues});else if(o.path.length===0)a._errors.push(r(o));else{let i=a,l=0;for(;l<o.path.length;){const u=o.path[l];l===o.path.length-1?(i[u]=i[u]||{_errors:[]},i[u]._errors.push(r(o))):i[u]=i[u]||{_errors:[]},i=i[u],l++}}};return n(t),a}const vv=t=>(e,r,a,n)=>{const s=a?Object.assign(a,{async:!1}):{async:!1},o=e._zod.run({value:r,issues:[]},s);if(o instanceof Promise)throw new Kn;if(o.issues.length){const i=new((n==null?void 0:n.Err)??t)(o.issues.map(l=>Mr(l,s,Nr())));throw Du(i,n==null?void 0:n.callee),i}return o.value},gv=t=>async(e,r,a,n)=>{const s=a?Object.assign(a,{async:!0}):{async:!0};let o=e._zod.run({value:r,issues:[]},s);if(o instanceof Promise&&(o=await o),o.issues.length){const i=new((n==null?void 0:n.Err)??t)(o.issues.map(l=>Mr(l,s,Nr())));throw Du(i,n==null?void 0:n.callee),i}return o.value},Uu=t=>(e,r,a)=>{const n=a?{...a,async:!1}:{async:!1},s=e._zod.run({value:r,issues:[]},n);if(s instanceof Promise)throw new Kn;return s.issues.length?{success:!1,error:new(t??zu)(s.issues.map(o=>Mr(o,n,Nr())))}:{success:!0,data:s.value}},yv=Uu(Lu),Fu=t=>async(e,r,a)=>{const n=a?Object.assign(a,{async:!0}):{async:!0};let s=e._zod.run({value:r,issues:[]},n);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(o=>Mr(o,n,Nr())))}:{success:!0,data:s.value}},_v=Fu(Lu),wv=/^[cC][^\s-]{8,}$/,bv=/^[0-9a-z]+$/,xv=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Ev=/^[0-9a-vA-V]{20}$/,Sv=/^[A-Za-z0-9]{27}$/,Iv=/^[a-zA-Z0-9_-]{21}$/,kv=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Tv=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,qu=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,Pv=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Cv="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Rv(){return new RegExp(Cv,"u")}const Ov=/^(?:(?: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])$/,$v=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,Av=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Nv=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Mv=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Zu=/^[A-Za-z0-9_-]*$/,Dv=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,jv=/^\+(?:[0-9]){6,14}[0-9]$/,Vu="(?:(?:\\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])))",zv=new RegExp(`^${Vu}$`);function Bu(t){const e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Lv(t){return new RegExp(`^${Bu(t)}$`)}function Uv(t){const e=Bu({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-]\\d{2}:\\d{2})");const a=`${e}(?:${r.join("|")})`;return new RegExp(`^${Vu}T(?:${a})$`)}const Fv=t=>{const e=t?`[\\s\\S]{${(t==null?void 0:t.minimum)??0},${(t==null?void 0:t.maximum)??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},qv=/^\d+$/,Zv=/^-?\d+(?:\.\d+)?/i,Vv=/true|false/i,Bv=/null/i,Hv=/^[^A-Z]*$/,Jv=/^[^a-z]*$/,Ct=z("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),Hu={number:"number",bigint:"bigint",object:"date"},Ju=z("$ZodCheckLessThan",(t,e)=>{Ct.init(t,e);const r=Hu[typeof e.value];t._zod.onattach.push(a=>{const n=a._zod.bag,s=(e.inclusive?n.maximum:n.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<s&&(e.inclusive?n.maximum=e.value:n.exclusiveMaximum=e.value)}),t._zod.check=a=>{(e.inclusive?a.value<=e.value:a.value<e.value)||a.issues.push({origin:r,code:"too_big",maximum:e.value,input:a.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Wu=z("$ZodCheckGreaterThan",(t,e)=>{Ct.init(t,e);const r=Hu[typeof e.value];t._zod.onattach.push(a=>{const n=a._zod.bag,s=(e.inclusive?n.minimum:n.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>s&&(e.inclusive?n.minimum=e.value:n.exclusiveMinimum=e.value)}),t._zod.check=a=>{(e.inclusive?a.value>=e.value:a.value>e.value)||a.issues.push({origin:r,code:"too_small",minimum:e.value,input:a.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Wv=z("$ZodCheckMultipleOf",(t,e)=>{Ct.init(t,e),t._zod.onattach.push(r=>{var a;(a=r._zod.bag).multipleOf??(a.multipleOf=e.value)}),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%e.value===BigInt(0):nv(r.value,e.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}}),Gv=z("$ZodCheckNumberFormat",(t,e)=>{var o;Ct.init(t,e),e.format=e.format||"float64";const r=(o=e.format)==null?void 0:o.includes("int"),a=r?"int":"number",[n,s]=iv[e.format];t._zod.onattach.push(i=>{const l=i._zod.bag;l.format=e.format,l.minimum=n,l.maximum=s,r&&(l.pattern=qv)}),t._zod.check=i=>{const l=i.value;if(r){if(!Number.isInteger(l)){i.issues.push({expected:a,format:e.format,code:"invalid_type",input:l,inst:t});return}if(!Number.isSafeInteger(l)){l>0?i.issues.push({input:l,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:a,continue:!e.abort}):i.issues.push({input:l,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:a,continue:!e.abort});return}}l<n&&i.issues.push({origin:"number",input:l,code:"too_small",minimum:n,inclusive:!0,inst:t,continue:!e.abort}),l>s&&i.issues.push({origin:"number",input:l,code:"too_big",maximum:s,inst:t})}}),Kv=z("$ZodCheckMaxLength",(t,e)=>{var r;Ct.init(t,e),(r=t._zod.def).when??(r.when=a=>{const n=a.value;return!So(n)&&n.length!==void 0}),t._zod.onattach.push(a=>{const n=a._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<n&&(a._zod.bag.maximum=e.maximum)}),t._zod.check=a=>{const n=a.value;if(n.length<=e.maximum)return;const o=ko(n);a.issues.push({origin:o,code:"too_big",maximum:e.maximum,inclusive:!0,input:n,inst:t,continue:!e.abort})}}),Qv=z("$ZodCheckMinLength",(t,e)=>{var r;Ct.init(t,e),(r=t._zod.def).when??(r.when=a=>{const n=a.value;return!So(n)&&n.length!==void 0}),t._zod.onattach.push(a=>{const n=a._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>n&&(a._zod.bag.minimum=e.minimum)}),t._zod.check=a=>{const n=a.value;if(n.length>=e.minimum)return;const o=ko(n);a.issues.push({origin:o,code:"too_small",minimum:e.minimum,inclusive:!0,input:n,inst:t,continue:!e.abort})}}),Yv=z("$ZodCheckLengthEquals",(t,e)=>{var r;Ct.init(t,e),(r=t._zod.def).when??(r.when=a=>{const n=a.value;return!So(n)&&n.length!==void 0}),t._zod.onattach.push(a=>{const n=a._zod.bag;n.minimum=e.length,n.maximum=e.length,n.length=e.length}),t._zod.check=a=>{const n=a.value,s=n.length;if(s===e.length)return;const o=ko(n),i=s>e.length;a.issues.push({origin:o,...i?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:a.value,inst:t,continue:!e.abort})}}),Wa=z("$ZodCheckStringFormat",(t,e)=>{var r,a;Ct.init(t,e),t._zod.onattach.push(n=>{const s=n._zod.bag;s.format=e.format,e.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=n=>{e.pattern.lastIndex=0,!e.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:e.format,input:n.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(a=t._zod).check??(a.check=()=>{})}),Xv=z("$ZodCheckRegex",(t,e)=>{Wa.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),eg=z("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Hv),Wa.init(t,e)}),tg=z("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Jv),Wa.init(t,e)}),rg=z("$ZodCheckIncludes",(t,e)=>{Ct.init(t,e);const r=Yn(e.includes),a=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=a,t._zod.onattach.push(n=>{const s=n._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(a)}),t._zod.check=n=>{n.value.includes(e.includes,e.position)||n.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:n.value,inst:t,continue:!e.abort})}}),ng=z("$ZodCheckStartsWith",(t,e)=>{Ct.init(t,e);const r=new RegExp(`^${Yn(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(a=>{const n=a._zod.bag;n.patterns??(n.patterns=new Set),n.patterns.add(r)}),t._zod.check=a=>{a.value.startsWith(e.prefix)||a.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:a.value,inst:t,continue:!e.abort})}}),ag=z("$ZodCheckEndsWith",(t,e)=>{Ct.init(t,e);const r=new RegExp(`.*${Yn(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(a=>{const n=a._zod.bag;n.patterns??(n.patterns=new Set),n.patterns.add(r)}),t._zod.check=a=>{a.value.endsWith(e.suffix)||a.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:a.value,inst:t,continue:!e.abort})}}),sg=z("$ZodCheckOverwrite",(t,e)=>{Ct.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}});class og{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}const a=e.split(`
8
- `).filter(o=>o),n=Math.min(...a.map(o=>o.length-o.trimStart().length)),s=a.map(o=>o.slice(n)).map(o=>" ".repeat(this.indent*2)+o);for(const o of s)this.content.push(o)}compile(){const e=Function,r=this==null?void 0:this.args,n=[...((this==null?void 0:this.content)??[""]).map(s=>` ${s}`)];return new e(...r,n.join(`
9
- `))}}const ig={major:4,minor:0,patch:0},Fe=z("$ZodType",(t,e)=>{var n;var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=ig;const a=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&a.unshift(t);for(const s of a)for(const o of s._zod.onattach)o(t);if(a.length===0)(r=t._zod).deferred??(r.deferred=[]),(n=t._zod.deferred)==null||n.push(()=>{t._zod.run=t._zod.parse});else{const s=(o,i,l)=>{let u=Xn(o),d;for(const v of i){if(v._zod.def.when){if(!v._zod.def.when(o))continue}else if(u)continue;const m=o.issues.length,c=v._zod.check(o);if(c instanceof Promise&&(l==null?void 0:l.async)===!1)throw new Kn;if(d||c instanceof Promise)d=(d??Promise.resolve()).then(async()=>{await c,o.issues.length!==m&&(u||(u=Xn(o,m)))});else{if(o.issues.length===m)continue;u||(u=Xn(o,m))}}return d?d.then(()=>o):o};t._zod.run=(o,i)=>{const l=t._zod.parse(o,i);if(l instanceof Promise){if(i.async===!1)throw new Kn;return l.then(u=>s(u,a,i))}return s(l,a,i)}}t["~standard"]={validate:s=>{var o;try{const i=yv(t,s);return i.success?{value:i.data}:{issues:(o=i.error)==null?void 0:o.issues}}catch{return _v(t,s).then(l=>{var u;return l.success?{value:l.data}:{issues:(u=l.error)==null?void 0:u.issues}})}},vendor:"zod",version:1}}),To=z("$ZodString",(t,e)=>{var r;Fe.init(t,e),t._zod.pattern=[...((r=t==null?void 0:t._zod.bag)==null?void 0:r.patterns)??[]].pop()??Fv(t._zod.bag),t._zod.parse=(a,n)=>{if(e.coerce)try{a.value=String(a.value)}catch{}return typeof a.value=="string"||a.issues.push({expected:"string",code:"invalid_type",input:a.value,inst:t}),a}}),Je=z("$ZodStringFormat",(t,e)=>{Wa.init(t,e),To.init(t,e)}),lg=z("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=Tv),Je.init(t,e)}),ug=z("$ZodUUID",(t,e)=>{if(e.version){const a={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(a===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=qu(a))}else e.pattern??(e.pattern=qu());Je.init(t,e)}),cg=z("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=Pv),Je.init(t,e)}),dg=z("$ZodURL",(t,e)=>{Je.init(t,e),t._zod.check=r=>{try{const a=r.value,n=new URL(a),s=n.href;e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(n.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:Dv.source,input:r.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(n.protocol.endsWith(":")?n.protocol.slice(0,-1):n.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:r.value,inst:t,continue:!e.abort})),!a.endsWith("/")&&s.endsWith("/")?r.value=s.slice(0,-1):r.value=s;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:t,continue:!e.abort})}}}),pg=z("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=Rv()),Je.init(t,e)}),hg=z("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=Iv),Je.init(t,e)}),fg=z("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=wv),Je.init(t,e)}),mg=z("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=bv),Je.init(t,e)}),vg=z("$ZodULID",(t,e)=>{e.pattern??(e.pattern=xv),Je.init(t,e)}),gg=z("$ZodXID",(t,e)=>{e.pattern??(e.pattern=Ev),Je.init(t,e)}),yg=z("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=Sv),Je.init(t,e)}),_g=z("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Uv(e)),Je.init(t,e)}),wg=z("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=zv),Je.init(t,e)}),bg=z("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=Lv(e)),Je.init(t,e)}),xg=z("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=kv),Je.init(t,e)}),Eg=z("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=Ov),Je.init(t,e),t._zod.onattach.push(r=>{const a=r._zod.bag;a.format="ipv4"})}),Sg=z("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=$v),Je.init(t,e),t._zod.onattach.push(r=>{const a=r._zod.bag;a.format="ipv6"}),t._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:t,continue:!e.abort})}}}),Ig=z("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=Av),Je.init(t,e)}),kg=z("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=Nv),Je.init(t,e),t._zod.check=r=>{const[a,n]=r.value.split("/");try{if(!n)throw new Error;const s=Number(n);if(`${s}`!==n)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${a}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:t,continue:!e.abort})}}});function Gu(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}const Tg=z("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=Mv),Je.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{Gu(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});function Pg(t){if(!Zu.test(t))return!1;const e=t.replace(/[-_]/g,a=>a==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return Gu(r)}const Cg=z("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Zu),Je.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{Pg(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),Rg=z("$ZodE164",(t,e)=>{e.pattern??(e.pattern=jv),Je.init(t,e)});function Og(t,e=null){try{const r=t.split(".");if(r.length!==3)return!1;const[a]=r;if(!a)return!1;const n=JSON.parse(atob(a));return!("typ"in n&&(n==null?void 0:n.typ)!=="JWT"||!n.alg||e&&(!("alg"in n)||n.alg!==e))}catch{return!1}}const $g=z("$ZodJWT",(t,e)=>{Je.init(t,e),t._zod.check=r=>{Og(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}}),Ku=z("$ZodNumber",(t,e)=>{Fe.init(t,e),t._zod.pattern=t._zod.bag.pattern??Zv,t._zod.parse=(r,a)=>{if(e.coerce)try{r.value=Number(r.value)}catch{}const n=r.value;if(typeof n=="number"&&!Number.isNaN(n)&&Number.isFinite(n))return r;const s=typeof n=="number"?Number.isNaN(n)?"NaN":Number.isFinite(n)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:n,inst:t,...s?{received:s}:{}}),r}}),Ag=z("$ZodNumber",(t,e)=>{Gv.init(t,e),Ku.init(t,e)}),Ng=z("$ZodBoolean",(t,e)=>{Fe.init(t,e),t._zod.pattern=Vv,t._zod.parse=(r,a)=>{if(e.coerce)try{r.value=!!r.value}catch{}const n=r.value;return typeof n=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:n,inst:t}),r}}),Mg=z("$ZodNull",(t,e)=>{Fe.init(t,e),t._zod.pattern=Bv,t._zod.values=new Set([null]),t._zod.parse=(r,a)=>{const n=r.value;return n===null||r.issues.push({expected:"null",code:"invalid_type",input:n,inst:t}),r}}),Dg=z("$ZodAny",(t,e)=>{Fe.init(t,e),t._zod.parse=r=>r}),jg=z("$ZodUnknown",(t,e)=>{Fe.init(t,e),t._zod.parse=r=>r}),zg=z("$ZodNever",(t,e)=>{Fe.init(t,e),t._zod.parse=(r,a)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});function Qu(t,e,r){t.issues.length&&e.issues.push(...Yr(r,t.issues)),e.value[r]=t.value}const Lg=z("$ZodArray",(t,e)=>{Fe.init(t,e),t._zod.parse=(r,a)=>{const n=r.value;if(!Array.isArray(n))return r.issues.push({expected:"array",code:"invalid_type",input:n,inst:t}),r;r.value=Array(n.length);const s=[];for(let o=0;o<n.length;o++){const i=n[o],l=e.element._zod.run({value:i,issues:[]},a);l instanceof Promise?s.push(l.then(u=>Qu(u,r,o))):Qu(l,r,o)}return s.length?Promise.all(s).then(()=>r):r}});function Ga(t,e,r){t.issues.length&&e.issues.push(...Yr(r,t.issues)),e.value[r]=t.value}function Yu(t,e,r,a){t.issues.length?a[r]===void 0?r in a?e.value[r]=void 0:e.value[r]=t.value:e.issues.push(...Yr(r,t.issues)):t.value===void 0?r in a&&(e.value[r]=void 0):e.value[r]=t.value}const Ug=z("$ZodObject",(t,e)=>{Fe.init(t,e);const r=Eo(()=>{const v=Object.keys(e.shape);for(const c of v)if(!(e.shape[c]instanceof Fe))throw new Error(`Invalid element at key "${c}": expected a Zod schema`);const m=ov(e.shape);return{shape:e.shape,keys:v,keySet:new Set(v),numKeys:v.length,optionalKeys:new Set(m)}});je(t._zod,"propValues",()=>{const v=e.shape,m={};for(const c in v){const h=v[c]._zod;if(h.values){m[c]??(m[c]=new Set);for(const g of h.values)m[c].add(g)}}return m});const a=v=>{const m=new og(["shape","payload","ctx"]),c=r.value,h=b=>{const y=Qn(b);return`shape[${y}]._zod.run({ value: input[${y}], issues: [] }, ctx)`};m.write("const input = payload.value;");const g=Object.create(null);let f=0;for(const b of c.keys)g[b]=`key_${f++}`;m.write("const newResult = {}");for(const b of c.keys)if(c.optionalKeys.has(b)){const y=g[b];m.write(`const ${y} = ${h(b)};`);const _=Qn(b);m.write(`
1
+ (function(un,or){typeof exports=="object"&&typeof module<"u"?or(exports):typeof define=="function"&&define.amd?define(["exports"],or):(un=typeof globalThis<"u"?globalThis:un||self,or(un.WebAgent={}))})(this,function(un){"use strict";var or="vercel.ai.error",wm=Symbol.for(or),Ac,bm=class vm extends Error{constructor({name:t,message:n,cause:r}){super(n),this[Ac]=!0,this.name=t,this.cause=r}static isInstance(t){return vm.hasMarker(t,or)}static hasMarker(t,n){const r=Symbol.for(n);return t!=null&&typeof t=="object"&&r in t&&typeof t[r]=="boolean"&&t[r]===!0}};Ac=wm;var ee=bm,Lc="AI_APICallError",jc=`vercel.ai.error.${Lc}`,$m=Symbol.for(jc),zc,Ie=class extends ee{constructor({message:e,url:t,requestBodyValues:n,statusCode:r,responseHeaders:o,responseBody:s,cause:i,isRetryable:a=r!=null&&(r===408||r===409||r===429||r>=500),data:l}){super({name:Lc,message:e,cause:i}),this[zc]=!0,this.url=t,this.requestBodyValues=n,this.statusCode=r,this.responseHeaders=o,this.responseBody=s,this.isRetryable=a,this.data=l}static isInstance(e){return ee.hasMarker(e,jc)}};zc=$m;var Dc="AI_EmptyResponseBodyError",Uc=`vercel.ai.error.${Dc}`,Sm=Symbol.for(Uc),qc,Zc=class extends ee{constructor({message:e="Empty response body"}={}){super({name:Dc,message:e}),this[qc]=!0}static isInstance(e){return ee.hasMarker(e,Uc)}};qc=Sm;function sr(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}var Fc="AI_InvalidArgumentError",Vc=`vercel.ai.error.${Fc}`,Cm=Symbol.for(Vc),Bc,vi=class extends ee{constructor({message:t,cause:n,argument:r}){super({name:Fc,message:t,cause:n}),this[Bc]=!0,this.argument=r}static isInstance(t){return ee.hasMarker(t,Vc)}};Bc=Cm;var Hc="AI_InvalidPromptError",Jc=`vercel.ai.error.${Hc}`,Em=Symbol.for(Jc),Gc,An=class extends ee{constructor({prompt:e,message:t,cause:n}){super({name:Hc,message:`Invalid prompt: ${t}`,cause:n}),this[Gc]=!0,this.prompt=e}static isInstance(e){return ee.hasMarker(e,Jc)}};Gc=Em;var Wc="AI_InvalidResponseDataError",Kc=`vercel.ai.error.${Wc}`,km=Symbol.for(Kc),Yc,Ar=class extends ee{constructor({data:e,message:t=`Invalid response data: ${JSON.stringify(e)}.`}){super({name:Wc,message:t}),this[Yc]=!0,this.data=e}static isInstance(e){return ee.hasMarker(e,Kc)}};Yc=km;var Qc="AI_JSONParseError",Xc=`vercel.ai.error.${Qc}`,Im=Symbol.for(Xc),eu,yn=class extends ee{constructor({text:e,cause:t}){super({name:Qc,message:`JSON parsing failed: Text: ${e}.
2
+ Error message: ${sr(t)}`,cause:t}),this[eu]=!0,this.text=e}static isInstance(e){return ee.hasMarker(e,Xc)}};eu=Im;var tu="AI_LoadAPIKeyError",nu=`vercel.ai.error.${tu}`,Tm=Symbol.for(nu),ru,No=class extends ee{constructor({message:e}){super({name:tu,message:e}),this[ru]=!0}static isInstance(e){return ee.hasMarker(e,nu)}};ru=Tm;var ou="AI_NoSuchModelError",su=`vercel.ai.error.${ou}`,xm=Symbol.for(su),iu,_i=class extends ee{constructor({errorName:e=ou,modelId:t,modelType:n,message:r=`No such ${n}: ${t}`}){super({name:e,message:r}),this[iu]=!0,this.modelId=t,this.modelType=n}static isInstance(e){return ee.hasMarker(e,su)}};iu=xm;var au="AI_TooManyEmbeddingValuesForCallError",lu=`vercel.ai.error.${au}`,Pm=Symbol.for(lu),cu,Rm=class extends ee{constructor(e){super({name:au,message:`Too many values for a single embedding call. The ${e.provider} model "${e.modelId}" can only embed up to ${e.maxEmbeddingsPerCall} values per call, but ${e.values.length} values were provided.`}),this[cu]=!0,this.provider=e.provider,this.modelId=e.modelId,this.maxEmbeddingsPerCall=e.maxEmbeddingsPerCall,this.values=e.values}static isInstance(e){return ee.hasMarker(e,lu)}};cu=Pm;var uu="AI_TypeValidationError",du=`vercel.ai.error.${uu}`,Om=Symbol.for(du),pu,Nm=class Mc extends ee{constructor({value:t,cause:n}){super({name:uu,message:`Type validation failed: Value: ${JSON.stringify(t)}.
3
+ Error message: ${sr(n)}`,cause:n}),this[pu]=!0,this.value=t}static isInstance(t){return ee.hasMarker(t,du)}static wrap({value:t,cause:n}){return Mc.isInstance(n)&&n.value===t?n:new Mc({value:t,cause:n})}};pu=Om;var Gt=Nm,fu="AI_UnsupportedFunctionalityError",hu=`vercel.ai.error.${fu}`,Mm=Symbol.for(hu),mu,Mt=class extends ee{constructor({functionality:e,message:t=`'${e}' functionality not supported.`}){super({name:fu,message:t}),this[mu]=!0,this.functionality=e}static isInstance(e){return ee.hasMarker(e,hu)}};mu=Mm;class gu extends Error{constructor(t,n){super(t),this.name="ParseError",this.type=n.type,this.field=n.field,this.value=n.value,this.line=n.line}}function yi(e){}function vu(e){if(typeof e=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:t=yi,onError:n=yi,onRetry:r=yi,onComment:o}=e;let s="",i=!0,a,l="",c="";function u(v){const m=i?v.replace(/^\xEF\xBB\xBF/,""):v,[d,w]=Am(`${s}${m}`);for(const y of d)h(y);s=w,i=!1}function h(v){if(v===""){f();return}if(v.startsWith(":")){o&&o(v.slice(v.startsWith(": ")?2:1));return}const m=v.indexOf(":");if(m!==-1){const d=v.slice(0,m),w=v[m+1]===" "?2:1,y=v.slice(m+w);_(d,y,v);return}_(v,"",v)}function _(v,m,d){switch(v){case"event":c=m;break;case"data":l=`${l}${m}
4
+ `;break;case"id":a=m.includes("\0")?void 0:m;break;case"retry":/^\d+$/.test(m)?r(parseInt(m,10)):n(new gu(`Invalid \`retry\` value: "${m}"`,{type:"invalid-retry",value:m,line:d}));break;default:n(new gu(`Unknown field "${v.length>20?`${v.slice(0,20)}…`:v}"`,{type:"unknown-field",field:v,value:m,line:d}));break}}function f(){l.length>0&&t({id:a,event:c||void 0,data:l.endsWith(`
5
+ `)?l.slice(0,-1):l}),a=void 0,l="",c=""}function g(v={}){s&&v.consume&&h(s),i=!0,a=void 0,l="",c="",s=""}return{feed:u,reset:g}}function Am(e){const t=[];let n="",r=0;for(;r<e.length;){const o=e.indexOf("\r",r),s=e.indexOf(`
6
+ `,r);let i=-1;if(o!==-1&&s!==-1?i=Math.min(o,s):o!==-1?o===e.length-1?i=-1:i=o:s!==-1&&(i=s),i===-1){n=e.slice(r);break}else{const a=e.slice(r,i);t.push(a),r=i+1,e[r-1]==="\r"&&e[r]===`
7
+ `&&r++}}return[t,n]}class Mo extends TransformStream{constructor({onError:t,onRetry:n,onComment:r}={}){let o;super({start(s){o=vu({onEvent:i=>{s.enqueue(i)},onError(i){t==="terminate"?s.error(i):typeof t=="function"&&t(i)},onRetry:n,onComment:r})},transform(s){o.feed(s)}})}}const Lm=Object.freeze({status:"aborted"});function A(e,t,n){function r(a,l){var c;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(c=a._zod).traits??(c.traits=new Set),a._zod.traits.add(e),t(a,l);for(const u in i.prototype)u in a||Object.defineProperty(a,u,{value:i.prototype[u].bind(a)});a._zod.constr=i,a._zod.def=l}const o=(n==null?void 0:n.Parent)??Object;class s extends o{}Object.defineProperty(s,"name",{value:e});function i(a){var l;const c=n!=null&&n.Parent?new s:this;r(c,a),(l=c._zod).deferred??(l.deferred=[]);for(const u of c._zod.deferred)u();return c}return Object.defineProperty(i,"init",{value:r}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>{var l,c;return n!=null&&n.Parent&&a instanceof n.Parent?!0:(c=(l=a==null?void 0:a._zod)==null?void 0:l.traits)==null?void 0:c.has(e)}}),Object.defineProperty(i,"name",{value:e}),i}class Lr extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const _u={};function wn(e){return _u}function yu(e){const t=Object.values(e).filter(r=>typeof r=="number");return Object.entries(e).filter(([r,o])=>t.indexOf(+r)===-1).map(([r,o])=>o)}function jm(e,t){return typeof t=="bigint"?t.toString():t}function wi(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function bi(e){return e==null}function $i(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function zm(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,o=n>r?n:r,s=Number.parseInt(e.toFixed(o).replace(".","")),i=Number.parseInt(t.toFixed(o).replace(".",""));return s%i/10**o}function be(e,t,n){Object.defineProperty(e,t,{get(){{const r=n();return e[t]=r,r}},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function Ao(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function jr(e){return JSON.stringify(e)}const wu=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function Lo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const Dm=wi(()=>{var e;if(typeof navigator<"u"&&((e=navigator==null?void 0:navigator.userAgent)!=null&&e.includes("Cloudflare")))return!1;try{const t=Function;return new t(""),!0}catch{return!1}});function jo(e){if(Lo(e)===!1)return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(Lo(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}const Um=new Set(["string","number","symbol"]);function zr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ln(e,t,n){const r=new e._zod.constr(t??e._zod.def);return(!t||n!=null&&n.parent)&&(r._zod.parent=e),r}function W(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if((t==null?void 0:t.message)!==void 0){if((t==null?void 0:t.error)!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function qm(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const Zm={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Fm(e,t){const n={},r=e._zod.def;for(const o in t){if(!(o in r.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&(n[o]=r.shape[o])}return Ln(e,{...e._zod.def,shape:n,checks:[]})}function Vm(e,t){const n={...e._zod.def.shape},r=e._zod.def;for(const o in t){if(!(o in r.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&delete n[o]}return Ln(e,{...e._zod.def,shape:n,checks:[]})}function Bm(e,t){if(!jo(t))throw new Error("Invalid input to extend: expected a plain object");const n={...e._zod.def,get shape(){const r={...e._zod.def.shape,...t};return Ao(this,"shape",r),r},checks:[]};return Ln(e,n)}function Hm(e,t){return Ln(e,{...e._zod.def,get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};return Ao(this,"shape",n),n},catchall:t._zod.def.catchall,checks:[]})}function Jm(e,t,n){const r=t._zod.def.shape,o={...r};if(n)for(const s in n){if(!(s in r))throw new Error(`Unrecognized key: "${s}"`);n[s]&&(o[s]=e?new e({type:"optional",innerType:r[s]}):r[s])}else for(const s in r)o[s]=e?new e({type:"optional",innerType:r[s]}):r[s];return Ln(t,{...t._zod.def,shape:o,checks:[]})}function Gm(e,t,n){const r=t._zod.def.shape,o={...r};if(n)for(const s in n){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);n[s]&&(o[s]=new e({type:"nonoptional",innerType:r[s]}))}else for(const s in r)o[s]=new e({type:"nonoptional",innerType:r[s]});return Ln(t,{...t._zod.def,shape:o,checks:[]})}function Dr(e,t=0){var n;for(let r=t;r<e.issues.length;r++)if(((n=e.issues[r])==null?void 0:n.continue)!==!0)return!0;return!1}function jn(e,t){return t.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}function zo(e){return typeof e=="string"?e:e==null?void 0:e.message}function bn(e,t,n){var o,s,i,a,l,c;const r={...e,path:e.path??[]};if(!e.message){const u=zo((i=(s=(o=e.inst)==null?void 0:o._zod.def)==null?void 0:s.error)==null?void 0:i.call(s,e))??zo((a=t==null?void 0:t.error)==null?void 0:a.call(t,e))??zo((l=n.customError)==null?void 0:l.call(n,e))??zo((c=n.localeError)==null?void 0:c.call(n,e))??"Invalid input";r.message=u}return delete r.inst,delete r.continue,t!=null&&t.reportInput||delete r.input,r}function Si(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Ur(...e){const[t,n,r]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:r}:{...t}}const bu=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),Object.defineProperty(e,"message",{get(){return JSON.stringify(t,jm,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},$u=A("$ZodError",bu),Su=A("$ZodError",bu,{Parent:Error});function Wm(e,t=n=>n.message){const n={},r=[];for(const o of e.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(t(o))):r.push(t(o));return{formErrors:r,fieldErrors:n}}function Km(e,t){const n=t||function(s){return s.message},r={_errors:[]},o=s=>{for(const i of s.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(a=>o({issues:a}));else if(i.code==="invalid_key")o({issues:i.issues});else if(i.code==="invalid_element")o({issues:i.issues});else if(i.path.length===0)r._errors.push(n(i));else{let a=r,l=0;for(;l<i.path.length;){const c=i.path[l];l===i.path.length-1?(a[c]=a[c]||{_errors:[]},a[c]._errors.push(n(i))):a[c]=a[c]||{_errors:[]},a=a[c],l++}}};return o(e),r}const Ym=e=>(t,n,r,o)=>{const s=r?Object.assign(r,{async:!1}):{async:!1},i=t._zod.run({value:n,issues:[]},s);if(i instanceof Promise)throw new Lr;if(i.issues.length){const a=new((o==null?void 0:o.Err)??e)(i.issues.map(l=>bn(l,s,wn())));throw wu(a,o==null?void 0:o.callee),a}return i.value},Qm=e=>async(t,n,r,o)=>{const s=r?Object.assign(r,{async:!0}):{async:!0};let i=t._zod.run({value:n,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){const a=new((o==null?void 0:o.Err)??e)(i.issues.map(l=>bn(l,s,wn())));throw wu(a,o==null?void 0:o.callee),a}return i.value},Cu=e=>(t,n,r)=>{const o=r?{...r,async:!1}:{async:!1},s=t._zod.run({value:n,issues:[]},o);if(s instanceof Promise)throw new Lr;return s.issues.length?{success:!1,error:new(e??$u)(s.issues.map(i=>bn(i,o,wn())))}:{success:!0,data:s.value}},Eu=Cu(Su),ku=e=>async(t,n,r)=>{const o=r?Object.assign(r,{async:!0}):{async:!0};let s=t._zod.run({value:n,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new e(s.issues.map(i=>bn(i,o,wn())))}:{success:!0,data:s.value}},Xm=ku(Su),e1=/^[cC][^\s-]{8,}$/,t1=/^[0-9a-z]+$/,n1=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,r1=/^[0-9a-vA-V]{20}$/,o1=/^[A-Za-z0-9]{27}$/,s1=/^[a-zA-Z0-9_-]{21}$/,i1=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,a1=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Iu=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,l1=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,c1="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function u1(){return new RegExp(c1,"u")}const d1=/^(?:(?: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])$/,p1=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,f1=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,h1=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,m1=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Tu=/^[A-Za-z0-9_-]*$/,g1=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,v1=/^\+(?:[0-9]){6,14}[0-9]$/,xu="(?:(?:\\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])))",_1=new RegExp(`^${xu}$`);function Pu(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function y1(e){return new RegExp(`^${Pu(e)}$`)}function w1(e){const t=Pu({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-]\\d{2}:\\d{2})");const r=`${t}(?:${n.join("|")})`;return new RegExp(`^${xu}T(?:${r})$`)}const b1=e=>{const t=e?`[\\s\\S]{${(e==null?void 0:e.minimum)??0},${(e==null?void 0:e.maximum)??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},$1=/^\d+$/,S1=/^-?\d+(?:\.\d+)?/i,C1=/true|false/i,E1=/null/i,k1=/^[^A-Z]*$/,I1=/^[^a-z]*$/,ut=A("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Ru={number:"number",bigint:"bigint",object:"date"},Ou=A("$ZodCheckLessThan",(e,t)=>{ut.init(e,t);const n=Ru[typeof t.value];e._zod.onattach.push(r=>{const o=r._zod.bag,s=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<s&&(t.inclusive?o.maximum=t.value:o.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:"too_big",maximum:t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Nu=A("$ZodCheckGreaterThan",(e,t)=>{ut.init(e,t);const n=Ru[typeof t.value];e._zod.onattach.push(r=>{const o=r._zod.bag,s=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>s&&(t.inclusive?o.minimum=t.value:o.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:"too_small",minimum:t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),T1=A("$ZodCheckMultipleOf",(e,t)=>{ut.init(e,t),e._zod.onattach.push(n=>{var r;(r=n._zod.bag).multipleOf??(r.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%t.value===BigInt(0):zm(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),x1=A("$ZodCheckNumberFormat",(e,t)=>{var i;ut.init(e,t),t.format=t.format||"float64";const n=(i=t.format)==null?void 0:i.includes("int"),r=n?"int":"number",[o,s]=Zm[t.format];e._zod.onattach.push(a=>{const l=a._zod.bag;l.format=t.format,l.minimum=o,l.maximum=s,n&&(l.pattern=$1)}),e._zod.check=a=>{const l=a.value;if(n){if(!Number.isInteger(l)){a.issues.push({expected:r,format:t.format,code:"invalid_type",input:l,inst:e});return}if(!Number.isSafeInteger(l)){l>0?a.issues.push({input:l,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,continue:!t.abort}):a.issues.push({input:l,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,continue:!t.abort});return}}l<o&&a.issues.push({origin:"number",input:l,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),l>s&&a.issues.push({origin:"number",input:l,code:"too_big",maximum:s,inst:e})}}),P1=A("$ZodCheckMaxLength",(e,t)=>{var n;ut.init(e,t),(n=e._zod.def).when??(n.when=r=>{const o=r.value;return!bi(o)&&o.length!==void 0}),e._zod.onattach.push(r=>{const o=r._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<o&&(r._zod.bag.maximum=t.maximum)}),e._zod.check=r=>{const o=r.value;if(o.length<=t.maximum)return;const i=Si(o);r.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),R1=A("$ZodCheckMinLength",(e,t)=>{var n;ut.init(e,t),(n=e._zod.def).when??(n.when=r=>{const o=r.value;return!bi(o)&&o.length!==void 0}),e._zod.onattach.push(r=>{const o=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(r._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{const o=r.value;if(o.length>=t.minimum)return;const i=Si(o);r.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),O1=A("$ZodCheckLengthEquals",(e,t)=>{var n;ut.init(e,t),(n=e._zod.def).when??(n.when=r=>{const o=r.value;return!bi(o)&&o.length!==void 0}),e._zod.onattach.push(r=>{const o=r._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=r=>{const o=r.value,s=o.length;if(s===t.length)return;const i=Si(o),a=s>t.length;r.issues.push({origin:i,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),Do=A("$ZodCheckStringFormat",(e,t)=>{var n,r;ut.init(e,t),e._zod.onattach.push(o=>{const s=o._zod.bag;s.format=t.format,t.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=o=>{t.pattern.lastIndex=0,!t.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),N1=A("$ZodCheckRegex",(e,t)=>{Do.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),M1=A("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=k1),Do.init(e,t)}),A1=A("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=I1),Do.init(e,t)}),L1=A("$ZodCheckIncludes",(e,t)=>{ut.init(e,t);const n=zr(t.includes),r=new RegExp(typeof t.position=="number"?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(o=>{const s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(r)}),e._zod.check=o=>{o.value.includes(t.includes,t.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),j1=A("$ZodCheckStartsWith",(e,t)=>{ut.init(e,t);const n=new RegExp(`^${zr(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),e._zod.check=r=>{r.value.startsWith(t.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),z1=A("$ZodCheckEndsWith",(e,t)=>{ut.init(e,t);const n=new RegExp(`.*${zr(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),e._zod.check=r=>{r.value.endsWith(t.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}}),D1=A("$ZodCheckOverwrite",(e,t)=>{ut.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});class U1{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const r=t.split(`
8
+ `).filter(i=>i),o=Math.min(...r.map(i=>i.length-i.trimStart().length)),s=r.map(i=>i.slice(o)).map(i=>" ".repeat(this.indent*2)+i);for(const i of s)this.content.push(i)}compile(){const t=Function,n=this==null?void 0:this.args,o=[...((this==null?void 0:this.content)??[""]).map(s=>` ${s}`)];return new t(...n,o.join(`
9
+ `))}}const q1={major:4,minor:0,patch:0},Te=A("$ZodType",(e,t)=>{var o;var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=q1;const r=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&r.unshift(e);for(const s of r)for(const i of s._zod.onattach)i(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),(o=e._zod.deferred)==null||o.push(()=>{e._zod.run=e._zod.parse});else{const s=(i,a,l)=>{let c=Dr(i),u;for(const h of a){if(h._zod.def.when){if(!h._zod.def.when(i))continue}else if(c)continue;const _=i.issues.length,f=h._zod.check(i);if(f instanceof Promise&&(l==null?void 0:l.async)===!1)throw new Lr;if(u||f instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await f,i.issues.length!==_&&(c||(c=Dr(i,_)))});else{if(i.issues.length===_)continue;c||(c=Dr(i,_))}}return u?u.then(()=>i):i};e._zod.run=(i,a)=>{const l=e._zod.parse(i,a);if(l instanceof Promise){if(a.async===!1)throw new Lr;return l.then(c=>s(c,r,a))}return s(l,r,a)}}e["~standard"]={validate:s=>{var i;try{const a=Eu(e,s);return a.success?{value:a.data}:{issues:(i=a.error)==null?void 0:i.issues}}catch{return Xm(e,s).then(l=>{var c;return l.success?{value:l.data}:{issues:(c=l.error)==null?void 0:c.issues}})}},vendor:"zod",version:1}}),Ci=A("$ZodString",(e,t)=>{var n;Te.init(e,t),e._zod.pattern=[...((n=e==null?void 0:e._zod.bag)==null?void 0:n.patterns)??[]].pop()??b1(e._zod.bag),e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),Me=A("$ZodStringFormat",(e,t)=>{Do.init(e,t),Ci.init(e,t)}),Z1=A("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=a1),Me.init(e,t)}),F1=A("$ZodUUID",(e,t)=>{if(t.version){const r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(r===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=Iu(r))}else t.pattern??(t.pattern=Iu());Me.init(e,t)}),V1=A("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=l1),Me.init(e,t)}),B1=A("$ZodURL",(e,t)=>{Me.init(e,t),e._zod.check=n=>{try{const r=n.value,o=new URL(r),s=o.href;t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(o.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:g1.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),!r.endsWith("/")&&s.endsWith("/")?n.value=s.slice(0,-1):n.value=s;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),H1=A("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=u1()),Me.init(e,t)}),J1=A("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=s1),Me.init(e,t)}),G1=A("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=e1),Me.init(e,t)}),W1=A("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=t1),Me.init(e,t)}),K1=A("$ZodULID",(e,t)=>{t.pattern??(t.pattern=n1),Me.init(e,t)}),Y1=A("$ZodXID",(e,t)=>{t.pattern??(t.pattern=r1),Me.init(e,t)}),Q1=A("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=o1),Me.init(e,t)}),X1=A("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=w1(t)),Me.init(e,t)}),eg=A("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=_1),Me.init(e,t)}),tg=A("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=y1(t)),Me.init(e,t)}),ng=A("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=i1),Me.init(e,t)}),rg=A("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=d1),Me.init(e,t),e._zod.onattach.push(n=>{const r=n._zod.bag;r.format="ipv4"})}),og=A("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=p1),Me.init(e,t),e._zod.onattach.push(n=>{const r=n._zod.bag;r.format="ipv6"}),e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),sg=A("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=f1),Me.init(e,t)}),ig=A("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=h1),Me.init(e,t),e._zod.check=n=>{const[r,o]=n.value.split("/");try{if(!o)throw new Error;const s=Number(o);if(`${s}`!==o)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${r}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function Mu(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const ag=A("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=m1),Me.init(e,t),e._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64"}),e._zod.check=n=>{Mu(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function lg(e){if(!Tu.test(e))return!1;const t=e.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return Mu(n)}const cg=A("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Tu),Me.init(e,t),e._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64url"}),e._zod.check=n=>{lg(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),ug=A("$ZodE164",(e,t)=>{t.pattern??(t.pattern=v1),Me.init(e,t)});function dg(e,t=null){try{const n=e.split(".");if(n.length!==3)return!1;const[r]=n;if(!r)return!1;const o=JSON.parse(atob(r));return!("typ"in o&&(o==null?void 0:o.typ)!=="JWT"||!o.alg||t&&(!("alg"in o)||o.alg!==t))}catch{return!1}}const pg=A("$ZodJWT",(e,t)=>{Me.init(e,t),e._zod.check=n=>{dg(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),Au=A("$ZodNumber",(e,t)=>{Te.init(e,t),e._zod.pattern=e._zod.bag.pattern??S1,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}const o=n.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return n;const s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...s?{received:s}:{}}),n}}),fg=A("$ZodNumber",(e,t)=>{x1.init(e,t),Au.init(e,t)}),hg=A("$ZodBoolean",(e,t)=>{Te.init(e,t),e._zod.pattern=C1,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}const o=n.value;return typeof o=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),n}}),mg=A("$ZodNull",(e,t)=>{Te.init(e,t),e._zod.pattern=E1,e._zod.values=new Set([null]),e._zod.parse=(n,r)=>{const o=n.value;return o===null||n.issues.push({expected:"null",code:"invalid_type",input:o,inst:e}),n}}),gg=A("$ZodAny",(e,t)=>{Te.init(e,t),e._zod.parse=n=>n}),vg=A("$ZodUnknown",(e,t)=>{Te.init(e,t),e._zod.parse=n=>n}),_g=A("$ZodNever",(e,t)=>{Te.init(e,t),e._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function Lu(e,t,n){e.issues.length&&t.issues.push(...jn(n,e.issues)),t.value[n]=e.value}const yg=A("$ZodArray",(e,t)=>{Te.init(e,t),e._zod.parse=(n,r)=>{const o=n.value;if(!Array.isArray(o))return n.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),n;n.value=Array(o.length);const s=[];for(let i=0;i<o.length;i++){const a=o[i],l=t.element._zod.run({value:a,issues:[]},r);l instanceof Promise?s.push(l.then(c=>Lu(c,n,i))):Lu(l,n,i)}return s.length?Promise.all(s).then(()=>n):n}});function Uo(e,t,n){e.issues.length&&t.issues.push(...jn(n,e.issues)),t.value[n]=e.value}function ju(e,t,n,r){e.issues.length?r[n]===void 0?n in r?t.value[n]=void 0:t.value[n]=e.value:t.issues.push(...jn(n,e.issues)):e.value===void 0?n in r&&(t.value[n]=void 0):t.value[n]=e.value}const wg=A("$ZodObject",(e,t)=>{Te.init(e,t);const n=wi(()=>{const h=Object.keys(t.shape);for(const f of h)if(!(t.shape[f]instanceof Te))throw new Error(`Invalid element at key "${f}": expected a Zod schema`);const _=qm(t.shape);return{shape:t.shape,keys:h,keySet:new Set(h),numKeys:h.length,optionalKeys:new Set(_)}});be(e._zod,"propValues",()=>{const h=t.shape,_={};for(const f in h){const g=h[f]._zod;if(g.values){_[f]??(_[f]=new Set);for(const v of g.values)_[f].add(v)}}return _});const r=h=>{const _=new U1(["shape","payload","ctx"]),f=n.value,g=w=>{const y=jr(w);return`shape[${y}]._zod.run({ value: input[${y}], issues: [] }, ctx)`};_.write("const input = payload.value;");const v=Object.create(null);let m=0;for(const w of f.keys)v[w]=`key_${m++}`;_.write("const newResult = {}");for(const w of f.keys)if(f.optionalKeys.has(w)){const y=v[w];_.write(`const ${y} = ${g(w)};`);const b=jr(w);_.write(`
10
10
  if (${y}.issues.length) {
11
- if (input[${_}] === undefined) {
12
- if (${_} in input) {
13
- newResult[${_}] = undefined;
11
+ if (input[${b}] === undefined) {
12
+ if (${b} in input) {
13
+ newResult[${b}] = undefined;
14
14
  }
15
15
  } else {
16
16
  payload.issues = payload.issues.concat(
17
17
  ${y}.issues.map((iss) => ({
18
18
  ...iss,
19
- path: iss.path ? [${_}, ...iss.path] : [${_}],
19
+ path: iss.path ? [${b}, ...iss.path] : [${b}],
20
20
  }))
21
21
  );
22
22
  }
23
23
  } else if (${y}.value === undefined) {
24
- if (${_} in input) newResult[${_}] = undefined;
24
+ if (${b} in input) newResult[${b}] = undefined;
25
25
  } else {
26
- newResult[${_}] = ${y}.value;
26
+ newResult[${b}] = ${y}.value;
27
27
  }
28
- `)}else{const y=g[b];m.write(`const ${y} = ${h(b)};`),m.write(`
28
+ `)}else{const y=v[w];_.write(`const ${y} = ${g(w)};`),_.write(`
29
29
  if (${y}.issues.length) payload.issues = payload.issues.concat(${y}.issues.map(iss => ({
30
30
  ...iss,
31
- path: iss.path ? [${Qn(b)}, ...iss.path] : [${Qn(b)}]
32
- })));`),m.write(`newResult[${Qn(b)}] = ${y}.value`)}m.write("payload.value = newResult;"),m.write("return payload;");const p=m.compile();return(b,y)=>p(v,b,y)};let n;const s=Ba,o=!Nu.jitless,l=o&&av.value,u=e.catchall;let d;t._zod.parse=(v,m)=>{d??(d=r.value);const c=v.value;if(!s(c))return v.issues.push({expected:"object",code:"invalid_type",input:c,inst:t}),v;const h=[];if(o&&l&&(m==null?void 0:m.async)===!1&&m.jitless!==!0)n||(n=a(e.shape)),v=n(v,m);else{v.value={};const y=d.shape;for(const _ of d.keys){const S=y[_],T=S._zod.run({value:c[_],issues:[]},m),I=S._zod.optin==="optional"&&S._zod.optout==="optional";T instanceof Promise?h.push(T.then(O=>I?Yu(O,v,_,c):Ga(O,v,_))):I?Yu(T,v,_,c):Ga(T,v,_)}}if(!u)return h.length?Promise.all(h).then(()=>v):v;const g=[],f=d.keySet,p=u._zod,b=p.def.type;for(const y of Object.keys(c)){if(f.has(y))continue;if(b==="never"){g.push(y);continue}const _=p.run({value:c[y],issues:[]},m);_ instanceof Promise?h.push(_.then(S=>Ga(S,v,y))):Ga(_,v,y)}return g.length&&v.issues.push({code:"unrecognized_keys",keys:g,input:c,inst:t}),h.length?Promise.all(h).then(()=>v):v}});function Xu(t,e,r,a){for(const n of t)if(n.issues.length===0)return e.value=n.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(n=>n.issues.map(s=>Mr(s,a,Nr())))}),e}const ec=z("$ZodUnion",(t,e)=>{Fe.init(t,e),je(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),je(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),je(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),je(t._zod,"pattern",()=>{if(e.options.every(r=>r._zod.pattern)){const r=e.options.map(a=>a._zod.pattern);return new RegExp(`^(${r.map(a=>Io(a.source)).join("|")})$`)}}),t._zod.parse=(r,a)=>{let n=!1;const s=[];for(const o of e.options){const i=o._zod.run({value:r.value,issues:[]},a);if(i instanceof Promise)s.push(i),n=!0;else{if(i.issues.length===0)return i;s.push(i)}}return n?Promise.all(s).then(o=>Xu(o,r,t,a)):Xu(s,r,t,a)}}),Fg=z("$ZodDiscriminatedUnion",(t,e)=>{ec.init(t,e);const r=t._zod.parse;je(t._zod,"propValues",()=>{const n={};for(const s of e.options){const o=s._zod.propValues;if(!o||Object.keys(o).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(const[i,l]of Object.entries(o)){n[i]||(n[i]=new Set);for(const u of l)n[i].add(u)}}return n});const a=Eo(()=>{const n=e.options,s=new Map;for(const o of n){const i=o._zod.propValues[e.discriminator];if(!i||i.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(o)}"`);for(const l of i){if(s.has(l))throw new Error(`Duplicate discriminator value "${String(l)}"`);s.set(l,o)}}return s});t._zod.parse=(n,s)=>{const o=n.value;if(!Ba(o))return n.issues.push({code:"invalid_type",expected:"object",input:o,inst:t}),n;const i=a.value.get(o==null?void 0:o[e.discriminator]);return i?i._zod.run(n,s):e.unionFallback?r(n,s):(n.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:o,path:[e.discriminator],inst:t}),n)}}),qg=z("$ZodIntersection",(t,e)=>{Fe.init(t,e),t._zod.parse=(r,a)=>{const n=r.value,s=e.left._zod.run({value:n,issues:[]},a),o=e.right._zod.run({value:n,issues:[]},a);return s instanceof Promise||o instanceof Promise?Promise.all([s,o]).then(([l,u])=>tc(r,l,u)):tc(r,s,o)}});function Po(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(Ha(t)&&Ha(e)){const r=Object.keys(e),a=Object.keys(t).filter(s=>r.indexOf(s)!==-1),n={...t,...e};for(const s of a){const o=Po(t[s],e[s]);if(!o.valid)return{valid:!1,mergeErrorPath:[s,...o.mergeErrorPath]};n[s]=o.data}return{valid:!0,data:n}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};const r=[];for(let a=0;a<t.length;a++){const n=t[a],s=e[a],o=Po(n,s);if(!o.valid)return{valid:!1,mergeErrorPath:[a,...o.mergeErrorPath]};r.push(o.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function tc(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),Xn(t))return t;const a=Po(e.value,r.value);if(!a.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(a.mergeErrorPath)}`);return t.value=a.data,t}const Zg=z("$ZodRecord",(t,e)=>{Fe.init(t,e),t._zod.parse=(r,a)=>{const n=r.value;if(!Ha(n))return r.issues.push({expected:"record",code:"invalid_type",input:n,inst:t}),r;const s=[];if(e.keyType._zod.values){const o=e.keyType._zod.values;r.value={};for(const l of o)if(typeof l=="string"||typeof l=="number"||typeof l=="symbol"){const u=e.valueType._zod.run({value:n[l],issues:[]},a);u instanceof Promise?s.push(u.then(d=>{d.issues.length&&r.issues.push(...Yr(l,d.issues)),r.value[l]=d.value})):(u.issues.length&&r.issues.push(...Yr(l,u.issues)),r.value[l]=u.value)}let i;for(const l in n)o.has(l)||(i=i??[],i.push(l));i&&i.length>0&&r.issues.push({code:"unrecognized_keys",input:n,inst:t,keys:i})}else{r.value={};for(const o of Reflect.ownKeys(n)){if(o==="__proto__")continue;const i=e.keyType._zod.run({value:o,issues:[]},a);if(i instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(i.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:i.issues.map(u=>Mr(u,a,Nr())),input:o,path:[o],inst:t}),r.value[i.value]=i.value;continue}const l=e.valueType._zod.run({value:n[o],issues:[]},a);l instanceof Promise?s.push(l.then(u=>{u.issues.length&&r.issues.push(...Yr(o,u.issues)),r.value[i.value]=u.value})):(l.issues.length&&r.issues.push(...Yr(o,l.issues)),r.value[i.value]=l.value)}}return s.length?Promise.all(s).then(()=>r):r}}),Vg=z("$ZodEnum",(t,e)=>{Fe.init(t,e);const r=Mu(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(a=>sv.has(typeof a)).map(a=>typeof a=="string"?Yn(a):a.toString()).join("|")})$`),t._zod.parse=(a,n)=>{const s=a.value;return t._zod.values.has(s)||a.issues.push({code:"invalid_value",values:r,input:s,inst:t}),a}}),Bg=z("$ZodLiteral",(t,e)=>{Fe.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?Yn(r):r?r.toString():String(r)).join("|")})$`),t._zod.parse=(r,a)=>{const n=r.value;return t._zod.values.has(n)||r.issues.push({code:"invalid_value",values:e.values,input:n,inst:t}),r}}),Hg=z("$ZodTransform",(t,e)=>{Fe.init(t,e),t._zod.parse=(r,a)=>{const n=e.transform(r.value,r);if(a.async)return(n instanceof Promise?n:Promise.resolve(n)).then(o=>(r.value=o,r));if(n instanceof Promise)throw new Kn;return r.value=n,r}}),Jg=z("$ZodOptional",(t,e)=>{Fe.init(t,e),t._zod.optin="optional",t._zod.optout="optional",je(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),je(t._zod,"pattern",()=>{const r=e.innerType._zod.pattern;return r?new RegExp(`^(${Io(r.source)})?$`):void 0}),t._zod.parse=(r,a)=>e.innerType._zod.optin==="optional"?e.innerType._zod.run(r,a):r.value===void 0?r:e.innerType._zod.run(r,a)}),Wg=z("$ZodNullable",(t,e)=>{Fe.init(t,e),je(t._zod,"optin",()=>e.innerType._zod.optin),je(t._zod,"optout",()=>e.innerType._zod.optout),je(t._zod,"pattern",()=>{const r=e.innerType._zod.pattern;return r?new RegExp(`^(${Io(r.source)}|null)$`):void 0}),je(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(r,a)=>r.value===null?r:e.innerType._zod.run(r,a)}),Gg=z("$ZodDefault",(t,e)=>{Fe.init(t,e),t._zod.optin="optional",je(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,a)=>{if(r.value===void 0)return r.value=e.defaultValue,r;const n=e.innerType._zod.run(r,a);return n instanceof Promise?n.then(s=>rc(s,e)):rc(n,e)}});function rc(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}const Kg=z("$ZodPrefault",(t,e)=>{Fe.init(t,e),t._zod.optin="optional",je(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,a)=>(r.value===void 0&&(r.value=e.defaultValue),e.innerType._zod.run(r,a))}),Qg=z("$ZodNonOptional",(t,e)=>{Fe.init(t,e),je(t._zod,"values",()=>{const r=e.innerType._zod.values;return r?new Set([...r].filter(a=>a!==void 0)):void 0}),t._zod.parse=(r,a)=>{const n=e.innerType._zod.run(r,a);return n instanceof Promise?n.then(s=>nc(s,t)):nc(n,t)}});function nc(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}const Yg=z("$ZodCatch",(t,e)=>{Fe.init(t,e),t._zod.optin="optional",je(t._zod,"optout",()=>e.innerType._zod.optout),je(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,a)=>{const n=e.innerType._zod.run(r,a);return n instanceof Promise?n.then(s=>(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(o=>Mr(o,a,Nr()))},input:r.value}),r.issues=[]),r)):(r.value=n.value,n.issues.length&&(r.value=e.catchValue({...r,error:{issues:n.issues.map(s=>Mr(s,a,Nr()))},input:r.value}),r.issues=[]),r)}}),Xg=z("$ZodPipe",(t,e)=>{Fe.init(t,e),je(t._zod,"values",()=>e.in._zod.values),je(t._zod,"optin",()=>e.in._zod.optin),je(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(r,a)=>{const n=e.in._zod.run(r,a);return n instanceof Promise?n.then(s=>ac(s,e,a)):ac(n,e,a)}});function ac(t,e,r){return Xn(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}const ey=z("$ZodReadonly",(t,e)=>{Fe.init(t,e),je(t._zod,"propValues",()=>e.innerType._zod.propValues),je(t._zod,"values",()=>e.innerType._zod.values),je(t._zod,"optin",()=>e.innerType._zod.optin),je(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(r,a)=>{const n=e.innerType._zod.run(r,a);return n instanceof Promise?n.then(sc):sc(n)}});function sc(t){return t.value=Object.freeze(t.value),t}const ty=z("$ZodLazy",(t,e)=>{Fe.init(t,e),je(t._zod,"innerType",()=>e.getter()),je(t._zod,"pattern",()=>t._zod.innerType._zod.pattern),je(t._zod,"propValues",()=>t._zod.innerType._zod.propValues),je(t._zod,"optin",()=>t._zod.innerType._zod.optin),je(t._zod,"optout",()=>t._zod.innerType._zod.optout),t._zod.parse=(r,a)=>t._zod.innerType._zod.run(r,a)}),ry=z("$ZodCustom",(t,e)=>{Ct.init(t,e),Fe.init(t,e),t._zod.parse=(r,a)=>r,t._zod.check=r=>{const a=r.value,n=e.fn(a);if(n instanceof Promise)return n.then(s=>oc(s,r,a,t));oc(n,r,a,t)}});function oc(t,e,r,a){if(!t){const n={code:"custom",input:r,inst:a,path:[...a._zod.def.path??[]],continue:!a._zod.def.abort};a._zod.def.params&&(n.params=a._zod.def.params),e.issues.push(ea(n))}}class ic{constructor(){this._map=new Map,this._idmap=new Map}add(e,...r){const a=r[0];if(this._map.set(e,a),a&&typeof a=="object"&&"id"in a){if(this._idmap.has(a.id))throw new Error(`ID ${a.id} already exists in the registry`);this._idmap.set(a.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){const r=this._map.get(e);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(e),this}get(e){const r=e._zod.parent;if(r){const a={...this.get(r)??{}};return delete a.id,{...a,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}}function ny(){return new ic}const ta=ny();function ay(t,e){return new t({type:"string",...ne(e)})}function sy(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...ne(e)})}function lc(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...ne(e)})}function oy(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...ne(e)})}function iy(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...ne(e)})}function ly(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...ne(e)})}function uy(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...ne(e)})}function cy(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...ne(e)})}function dy(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...ne(e)})}function py(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...ne(e)})}function hy(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...ne(e)})}function fy(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...ne(e)})}function my(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...ne(e)})}function vy(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...ne(e)})}function gy(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...ne(e)})}function yy(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...ne(e)})}function _y(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...ne(e)})}function wy(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...ne(e)})}function by(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...ne(e)})}function uc(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...ne(e)})}function xy(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...ne(e)})}function Ey(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...ne(e)})}function Sy(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...ne(e)})}function Iy(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...ne(e)})}function ky(t,e){return new t({type:"string",format:"date",check:"string_format",...ne(e)})}function Ty(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...ne(e)})}function Py(t,e){return new t({type:"string",format:"duration",check:"string_format",...ne(e)})}function Cy(t,e){return new t({type:"number",checks:[],...ne(e)})}function Ry(t,e){return new t({type:"number",coerce:!0,checks:[],...ne(e)})}function Oy(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...ne(e)})}function $y(t,e){return new t({type:"boolean",...ne(e)})}function Ay(t,e){return new t({type:"null",...ne(e)})}function Ny(t){return new t({type:"any"})}function My(t){return new t({type:"unknown"})}function Dy(t,e){return new t({type:"never",...ne(e)})}function cc(t,e){return new Ju({check:"less_than",...ne(e),value:t,inclusive:!1})}function Co(t,e){return new Ju({check:"less_than",...ne(e),value:t,inclusive:!0})}function dc(t,e){return new Wu({check:"greater_than",...ne(e),value:t,inclusive:!1})}function Ro(t,e){return new Wu({check:"greater_than",...ne(e),value:t,inclusive:!0})}function pc(t,e){return new Wv({check:"multiple_of",...ne(e),value:t})}function hc(t,e){return new Kv({check:"max_length",...ne(e),maximum:t})}function Ka(t,e){return new Qv({check:"min_length",...ne(e),minimum:t})}function fc(t,e){return new Yv({check:"length_equals",...ne(e),length:t})}function jy(t,e){return new Xv({check:"string_format",format:"regex",...ne(e),pattern:t})}function zy(t){return new eg({check:"string_format",format:"lowercase",...ne(t)})}function Ly(t){return new tg({check:"string_format",format:"uppercase",...ne(t)})}function Uy(t,e){return new rg({check:"string_format",format:"includes",...ne(e),includes:t})}function Fy(t,e){return new ng({check:"string_format",format:"starts_with",...ne(e),prefix:t})}function qy(t,e){return new ag({check:"string_format",format:"ends_with",...ne(e),suffix:t})}function ra(t){return new sg({check:"overwrite",tx:t})}function Zy(t){return ra(e=>e.normalize(t))}function Vy(){return ra(t=>t.trim())}function By(){return ra(t=>t.toLowerCase())}function Hy(){return ra(t=>t.toUpperCase())}function Jy(t,e,r){return new t({type:"array",element:e,...ne(r)})}function Wy(t,e,r){const a=ne(r);return a.abort??(a.abort=!0),new t({type:"custom",check:"custom",fn:e,...a})}function Gy(t,e,r){return new t({type:"custom",check:"custom",fn:e,...ne(r)})}class mc{constructor(e){this.counter=0,this.metadataRegistry=(e==null?void 0:e.metadata)??ta,this.target=(e==null?void 0:e.target)??"draft-2020-12",this.unrepresentable=(e==null?void 0:e.unrepresentable)??"throw",this.override=(e==null?void 0:e.override)??(()=>{}),this.io=(e==null?void 0:e.io)??"output",this.seen=new Map}process(e,r={path:[],schemaPath:[]}){var v,m,c;var a;const n=e._zod.def,s={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},o=this.seen.get(e);if(o)return o.count++,r.schemaPath.includes(e)&&(o.cycle=r.path),o.schema;const i={schema:{},count:1,cycle:void 0,path:r.path};this.seen.set(e,i);const l=(m=(v=e._zod).toJSONSchema)==null?void 0:m.call(v);if(l)i.schema=l;else{const h={...r,schemaPath:[...r.schemaPath,e],path:r.path},g=e._zod.parent;if(g)i.ref=g,this.process(g,h),this.seen.get(g).isParent=!0;else{const f=i.schema;switch(n.type){case"string":{const p=f;p.type="string";const{minimum:b,maximum:y,format:_,patterns:S,contentEncoding:T}=e._zod.bag;if(typeof b=="number"&&(p.minLength=b),typeof y=="number"&&(p.maxLength=y),_&&(p.format=s[_]??_,p.format===""&&delete p.format),T&&(p.contentEncoding=T),S&&S.size>0){const I=[...S];I.length===1?p.pattern=I[0].source:I.length>1&&(i.schema.allOf=[...I.map(O=>({...this.target==="draft-7"?{type:"string"}:{},pattern:O.source}))])}break}case"number":{const p=f,{minimum:b,maximum:y,format:_,multipleOf:S,exclusiveMaximum:T,exclusiveMinimum:I}=e._zod.bag;typeof _=="string"&&_.includes("int")?p.type="integer":p.type="number",typeof I=="number"&&(p.exclusiveMinimum=I),typeof b=="number"&&(p.minimum=b,typeof I=="number"&&(I>=b?delete p.minimum:delete p.exclusiveMinimum)),typeof T=="number"&&(p.exclusiveMaximum=T),typeof y=="number"&&(p.maximum=y,typeof T=="number"&&(T<=y?delete p.maximum:delete p.exclusiveMaximum)),typeof S=="number"&&(p.multipleOf=S);break}case"boolean":{const p=f;p.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{f.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{f.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{const p=f,{minimum:b,maximum:y}=e._zod.bag;typeof b=="number"&&(p.minItems=b),typeof y=="number"&&(p.maxItems=y),p.type="array",p.items=this.process(n.element,{...h,path:[...h.path,"items"]});break}case"object":{const p=f;p.type="object",p.properties={};const b=n.shape;for(const S in b)p.properties[S]=this.process(b[S],{...h,path:[...h.path,"properties",S]});const y=new Set(Object.keys(b)),_=new Set([...y].filter(S=>{const T=n.shape[S]._zod;return this.io==="input"?T.optin===void 0:T.optout===void 0}));_.size>0&&(p.required=Array.from(_)),((c=n.catchall)==null?void 0:c._zod.def.type)==="never"?p.additionalProperties=!1:n.catchall?n.catchall&&(p.additionalProperties=this.process(n.catchall,{...h,path:[...h.path,"additionalProperties"]})):this.io==="output"&&(p.additionalProperties=!1);break}case"union":{const p=f;p.anyOf=n.options.map((b,y)=>this.process(b,{...h,path:[...h.path,"anyOf",y]}));break}case"intersection":{const p=f,b=this.process(n.left,{...h,path:[...h.path,"allOf",0]}),y=this.process(n.right,{...h,path:[...h.path,"allOf",1]}),_=T=>"allOf"in T&&Object.keys(T).length===1,S=[..._(b)?b.allOf:[b],..._(y)?y.allOf:[y]];p.allOf=S;break}case"tuple":{const p=f;p.type="array";const b=n.items.map((S,T)=>this.process(S,{...h,path:[...h.path,"prefixItems",T]}));if(this.target==="draft-2020-12"?p.prefixItems=b:p.items=b,n.rest){const S=this.process(n.rest,{...h,path:[...h.path,"items"]});this.target==="draft-2020-12"?p.items=S:p.additionalItems=S}n.rest&&(p.items=this.process(n.rest,{...h,path:[...h.path,"items"]}));const{minimum:y,maximum:_}=e._zod.bag;typeof y=="number"&&(p.minItems=y),typeof _=="number"&&(p.maxItems=_);break}case"record":{const p=f;p.type="object",p.propertyNames=this.process(n.keyType,{...h,path:[...h.path,"propertyNames"]}),p.additionalProperties=this.process(n.valueType,{...h,path:[...h.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{const p=f,b=Mu(n.entries);b.every(y=>typeof y=="number")&&(p.type="number"),b.every(y=>typeof y=="string")&&(p.type="string"),p.enum=b;break}case"literal":{const p=f,b=[];for(const y of n.values)if(y===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof y=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");b.push(Number(y))}else b.push(y);if(b.length!==0)if(b.length===1){const y=b[0];p.type=y===null?"null":typeof y,p.const=y}else b.every(y=>typeof y=="number")&&(p.type="number"),b.every(y=>typeof y=="string")&&(p.type="string"),b.every(y=>typeof y=="boolean")&&(p.type="string"),b.every(y=>y===null)&&(p.type="null"),p.enum=b;break}case"file":{const p=f,b={type:"string",format:"binary",contentEncoding:"binary"},{minimum:y,maximum:_,mime:S}=e._zod.bag;y!==void 0&&(b.minLength=y),_!==void 0&&(b.maxLength=_),S?S.length===1?(b.contentMediaType=S[0],Object.assign(p,b)):p.anyOf=S.map(T=>({...b,contentMediaType:T})):Object.assign(p,b);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{const p=this.process(n.innerType,h);f.anyOf=[p,{type:"null"}];break}case"nonoptional":{this.process(n.innerType,h),i.ref=n.innerType;break}case"success":{const p=f;p.type="boolean";break}case"default":{this.process(n.innerType,h),i.ref=n.innerType,f.default=JSON.parse(JSON.stringify(n.defaultValue));break}case"prefault":{this.process(n.innerType,h),i.ref=n.innerType,this.io==="input"&&(f._prefault=JSON.parse(JSON.stringify(n.defaultValue)));break}case"catch":{this.process(n.innerType,h),i.ref=n.innerType;let p;try{p=n.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}f.default=p;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{const p=f,b=e._zod.pattern;if(!b)throw new Error("Pattern not found in template literal");p.type="string",p.pattern=b.source;break}case"pipe":{const p=this.io==="input"?n.in._zod.def.type==="transform"?n.out:n.in:n.out;this.process(p,h),i.ref=p;break}case"readonly":{this.process(n.innerType,h),i.ref=n.innerType,f.readOnly=!0;break}case"promise":{this.process(n.innerType,h),i.ref=n.innerType;break}case"optional":{this.process(n.innerType,h),i.ref=n.innerType;break}case"lazy":{const p=e._zod.innerType;this.process(p,h),i.ref=p;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}}}}const u=this.metadataRegistry.get(e);return u&&Object.assign(i.schema,u),this.io==="input"&&ct(e)&&(delete i.schema.examples,delete i.schema.default),this.io==="input"&&i.schema._prefault&&((a=i.schema).default??(a.default=i.schema._prefault)),delete i.schema._prefault,this.seen.get(e).schema}emit(e,r){var d,v,m,c,h,g;const a={cycles:(r==null?void 0:r.cycles)??"ref",reused:(r==null?void 0:r.reused)??"inline",external:(r==null?void 0:r.external)??void 0},n=this.seen.get(e);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const s=f=>{var S;const p=this.target==="draft-2020-12"?"$defs":"definitions";if(a.external){const T=(S=a.external.registry.get(f[0]))==null?void 0:S.id,I=a.external.uri??(R=>R);if(T)return{ref:I(T)};const O=f[1].defId??f[1].schema.id??`schema${this.counter++}`;return f[1].defId=O,{defId:O,ref:`${I("__shared")}#/${p}/${O}`}}if(f[1]===n)return{ref:"#"};const y=`#/${p}/`,_=f[1].schema.id??`__schema${this.counter++}`;return{defId:_,ref:y+_}},o=f=>{if(f[1].schema.$ref)return;const p=f[1],{ref:b,defId:y}=s(f);p.def={...p.schema},y&&(p.defId=y);const _=p.schema;for(const S in _)delete _[S];_.$ref=b};if(a.cycles==="throw")for(const f of this.seen.entries()){const p=f[1];if(p.cycle)throw new Error(`Cycle detected: #/${(d=p.cycle)==null?void 0:d.join("/")}/<root>
31
+ path: iss.path ? [${jr(w)}, ...iss.path] : [${jr(w)}]
32
+ })));`),_.write(`newResult[${jr(w)}] = ${y}.value`)}_.write("payload.value = newResult;"),_.write("return payload;");const d=_.compile();return(w,y)=>d(h,w,y)};let o;const s=Lo,i=!_u.jitless,l=i&&Dm.value,c=t.catchall;let u;e._zod.parse=(h,_)=>{u??(u=n.value);const f=h.value;if(!s(f))return h.issues.push({expected:"object",code:"invalid_type",input:f,inst:e}),h;const g=[];if(i&&l&&(_==null?void 0:_.async)===!1&&_.jitless!==!0)o||(o=r(t.shape)),h=o(h,_);else{h.value={};const y=u.shape;for(const b of u.keys){const k=y[b],x=k._zod.run({value:f[b],issues:[]},_),T=k._zod.optin==="optional"&&k._zod.optout==="optional";x instanceof Promise?g.push(x.then(D=>T?ju(D,h,b,f):Uo(D,h,b))):T?ju(x,h,b,f):Uo(x,h,b)}}if(!c)return g.length?Promise.all(g).then(()=>h):h;const v=[],m=u.keySet,d=c._zod,w=d.def.type;for(const y of Object.keys(f)){if(m.has(y))continue;if(w==="never"){v.push(y);continue}const b=d.run({value:f[y],issues:[]},_);b instanceof Promise?g.push(b.then(k=>Uo(k,h,y))):Uo(b,h,y)}return v.length&&h.issues.push({code:"unrecognized_keys",keys:v,input:f,inst:e}),g.length?Promise.all(g).then(()=>h):h}});function zu(e,t,n,r){for(const o of e)if(o.issues.length===0)return t.value=o.value,t;return t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(o=>o.issues.map(s=>bn(s,r,wn())))}),t}const Du=A("$ZodUnion",(e,t)=>{Te.init(e,t),be(e._zod,"optin",()=>t.options.some(n=>n._zod.optin==="optional")?"optional":void 0),be(e._zod,"optout",()=>t.options.some(n=>n._zod.optout==="optional")?"optional":void 0),be(e._zod,"values",()=>{if(t.options.every(n=>n._zod.values))return new Set(t.options.flatMap(n=>Array.from(n._zod.values)))}),be(e._zod,"pattern",()=>{if(t.options.every(n=>n._zod.pattern)){const n=t.options.map(r=>r._zod.pattern);return new RegExp(`^(${n.map(r=>$i(r.source)).join("|")})$`)}}),e._zod.parse=(n,r)=>{let o=!1;const s=[];for(const i of t.options){const a=i._zod.run({value:n.value,issues:[]},r);if(a instanceof Promise)s.push(a),o=!0;else{if(a.issues.length===0)return a;s.push(a)}}return o?Promise.all(s).then(i=>zu(i,n,e,r)):zu(s,n,e,r)}}),bg=A("$ZodDiscriminatedUnion",(e,t)=>{Du.init(e,t);const n=e._zod.parse;be(e._zod,"propValues",()=>{const o={};for(const s of t.options){const i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(const[a,l]of Object.entries(i)){o[a]||(o[a]=new Set);for(const c of l)o[a].add(c)}}return o});const r=wi(()=>{const o=t.options,s=new Map;for(const i of o){const a=i._zod.propValues[t.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(i)}"`);for(const l of a){if(s.has(l))throw new Error(`Duplicate discriminator value "${String(l)}"`);s.set(l,i)}}return s});e._zod.parse=(o,s)=>{const i=o.value;if(!Lo(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:e}),o;const a=r.value.get(i==null?void 0:i[t.discriminator]);return a?a._zod.run(o,s):t.unionFallback?n(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:i,path:[t.discriminator],inst:e}),o)}}),$g=A("$ZodIntersection",(e,t)=>{Te.init(e,t),e._zod.parse=(n,r)=>{const o=n.value,s=t.left._zod.run({value:o,issues:[]},r),i=t.right._zod.run({value:o,issues:[]},r);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([l,c])=>Uu(n,l,c)):Uu(n,s,i)}});function Ei(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(jo(e)&&jo(t)){const n=Object.keys(t),r=Object.keys(e).filter(s=>n.indexOf(s)!==-1),o={...e,...t};for(const s of r){const i=Ei(e[s],t[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};o[s]=i.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;r<e.length;r++){const o=e[r],s=t[r],i=Ei(o,s);if(!i.valid)return{valid:!1,mergeErrorPath:[r,...i.mergeErrorPath]};n.push(i.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function Uu(e,t,n){if(t.issues.length&&e.issues.push(...t.issues),n.issues.length&&e.issues.push(...n.issues),Dr(e))return e;const r=Ei(t.value,n.value);if(!r.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(r.mergeErrorPath)}`);return e.value=r.data,e}const Sg=A("$ZodRecord",(e,t)=>{Te.init(e,t),e._zod.parse=(n,r)=>{const o=n.value;if(!jo(o))return n.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),n;const s=[];if(t.keyType._zod.values){const i=t.keyType._zod.values;n.value={};for(const l of i)if(typeof l=="string"||typeof l=="number"||typeof l=="symbol"){const c=t.valueType._zod.run({value:o[l],issues:[]},r);c instanceof Promise?s.push(c.then(u=>{u.issues.length&&n.issues.push(...jn(l,u.issues)),n.value[l]=u.value})):(c.issues.length&&n.issues.push(...jn(l,c.issues)),n.value[l]=c.value)}let a;for(const l in o)i.has(l)||(a=a??[],a.push(l));a&&a.length>0&&n.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:a})}else{n.value={};for(const i of Reflect.ownKeys(o)){if(i==="__proto__")continue;const a=t.keyType._zod.run({value:i,issues:[]},r);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){n.issues.push({origin:"record",code:"invalid_key",issues:a.issues.map(c=>bn(c,r,wn())),input:i,path:[i],inst:e}),n.value[a.value]=a.value;continue}const l=t.valueType._zod.run({value:o[i],issues:[]},r);l instanceof Promise?s.push(l.then(c=>{c.issues.length&&n.issues.push(...jn(i,c.issues)),n.value[a.value]=c.value})):(l.issues.length&&n.issues.push(...jn(i,l.issues)),n.value[a.value]=l.value)}}return s.length?Promise.all(s).then(()=>n):n}}),Cg=A("$ZodEnum",(e,t)=>{Te.init(e,t);const n=yu(t.entries);e._zod.values=new Set(n),e._zod.pattern=new RegExp(`^(${n.filter(r=>Um.has(typeof r)).map(r=>typeof r=="string"?zr(r):r.toString()).join("|")})$`),e._zod.parse=(r,o)=>{const s=r.value;return e._zod.values.has(s)||r.issues.push({code:"invalid_value",values:n,input:s,inst:e}),r}}),Eg=A("$ZodLiteral",(e,t)=>{Te.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map(n=>typeof n=="string"?zr(n):n?n.toString():String(n)).join("|")})$`),e._zod.parse=(n,r)=>{const o=n.value;return e._zod.values.has(o)||n.issues.push({code:"invalid_value",values:t.values,input:o,inst:e}),n}}),kg=A("$ZodTransform",(e,t)=>{Te.init(e,t),e._zod.parse=(n,r)=>{const o=t.transform(n.value,n);if(r.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(n.value=i,n));if(o instanceof Promise)throw new Lr;return n.value=o,n}}),Ig=A("$ZodOptional",(e,t)=>{Te.init(e,t),e._zod.optin="optional",e._zod.optout="optional",be(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),be(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${$i(n.source)})?$`):void 0}),e._zod.parse=(n,r)=>t.innerType._zod.optin==="optional"?t.innerType._zod.run(n,r):n.value===void 0?n:t.innerType._zod.run(n,r)}),Tg=A("$ZodNullable",(e,t)=>{Te.init(e,t),be(e._zod,"optin",()=>t.innerType._zod.optin),be(e._zod,"optout",()=>t.innerType._zod.optout),be(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${$i(n.source)}|null)$`):void 0}),be(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(n,r)=>n.value===null?n:t.innerType._zod.run(n,r)}),xg=A("$ZodDefault",(e,t)=>{Te.init(e,t),e._zod.optin="optional",be(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(n.value===void 0)return n.value=t.defaultValue,n;const o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>qu(s,t)):qu(o,t)}});function qu(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const Pg=A("$ZodPrefault",(e,t)=>{Te.init(e,t),e._zod.optin="optional",be(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>(n.value===void 0&&(n.value=t.defaultValue),t.innerType._zod.run(n,r))}),Rg=A("$ZodNonOptional",(e,t)=>{Te.init(e,t),be(e._zod,"values",()=>{const n=t.innerType._zod.values;return n?new Set([...n].filter(r=>r!==void 0)):void 0}),e._zod.parse=(n,r)=>{const o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>Zu(s,e)):Zu(o,e)}});function Zu(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const Og=A("$ZodCatch",(e,t)=>{Te.init(e,t),e._zod.optin="optional",be(e._zod,"optout",()=>t.innerType._zod.optout),be(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{const o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>(n.value=s.value,s.issues.length&&(n.value=t.catchValue({...n,error:{issues:s.issues.map(i=>bn(i,r,wn()))},input:n.value}),n.issues=[]),n)):(n.value=o.value,o.issues.length&&(n.value=t.catchValue({...n,error:{issues:o.issues.map(s=>bn(s,r,wn()))},input:n.value}),n.issues=[]),n)}}),Ng=A("$ZodPipe",(e,t)=>{Te.init(e,t),be(e._zod,"values",()=>t.in._zod.values),be(e._zod,"optin",()=>t.in._zod.optin),be(e._zod,"optout",()=>t.out._zod.optout),e._zod.parse=(n,r)=>{const o=t.in._zod.run(n,r);return o instanceof Promise?o.then(s=>Fu(s,t,r)):Fu(o,t,r)}});function Fu(e,t,n){return Dr(e)?e:t.out._zod.run({value:e.value,issues:e.issues},n)}const Mg=A("$ZodReadonly",(e,t)=>{Te.init(e,t),be(e._zod,"propValues",()=>t.innerType._zod.propValues),be(e._zod,"values",()=>t.innerType._zod.values),be(e._zod,"optin",()=>t.innerType._zod.optin),be(e._zod,"optout",()=>t.innerType._zod.optout),e._zod.parse=(n,r)=>{const o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(Vu):Vu(o)}});function Vu(e){return e.value=Object.freeze(e.value),e}const Ag=A("$ZodLazy",(e,t)=>{Te.init(e,t),be(e._zod,"innerType",()=>t.getter()),be(e._zod,"pattern",()=>e._zod.innerType._zod.pattern),be(e._zod,"propValues",()=>e._zod.innerType._zod.propValues),be(e._zod,"optin",()=>e._zod.innerType._zod.optin),be(e._zod,"optout",()=>e._zod.innerType._zod.optout),e._zod.parse=(n,r)=>e._zod.innerType._zod.run(n,r)}),Lg=A("$ZodCustom",(e,t)=>{ut.init(e,t),Te.init(e,t),e._zod.parse=(n,r)=>n,e._zod.check=n=>{const r=n.value,o=t.fn(r);if(o instanceof Promise)return o.then(s=>Bu(s,n,r,e));Bu(o,n,r,e)}});function Bu(e,t,n,r){if(!e){const o={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(o.params=r._zod.def.params),t.issues.push(Ur(o))}}class Hu{constructor(){this._map=new Map,this._idmap=new Map}add(t,...n){const r=n[0];if(this._map.set(t,r),r&&typeof r=="object"&&"id"in r){if(this._idmap.has(r.id))throw new Error(`ID ${r.id} already exists in the registry`);this._idmap.set(r.id,t)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(t){const n=this._map.get(t);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(t),this}get(t){const n=t._zod.parent;if(n){const r={...this.get(n)??{}};return delete r.id,{...r,...this._map.get(t)}}return this._map.get(t)}has(t){return this._map.has(t)}}function jg(){return new Hu}const qr=jg();function zg(e,t){return new e({type:"string",...W(t)})}function Dg(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...W(t)})}function Ju(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...W(t)})}function Ug(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...W(t)})}function qg(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...W(t)})}function Zg(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...W(t)})}function Fg(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...W(t)})}function Gu(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...W(t)})}function Vg(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...W(t)})}function Bg(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...W(t)})}function Hg(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...W(t)})}function Jg(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...W(t)})}function Gg(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...W(t)})}function Wg(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...W(t)})}function Kg(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...W(t)})}function Yg(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...W(t)})}function Qg(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...W(t)})}function Xg(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...W(t)})}function ev(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...W(t)})}function Wu(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...W(t)})}function tv(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...W(t)})}function nv(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...W(t)})}function rv(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...W(t)})}function ov(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...W(t)})}function sv(e,t){return new e({type:"string",format:"date",check:"string_format",...W(t)})}function iv(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...W(t)})}function av(e,t){return new e({type:"string",format:"duration",check:"string_format",...W(t)})}function lv(e,t){return new e({type:"number",checks:[],...W(t)})}function cv(e,t){return new e({type:"number",coerce:!0,checks:[],...W(t)})}function uv(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...W(t)})}function dv(e,t){return new e({type:"boolean",...W(t)})}function pv(e,t){return new e({type:"null",...W(t)})}function fv(e){return new e({type:"any"})}function hv(e){return new e({type:"unknown"})}function mv(e,t){return new e({type:"never",...W(t)})}function Ku(e,t){return new Ou({check:"less_than",...W(t),value:e,inclusive:!1})}function ki(e,t){return new Ou({check:"less_than",...W(t),value:e,inclusive:!0})}function Yu(e,t){return new Nu({check:"greater_than",...W(t),value:e,inclusive:!1})}function Ii(e,t){return new Nu({check:"greater_than",...W(t),value:e,inclusive:!0})}function Qu(e,t){return new T1({check:"multiple_of",...W(t),value:e})}function Xu(e,t){return new P1({check:"max_length",...W(t),maximum:e})}function qo(e,t){return new R1({check:"min_length",...W(t),minimum:e})}function ed(e,t){return new O1({check:"length_equals",...W(t),length:e})}function gv(e,t){return new N1({check:"string_format",format:"regex",...W(t),pattern:e})}function vv(e){return new M1({check:"string_format",format:"lowercase",...W(e)})}function _v(e){return new A1({check:"string_format",format:"uppercase",...W(e)})}function yv(e,t){return new L1({check:"string_format",format:"includes",...W(t),includes:e})}function wv(e,t){return new j1({check:"string_format",format:"starts_with",...W(t),prefix:e})}function bv(e,t){return new z1({check:"string_format",format:"ends_with",...W(t),suffix:e})}function Zr(e){return new D1({check:"overwrite",tx:e})}function $v(e){return Zr(t=>t.normalize(e))}function Sv(){return Zr(e=>e.trim())}function Cv(){return Zr(e=>e.toLowerCase())}function Ev(){return Zr(e=>e.toUpperCase())}function kv(e,t,n){return new e({type:"array",element:t,...W(n)})}function Iv(e,t,n){const r=W(n);return r.abort??(r.abort=!0),new e({type:"custom",check:"custom",fn:t,...r})}function Tv(e,t,n){return new e({type:"custom",check:"custom",fn:t,...W(n)})}class td{constructor(t){this.counter=0,this.metadataRegistry=(t==null?void 0:t.metadata)??qr,this.target=(t==null?void 0:t.target)??"draft-2020-12",this.unrepresentable=(t==null?void 0:t.unrepresentable)??"throw",this.override=(t==null?void 0:t.override)??(()=>{}),this.io=(t==null?void 0:t.io)??"output",this.seen=new Map}process(t,n={path:[],schemaPath:[]}){var h,_,f;var r;const o=t._zod.def,s={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},i=this.seen.get(t);if(i)return i.count++,n.schemaPath.includes(t)&&(i.cycle=n.path),i.schema;const a={schema:{},count:1,cycle:void 0,path:n.path};this.seen.set(t,a);const l=(_=(h=t._zod).toJSONSchema)==null?void 0:_.call(h);if(l)a.schema=l;else{const g={...n,schemaPath:[...n.schemaPath,t],path:n.path},v=t._zod.parent;if(v)a.ref=v,this.process(v,g),this.seen.get(v).isParent=!0;else{const m=a.schema;switch(o.type){case"string":{const d=m;d.type="string";const{minimum:w,maximum:y,format:b,patterns:k,contentEncoding:x}=t._zod.bag;if(typeof w=="number"&&(d.minLength=w),typeof y=="number"&&(d.maxLength=y),b&&(d.format=s[b]??b,d.format===""&&delete d.format),x&&(d.contentEncoding=x),k&&k.size>0){const T=[...k];T.length===1?d.pattern=T[0].source:T.length>1&&(a.schema.allOf=[...T.map(D=>({...this.target==="draft-7"?{type:"string"}:{},pattern:D.source}))])}break}case"number":{const d=m,{minimum:w,maximum:y,format:b,multipleOf:k,exclusiveMaximum:x,exclusiveMinimum:T}=t._zod.bag;typeof b=="string"&&b.includes("int")?d.type="integer":d.type="number",typeof T=="number"&&(d.exclusiveMinimum=T),typeof w=="number"&&(d.minimum=w,typeof T=="number"&&(T>=w?delete d.minimum:delete d.exclusiveMinimum)),typeof x=="number"&&(d.exclusiveMaximum=x),typeof y=="number"&&(d.maximum=y,typeof x=="number"&&(x<=y?delete d.maximum:delete d.exclusiveMaximum)),typeof k=="number"&&(d.multipleOf=k);break}case"boolean":{const d=m;d.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{m.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{m.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{const d=m,{minimum:w,maximum:y}=t._zod.bag;typeof w=="number"&&(d.minItems=w),typeof y=="number"&&(d.maxItems=y),d.type="array",d.items=this.process(o.element,{...g,path:[...g.path,"items"]});break}case"object":{const d=m;d.type="object",d.properties={};const w=o.shape;for(const k in w)d.properties[k]=this.process(w[k],{...g,path:[...g.path,"properties",k]});const y=new Set(Object.keys(w)),b=new Set([...y].filter(k=>{const x=o.shape[k]._zod;return this.io==="input"?x.optin===void 0:x.optout===void 0}));b.size>0&&(d.required=Array.from(b)),((f=o.catchall)==null?void 0:f._zod.def.type)==="never"?d.additionalProperties=!1:o.catchall?o.catchall&&(d.additionalProperties=this.process(o.catchall,{...g,path:[...g.path,"additionalProperties"]})):this.io==="output"&&(d.additionalProperties=!1);break}case"union":{const d=m;d.anyOf=o.options.map((w,y)=>this.process(w,{...g,path:[...g.path,"anyOf",y]}));break}case"intersection":{const d=m,w=this.process(o.left,{...g,path:[...g.path,"allOf",0]}),y=this.process(o.right,{...g,path:[...g.path,"allOf",1]}),b=x=>"allOf"in x&&Object.keys(x).length===1,k=[...b(w)?w.allOf:[w],...b(y)?y.allOf:[y]];d.allOf=k;break}case"tuple":{const d=m;d.type="array";const w=o.items.map((k,x)=>this.process(k,{...g,path:[...g.path,"prefixItems",x]}));if(this.target==="draft-2020-12"?d.prefixItems=w:d.items=w,o.rest){const k=this.process(o.rest,{...g,path:[...g.path,"items"]});this.target==="draft-2020-12"?d.items=k:d.additionalItems=k}o.rest&&(d.items=this.process(o.rest,{...g,path:[...g.path,"items"]}));const{minimum:y,maximum:b}=t._zod.bag;typeof y=="number"&&(d.minItems=y),typeof b=="number"&&(d.maxItems=b);break}case"record":{const d=m;d.type="object",d.propertyNames=this.process(o.keyType,{...g,path:[...g.path,"propertyNames"]}),d.additionalProperties=this.process(o.valueType,{...g,path:[...g.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{const d=m,w=yu(o.entries);w.every(y=>typeof y=="number")&&(d.type="number"),w.every(y=>typeof y=="string")&&(d.type="string"),d.enum=w;break}case"literal":{const d=m,w=[];for(const y of o.values)if(y===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof y=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");w.push(Number(y))}else w.push(y);if(w.length!==0)if(w.length===1){const y=w[0];d.type=y===null?"null":typeof y,d.const=y}else w.every(y=>typeof y=="number")&&(d.type="number"),w.every(y=>typeof y=="string")&&(d.type="string"),w.every(y=>typeof y=="boolean")&&(d.type="string"),w.every(y=>y===null)&&(d.type="null"),d.enum=w;break}case"file":{const d=m,w={type:"string",format:"binary",contentEncoding:"binary"},{minimum:y,maximum:b,mime:k}=t._zod.bag;y!==void 0&&(w.minLength=y),b!==void 0&&(w.maxLength=b),k?k.length===1?(w.contentMediaType=k[0],Object.assign(d,w)):d.anyOf=k.map(x=>({...w,contentMediaType:x})):Object.assign(d,w);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{const d=this.process(o.innerType,g);m.anyOf=[d,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,g),a.ref=o.innerType;break}case"success":{const d=m;d.type="boolean";break}case"default":{this.process(o.innerType,g),a.ref=o.innerType,m.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,g),a.ref=o.innerType,this.io==="input"&&(m._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,g),a.ref=o.innerType;let d;try{d=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}m.default=d;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{const d=m,w=t._zod.pattern;if(!w)throw new Error("Pattern not found in template literal");d.type="string",d.pattern=w.source;break}case"pipe":{const d=this.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;this.process(d,g),a.ref=d;break}case"readonly":{this.process(o.innerType,g),a.ref=o.innerType,m.readOnly=!0;break}case"promise":{this.process(o.innerType,g),a.ref=o.innerType;break}case"optional":{this.process(o.innerType,g),a.ref=o.innerType;break}case"lazy":{const d=t._zod.innerType;this.process(d,g),a.ref=d;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}}}}const c=this.metadataRegistry.get(t);return c&&Object.assign(a.schema,c),this.io==="input"&&De(t)&&(delete a.schema.examples,delete a.schema.default),this.io==="input"&&a.schema._prefault&&((r=a.schema).default??(r.default=a.schema._prefault)),delete a.schema._prefault,this.seen.get(t).schema}emit(t,n){var u,h,_,f,g,v;const r={cycles:(n==null?void 0:n.cycles)??"ref",reused:(n==null?void 0:n.reused)??"inline",external:(n==null?void 0:n.external)??void 0},o=this.seen.get(t);if(!o)throw new Error("Unprocessed schema. This is a bug in Zod.");const s=m=>{var k;const d=this.target==="draft-2020-12"?"$defs":"definitions";if(r.external){const x=(k=r.external.registry.get(m[0]))==null?void 0:k.id,T=r.external.uri??(U=>U);if(x)return{ref:T(x)};const D=m[1].defId??m[1].schema.id??`schema${this.counter++}`;return m[1].defId=D,{defId:D,ref:`${T("__shared")}#/${d}/${D}`}}if(m[1]===o)return{ref:"#"};const y=`#/${d}/`,b=m[1].schema.id??`__schema${this.counter++}`;return{defId:b,ref:y+b}},i=m=>{if(m[1].schema.$ref)return;const d=m[1],{ref:w,defId:y}=s(m);d.def={...d.schema},y&&(d.defId=y);const b=d.schema;for(const k in b)delete b[k];b.$ref=w};if(r.cycles==="throw")for(const m of this.seen.entries()){const d=m[1];if(d.cycle)throw new Error(`Cycle detected: #/${(u=d.cycle)==null?void 0:u.join("/")}/<root>
33
33
 
34
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const f of this.seen.entries()){const p=f[1];if(e===f[0]){o(f);continue}if(a.external){const y=(v=a.external.registry.get(f[0]))==null?void 0:v.id;if(e!==f[0]&&y){o(f);continue}}if((m=this.metadataRegistry.get(f[0]))==null?void 0:m.id){o(f);continue}if(p.cycle){o(f);continue}if(p.count>1&&a.reused==="ref"){o(f);continue}}const i=(f,p)=>{const b=this.seen.get(f),y=b.def??b.schema,_={...y};if(b.ref===null)return;const S=b.ref;if(b.ref=null,S){i(S,p);const T=this.seen.get(S).schema;T.$ref&&p.target==="draft-7"?(y.allOf=y.allOf??[],y.allOf.push(T)):(Object.assign(y,T),Object.assign(y,_))}b.isParent||this.override({zodSchema:f,jsonSchema:y,path:b.path??[]})};for(const f of[...this.seen.entries()].reverse())i(f[0],{target:this.target});const l={};if(this.target==="draft-2020-12"?l.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?l.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),(c=a.external)!=null&&c.uri){const f=(h=a.external.registry.get(e))==null?void 0:h.id;if(!f)throw new Error("Schema is missing an `id` property");l.$id=a.external.uri(f)}Object.assign(l,n.def);const u=((g=a.external)==null?void 0:g.defs)??{};for(const f of this.seen.entries()){const p=f[1];p.def&&p.defId&&(u[p.defId]=p.def)}a.external||Object.keys(u).length>0&&(this.target==="draft-2020-12"?l.$defs=u:l.definitions=u);try{return JSON.parse(JSON.stringify(l))}catch{throw new Error("Error converting schema to JSON.")}}}function Ky(t,e){if(t instanceof ic){const a=new mc(e),n={};for(const i of t._idmap.entries()){const[l,u]=i;a.process(u)}const s={},o={registry:t,uri:e==null?void 0:e.uri,defs:n};for(const i of t._idmap.entries()){const[l,u]=i;s[l]=a.emit(u,{...e,external:o})}if(Object.keys(n).length>0){const i=a.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[i]:n}}return{schemas:s}}const r=new mc(e);return r.process(t),r.emit(t,e)}function ct(t,e){const r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);const n=t._zod.def;switch(n.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return ct(n.element,r);case"object":{for(const s in n.shape)if(ct(n.shape[s],r))return!0;return!1}case"union":{for(const s of n.options)if(ct(s,r))return!0;return!1}case"intersection":return ct(n.left,r)||ct(n.right,r);case"tuple":{for(const s of n.items)if(ct(s,r))return!0;return!!(n.rest&&ct(n.rest,r))}case"record":return ct(n.keyType,r)||ct(n.valueType,r);case"map":return ct(n.keyType,r)||ct(n.valueType,r);case"set":return ct(n.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return ct(n.innerType,r);case"lazy":return ct(n.getter(),r);case"default":return ct(n.innerType,r);case"prefault":return ct(n.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return ct(n.in,r)||ct(n.out,r);case"success":return!1;case"catch":return!1}throw new Error(`Unknown schema type: ${n.type}`)}const Qy=z("ZodISODateTime",(t,e)=>{_g.init(t,e),Ye.init(t,e)});function Yy(t){return Iy(Qy,t)}const Xy=z("ZodISODate",(t,e)=>{wg.init(t,e),Ye.init(t,e)});function e_(t){return ky(Xy,t)}const t_=z("ZodISOTime",(t,e)=>{bg.init(t,e),Ye.init(t,e)});function r_(t){return Ty(t_,t)}const n_=z("ZodISODuration",(t,e)=>{xg.init(t,e),Ye.init(t,e)});function a_(t){return Py(n_,t)}const Qa=z("ZodError",(t,e)=>{zu.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>mv(t,r)},flatten:{value:r=>fv(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},{Parent:Error}),s_=vv(Qa),o_=gv(Qa),i_=Uu(Qa),vc=Fu(Qa),Ve=z("ZodType",(t,e)=>(Fe.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(a=>typeof a=="function"?{_zod:{check:a,def:{check:"custom"},onattach:[]}}:a)]}),t.clone=(r,a)=>Qr(t,r,a),t.brand=()=>t,t.register=(r,a)=>(r.add(t,a),t),t.parse=(r,a)=>s_(t,r,a,{callee:t.parse}),t.safeParse=(r,a)=>i_(t,r,a),t.parseAsync=async(r,a)=>o_(t,r,a,{callee:t.parseAsync}),t.safeParseAsync=async(r,a)=>vc(t,r,a),t.spa=t.safeParseAsync,t.refine=(r,a)=>t.check(t0(r,a)),t.superRefine=r=>t.check(r0(r)),t.overwrite=r=>t.check(ra(r)),t.optional=()=>it(t),t.nullable=()=>Ic(t),t.nullish=()=>it(Ic(t)),t.nonoptional=r=>H_(t,r),t.array=()=>K(t),t.or=r=>Ne([t,r]),t.and=r=>D_(t,r),t.transform=r=>Tc(t,U_(r)),t.default=r=>Z_(t,r),t.prefault=r=>B_(t,r),t.catch=r=>W_(t,r),t.pipe=r=>Tc(t,r),t.readonly=()=>Q_(t),t.describe=r=>{const a=t.clone();return ta.add(a,{description:r}),a},Object.defineProperty(t,"description",{get(){var r;return(r=ta.get(t))==null?void 0:r.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return ta.get(t);const a=t.clone();return ta.add(a,r[0]),a},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),gc=z("_ZodString",(t,e)=>{To.init(t,e),Ve.init(t,e);const r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,t.regex=(...a)=>t.check(jy(...a)),t.includes=(...a)=>t.check(Uy(...a)),t.startsWith=(...a)=>t.check(Fy(...a)),t.endsWith=(...a)=>t.check(qy(...a)),t.min=(...a)=>t.check(Ka(...a)),t.max=(...a)=>t.check(hc(...a)),t.length=(...a)=>t.check(fc(...a)),t.nonempty=(...a)=>t.check(Ka(1,...a)),t.lowercase=a=>t.check(zy(a)),t.uppercase=a=>t.check(Ly(a)),t.trim=()=>t.check(Vy()),t.normalize=(...a)=>t.check(Zy(...a)),t.toLowerCase=()=>t.check(By()),t.toUpperCase=()=>t.check(Hy())}),l_=z("ZodString",(t,e)=>{To.init(t,e),gc.init(t,e),t.email=r=>t.check(sy(u_,r)),t.url=r=>t.check(cy(c_,r)),t.jwt=r=>t.check(Sy(S_,r)),t.emoji=r=>t.check(dy(d_,r)),t.guid=r=>t.check(lc(yc,r)),t.uuid=r=>t.check(oy(Ya,r)),t.uuidv4=r=>t.check(iy(Ya,r)),t.uuidv6=r=>t.check(ly(Ya,r)),t.uuidv7=r=>t.check(uy(Ya,r)),t.nanoid=r=>t.check(py(p_,r)),t.guid=r=>t.check(lc(yc,r)),t.cuid=r=>t.check(hy(h_,r)),t.cuid2=r=>t.check(fy(f_,r)),t.ulid=r=>t.check(my(m_,r)),t.base64=r=>t.check(uc(_c,r)),t.base64url=r=>t.check(xy(x_,r)),t.xid=r=>t.check(vy(v_,r)),t.ksuid=r=>t.check(gy(g_,r)),t.ipv4=r=>t.check(yy(y_,r)),t.ipv6=r=>t.check(_y(__,r)),t.cidrv4=r=>t.check(wy(w_,r)),t.cidrv6=r=>t.check(by(b_,r)),t.e164=r=>t.check(Ey(E_,r)),t.datetime=r=>t.check(Yy(r)),t.date=r=>t.check(e_(r)),t.time=r=>t.check(r_(r)),t.duration=r=>t.check(a_(r))});function w(t){return ay(l_,t)}const Ye=z("ZodStringFormat",(t,e)=>{Je.init(t,e),gc.init(t,e)}),u_=z("ZodEmail",(t,e)=>{cg.init(t,e),Ye.init(t,e)}),yc=z("ZodGUID",(t,e)=>{lg.init(t,e),Ye.init(t,e)}),Ya=z("ZodUUID",(t,e)=>{ug.init(t,e),Ye.init(t,e)}),c_=z("ZodURL",(t,e)=>{dg.init(t,e),Ye.init(t,e)}),d_=z("ZodEmoji",(t,e)=>{pg.init(t,e),Ye.init(t,e)}),p_=z("ZodNanoID",(t,e)=>{hg.init(t,e),Ye.init(t,e)}),h_=z("ZodCUID",(t,e)=>{fg.init(t,e),Ye.init(t,e)}),f_=z("ZodCUID2",(t,e)=>{mg.init(t,e),Ye.init(t,e)}),m_=z("ZodULID",(t,e)=>{vg.init(t,e),Ye.init(t,e)}),v_=z("ZodXID",(t,e)=>{gg.init(t,e),Ye.init(t,e)}),g_=z("ZodKSUID",(t,e)=>{yg.init(t,e),Ye.init(t,e)}),y_=z("ZodIPv4",(t,e)=>{Eg.init(t,e),Ye.init(t,e)}),__=z("ZodIPv6",(t,e)=>{Sg.init(t,e),Ye.init(t,e)}),w_=z("ZodCIDRv4",(t,e)=>{Ig.init(t,e),Ye.init(t,e)}),b_=z("ZodCIDRv6",(t,e)=>{kg.init(t,e),Ye.init(t,e)}),_c=z("ZodBase64",(t,e)=>{Tg.init(t,e),Ye.init(t,e)});function wc(t){return uc(_c,t)}const x_=z("ZodBase64URL",(t,e)=>{Cg.init(t,e),Ye.init(t,e)}),E_=z("ZodE164",(t,e)=>{Rg.init(t,e),Ye.init(t,e)}),S_=z("ZodJWT",(t,e)=>{$g.init(t,e),Ye.init(t,e)}),Oo=z("ZodNumber",(t,e)=>{Ku.init(t,e),Ve.init(t,e),t.gt=(a,n)=>t.check(dc(a,n)),t.gte=(a,n)=>t.check(Ro(a,n)),t.min=(a,n)=>t.check(Ro(a,n)),t.lt=(a,n)=>t.check(cc(a,n)),t.lte=(a,n)=>t.check(Co(a,n)),t.max=(a,n)=>t.check(Co(a,n)),t.int=a=>t.check(bc(a)),t.safe=a=>t.check(bc(a)),t.positive=a=>t.check(dc(0,a)),t.nonnegative=a=>t.check(Ro(0,a)),t.negative=a=>t.check(cc(0,a)),t.nonpositive=a=>t.check(Co(0,a)),t.multipleOf=(a,n)=>t.check(pc(a,n)),t.step=(a,n)=>t.check(pc(a,n)),t.finite=()=>t;const r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});function D(t){return Cy(Oo,t)}const I_=z("ZodNumberFormat",(t,e)=>{Ag.init(t,e),Oo.init(t,e)});function bc(t){return Oy(I_,t)}const k_=z("ZodBoolean",(t,e)=>{Ng.init(t,e),Ve.init(t,e)});function st(t){return $y(k_,t)}const T_=z("ZodNull",(t,e)=>{Mg.init(t,e),Ve.init(t,e)});function P_(t){return Ay(T_,t)}const C_=z("ZodAny",(t,e)=>{Dg.init(t,e),Ve.init(t,e)});function Ft(){return Ny(C_)}const R_=z("ZodUnknown",(t,e)=>{jg.init(t,e),Ve.init(t,e)});function Xt(){return My(R_)}const O_=z("ZodNever",(t,e)=>{zg.init(t,e),Ve.init(t,e)});function $_(t){return Dy(O_,t)}const A_=z("ZodArray",(t,e)=>{Lg.init(t,e),Ve.init(t,e),t.element=e.element,t.min=(r,a)=>t.check(Ka(r,a)),t.nonempty=r=>t.check(Ka(1,r)),t.max=(r,a)=>t.check(hc(r,a)),t.length=(r,a)=>t.check(fc(r,a)),t.unwrap=()=>t.element});function K(t,e){return Jy(A_,t,e)}const xc=z("ZodObject",(t,e)=>{Ug.init(t,e),Ve.init(t,e),je(t,"shape",()=>e.shape),t.keyof=()=>Xe(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:Xt()}),t.loose=()=>t.clone({...t._zod.def,catchall:Xt()}),t.strict=()=>t.clone({...t._zod.def,catchall:$_()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>cv(t,r),t.merge=r=>dv(t,r),t.pick=r=>lv(t,r),t.omit=r=>uv(t,r),t.partial=(...r)=>pv(Sc,t,r[0]),t.required=(...r)=>hv(kc,t,r[0])});function E(t,e){const r={type:"object",get shape(){return Va(this,"shape",{...t}),this.shape},...ne(e)};return new xc(r)}function Sn(t,e){return new xc({type:"object",get shape(){return Va(this,"shape",{...t}),this.shape},catchall:Xt(),...ne(e)})}const Ec=z("ZodUnion",(t,e)=>{ec.init(t,e),Ve.init(t,e),t.options=e.options});function Ne(t,e){return new Ec({type:"union",options:t,...ne(e)})}const N_=z("ZodDiscriminatedUnion",(t,e)=>{Ec.init(t,e),Fg.init(t,e)});function Rt(t,e,r){return new N_({type:"union",options:e,discriminator:t,...ne(r)})}const M_=z("ZodIntersection",(t,e)=>{qg.init(t,e),Ve.init(t,e)});function D_(t,e){return new M_({type:"intersection",left:t,right:e})}const j_=z("ZodRecord",(t,e)=>{Zg.init(t,e),Ve.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});function ot(t,e,r){return new j_({type:"record",keyType:t,valueType:e,...ne(r)})}const $o=z("ZodEnum",(t,e)=>{Vg.init(t,e),Ve.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);const r=new Set(Object.keys(e.entries));t.extract=(a,n)=>{const s={};for(const o of a)if(r.has(o))s[o]=e.entries[o];else throw new Error(`Key ${o} not found in enum`);return new $o({...e,checks:[],...ne(n),entries:s})},t.exclude=(a,n)=>{const s={...e.entries};for(const o of a)if(r.has(o))delete s[o];else throw new Error(`Key ${o} not found in enum`);return new $o({...e,checks:[],...ne(n),entries:s})}});function Xe(t,e){const r=Array.isArray(t)?Object.fromEntries(t.map(a=>[a,a])):t;return new $o({type:"enum",entries:r,...ne(e)})}const z_=z("ZodLiteral",(t,e)=>{Bg.init(t,e),Ve.init(t,e),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function q(t,e){return new z_({type:"literal",values:Array.isArray(t)?t:[t],...ne(e)})}const L_=z("ZodTransform",(t,e)=>{Hg.init(t,e),Ve.init(t,e),t._zod.parse=(r,a)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(ea(s,r.value,e));else{const o=s;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=t),o.continue??(o.continue=!0),r.issues.push(ea(o))}};const n=e.transform(r.value,r);return n instanceof Promise?n.then(s=>(r.value=s,r)):(r.value=n,r)}});function U_(t){return new L_({type:"transform",transform:t})}const Sc=z("ZodOptional",(t,e)=>{Jg.init(t,e),Ve.init(t,e),t.unwrap=()=>t._zod.def.innerType});function it(t){return new Sc({type:"optional",innerType:t})}const F_=z("ZodNullable",(t,e)=>{Wg.init(t,e),Ve.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Ic(t){return new F_({type:"nullable",innerType:t})}const q_=z("ZodDefault",(t,e)=>{Gg.init(t,e),Ve.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function Z_(t,e){return new q_({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}const V_=z("ZodPrefault",(t,e)=>{Kg.init(t,e),Ve.init(t,e),t.unwrap=()=>t._zod.def.innerType});function B_(t,e){return new V_({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}const kc=z("ZodNonOptional",(t,e)=>{Qg.init(t,e),Ve.init(t,e),t.unwrap=()=>t._zod.def.innerType});function H_(t,e){return new kc({type:"nonoptional",innerType:t,...ne(e)})}const J_=z("ZodCatch",(t,e)=>{Yg.init(t,e),Ve.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function W_(t,e){return new J_({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}const G_=z("ZodPipe",(t,e)=>{Xg.init(t,e),Ve.init(t,e),t.in=e.in,t.out=e.out});function Tc(t,e){return new G_({type:"pipe",in:t,out:e})}const K_=z("ZodReadonly",(t,e)=>{ey.init(t,e),Ve.init(t,e)});function Q_(t){return new K_({type:"readonly",innerType:t})}const Y_=z("ZodLazy",(t,e)=>{ty.init(t,e),Ve.init(t,e),t.unwrap=()=>t._zod.def.getter()});function Pc(t){return new Y_({type:"lazy",getter:t})}const Ao=z("ZodCustom",(t,e)=>{ry.init(t,e),Ve.init(t,e)});function X_(t){const e=new Ct({check:"custom"});return e._zod.check=t,e}function e0(t,e){return Wy(Ao,t??(()=>!0),e)}function t0(t,e={}){return Gy(Ao,t,e)}function r0(t){const e=X_(r=>(r.addIssue=a=>{if(typeof a=="string")r.issues.push(ea(a,r.value,e._zod.def));else{const n=a;n.fatal&&(n.continue=!1),n.code??(n.code="custom"),n.input??(n.input=r.value),n.inst??(n.inst=e),n.continue??(n.continue=!e._zod.def.abort),r.issues.push(ea(n))}},t(r.value,r)));return e}function Xa(t,e={error:`Input not instance of ${t.name}`}){const r=new Ao({type:"custom",check:"custom",fn:a=>a instanceof t,abort:!0,...ne(e)});return r._zod.bag.Class=t,r}function n0(t){return Ry(Oo,t)}var Ae;(function(t){t.assertEqual=n=>{};function e(n){}t.assertIs=e;function r(n){throw new Error}t.assertNever=r,t.arrayToEnum=n=>{const s={};for(const o of n)s[o]=o;return s},t.getValidEnumValues=n=>{const s=t.objectKeys(n).filter(i=>typeof n[n[i]]!="number"),o={};for(const i of s)o[i]=n[i];return t.objectValues(o)},t.objectValues=n=>t.objectKeys(n).map(function(s){return n[s]}),t.objectKeys=typeof Object.keys=="function"?n=>Object.keys(n):n=>{const s=[];for(const o in n)Object.prototype.hasOwnProperty.call(n,o)&&s.push(o);return s},t.find=(n,s)=>{for(const o of n)if(s(o))return o},t.isInteger=typeof Number.isInteger=="function"?n=>Number.isInteger(n):n=>typeof n=="number"&&Number.isFinite(n)&&Math.floor(n)===n;function a(n,s=" | "){return n.map(o=>typeof o=="string"?`'${o}'`:o).join(s)}t.joinValues=a,t.jsonStringifyReplacer=(n,s)=>typeof s=="bigint"?s.toString():s})(Ae||(Ae={}));var Cc;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Cc||(Cc={}));const ee=Ae.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Dr=t=>{switch(typeof t){case"undefined":return ee.undefined;case"string":return ee.string;case"number":return Number.isNaN(t)?ee.nan:ee.number;case"boolean":return ee.boolean;case"function":return ee.function;case"bigint":return ee.bigint;case"symbol":return ee.symbol;case"object":return Array.isArray(t)?ee.array:t===null?ee.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?ee.promise:typeof Map<"u"&&t instanceof Map?ee.map:typeof Set<"u"&&t instanceof Set?ee.set:typeof Date<"u"&&t instanceof Date?ee.date:ee.object;default:return ee.unknown}},B=Ae.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class kr extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=a=>{this.issues=[...this.issues,a]},this.addIssues=(a=[])=>{this.issues=[...this.issues,...a]};const r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){const r=e||function(s){return s.message},a={_errors:[]},n=s=>{for(const o of s.issues)if(o.code==="invalid_union")o.unionErrors.map(n);else if(o.code==="invalid_return_type")n(o.returnTypeError);else if(o.code==="invalid_arguments")n(o.argumentsError);else if(o.path.length===0)a._errors.push(r(o));else{let i=a,l=0;for(;l<o.path.length;){const u=o.path[l];l===o.path.length-1?(i[u]=i[u]||{_errors:[]},i[u]._errors.push(r(o))):i[u]=i[u]||{_errors:[]},i=i[u],l++}}};return n(this),a}static assert(e){if(!(e instanceof kr))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Ae.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){const r={},a=[];for(const n of this.issues)if(n.path.length>0){const s=n.path[0];r[s]=r[s]||[],r[s].push(e(n))}else a.push(e(n));return{formErrors:a,fieldErrors:r}}get formErrors(){return this.flatten()}}kr.create=t=>new kr(t);const No=(t,e)=>{let r;switch(t.code){case B.invalid_type:t.received===ee.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case B.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,Ae.jsonStringifyReplacer)}`;break;case B.unrecognized_keys:r=`Unrecognized key(s) in object: ${Ae.joinValues(t.keys,", ")}`;break;case B.invalid_union:r="Invalid input";break;case B.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Ae.joinValues(t.options)}`;break;case B.invalid_enum_value:r=`Invalid enum value. Expected ${Ae.joinValues(t.options)}, received '${t.received}'`;break;case B.invalid_arguments:r="Invalid function arguments";break;case B.invalid_return_type:r="Invalid function return type";break;case B.invalid_date:r="Invalid date";break;case B.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:Ae.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case B.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case B.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case B.custom:r="Invalid input";break;case B.invalid_intersection_types:r="Intersection results could not be merged";break;case B.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case B.not_finite:r="Number must be finite";break;default:r=e.defaultError,Ae.assertNever(t)}return{message:r}};let a0=No;function s0(){return a0}const o0=t=>{const{data:e,path:r,errorMaps:a,issueData:n}=t,s=[...r,...n.path||[]],o={...n,path:s};if(n.message!==void 0)return{...n,path:s,message:n.message};let i="";const l=a.filter(u=>!!u).slice().reverse();for(const u of l)i=u(o,{data:e,defaultError:i}).message;return{...n,path:s,message:i}};function Q(t,e){const r=s0(),a=o0({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===No?void 0:No].filter(n=>!!n)});t.common.issues.push(a)}class Et{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){const a=[];for(const n of r){if(n.status==="aborted")return he;n.status==="dirty"&&e.dirty(),a.push(n.value)}return{status:e.value,value:a}}static async mergeObjectAsync(e,r){const a=[];for(const n of r){const s=await n.key,o=await n.value;a.push({key:s,value:o})}return Et.mergeObjectSync(e,a)}static mergeObjectSync(e,r){const a={};for(const n of r){const{key:s,value:o}=n;if(s.status==="aborted"||o.status==="aborted")return he;s.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof o.value<"u"||n.alwaysSet)&&(a[s.value]=o.value)}return{status:e.value,value:a}}}const he=Object.freeze({status:"aborted"}),na=t=>({status:"dirty",value:t}),qt=t=>({status:"valid",value:t}),Rc=t=>t.status==="aborted",Oc=t=>t.status==="dirty",In=t=>t.status==="valid",es=t=>typeof Promise<"u"&&t instanceof Promise;var se;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e==null?void 0:e.message})(se||(se={}));class lr{constructor(e,r,a,n){this._cachedPath=[],this.parent=e,this.data=r,this._path=a,this._key=n}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}}const $c=(t,e)=>{if(In(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const r=new kr(t.common.issues);return this._error=r,this._error}}};function we(t){if(!t)return{};const{errorMap:e,invalid_type_error:r,required_error:a,description:n}=t;if(e&&(r||a))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:n}:{errorMap:(o,i)=>{const{message:l}=t;return o.code==="invalid_enum_value"?{message:l??i.defaultError}:typeof i.data>"u"?{message:l??a??i.defaultError}:o.code!=="invalid_type"?{message:i.defaultError}:{message:l??r??i.defaultError}},description:n}}class Re{get description(){return this._def.description}_getType(e){return Dr(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:Dr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Et,ctx:{common:e.parent.common,data:e.data,parsedType:Dr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const r=this._parse(e);if(es(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){const r=this._parse(e);return Promise.resolve(r)}parse(e,r){const a=this.safeParse(e,r);if(a.success)return a.data;throw a.error}safeParse(e,r){const a={common:{issues:[],async:(r==null?void 0:r.async)??!1,contextualErrorMap:r==null?void 0:r.errorMap},path:(r==null?void 0:r.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Dr(e)},n=this._parseSync({data:e,path:a.path,parent:a});return $c(a,n)}"~validate"(e){var a,n;const r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Dr(e)};if(!this["~standard"].async)try{const s=this._parseSync({data:e,path:[],parent:r});return In(s)?{value:s.value}:{issues:r.common.issues}}catch(s){(n=(a=s==null?void 0:s.message)==null?void 0:a.toLowerCase())!=null&&n.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(s=>In(s)?{value:s.value}:{issues:r.common.issues})}async parseAsync(e,r){const a=await this.safeParseAsync(e,r);if(a.success)return a.data;throw a.error}async safeParseAsync(e,r){const a={common:{issues:[],contextualErrorMap:r==null?void 0:r.errorMap,async:!0},path:(r==null?void 0:r.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Dr(e)},n=this._parse({data:e,path:a.path,parent:a}),s=await(es(n)?n:Promise.resolve(n));return $c(a,s)}refine(e,r){const a=n=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(n):r;return this._refinement((n,s)=>{const o=e(n),i=()=>s.addIssue({code:B.custom,...a(n)});return typeof Promise<"u"&&o instanceof Promise?o.then(l=>l?!0:(i(),!1)):o?!0:(i(),!1)})}refinement(e,r){return this._refinement((a,n)=>e(a)?!0:(n.addIssue(typeof r=="function"?r(a,n):r),!1))}_refinement(e){return new tn({schema:this,typeName:H.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return Cr.create(this,this._def)}nullable(){return rn.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ur.create(this)}promise(){return os.create(this,this._def)}or(e){return rs.create([this,e],this._def)}and(e){return ns.create(this,e,this._def)}transform(e){return new tn({...we(this._def),schema:this,typeName:H.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const r=typeof e=="function"?e:()=>e;return new is({...we(this._def),innerType:this,defaultValue:r,typeName:H.ZodDefault})}brand(){return new Uc({typeName:H.ZodBranded,type:this,...we(this._def)})}catch(e){const r=typeof e=="function"?e:()=>e;return new ls({...we(this._def),innerType:this,catchValue:r,typeName:H.ZodCatch})}describe(e){const r=this.constructor;return new r({...this._def,description:e})}pipe(e){return Bo.create(this,e)}readonly(){return us.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const i0=/^c[^\s-]{8,}$/i,l0=/^[0-9a-z]+$/,u0=/^[0-9A-HJKMNP-TV-Z]{26}$/i,c0=/^[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,d0=/^[a-z0-9_-]{21}$/i,p0=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,h0=/^[-+]?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)?)??$/,f0=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,m0="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Mo;const v0=/^(?:(?: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])$/,g0=/^(?:(?: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])$/,y0=/^(([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]))$/,_0=/^(([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])$/,w0=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,b0=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Ac="((\\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])))",x0=new RegExp(`^${Ac}$`);function Nc(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);const r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function E0(t){return new RegExp(`^${Nc(t)}$`)}function S0(t){let e=`${Ac}T${Nc(t)}`;const r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function I0(t,e){return!!((e==="v4"||!e)&&v0.test(t)||(e==="v6"||!e)&&y0.test(t))}function k0(t,e){if(!p0.test(t))return!1;try{const[r]=t.split(".");if(!r)return!1;const a=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),n=JSON.parse(atob(a));return!(typeof n!="object"||n===null||"typ"in n&&(n==null?void 0:n.typ)!=="JWT"||!n.alg||e&&n.alg!==e)}catch{return!1}}function T0(t,e){return!!((e==="v4"||!e)&&g0.test(t)||(e==="v6"||!e)&&_0.test(t))}class Tr extends Re{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==ee.string){const s=this._getOrReturnCtx(e);return Q(s,{code:B.invalid_type,expected:ee.string,received:s.parsedType}),he}const a=new Et;let n;for(const s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(n=this._getOrReturnCtx(e,n),Q(n,{code:B.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),a.dirty());else if(s.kind==="max")e.data.length>s.value&&(n=this._getOrReturnCtx(e,n),Q(n,{code:B.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),a.dirty());else if(s.kind==="length"){const o=e.data.length>s.value,i=e.data.length<s.value;(o||i)&&(n=this._getOrReturnCtx(e,n),o?Q(n,{code:B.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):i&&Q(n,{code:B.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),a.dirty())}else if(s.kind==="email")f0.test(e.data)||(n=this._getOrReturnCtx(e,n),Q(n,{validation:"email",code:B.invalid_string,message:s.message}),a.dirty());else if(s.kind==="emoji")Mo||(Mo=new RegExp(m0,"u")),Mo.test(e.data)||(n=this._getOrReturnCtx(e,n),Q(n,{validation:"emoji",code:B.invalid_string,message:s.message}),a.dirty());else if(s.kind==="uuid")c0.test(e.data)||(n=this._getOrReturnCtx(e,n),Q(n,{validation:"uuid",code:B.invalid_string,message:s.message}),a.dirty());else if(s.kind==="nanoid")d0.test(e.data)||(n=this._getOrReturnCtx(e,n),Q(n,{validation:"nanoid",code:B.invalid_string,message:s.message}),a.dirty());else if(s.kind==="cuid")i0.test(e.data)||(n=this._getOrReturnCtx(e,n),Q(n,{validation:"cuid",code:B.invalid_string,message:s.message}),a.dirty());else if(s.kind==="cuid2")l0.test(e.data)||(n=this._getOrReturnCtx(e,n),Q(n,{validation:"cuid2",code:B.invalid_string,message:s.message}),a.dirty());else if(s.kind==="ulid")u0.test(e.data)||(n=this._getOrReturnCtx(e,n),Q(n,{validation:"ulid",code:B.invalid_string,message:s.message}),a.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),Q(n,{validation:"url",code:B.invalid_string,message:s.message}),a.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),Q(n,{validation:"regex",code:B.invalid_string,message:s.message}),a.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(n=this._getOrReturnCtx(e,n),Q(n,{code:B.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),a.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(n=this._getOrReturnCtx(e,n),Q(n,{code:B.invalid_string,validation:{startsWith:s.value},message:s.message}),a.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(n=this._getOrReturnCtx(e,n),Q(n,{code:B.invalid_string,validation:{endsWith:s.value},message:s.message}),a.dirty()):s.kind==="datetime"?S0(s).test(e.data)||(n=this._getOrReturnCtx(e,n),Q(n,{code:B.invalid_string,validation:"datetime",message:s.message}),a.dirty()):s.kind==="date"?x0.test(e.data)||(n=this._getOrReturnCtx(e,n),Q(n,{code:B.invalid_string,validation:"date",message:s.message}),a.dirty()):s.kind==="time"?E0(s).test(e.data)||(n=this._getOrReturnCtx(e,n),Q(n,{code:B.invalid_string,validation:"time",message:s.message}),a.dirty()):s.kind==="duration"?h0.test(e.data)||(n=this._getOrReturnCtx(e,n),Q(n,{validation:"duration",code:B.invalid_string,message:s.message}),a.dirty()):s.kind==="ip"?I0(e.data,s.version)||(n=this._getOrReturnCtx(e,n),Q(n,{validation:"ip",code:B.invalid_string,message:s.message}),a.dirty()):s.kind==="jwt"?k0(e.data,s.alg)||(n=this._getOrReturnCtx(e,n),Q(n,{validation:"jwt",code:B.invalid_string,message:s.message}),a.dirty()):s.kind==="cidr"?T0(e.data,s.version)||(n=this._getOrReturnCtx(e,n),Q(n,{validation:"cidr",code:B.invalid_string,message:s.message}),a.dirty()):s.kind==="base64"?w0.test(e.data)||(n=this._getOrReturnCtx(e,n),Q(n,{validation:"base64",code:B.invalid_string,message:s.message}),a.dirty()):s.kind==="base64url"?b0.test(e.data)||(n=this._getOrReturnCtx(e,n),Q(n,{validation:"base64url",code:B.invalid_string,message:s.message}),a.dirty()):Ae.assertNever(s);return{status:a.value,value:e.data}}_regex(e,r,a){return this.refinement(n=>e.test(n),{validation:r,code:B.invalid_string,...se.errToObj(a)})}_addCheck(e){return new Tr({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...se.errToObj(e)})}url(e){return this._addCheck({kind:"url",...se.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...se.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...se.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...se.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...se.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...se.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...se.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...se.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...se.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...se.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...se.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...se.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,offset:(e==null?void 0:e.offset)??!1,local:(e==null?void 0:e.local)??!1,...se.errToObj(e==null?void 0:e.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,...se.errToObj(e==null?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...se.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...se.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r==null?void 0:r.position,...se.errToObj(r==null?void 0:r.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...se.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...se.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...se.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...se.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...se.errToObj(r)})}nonempty(e){return this.min(1,se.errToObj(e))}trim(){return new Tr({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Tr({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Tr({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}}Tr.create=t=>new Tr({checks:[],typeName:H.ZodString,coerce:(t==null?void 0:t.coerce)??!1,...we(t)});function P0(t,e){const r=(t.toString().split(".")[1]||"").length,a=(e.toString().split(".")[1]||"").length,n=r>a?r:a,s=Number.parseInt(t.toFixed(n).replace(".","")),o=Number.parseInt(e.toFixed(n).replace(".",""));return s%o/10**n}class kn extends Re{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==ee.number){const s=this._getOrReturnCtx(e);return Q(s,{code:B.invalid_type,expected:ee.number,received:s.parsedType}),he}let a;const n=new Et;for(const s of this._def.checks)s.kind==="int"?Ae.isInteger(e.data)||(a=this._getOrReturnCtx(e,a),Q(a,{code:B.invalid_type,expected:"integer",received:"float",message:s.message}),n.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(a=this._getOrReturnCtx(e,a),Q(a,{code:B.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),n.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(a=this._getOrReturnCtx(e,a),Q(a,{code:B.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),n.dirty()):s.kind==="multipleOf"?P0(e.data,s.value)!==0&&(a=this._getOrReturnCtx(e,a),Q(a,{code:B.not_multiple_of,multipleOf:s.value,message:s.message}),n.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(a=this._getOrReturnCtx(e,a),Q(a,{code:B.not_finite,message:s.message}),n.dirty()):Ae.assertNever(s);return{status:n.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,se.toString(r))}gt(e,r){return this.setLimit("min",e,!1,se.toString(r))}lte(e,r){return this.setLimit("max",e,!0,se.toString(r))}lt(e,r){return this.setLimit("max",e,!1,se.toString(r))}setLimit(e,r,a,n){return new kn({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:a,message:se.toString(n)}]})}_addCheck(e){return new kn({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:se.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:se.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:se.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:se.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:se.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:se.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:se.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:se.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:se.toString(e)})}get minValue(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&Ae.isInteger(e.value))}get isFinite(){let e=null,r=null;for(const a of this._def.checks){if(a.kind==="finite"||a.kind==="int"||a.kind==="multipleOf")return!0;a.kind==="min"?(r===null||a.value>r)&&(r=a.value):a.kind==="max"&&(e===null||a.value<e)&&(e=a.value)}return Number.isFinite(r)&&Number.isFinite(e)}}kn.create=t=>new kn({checks:[],typeName:H.ZodNumber,coerce:(t==null?void 0:t.coerce)||!1,...we(t)});class aa extends Re{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==ee.bigint)return this._getInvalidInput(e);let a;const n=new Et;for(const s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(a=this._getOrReturnCtx(e,a),Q(a,{code:B.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),n.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(a=this._getOrReturnCtx(e,a),Q(a,{code:B.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),n.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(a=this._getOrReturnCtx(e,a),Q(a,{code:B.not_multiple_of,multipleOf:s.value,message:s.message}),n.dirty()):Ae.assertNever(s);return{status:n.value,value:e.data}}_getInvalidInput(e){const r=this._getOrReturnCtx(e);return Q(r,{code:B.invalid_type,expected:ee.bigint,received:r.parsedType}),he}gte(e,r){return this.setLimit("min",e,!0,se.toString(r))}gt(e,r){return this.setLimit("min",e,!1,se.toString(r))}lte(e,r){return this.setLimit("max",e,!0,se.toString(r))}lt(e,r){return this.setLimit("max",e,!1,se.toString(r))}setLimit(e,r,a,n){return new aa({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:a,message:se.toString(n)}]})}_addCheck(e){return new aa({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:se.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:se.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:se.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:se.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:se.toString(r)})}get minValue(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}}aa.create=t=>new aa({checks:[],typeName:H.ZodBigInt,coerce:(t==null?void 0:t.coerce)??!1,...we(t)});class Do extends Re{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==ee.boolean){const a=this._getOrReturnCtx(e);return Q(a,{code:B.invalid_type,expected:ee.boolean,received:a.parsedType}),he}return qt(e.data)}}Do.create=t=>new Do({typeName:H.ZodBoolean,coerce:(t==null?void 0:t.coerce)||!1,...we(t)});class ts extends Re{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==ee.date){const s=this._getOrReturnCtx(e);return Q(s,{code:B.invalid_type,expected:ee.date,received:s.parsedType}),he}if(Number.isNaN(e.data.getTime())){const s=this._getOrReturnCtx(e);return Q(s,{code:B.invalid_date}),he}const a=new Et;let n;for(const s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(n=this._getOrReturnCtx(e,n),Q(n,{code:B.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),a.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(n=this._getOrReturnCtx(e,n),Q(n,{code:B.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),a.dirty()):Ae.assertNever(s);return{status:a.value,value:new Date(e.data.getTime())}}_addCheck(e){return new ts({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:se.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:se.toString(r)})}get minDate(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}}ts.create=t=>new ts({checks:[],coerce:(t==null?void 0:t.coerce)||!1,typeName:H.ZodDate,...we(t)});class Mc extends Re{_parse(e){if(this._getType(e)!==ee.symbol){const a=this._getOrReturnCtx(e);return Q(a,{code:B.invalid_type,expected:ee.symbol,received:a.parsedType}),he}return qt(e.data)}}Mc.create=t=>new Mc({typeName:H.ZodSymbol,...we(t)});class jo extends Re{_parse(e){if(this._getType(e)!==ee.undefined){const a=this._getOrReturnCtx(e);return Q(a,{code:B.invalid_type,expected:ee.undefined,received:a.parsedType}),he}return qt(e.data)}}jo.create=t=>new jo({typeName:H.ZodUndefined,...we(t)});class zo extends Re{_parse(e){if(this._getType(e)!==ee.null){const a=this._getOrReturnCtx(e);return Q(a,{code:B.invalid_type,expected:ee.null,received:a.parsedType}),he}return qt(e.data)}}zo.create=t=>new zo({typeName:H.ZodNull,...we(t)});class Lo extends Re{constructor(){super(...arguments),this._any=!0}_parse(e){return qt(e.data)}}Lo.create=t=>new Lo({typeName:H.ZodAny,...we(t)});class Uo extends Re{constructor(){super(...arguments),this._unknown=!0}_parse(e){return qt(e.data)}}Uo.create=t=>new Uo({typeName:H.ZodUnknown,...we(t)});class jr extends Re{_parse(e){const r=this._getOrReturnCtx(e);return Q(r,{code:B.invalid_type,expected:ee.never,received:r.parsedType}),he}}jr.create=t=>new jr({typeName:H.ZodNever,...we(t)});class Dc extends Re{_parse(e){if(this._getType(e)!==ee.undefined){const a=this._getOrReturnCtx(e);return Q(a,{code:B.invalid_type,expected:ee.void,received:a.parsedType}),he}return qt(e.data)}}Dc.create=t=>new Dc({typeName:H.ZodVoid,...we(t)});class ur extends Re{_parse(e){const{ctx:r,status:a}=this._processInputParams(e),n=this._def;if(r.parsedType!==ee.array)return Q(r,{code:B.invalid_type,expected:ee.array,received:r.parsedType}),he;if(n.exactLength!==null){const o=r.data.length>n.exactLength.value,i=r.data.length<n.exactLength.value;(o||i)&&(Q(r,{code:o?B.too_big:B.too_small,minimum:i?n.exactLength.value:void 0,maximum:o?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),a.dirty())}if(n.minLength!==null&&r.data.length<n.minLength.value&&(Q(r,{code:B.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),a.dirty()),n.maxLength!==null&&r.data.length>n.maxLength.value&&(Q(r,{code:B.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),a.dirty()),r.common.async)return Promise.all([...r.data].map((o,i)=>n.type._parseAsync(new lr(r,o,r.path,i)))).then(o=>Et.mergeArray(a,o));const s=[...r.data].map((o,i)=>n.type._parseSync(new lr(r,o,r.path,i)));return Et.mergeArray(a,s)}get element(){return this._def.type}min(e,r){return new ur({...this._def,minLength:{value:e,message:se.toString(r)}})}max(e,r){return new ur({...this._def,maxLength:{value:e,message:se.toString(r)}})}length(e,r){return new ur({...this._def,exactLength:{value:e,message:se.toString(r)}})}nonempty(e){return this.min(1,e)}}ur.create=(t,e)=>new ur({type:t,minLength:null,maxLength:null,exactLength:null,typeName:H.ZodArray,...we(e)});function Tn(t){if(t instanceof lt){const e={};for(const r in t.shape){const a=t.shape[r];e[r]=Cr.create(Tn(a))}return new lt({...t._def,shape:()=>e})}else return t instanceof ur?new ur({...t._def,type:Tn(t.element)}):t instanceof Cr?Cr.create(Tn(t.unwrap())):t instanceof rn?rn.create(Tn(t.unwrap())):t instanceof Xr?Xr.create(t.items.map(e=>Tn(e))):t}class lt extends Re{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),r=Ae.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==ee.object){const u=this._getOrReturnCtx(e);return Q(u,{code:B.invalid_type,expected:ee.object,received:u.parsedType}),he}const{status:a,ctx:n}=this._processInputParams(e),{shape:s,keys:o}=this._getCached(),i=[];if(!(this._def.catchall instanceof jr&&this._def.unknownKeys==="strip"))for(const u in n.data)o.includes(u)||i.push(u);const l=[];for(const u of o){const d=s[u],v=n.data[u];l.push({key:{status:"valid",value:u},value:d._parse(new lr(n,v,n.path,u)),alwaysSet:u in n.data})}if(this._def.catchall instanceof jr){const u=this._def.unknownKeys;if(u==="passthrough")for(const d of i)l.push({key:{status:"valid",value:d},value:{status:"valid",value:n.data[d]}});else if(u==="strict")i.length>0&&(Q(n,{code:B.unrecognized_keys,keys:i}),a.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const u=this._def.catchall;for(const d of i){const v=n.data[d];l.push({key:{status:"valid",value:d},value:u._parse(new lr(n,v,n.path,d)),alwaysSet:d in n.data})}}return n.common.async?Promise.resolve().then(async()=>{const u=[];for(const d of l){const v=await d.key,m=await d.value;u.push({key:v,value:m,alwaysSet:d.alwaysSet})}return u}).then(u=>Et.mergeObjectSync(a,u)):Et.mergeObjectSync(a,l)}get shape(){return this._def.shape()}strict(e){return se.errToObj,new lt({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,a)=>{var s,o;const n=((o=(s=this._def).errorMap)==null?void 0:o.call(s,r,a).message)??a.defaultError;return r.code==="unrecognized_keys"?{message:se.errToObj(e).message??n}:{message:n}}}:{}})}strip(){return new lt({...this._def,unknownKeys:"strip"})}passthrough(){return new lt({...this._def,unknownKeys:"passthrough"})}extend(e){return new lt({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new lt({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:H.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new lt({...this._def,catchall:e})}pick(e){const r={};for(const a of Ae.objectKeys(e))e[a]&&this.shape[a]&&(r[a]=this.shape[a]);return new lt({...this._def,shape:()=>r})}omit(e){const r={};for(const a of Ae.objectKeys(this.shape))e[a]||(r[a]=this.shape[a]);return new lt({...this._def,shape:()=>r})}deepPartial(){return Tn(this)}partial(e){const r={};for(const a of Ae.objectKeys(this.shape)){const n=this.shape[a];e&&!e[a]?r[a]=n:r[a]=n.optional()}return new lt({...this._def,shape:()=>r})}required(e){const r={};for(const a of Ae.objectKeys(this.shape))if(e&&!e[a])r[a]=this.shape[a];else{let s=this.shape[a];for(;s instanceof Cr;)s=s._def.innerType;r[a]=s}return new lt({...this._def,shape:()=>r})}keyof(){return zc(Ae.objectKeys(this.shape))}}lt.create=(t,e)=>new lt({shape:()=>t,unknownKeys:"strip",catchall:jr.create(),typeName:H.ZodObject,...we(e)}),lt.strictCreate=(t,e)=>new lt({shape:()=>t,unknownKeys:"strict",catchall:jr.create(),typeName:H.ZodObject,...we(e)}),lt.lazycreate=(t,e)=>new lt({shape:t,unknownKeys:"strip",catchall:jr.create(),typeName:H.ZodObject,...we(e)});class rs extends Re{_parse(e){const{ctx:r}=this._processInputParams(e),a=this._def.options;function n(s){for(const i of s)if(i.result.status==="valid")return i.result;for(const i of s)if(i.result.status==="dirty")return r.common.issues.push(...i.ctx.common.issues),i.result;const o=s.map(i=>new kr(i.ctx.common.issues));return Q(r,{code:B.invalid_union,unionErrors:o}),he}if(r.common.async)return Promise.all(a.map(async s=>{const o={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:o}),ctx:o}})).then(n);{let s;const o=[];for(const l of a){const u={...r,common:{...r.common,issues:[]},parent:null},d=l._parseSync({data:r.data,path:r.path,parent:u});if(d.status==="valid")return d;d.status==="dirty"&&!s&&(s={result:d,ctx:u}),u.common.issues.length&&o.push(u.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;const i=o.map(l=>new kr(l));return Q(r,{code:B.invalid_union,unionErrors:i}),he}}get options(){return this._def.options}}rs.create=(t,e)=>new rs({options:t,typeName:H.ZodUnion,...we(e)});const Pr=t=>t instanceof Zo?Pr(t.schema):t instanceof tn?Pr(t.innerType()):t instanceof ss?[t.value]:t instanceof en?t.options:t instanceof Vo?Ae.objectValues(t.enum):t instanceof is?Pr(t._def.innerType):t instanceof jo?[void 0]:t instanceof zo?[null]:t instanceof Cr?[void 0,...Pr(t.unwrap())]:t instanceof rn?[null,...Pr(t.unwrap())]:t instanceof Uc||t instanceof us?Pr(t.unwrap()):t instanceof ls?Pr(t._def.innerType):[];class Fo extends Re{_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==ee.object)return Q(r,{code:B.invalid_type,expected:ee.object,received:r.parsedType}),he;const a=this.discriminator,n=r.data[a],s=this.optionsMap.get(n);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}):(Q(r,{code:B.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[a]}),he)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,a){const n=new Map;for(const s of r){const o=Pr(s.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const i of o){if(n.has(i))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(i)}`);n.set(i,s)}}return new Fo({typeName:H.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:n,...we(a)})}}function qo(t,e){const r=Dr(t),a=Dr(e);if(t===e)return{valid:!0,data:t};if(r===ee.object&&a===ee.object){const n=Ae.objectKeys(e),s=Ae.objectKeys(t).filter(i=>n.indexOf(i)!==-1),o={...t,...e};for(const i of s){const l=qo(t[i],e[i]);if(!l.valid)return{valid:!1};o[i]=l.data}return{valid:!0,data:o}}else if(r===ee.array&&a===ee.array){if(t.length!==e.length)return{valid:!1};const n=[];for(let s=0;s<t.length;s++){const o=t[s],i=e[s],l=qo(o,i);if(!l.valid)return{valid:!1};n.push(l.data)}return{valid:!0,data:n}}else return r===ee.date&&a===ee.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}class ns extends Re{_parse(e){const{status:r,ctx:a}=this._processInputParams(e),n=(s,o)=>{if(Rc(s)||Rc(o))return he;const i=qo(s.value,o.value);return i.valid?((Oc(s)||Oc(o))&&r.dirty(),{status:r.value,value:i.data}):(Q(a,{code:B.invalid_intersection_types}),he)};return a.common.async?Promise.all([this._def.left._parseAsync({data:a.data,path:a.path,parent:a}),this._def.right._parseAsync({data:a.data,path:a.path,parent:a})]).then(([s,o])=>n(s,o)):n(this._def.left._parseSync({data:a.data,path:a.path,parent:a}),this._def.right._parseSync({data:a.data,path:a.path,parent:a}))}}ns.create=(t,e,r)=>new ns({left:t,right:e,typeName:H.ZodIntersection,...we(r)});class Xr extends Re{_parse(e){const{status:r,ctx:a}=this._processInputParams(e);if(a.parsedType!==ee.array)return Q(a,{code:B.invalid_type,expected:ee.array,received:a.parsedType}),he;if(a.data.length<this._def.items.length)return Q(a,{code:B.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),he;!this._def.rest&&a.data.length>this._def.items.length&&(Q(a,{code:B.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());const s=[...a.data].map((o,i)=>{const l=this._def.items[i]||this._def.rest;return l?l._parse(new lr(a,o,a.path,i)):null}).filter(o=>!!o);return a.common.async?Promise.all(s).then(o=>Et.mergeArray(r,o)):Et.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new Xr({...this._def,rest:e})}}Xr.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Xr({items:t,typeName:H.ZodTuple,rest:null,...we(e)})};class as extends Re{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:r,ctx:a}=this._processInputParams(e);if(a.parsedType!==ee.object)return Q(a,{code:B.invalid_type,expected:ee.object,received:a.parsedType}),he;const n=[],s=this._def.keyType,o=this._def.valueType;for(const i in a.data)n.push({key:s._parse(new lr(a,i,a.path,i)),value:o._parse(new lr(a,a.data[i],a.path,i)),alwaysSet:i in a.data});return a.common.async?Et.mergeObjectAsync(r,n):Et.mergeObjectSync(r,n)}get element(){return this._def.valueType}static create(e,r,a){return r instanceof Re?new as({keyType:e,valueType:r,typeName:H.ZodRecord,...we(a)}):new as({keyType:Tr.create(),valueType:e,typeName:H.ZodRecord,...we(r)})}}class jc extends Re{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:r,ctx:a}=this._processInputParams(e);if(a.parsedType!==ee.map)return Q(a,{code:B.invalid_type,expected:ee.map,received:a.parsedType}),he;const n=this._def.keyType,s=this._def.valueType,o=[...a.data.entries()].map(([i,l],u)=>({key:n._parse(new lr(a,i,a.path,[u,"key"])),value:s._parse(new lr(a,l,a.path,[u,"value"]))}));if(a.common.async){const i=new Map;return Promise.resolve().then(async()=>{for(const l of o){const u=await l.key,d=await l.value;if(u.status==="aborted"||d.status==="aborted")return he;(u.status==="dirty"||d.status==="dirty")&&r.dirty(),i.set(u.value,d.value)}return{status:r.value,value:i}})}else{const i=new Map;for(const l of o){const u=l.key,d=l.value;if(u.status==="aborted"||d.status==="aborted")return he;(u.status==="dirty"||d.status==="dirty")&&r.dirty(),i.set(u.value,d.value)}return{status:r.value,value:i}}}}jc.create=(t,e,r)=>new jc({valueType:e,keyType:t,typeName:H.ZodMap,...we(r)});class sa extends Re{_parse(e){const{status:r,ctx:a}=this._processInputParams(e);if(a.parsedType!==ee.set)return Q(a,{code:B.invalid_type,expected:ee.set,received:a.parsedType}),he;const n=this._def;n.minSize!==null&&a.data.size<n.minSize.value&&(Q(a,{code:B.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),r.dirty()),n.maxSize!==null&&a.data.size>n.maxSize.value&&(Q(a,{code:B.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),r.dirty());const s=this._def.valueType;function o(l){const u=new Set;for(const d of l){if(d.status==="aborted")return he;d.status==="dirty"&&r.dirty(),u.add(d.value)}return{status:r.value,value:u}}const i=[...a.data.values()].map((l,u)=>s._parse(new lr(a,l,a.path,u)));return a.common.async?Promise.all(i).then(l=>o(l)):o(i)}min(e,r){return new sa({...this._def,minSize:{value:e,message:se.toString(r)}})}max(e,r){return new sa({...this._def,maxSize:{value:e,message:se.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}}sa.create=(t,e)=>new sa({valueType:t,minSize:null,maxSize:null,typeName:H.ZodSet,...we(e)});class Zo extends Re{get schema(){return this._def.getter()}_parse(e){const{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}}Zo.create=(t,e)=>new Zo({getter:t,typeName:H.ZodLazy,...we(e)});class ss extends Re{_parse(e){if(e.data!==this._def.value){const r=this._getOrReturnCtx(e);return Q(r,{received:r.data,code:B.invalid_literal,expected:this._def.value}),he}return{status:"valid",value:e.data}}get value(){return this._def.value}}ss.create=(t,e)=>new ss({value:t,typeName:H.ZodLiteral,...we(e)});function zc(t,e){return new en({values:t,typeName:H.ZodEnum,...we(e)})}class en extends Re{_parse(e){if(typeof e.data!="string"){const r=this._getOrReturnCtx(e),a=this._def.values;return Q(r,{expected:Ae.joinValues(a),received:r.parsedType,code:B.invalid_type}),he}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const r=this._getOrReturnCtx(e),a=this._def.values;return Q(r,{received:r.data,code:B.invalid_enum_value,options:a}),he}return qt(e.data)}get options(){return this._def.values}get enum(){const e={};for(const r of this._def.values)e[r]=r;return e}get Values(){const e={};for(const r of this._def.values)e[r]=r;return e}get Enum(){const e={};for(const r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return en.create(e,{...this._def,...r})}exclude(e,r=this._def){return en.create(this.options.filter(a=>!e.includes(a)),{...this._def,...r})}}en.create=zc;class Vo extends Re{_parse(e){const r=Ae.getValidEnumValues(this._def.values),a=this._getOrReturnCtx(e);if(a.parsedType!==ee.string&&a.parsedType!==ee.number){const n=Ae.objectValues(r);return Q(a,{expected:Ae.joinValues(n),received:a.parsedType,code:B.invalid_type}),he}if(this._cache||(this._cache=new Set(Ae.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const n=Ae.objectValues(r);return Q(a,{received:a.data,code:B.invalid_enum_value,options:n}),he}return qt(e.data)}get enum(){return this._def.values}}Vo.create=(t,e)=>new Vo({values:t,typeName:H.ZodNativeEnum,...we(e)});class os extends Re{unwrap(){return this._def.type}_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==ee.promise&&r.common.async===!1)return Q(r,{code:B.invalid_type,expected:ee.promise,received:r.parsedType}),he;const a=r.parsedType===ee.promise?r.data:Promise.resolve(r.data);return qt(a.then(n=>this._def.type.parseAsync(n,{path:r.path,errorMap:r.common.contextualErrorMap})))}}os.create=(t,e)=>new os({type:t,typeName:H.ZodPromise,...we(e)});class tn extends Re{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===H.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:r,ctx:a}=this._processInputParams(e),n=this._def.effect||null,s={addIssue:o=>{Q(a,o),o.fatal?r.abort():r.dirty()},get path(){return a.path}};if(s.addIssue=s.addIssue.bind(s),n.type==="preprocess"){const o=n.transform(a.data,s);if(a.common.async)return Promise.resolve(o).then(async i=>{if(r.value==="aborted")return he;const l=await this._def.schema._parseAsync({data:i,path:a.path,parent:a});return l.status==="aborted"?he:l.status==="dirty"||r.value==="dirty"?na(l.value):l});{if(r.value==="aborted")return he;const i=this._def.schema._parseSync({data:o,path:a.path,parent:a});return i.status==="aborted"?he:i.status==="dirty"||r.value==="dirty"?na(i.value):i}}if(n.type==="refinement"){const o=i=>{const l=n.refinement(i,s);if(a.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return i};if(a.common.async===!1){const i=this._def.schema._parseSync({data:a.data,path:a.path,parent:a});return i.status==="aborted"?he:(i.status==="dirty"&&r.dirty(),o(i.value),{status:r.value,value:i.value})}else return this._def.schema._parseAsync({data:a.data,path:a.path,parent:a}).then(i=>i.status==="aborted"?he:(i.status==="dirty"&&r.dirty(),o(i.value).then(()=>({status:r.value,value:i.value}))))}if(n.type==="transform")if(a.common.async===!1){const o=this._def.schema._parseSync({data:a.data,path:a.path,parent:a});if(!In(o))return he;const i=n.transform(o.value,s);if(i instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:i}}else return this._def.schema._parseAsync({data:a.data,path:a.path,parent:a}).then(o=>In(o)?Promise.resolve(n.transform(o.value,s)).then(i=>({status:r.value,value:i})):he);Ae.assertNever(n)}}tn.create=(t,e,r)=>new tn({schema:t,typeName:H.ZodEffects,effect:e,...we(r)}),tn.createWithPreprocess=(t,e,r)=>new tn({schema:e,effect:{type:"preprocess",transform:t},typeName:H.ZodEffects,...we(r)});class Cr extends Re{_parse(e){return this._getType(e)===ee.undefined?qt(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Cr.create=(t,e)=>new Cr({innerType:t,typeName:H.ZodOptional,...we(e)});class rn extends Re{_parse(e){return this._getType(e)===ee.null?qt(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}rn.create=(t,e)=>new rn({innerType:t,typeName:H.ZodNullable,...we(e)});class is extends Re{_parse(e){const{ctx:r}=this._processInputParams(e);let a=r.data;return r.parsedType===ee.undefined&&(a=this._def.defaultValue()),this._def.innerType._parse({data:a,path:r.path,parent:r})}removeDefault(){return this._def.innerType}}is.create=(t,e)=>new is({innerType:t,typeName:H.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...we(e)});class ls extends Re{_parse(e){const{ctx:r}=this._processInputParams(e),a={...r,common:{...r.common,issues:[]}},n=this._def.innerType._parse({data:a.data,path:a.path,parent:{...a}});return es(n)?n.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new kr(a.common.issues)},input:a.data})})):{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new kr(a.common.issues)},input:a.data})}}removeCatch(){return this._def.innerType}}ls.create=(t,e)=>new ls({innerType:t,typeName:H.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...we(e)});class Lc extends Re{_parse(e){if(this._getType(e)!==ee.nan){const a=this._getOrReturnCtx(e);return Q(a,{code:B.invalid_type,expected:ee.nan,received:a.parsedType}),he}return{status:"valid",value:e.data}}}Lc.create=t=>new Lc({typeName:H.ZodNaN,...we(t)});class Uc extends Re{_parse(e){const{ctx:r}=this._processInputParams(e),a=r.data;return this._def.type._parse({data:a,path:r.path,parent:r})}unwrap(){return this._def.type}}class Bo extends Re{_parse(e){const{status:r,ctx:a}=this._processInputParams(e);if(a.common.async)return(async()=>{const s=await this._def.in._parseAsync({data:a.data,path:a.path,parent:a});return s.status==="aborted"?he:s.status==="dirty"?(r.dirty(),na(s.value)):this._def.out._parseAsync({data:s.value,path:a.path,parent:a})})();{const n=this._def.in._parseSync({data:a.data,path:a.path,parent:a});return n.status==="aborted"?he:n.status==="dirty"?(r.dirty(),{status:"dirty",value:n.value}):this._def.out._parseSync({data:n.value,path:a.path,parent:a})}}static create(e,r){return new Bo({in:e,out:r,typeName:H.ZodPipeline})}}class us extends Re{_parse(e){const r=this._def.innerType._parse(e),a=n=>(In(n)&&(n.value=Object.freeze(n.value)),n);return es(r)?r.then(n=>a(n)):a(r)}unwrap(){return this._def.innerType}}us.create=(t,e)=>new us({innerType:t,typeName:H.ZodReadonly,...we(e)});var H;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(H||(H={}));const $=Tr.create,mt=kn.create,dt=Do.create,C0=Lo.create,oa=Uo.create;jr.create;const re=ur.create,W=lt.create,St=rs.create,R0=Fo.create;ns.create,Xr.create;const ia=as.create,_e=ss.create,Rr=en.create;os.create;const V=Cr.create;rn.create;const O0=he;function It(...t){return t.reduce((e,r)=>({...e,...r??{}}),{})}async function $0(t,e){if(t==null)return Promise.resolve();const r=e==null?void 0:e.abortSignal;return new Promise((a,n)=>{if(r!=null&&r.aborted){n(Fc());return}const s=setTimeout(()=>{o(),a()},t),o=()=>{clearTimeout(s),r==null||r.removeEventListener("abort",i)},i=()=>{o(),n(Fc())};r==null||r.addEventListener("abort",i)})}function Fc(){return new DOMException("Delay was aborted","AbortError")}function Pn(t){return Object.fromEntries([...t.headers])}var la=({prefix:t,size:e=16,alphabet:r="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:a="-"}={})=>{const n=()=>{const s=r.length,o=new Array(e);for(let i=0;i<e;i++)o[i]=r[Math.random()*s|0];return o.join("")};if(t==null)return n;if(r.includes(a))throw new ou({argument:"separator",message:`The separator "${a}" must not be part of the alphabet "${r}".`});return()=>`${t}${a}${n()}`},Ot=la();function Ho(t){return t==null?"unknown error":typeof t=="string"?t:t instanceof Error?t.message:JSON.stringify(t)}function nn(t){return(t instanceof Error||t instanceof DOMException)&&(t.name==="AbortError"||t.name==="ResponseAborted"||t.name==="TimeoutError")}var A0=["fetch failed","failed to fetch"];function qc({error:t,url:e,requestBodyValues:r}){if(nn(t))return t;if(t instanceof TypeError&&A0.includes(t.message.toLowerCase())){const a=t.cause;if(a!=null)return new ft({message:`Cannot connect to API: ${a.message}`,cause:a,url:e,requestBodyValues:r,isRetryable:!0})}return t}function Jo(t=globalThis){var e,r,a;return t.window?"runtime/browser":(e=t.navigator)!=null&&e.userAgent?`runtime/${t.navigator.userAgent.toLowerCase()}`:(a=(r=t.process)==null?void 0:r.versions)!=null&&a.node?`runtime/node.js/${t.process.version.substring(0)}`:t.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function N0(t){return Object.fromEntries(Object.entries(t).filter(([e,r])=>r!=null))}function an(t,...e){const r=N0(t??{}),a=new Headers(r),n=a.get("user-agent")||"";return a.set("user-agent",[n,...e].filter(Boolean).join(" ")),Object.fromEntries(a)}var Zc="3.0.12",M0=()=>globalThis.fetch,Vc=async({url:t,headers:e={},successfulResponseHandler:r,failedResponseHandler:a,abortSignal:n,fetch:s=M0()})=>{try{const o=await s(t,{method:"GET",headers:an(e,`ai-sdk/provider-utils/${Zc}`,Jo()),signal:n}),i=Pn(o);if(!o.ok){let l;try{l=await a({response:o,url:t,requestBodyValues:{}})}catch(u){throw nn(u)||ft.isInstance(u)?u:new ft({message:"Failed to process error response",cause:u,statusCode:o.status,url:t,responseHeaders:i,requestBodyValues:{}})}throw l.value}try{return await r({response:o,url:t,requestBodyValues:{}})}catch(l){throw l instanceof Error&&(nn(l)||ft.isInstance(l))?l:new ft({message:"Failed to process successful response",cause:l,statusCode:o.status,url:t,responseHeaders:i,requestBodyValues:{}})}}catch(o){throw qc({error:o,url:t,requestBodyValues:{}})}};function D0({mediaType:t,url:e,supportedUrls:r}){return e=e.toLowerCase(),t=t.toLowerCase(),Object.entries(r).map(([a,n])=>{const s=a.toLowerCase();return s==="*"||s==="*/*"?{mediaTypePrefix:"",regexes:n}:{mediaTypePrefix:s.replace(/\*/,""),regexes:n}}).filter(({mediaTypePrefix:a})=>t.startsWith(a)).flatMap(({regexes:a})=>a).some(a=>a.test(e))}function Bc({apiKey:t,environmentVariableName:e,apiKeyParameterName:r="apiKey",description:a}){if(typeof t=="string")return t;if(t!=null)throw new Za({message:`${a} API key must be a string.`});if(typeof process>"u")throw new Za({message:`${a} API key is missing. Pass it using the '${r}' parameter. Environment variables is not supported in this environment.`});if(t=process.env[e],t==null)throw new Za({message:`${a} API key is missing. Pass it using the '${r}' parameter or the ${e} environment variable.`});if(typeof t!="string")throw new Za({message:`${a} API key must be a string. The value of the ${e} environment variable is not a string.`});return t}function ua({settingValue:t,environmentVariableName:e}){if(typeof t=="string")return t;if(!(t!=null||typeof process>"u")&&(t=process.env[e],!(t==null||typeof t!="string")))return t}function j0(t){var e;const[r,a=""]=t.toLowerCase().split("/");return(e={mpeg:"mp3","x-wav":"wav",opus:"ogg",mp4:"m4a","x-m4a":"m4a"}[a])!=null?e:a}var z0=/"__proto__"\s*:/,L0=/"constructor"\s*:/;function U0(t){const e=JSON.parse(t);return e===null||typeof e!="object"||z0.test(t)===!1&&L0.test(t)===!1?e:F0(e)}function F0(t){let e=[t];for(;e.length;){const r=e;e=[];for(const a of r){if(Object.prototype.hasOwnProperty.call(a,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(a,"constructor")&&Object.prototype.hasOwnProperty.call(a.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const n in a){const s=a[n];s&&typeof s=="object"&&e.push(s)}}}return t}function Wo(t){const{stackTraceLimit:e}=Error;Error.stackTraceLimit=0;try{return U0(t)}finally{Error.stackTraceLimit=e}}var cs=Symbol.for("vercel.ai.validator");function q0(t){return{[cs]:!0,validate:t}}function Z0(t){return typeof t=="object"&&t!==null&&cs in t&&t[cs]===!0&&"validate"in t}function rt(t){let e;return()=>(e==null&&(e=t()),e)}function V0(t){return Z0(t)?t:typeof t=="function"?t():B0(t)}function B0(t){return q0(async e=>{const r=await t["~standard"].validate(e);return r.issues==null?{success:!0,value:r.value}:{success:!1,error:new Gn({value:e,cause:r.issues})}})}async function cr({value:t,schema:e}){const r=await er({value:t,schema:e});if(!r.success)throw Gn.wrap({value:t,cause:r.error});return r.value}async function er({value:t,schema:e}){const r=V0(e);try{if(r.validate==null)return{success:!0,value:t,rawValue:t};const a=await r.validate(t);return a.success?{success:!0,value:a.value,rawValue:t}:{success:!1,error:Gn.wrap({value:t,cause:a.error}),rawValue:t}}catch(a){return{success:!1,error:Gn.wrap({value:t,cause:a}),rawValue:t}}}async function H0({text:t,schema:e}){try{const r=Wo(t);return e==null?r:cr({value:r,schema:e})}catch(r){throw qa.isInstance(r)||Gn.isInstance(r)?r:new qa({text:t,cause:r})}}async function sn({text:t,schema:e}){try{const r=Wo(t);return e==null?{success:!0,value:r,rawValue:r}:await er({value:r,schema:e})}catch(r){return{success:!1,error:qa.isInstance(r)?r:new qa({text:t,cause:r}),rawValue:void 0}}}function ds(t){try{return Wo(t),!0}catch{return!1}}function J0({stream:t,schema:e}){return t.pipeThrough(new TextDecoderStream).pipeThrough(new Au).pipeThrough(new TransformStream({async transform({data:r},a){r!=="[DONE]"&&a.enqueue(await sn({text:r,schema:e}))}}))}async function dr({provider:t,providerOptions:e,schema:r}){if((e==null?void 0:e[t])==null)return;const a=await er({value:e[t],schema:r});if(!a.success)throw new ou({argument:"providerOptions",message:`invalid ${t} provider options`,cause:a.error});return a.value}var W0=()=>globalThis.fetch,$t=async({url:t,headers:e,body:r,failedResponseHandler:a,successfulResponseHandler:n,abortSignal:s,fetch:o})=>Hc({url:t,headers:{"Content-Type":"application/json",...e},body:{content:JSON.stringify(r),values:r},failedResponseHandler:a,successfulResponseHandler:n,abortSignal:s,fetch:o}),G0=async({url:t,headers:e,formData:r,failedResponseHandler:a,successfulResponseHandler:n,abortSignal:s,fetch:o})=>Hc({url:t,headers:e,body:{content:r,values:Object.fromEntries(r.entries())},failedResponseHandler:a,successfulResponseHandler:n,abortSignal:s,fetch:o}),Hc=async({url:t,headers:e={},body:r,successfulResponseHandler:a,failedResponseHandler:n,abortSignal:s,fetch:o=W0()})=>{try{const i=await o(t,{method:"POST",headers:an(e,`ai-sdk/provider-utils/${Zc}`,Jo()),body:r.content,signal:s}),l=Pn(i);if(!i.ok){let u;try{u=await n({response:i,url:t,requestBodyValues:r.values})}catch(d){throw nn(d)||ft.isInstance(d)?d:new ft({message:"Failed to process error response",cause:d,statusCode:i.status,url:t,responseHeaders:l,requestBodyValues:r.values})}throw u.value}try{return await a({response:i,url:t,requestBodyValues:r.values})}catch(u){throw u instanceof Error&&(nn(u)||ft.isInstance(u))?u:new ft({message:"Failed to process successful response",cause:u,statusCode:i.status,url:t,responseHeaders:l,requestBodyValues:r.values})}}catch(i){throw qc({error:i,url:t,requestBodyValues:r.values})}};function KC(t){return t}function K0(t){return{...t,type:"dynamic"}}function Cn({id:t,name:e,inputSchema:r,outputSchema:a}){return({execute:n,toModelOutput:s,onInputStart:o,onInputDelta:i,onInputAvailable:l,...u})=>({type:"provider-defined",id:t,name:e,args:u,inputSchema:r,outputSchema:a,execute:n,toModelOutput:s,onInputStart:o,onInputDelta:i,onInputAvailable:l})}async function zr(t){return typeof t=="function"&&(t=t()),Promise.resolve(t)}var on=({errorSchema:t,errorToMessage:e,isRetryable:r})=>async({response:a,url:n,requestBodyValues:s})=>{const o=await a.text(),i=Pn(a);if(o.trim()==="")return{responseHeaders:i,value:new ft({message:a.statusText,url:n,requestBodyValues:s,statusCode:a.status,responseHeaders:i,responseBody:o,isRetryable:r==null?void 0:r(a)})};try{const l=await H0({text:o,schema:t});return{responseHeaders:i,value:new ft({message:e(l),url:n,requestBodyValues:s,statusCode:a.status,responseHeaders:i,responseBody:o,data:l,isRetryable:r==null?void 0:r(a,l)})}}catch{return{responseHeaders:i,value:new ft({message:a.statusText,url:n,requestBodyValues:s,statusCode:a.status,responseHeaders:i,responseBody:o,isRetryable:r==null?void 0:r(a)})}}},ca=t=>async({response:e})=>{const r=Pn(e);if(e.body==null)throw new Zm({});return{responseHeaders:r,value:J0({stream:e.body,schema:t})}},tr=t=>async({response:e,url:r,requestBodyValues:a})=>{const n=await e.text(),s=await sn({text:n,schema:t}),o=Pn(e);if(!s.success)throw new ft({message:"Invalid JSON response",cause:s.error,statusCode:e.status,responseHeaders:o,responseBody:n,url:r,requestBodyValues:a});return{responseHeaders:o,value:s.value,rawValue:s.rawValue}},Q0=()=>async({response:t,url:e,requestBodyValues:r})=>{const a=Pn(t);if(!t.body)throw new ft({message:"Response body is empty",url:e,requestBodyValues:r,statusCode:t.status,responseHeaders:a,responseBody:void 0});try{const n=await t.arrayBuffer();return{responseHeaders:a,value:new Uint8Array(n)}}catch(n){throw new ft({message:"Failed to read response as array buffer",url:e,requestBodyValues:r,statusCode:t.status,responseHeaders:a,responseBody:void 0,cause:n})}},Y0=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")},X0=Symbol("Let zodToJsonSchema decide on which parser to use"),Jc={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",strictUnions:!1,definitions:{},errorMessages:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},ew=t=>typeof t=="string"?{...Jc,name:t}:{...Jc,...t};function Dt(){return{}}function tw(t,e){var r,a,n;const s={type:"array"};return(r=t.type)!=null&&r._def&&((n=(a=t.type)==null?void 0:a._def)==null?void 0:n.typeName)!==H.ZodAny&&(s.items=ze(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&(s.minItems=t.minLength.value),t.maxLength&&(s.maxItems=t.maxLength.value),t.exactLength&&(s.minItems=t.exactLength.value,s.maxItems=t.exactLength.value),s}function rw(t){const e={type:"integer",format:"int64"};if(!t.checks)return e;for(const r of t.checks)switch(r.kind){case"min":r.inclusive?e.minimum=r.value:e.exclusiveMinimum=r.value;break;case"max":r.inclusive?e.maximum=r.value:e.exclusiveMaximum=r.value;break;case"multipleOf":e.multipleOf=r.value;break}return e}function nw(){return{type:"boolean"}}function Wc(t,e){return ze(t.type._def,e)}var aw=(t,e)=>ze(t.innerType._def,e);function Gc(t,e,r){const a=r??e.dateStrategy;if(Array.isArray(a))return{anyOf:a.map((n,s)=>Gc(t,e,n))};switch(a){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return sw(t)}}var sw=t=>{const e={type:"integer",format:"unix-time"};for(const r of t.checks)switch(r.kind){case"min":e.minimum=r.value;break;case"max":e.maximum=r.value;break}return e};function ow(t,e){return{...ze(t.innerType._def,e),default:t.defaultValue()}}function iw(t,e){return e.effectStrategy==="input"?ze(t.schema._def,e):Dt()}function lw(t){return{type:"string",enum:Array.from(t.values)}}var uw=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function cw(t,e){const r=[ze(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),ze(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(n=>!!n),a=[];return r.forEach(n=>{if(uw(n))a.push(...n.allOf);else{let s=n;if("additionalProperties"in n&&n.additionalProperties===!1){const{additionalProperties:o,...i}=n;s=i}a.push(s)}}),a.length?{allOf:a}:void 0}function dw(t){const e=typeof t.value;return e!=="bigint"&&e!=="number"&&e!=="boolean"&&e!=="string"?{type:Array.isArray(t.value)?"array":"object"}:{type:e==="bigint"?"integer":e,const:t.value}}var Go=void 0,rr={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:()=>(Go===void 0&&(Go=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Go),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 Kc(t,e){const r={type:"string"};if(t.checks)for(const a of t.checks)switch(a.kind){case"min":r.minLength=typeof r.minLength=="number"?Math.max(r.minLength,a.value):a.value;break;case"max":r.maxLength=typeof r.maxLength=="number"?Math.min(r.maxLength,a.value):a.value;break;case"email":switch(e.emailStrategy){case"format:email":nr(r,"email",a.message,e);break;case"format:idn-email":nr(r,"idn-email",a.message,e);break;case"pattern:zod":kt(r,rr.email,a.message,e);break}break;case"url":nr(r,"uri",a.message,e);break;case"uuid":nr(r,"uuid",a.message,e);break;case"regex":kt(r,a.regex,a.message,e);break;case"cuid":kt(r,rr.cuid,a.message,e);break;case"cuid2":kt(r,rr.cuid2,a.message,e);break;case"startsWith":kt(r,RegExp(`^${Ko(a.value,e)}`),a.message,e);break;case"endsWith":kt(r,RegExp(`${Ko(a.value,e)}$`),a.message,e);break;case"datetime":nr(r,"date-time",a.message,e);break;case"date":nr(r,"date",a.message,e);break;case"time":nr(r,"time",a.message,e);break;case"duration":nr(r,"duration",a.message,e);break;case"length":r.minLength=typeof r.minLength=="number"?Math.max(r.minLength,a.value):a.value,r.maxLength=typeof r.maxLength=="number"?Math.min(r.maxLength,a.value):a.value;break;case"includes":{kt(r,RegExp(Ko(a.value,e)),a.message,e);break}case"ip":{a.version!=="v6"&&nr(r,"ipv4",a.message,e),a.version!=="v4"&&nr(r,"ipv6",a.message,e);break}case"base64url":kt(r,rr.base64url,a.message,e);break;case"jwt":kt(r,rr.jwt,a.message,e);break;case"cidr":{a.version!=="v6"&&kt(r,rr.ipv4Cidr,a.message,e),a.version!=="v4"&&kt(r,rr.ipv6Cidr,a.message,e);break}case"emoji":kt(r,rr.emoji(),a.message,e);break;case"ulid":{kt(r,rr.ulid,a.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{nr(r,"binary",a.message,e);break}case"contentEncoding:base64":{r.contentEncoding="base64";break}case"pattern:zod":{kt(r,rr.base64,a.message,e);break}}break}case"nanoid":kt(r,rr.nanoid,a.message,e)}return r}function Ko(t,e){return e.patternStrategy==="escape"?hw(t):t}var pw=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function hw(t){let e="";for(let r=0;r<t.length;r++)pw.has(t[r])||(e+="\\"),e+=t[r];return e}function nr(t,e,r,a){var n;t.format||(n=t.anyOf)!=null&&n.some(s=>s.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format}),delete t.format),t.anyOf.push({format:e,...r&&a.errorMessages&&{errorMessage:{format:r}}})):t.format=e}function kt(t,e,r,a){var n;t.pattern||(n=t.allOf)!=null&&n.some(s=>s.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern}),delete t.pattern),t.allOf.push({pattern:Qc(e,a),...r&&a.errorMessages&&{errorMessage:{pattern:r}}})):t.pattern=Qc(e,a)}function Qc(t,e){var r;if(!e.applyRegexFlags||!t.flags)return t.source;const a={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=a.i?t.source.toLowerCase():t.source;let s="",o=!1,i=!1,l=!1;for(let u=0;u<n.length;u++){if(o){s+=n[u],o=!1;continue}if(a.i){if(i){if(n[u].match(/[a-z]/)){l?(s+=n[u],s+=`${n[u-2]}-${n[u]}`.toUpperCase(),l=!1):n[u+1]==="-"&&((r=n[u+2])!=null&&r.match(/[a-z]/))?(s+=n[u],l=!0):s+=`${n[u]}${n[u].toUpperCase()}`;continue}}else if(n[u].match(/[a-z]/)){s+=`[${n[u]}${n[u].toUpperCase()}]`;continue}}if(a.m){if(n[u]==="^"){s+=`(^|(?<=[\r
35
- ]))`;continue}else if(n[u]==="$"){s+=`($|(?=[\r
36
- ]))`;continue}}if(a.s&&n[u]==="."){s+=i?`${n[u]}\r
37
- `:`[${n[u]}\r
38
- ]`;continue}s+=n[u],n[u]==="\\"?o=!0:i&&n[u]==="]"?i=!1:!i&&n[u]==="["&&(i=!0)}try{new RegExp(s)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return s}function Yc(t,e){var r,a,n,s,o,i;const l={type:"object",additionalProperties:(r=ze(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]}))!=null?r:e.allowedAdditionalProperties};if(((a=t.keyType)==null?void 0:a._def.typeName)===H.ZodString&&((n=t.keyType._def.checks)!=null&&n.length)){const{type:u,...d}=Kc(t.keyType._def,e);return{...l,propertyNames:d}}else{if(((s=t.keyType)==null?void 0:s._def.typeName)===H.ZodEnum)return{...l,propertyNames:{enum:t.keyType._def.values}};if(((o=t.keyType)==null?void 0:o._def.typeName)===H.ZodBranded&&t.keyType._def.type._def.typeName===H.ZodString&&((i=t.keyType._def.type._def.checks)!=null&&i.length)){const{type:u,...d}=Wc(t.keyType._def,e);return{...l,propertyNames:d}}}return l}function fw(t,e){if(e.mapStrategy==="record")return Yc(t,e);const r=ze(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Dt(),a=ze(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Dt();return{type:"array",maxItems:125,items:{type:"array",items:[r,a],minItems:2,maxItems:2}}}function mw(t){const e=t.values,a=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),n=Array.from(new Set(a.map(s=>typeof s)));return{type:n.length===1?n[0]==="string"?"string":"number":["string","number"],enum:a}}function vw(){return{not:Dt()}}function gw(){return{type:"null"}}var Qo={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function yw(t,e){const r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(a=>a._def.typeName in Qo&&(!a._def.checks||!a._def.checks.length))){const a=r.reduce((n,s)=>{const o=Qo[s._def.typeName];return o&&!n.includes(o)?[...n,o]:n},[]);return{type:a.length>1?a:a[0]}}else if(r.every(a=>a._def.typeName==="ZodLiteral"&&!a.description)){const a=r.reduce((n,s)=>{const o=typeof s._def.value;switch(o){case"string":case"number":case"boolean":return[...n,o];case"bigint":return[...n,"integer"];case"object":if(s._def.value===null)return[...n,"null"];case"symbol":case"undefined":case"function":default:return n}},[]);if(a.length===r.length){const n=a.filter((s,o,i)=>i.indexOf(s)===o);return{type:n.length>1?n:n[0],enum:r.reduce((s,o)=>s.includes(o._def.value)?s:[...s,o._def.value],[])}}}else if(r.every(a=>a._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((a,n)=>[...a,...n._def.values.filter(s=>!a.includes(s))],[])};return _w(t,e)}var _w=(t,e)=>{const r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((a,n)=>ze(a._def,{...e,currentPath:[...e.currentPath,"anyOf",`${n}`]})).filter(a=>!!a&&(!e.strictUnions||typeof a=="object"&&Object.keys(a).length>0));return r.length?{anyOf:r}:void 0};function ww(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return{type:[Qo[t.innerType._def.typeName],"null"]};const r=ze(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function bw(t){const e={type:"number"};if(!t.checks)return e;for(const r of t.checks)switch(r.kind){case"int":e.type="integer";break;case"min":r.inclusive?e.minimum=r.value:e.exclusiveMinimum=r.value;break;case"max":r.inclusive?e.maximum=r.value:e.exclusiveMaximum=r.value;break;case"multipleOf":e.multipleOf=r.value;break}return e}function xw(t,e){const r={type:"object",properties:{}},a=[],n=t.shape();for(const o in n){let i=n[o];if(i===void 0||i._def===void 0)continue;const l=Sw(i),u=ze(i._def,{...e,currentPath:[...e.currentPath,"properties",o],propertyPath:[...e.currentPath,"properties",o]});u!==void 0&&(r.properties[o]=u,l||a.push(o))}a.length&&(r.required=a);const s=Ew(t,e);return s!==void 0&&(r.additionalProperties=s),r}function Ew(t,e){if(t.catchall._def.typeName!=="ZodNever")return ze(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function Sw(t){try{return t.isOptional()}catch{return!0}}var Iw=(t,e)=>{var r;if(e.currentPath.toString()===((r=e.propertyPath)==null?void 0:r.toString()))return ze(t.innerType._def,e);const a=ze(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return a?{anyOf:[{not:Dt()},a]}:Dt()},kw=(t,e)=>{if(e.pipeStrategy==="input")return ze(t.in._def,e);if(e.pipeStrategy==="output")return ze(t.out._def,e);const r=ze(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),a=ze(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,a].filter(n=>n!==void 0)}};function Tw(t,e){return ze(t.type._def,e)}function Pw(t,e){const a={type:"array",uniqueItems:!0,items:ze(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&(a.minItems=t.minSize.value),t.maxSize&&(a.maxItems=t.maxSize.value),a}function Cw(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,a)=>ze(r._def,{...e,currentPath:[...e.currentPath,"items",`${a}`]})).reduce((r,a)=>a===void 0?r:[...r,a],[]),additionalItems:ze(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,a)=>ze(r._def,{...e,currentPath:[...e.currentPath,"items",`${a}`]})).reduce((r,a)=>a===void 0?r:[...r,a],[])}}function Rw(){return{not:Dt()}}function Ow(){return Dt()}var $w=(t,e)=>ze(t.innerType._def,e),Aw=(t,e,r)=>{switch(e){case H.ZodString:return Kc(t,r);case H.ZodNumber:return bw(t);case H.ZodObject:return xw(t,r);case H.ZodBigInt:return rw(t);case H.ZodBoolean:return nw();case H.ZodDate:return Gc(t,r);case H.ZodUndefined:return Rw();case H.ZodNull:return gw();case H.ZodArray:return tw(t,r);case H.ZodUnion:case H.ZodDiscriminatedUnion:return yw(t,r);case H.ZodIntersection:return cw(t,r);case H.ZodTuple:return Cw(t,r);case H.ZodRecord:return Yc(t,r);case H.ZodLiteral:return dw(t);case H.ZodEnum:return lw(t);case H.ZodNativeEnum:return mw(t);case H.ZodNullable:return ww(t,r);case H.ZodOptional:return Iw(t,r);case H.ZodMap:return fw(t,r);case H.ZodSet:return Pw(t,r);case H.ZodLazy:return()=>t.getter()._def;case H.ZodPromise:return Tw(t,r);case H.ZodNaN:case H.ZodNever:return vw();case H.ZodEffects:return iw(t,r);case H.ZodAny:return Dt();case H.ZodUnknown:return Ow();case H.ZodDefault:return ow(t,r);case H.ZodBranded:return Wc(t,r);case H.ZodReadonly:return $w(t,r);case H.ZodCatch:return aw(t,r);case H.ZodPipeline:return kw(t,r);case H.ZodFunction:case H.ZodVoid:case H.ZodSymbol:return;default:return(a=>{})()}};function ze(t,e,r=!1){var a;const n=e.seen.get(t);if(e.override){const l=(a=e.override)==null?void 0:a.call(e,t,e,n,r);if(l!==X0)return l}if(n&&!r){const l=Nw(n,e);if(l!==void 0)return l}const s={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,s);const o=Aw(t,t.typeName,e),i=typeof o=="function"?ze(o(),e):o;if(i&&Mw(t,e,i),e.postProcess){const l=e.postProcess(i,t,e);return s.jsonSchema=i,l}return s.jsonSchema=i,i}var Nw=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Y0(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,a)=>e.currentPath[a]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),Dt()):e.$refStrategy==="seen"?Dt():void 0}},Mw=(t,e,r)=>(t.description&&(r.description=t.description),r),Dw=t=>{const e=ew(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([a,n])=>[n._def,{def:n._def,path:[...e.basePath,e.definitionPath,a],jsonSchema:void 0}]))}},jw=(t,e)=>{var r;const a=Dw(e);let n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((u,[d,v])=>{var m;return{...u,[d]:(m=ze(v._def,{...a,currentPath:[...a.basePath,a.definitionPath,d]},!0))!=null?m:Dt()}},{}):void 0;const s=typeof e=="string"?e:(e==null?void 0:e.nameStrategy)==="title"||e==null?void 0:e.name,o=(r=ze(t._def,s===void 0?a:{...a,currentPath:[...a.basePath,a.definitionPath,s]},!1))!=null?r:Dt(),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(o.title=i);const l=s===void 0?n?{...o,[a.definitionPath]:n}:o:{$ref:[...a.$refStrategy==="relative"?[]:a.basePath,a.definitionPath,s].join("/"),[a.definitionPath]:{...n,[s]:o}};return l.$schema="http://json-schema.org/draft-07/schema#",l},zw=jw;function Lw(t,e){var r;const a=(r=void 0)!=null?r:!1;return ps(()=>zw(t,{$refStrategy:a?"root":"none"}),{validate:async n=>{const s=await t.safeParseAsync(n);return s.success?{success:!0,value:s.data}:{success:!1,error:s.error}}})}function Uw(t,e){var r;const a=(r=void 0)!=null?r:!1;return ps(()=>Ky(t,{target:"draft-7",io:"output",reused:a?"ref":"inline"}),{validate:async n=>{const s=await vc(t,n);return s.success?{success:!0,value:s.data}:{success:!1,error:s.error}}})}function Fw(t){return"_zod"in t}function Ie(t,e){return Fw(t)?Uw(t):Lw(t)}var Yo=Symbol.for("vercel.ai.schema");function bt(t){let e;return()=>(e==null&&(e=t()),e)}function ps(t,{validate:e}={}){return{[Yo]:!0,_type:void 0,[cs]:!0,get jsonSchema(){return typeof t=="function"&&(t=t()),t},validate:e}}function qw(t){return typeof t=="object"&&t!==null&&Yo in t&&t[Yo]===!0&&"jsonSchema"in t&&"validate"in t}function hs(t){return t==null?ps({properties:{},additionalProperties:!1}):qw(t)?t:typeof t=="function"?t():Ie(t)}var{btoa:Zw,atob:Vw}=globalThis;function fs(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),r=Vw(e);return Uint8Array.from(r,a=>a.codePointAt(0))}function ms(t){let e="";for(let r=0;r<t.length;r++)e+=String.fromCodePoint(t[r]);return Zw(e)}function ln(t){return t instanceof Uint8Array?ms(t):t}function Xo(t){return t==null?void 0:t.replace(/\/$/,"")}function Bw(t){return t!=null&&typeof t[Symbol.asyncIterator]=="function"}async function*Xc({execute:t,input:e,options:r}){const a=t(e,r);if(Bw(a)){let n;for await(const s of a)n=s,yield{type:"preliminary",output:s};yield{type:"final",output:n}}else yield{type:"final",output:await a}}var Hw=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Jw(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var ei=Object.defineProperty,Ww=Object.getOwnPropertyDescriptor,Gw=Object.getOwnPropertyNames,Kw=Object.prototype.hasOwnProperty,Qw=(t,e)=>{for(var r in e)ei(t,r,{get:e[r],enumerable:!0})},Yw=(t,e,r,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Gw(e))!Kw.call(t,n)&&n!==r&&ei(t,n,{get:()=>e[n],enumerable:!(a=Ww(e,n))||a.enumerable});return t},Xw=t=>Yw(ei({},"__esModule",{value:!0}),t),ed={};Qw(ed,{SYMBOL_FOR_REQ_CONTEXT:()=>td,getContext:()=>tb});var eb=Xw(ed);const td=Symbol.for("@vercel/request-context");function tb(){var e,r;return((r=(e=globalThis[td])==null?void 0:e.get)==null?void 0:r.call(e))??{}}var ti=Object.defineProperty,rb=Object.getOwnPropertyDescriptor,nb=Object.getOwnPropertyNames,ab=Object.prototype.hasOwnProperty,sb=(t,e)=>{for(var r in e)ti(t,r,{get:e[r],enumerable:!0})},ob=(t,e,r,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of nb(e))!ab.call(t,n)&&n!==r&&ti(t,n,{get:()=>e[n],enumerable:!(a=rb(e,n))||a.enumerable});return t},ib=t=>ob(ti({},"__esModule",{value:!0}),t),rd={};sb(rd,{getContext:()=>lb.getContext,getVercelOidcToken:()=>ub,getVercelOidcTokenSync:()=>cb});var nd=ib(rd),lb=eb;async function ub(){return""}function cb(){return""}var db="vercel.ai.gateway.error",ri=Symbol.for(db),ad,sd,jt=class jm extends(sd=Error,ad=ri,sd){constructor({message:e,statusCode:r=500,cause:a}){super(e),this[ad]=!0,this.statusCode=r,this.cause=a}static isInstance(e){return jm.hasMarker(e)}static hasMarker(e){return typeof e=="object"&&e!==null&&ri in e&&e[ri]===!0}},od="GatewayAuthenticationError",pb=`vercel.ai.gateway.error.${od}`,id=Symbol.for(pb),ld,ud,ni=class zm extends(ud=jt,ld=id,ud){constructor({message:e="Authentication failed",statusCode:r=401,cause:a}={}){super({message:e,statusCode:r,cause:a}),this[ld]=!0,this.name=od,this.type="authentication_error"}static isInstance(e){return jt.hasMarker(e)&&id in e}static createContextualError({apiKeyProvided:e,oidcTokenProvided:r,message:a="Authentication failed",statusCode:n=401,cause:s}){let o;return e?o=`AI Gateway authentication failed: Invalid API key.
34
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const m of this.seen.entries()){const d=m[1];if(t===m[0]){i(m);continue}if(r.external){const y=(h=r.external.registry.get(m[0]))==null?void 0:h.id;if(t!==m[0]&&y){i(m);continue}}if((_=this.metadataRegistry.get(m[0]))==null?void 0:_.id){i(m);continue}if(d.cycle){i(m);continue}if(d.count>1&&r.reused==="ref"){i(m);continue}}const a=(m,d)=>{const w=this.seen.get(m),y=w.def??w.schema,b={...y};if(w.ref===null)return;const k=w.ref;if(w.ref=null,k){a(k,d);const x=this.seen.get(k).schema;x.$ref&&d.target==="draft-7"?(y.allOf=y.allOf??[],y.allOf.push(x)):(Object.assign(y,x),Object.assign(y,b))}w.isParent||this.override({zodSchema:m,jsonSchema:y,path:w.path??[]})};for(const m of[...this.seen.entries()].reverse())a(m[0],{target:this.target});const l={};if(this.target==="draft-2020-12"?l.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?l.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),(f=r.external)!=null&&f.uri){const m=(g=r.external.registry.get(t))==null?void 0:g.id;if(!m)throw new Error("Schema is missing an `id` property");l.$id=r.external.uri(m)}Object.assign(l,o.def);const c=((v=r.external)==null?void 0:v.defs)??{};for(const m of this.seen.entries()){const d=m[1];d.def&&d.defId&&(c[d.defId]=d.def)}r.external||Object.keys(c).length>0&&(this.target==="draft-2020-12"?l.$defs=c:l.definitions=c);try{return JSON.parse(JSON.stringify(l))}catch{throw new Error("Error converting schema to JSON.")}}}function nd(e,t){if(e instanceof Hu){const r=new td(t),o={};for(const a of e._idmap.entries()){const[l,c]=a;r.process(c)}const s={},i={registry:e,uri:t==null?void 0:t.uri,defs:o};for(const a of e._idmap.entries()){const[l,c]=a;s[l]=r.emit(c,{...t,external:i})}if(Object.keys(o).length>0){const a=r.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[a]:o}}return{schemas:s}}const n=new td(t);return n.process(e),n.emit(e,t)}function De(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const o=e._zod.def;switch(o.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return De(o.element,n);case"object":{for(const s in o.shape)if(De(o.shape[s],n))return!0;return!1}case"union":{for(const s of o.options)if(De(s,n))return!0;return!1}case"intersection":return De(o.left,n)||De(o.right,n);case"tuple":{for(const s of o.items)if(De(s,n))return!0;return!!(o.rest&&De(o.rest,n))}case"record":return De(o.keyType,n)||De(o.valueType,n);case"map":return De(o.keyType,n)||De(o.valueType,n);case"set":return De(o.valueType,n);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return De(o.innerType,n);case"lazy":return De(o.getter(),n);case"default":return De(o.innerType,n);case"prefault":return De(o.innerType,n);case"custom":return!1;case"transform":return!0;case"pipe":return De(o.in,n)||De(o.out,n);case"success":return!1;case"catch":return!1}throw new Error(`Unknown schema type: ${o.type}`)}const xv=A("ZodISODateTime",(e,t)=>{X1.init(e,t),je.init(e,t)});function Pv(e){return ov(xv,e)}const Rv=A("ZodISODate",(e,t)=>{eg.init(e,t),je.init(e,t)});function Ov(e){return sv(Rv,e)}const Nv=A("ZodISOTime",(e,t)=>{tg.init(e,t),je.init(e,t)});function Mv(e){return iv(Nv,e)}const Av=A("ZodISODuration",(e,t)=>{ng.init(e,t),je.init(e,t)});function Lv(e){return av(Av,e)}const Zo=A("ZodError",(e,t)=>{$u.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>Km(e,n)},flatten:{value:n=>Wm(e,n)},addIssue:{value:n=>e.issues.push(n)},addIssues:{value:n=>e.issues.push(...n)},isEmpty:{get(){return e.issues.length===0}}})},{Parent:Error}),jv=Ym(Zo),zv=Qm(Zo),Dv=Cu(Zo),Ti=ku(Zo),Re=A("ZodType",(e,t)=>(Te.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),e.clone=(n,r)=>Ln(e,n,r),e.brand=()=>e,e.register=(n,r)=>(n.add(e,r),e),e.parse=(n,r)=>jv(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>Dv(e,n,r),e.parseAsync=async(n,r)=>zv(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>Ti(e,n,r),e.spa=e.safeParseAsync,e.refine=(n,r)=>e.check(P_(n,r)),e.superRefine=n=>e.check(R_(n)),e.overwrite=n=>e.check(Zr(n)),e.optional=()=>Y(e),e.nullable=()=>fd(e),e.nullish=()=>Y(fd(e)),e.nonoptional=n=>$_(e,n),e.array=()=>N(e),e.or=n=>Q([e,n]),e.and=n=>Pi(e,n),e.transform=n=>Oi(e,dd(n)),e.default=n=>y_(e,n),e.prefault=n=>b_(e,n),e.catch=n=>C_(e,n),e.pipe=n=>Oi(e,n),e.readonly=()=>I_(e),e.describe=n=>{const r=e.clone();return qr.add(r,{description:n}),r},Object.defineProperty(e,"description",{get(){var n;return(n=qr.get(e))==null?void 0:n.description},configurable:!0}),e.meta=(...n)=>{if(n.length===0)return qr.get(e);const r=e.clone();return qr.add(r,n[0]),r},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),rd=A("_ZodString",(e,t)=>{Ci.init(e,t),Re.init(e,t);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,e.regex=(...r)=>e.check(gv(...r)),e.includes=(...r)=>e.check(yv(...r)),e.startsWith=(...r)=>e.check(wv(...r)),e.endsWith=(...r)=>e.check(bv(...r)),e.min=(...r)=>e.check(qo(...r)),e.max=(...r)=>e.check(Xu(...r)),e.length=(...r)=>e.check(ed(...r)),e.nonempty=(...r)=>e.check(qo(1,...r)),e.lowercase=r=>e.check(vv(r)),e.uppercase=r=>e.check(_v(r)),e.trim=()=>e.check(Sv()),e.normalize=(...r)=>e.check($v(...r)),e.toLowerCase=()=>e.check(Cv()),e.toUpperCase=()=>e.check(Ev())}),Uv=A("ZodString",(e,t)=>{Ci.init(e,t),rd.init(e,t),e.email=n=>e.check(Dg(qv,n)),e.url=n=>e.check(Gu(sd,n)),e.jwt=n=>e.check(rv(n_,n)),e.emoji=n=>e.check(Vg(Fv,n)),e.guid=n=>e.check(Ju(od,n)),e.uuid=n=>e.check(Ug(Fo,n)),e.uuidv4=n=>e.check(qg(Fo,n)),e.uuidv6=n=>e.check(Zg(Fo,n)),e.uuidv7=n=>e.check(Fg(Fo,n)),e.nanoid=n=>e.check(Bg(Vv,n)),e.guid=n=>e.check(Ju(od,n)),e.cuid=n=>e.check(Hg(Bv,n)),e.cuid2=n=>e.check(Jg(Hv,n)),e.ulid=n=>e.check(Gg(Jv,n)),e.base64=n=>e.check(Wu(id,n)),e.base64url=n=>e.check(tv(e_,n)),e.xid=n=>e.check(Wg(Gv,n)),e.ksuid=n=>e.check(Kg(Wv,n)),e.ipv4=n=>e.check(Yg(Kv,n)),e.ipv6=n=>e.check(Qg(Yv,n)),e.cidrv4=n=>e.check(Xg(Qv,n)),e.cidrv6=n=>e.check(ev(Xv,n)),e.e164=n=>e.check(nv(t_,n)),e.datetime=n=>e.check(Pv(n)),e.date=n=>e.check(Ov(n)),e.time=n=>e.check(Mv(n)),e.duration=n=>e.check(Lv(n))});function p(e){return zg(Uv,e)}const je=A("ZodStringFormat",(e,t)=>{Me.init(e,t),rd.init(e,t)}),qv=A("ZodEmail",(e,t)=>{V1.init(e,t),je.init(e,t)}),od=A("ZodGUID",(e,t)=>{Z1.init(e,t),je.init(e,t)}),Fo=A("ZodUUID",(e,t)=>{F1.init(e,t),je.init(e,t)}),sd=A("ZodURL",(e,t)=>{B1.init(e,t),je.init(e,t)});function Zv(e){return Gu(sd,e)}const Fv=A("ZodEmoji",(e,t)=>{H1.init(e,t),je.init(e,t)}),Vv=A("ZodNanoID",(e,t)=>{J1.init(e,t),je.init(e,t)}),Bv=A("ZodCUID",(e,t)=>{G1.init(e,t),je.init(e,t)}),Hv=A("ZodCUID2",(e,t)=>{W1.init(e,t),je.init(e,t)}),Jv=A("ZodULID",(e,t)=>{K1.init(e,t),je.init(e,t)}),Gv=A("ZodXID",(e,t)=>{Y1.init(e,t),je.init(e,t)}),Wv=A("ZodKSUID",(e,t)=>{Q1.init(e,t),je.init(e,t)}),Kv=A("ZodIPv4",(e,t)=>{rg.init(e,t),je.init(e,t)}),Yv=A("ZodIPv6",(e,t)=>{og.init(e,t),je.init(e,t)}),Qv=A("ZodCIDRv4",(e,t)=>{sg.init(e,t),je.init(e,t)}),Xv=A("ZodCIDRv6",(e,t)=>{ig.init(e,t),je.init(e,t)}),id=A("ZodBase64",(e,t)=>{ag.init(e,t),je.init(e,t)});function ad(e){return Wu(id,e)}const e_=A("ZodBase64URL",(e,t)=>{cg.init(e,t),je.init(e,t)}),t_=A("ZodE164",(e,t)=>{ug.init(e,t),je.init(e,t)}),n_=A("ZodJWT",(e,t)=>{pg.init(e,t),je.init(e,t)}),xi=A("ZodNumber",(e,t)=>{Au.init(e,t),Re.init(e,t),e.gt=(r,o)=>e.check(Yu(r,o)),e.gte=(r,o)=>e.check(Ii(r,o)),e.min=(r,o)=>e.check(Ii(r,o)),e.lt=(r,o)=>e.check(Ku(r,o)),e.lte=(r,o)=>e.check(ki(r,o)),e.max=(r,o)=>e.check(ki(r,o)),e.int=r=>e.check(ld(r)),e.safe=r=>e.check(ld(r)),e.positive=r=>e.check(Yu(0,r)),e.nonnegative=r=>e.check(Ii(0,r)),e.negative=r=>e.check(Ku(0,r)),e.nonpositive=r=>e.check(ki(0,r)),e.multipleOf=(r,o)=>e.check(Qu(r,o)),e.step=(r,o)=>e.check(Qu(r,o)),e.finite=()=>e;const n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function R(e){return lv(xi,e)}const r_=A("ZodNumberFormat",(e,t)=>{fg.init(e,t),xi.init(e,t)});function ld(e){return uv(r_,e)}const o_=A("ZodBoolean",(e,t)=>{hg.init(e,t),Re.init(e,t)});function ne(e){return dv(o_,e)}const s_=A("ZodNull",(e,t)=>{mg.init(e,t),Re.init(e,t)});function i_(e){return pv(s_,e)}const a_=A("ZodAny",(e,t)=>{gg.init(e,t),Re.init(e,t)});function yt(){return fv(a_)}const l_=A("ZodUnknown",(e,t)=>{vg.init(e,t),Re.init(e,t)});function ke(){return hv(l_)}const c_=A("ZodNever",(e,t)=>{_g.init(e,t),Re.init(e,t)});function u_(e){return mv(c_,e)}const d_=A("ZodArray",(e,t)=>{yg.init(e,t),Re.init(e,t),e.element=t.element,e.min=(n,r)=>e.check(qo(n,r)),e.nonempty=n=>e.check(qo(1,n)),e.max=(n,r)=>e.check(Xu(n,r)),e.length=(n,r)=>e.check(ed(n,r)),e.unwrap=()=>e.element});function N(e,t){return kv(d_,e,t)}const cd=A("ZodObject",(e,t)=>{wg.init(e,t),Re.init(e,t),be(e,"shape",()=>t.shape),e.keyof=()=>me(Object.keys(e._zod.def.shape)),e.catchall=n=>e.clone({...e._zod.def,catchall:n}),e.passthrough=()=>e.clone({...e._zod.def,catchall:ke()}),e.loose=()=>e.clone({...e._zod.def,catchall:ke()}),e.strict=()=>e.clone({...e._zod.def,catchall:u_()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=n=>Bm(e,n),e.merge=n=>Hm(e,n),e.pick=n=>Fm(e,n),e.omit=n=>Vm(e,n),e.partial=(...n)=>Jm(pd,e,n[0]),e.required=(...n)=>Gm(hd,e,n[0])});function S(e,t){const n={type:"object",get shape(){return Ao(this,"shape",{...e}),this.shape},...W(t)};return new cd(n)}function He(e,t){return new cd({type:"object",get shape(){return Ao(this,"shape",{...e}),this.shape},catchall:ke(),...W(t)})}const ud=A("ZodUnion",(e,t)=>{Du.init(e,t),Re.init(e,t),e.options=t.options});function Q(e,t){return new ud({type:"union",options:e,...W(t)})}const p_=A("ZodDiscriminatedUnion",(e,t)=>{ud.init(e,t),bg.init(e,t)});function Fe(e,t,n){return new p_({type:"union",options:t,discriminator:e,...W(n)})}const f_=A("ZodIntersection",(e,t)=>{$g.init(e,t),Re.init(e,t)});function Pi(e,t){return new f_({type:"intersection",left:e,right:t})}const h_=A("ZodRecord",(e,t)=>{Sg.init(e,t),Re.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function ie(e,t,n){return new h_({type:"record",keyType:e,valueType:t,...W(n)})}const Ri=A("ZodEnum",(e,t)=>{Cg.init(e,t),Re.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(r,o)=>{const s={};for(const i of r)if(n.has(i))s[i]=t.entries[i];else throw new Error(`Key ${i} not found in enum`);return new Ri({...t,checks:[],...W(o),entries:s})},e.exclude=(r,o)=>{const s={...t.entries};for(const i of r)if(n.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new Ri({...t,checks:[],...W(o),entries:s})}});function me(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(r=>[r,r])):e;return new Ri({type:"enum",entries:n,...W(t)})}const m_=A("ZodLiteral",(e,t)=>{Eg.init(e,t),Re.init(e,t),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function O(e,t){return new m_({type:"literal",values:Array.isArray(e)?e:[e],...W(t)})}const g_=A("ZodTransform",(e,t)=>{kg.init(e,t),Re.init(e,t),e._zod.parse=(n,r)=>{n.addIssue=s=>{if(typeof s=="string")n.issues.push(Ur(s,n.value,t));else{const i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=n.value),i.inst??(i.inst=e),i.continue??(i.continue=!0),n.issues.push(Ur(i))}};const o=t.transform(n.value,n);return o instanceof Promise?o.then(s=>(n.value=s,n)):(n.value=o,n)}});function dd(e){return new g_({type:"transform",transform:e})}const pd=A("ZodOptional",(e,t)=>{Ig.init(e,t),Re.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Y(e){return new pd({type:"optional",innerType:e})}const v_=A("ZodNullable",(e,t)=>{Tg.init(e,t),Re.init(e,t),e.unwrap=()=>e._zod.def.innerType});function fd(e){return new v_({type:"nullable",innerType:e})}const __=A("ZodDefault",(e,t)=>{xg.init(e,t),Re.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function y_(e,t){return new __({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const w_=A("ZodPrefault",(e,t)=>{Pg.init(e,t),Re.init(e,t),e.unwrap=()=>e._zod.def.innerType});function b_(e,t){return new w_({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const hd=A("ZodNonOptional",(e,t)=>{Rg.init(e,t),Re.init(e,t),e.unwrap=()=>e._zod.def.innerType});function $_(e,t){return new hd({type:"nonoptional",innerType:e,...W(t)})}const S_=A("ZodCatch",(e,t)=>{Og.init(e,t),Re.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function C_(e,t){return new S_({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const E_=A("ZodPipe",(e,t)=>{Ng.init(e,t),Re.init(e,t),e.in=t.in,e.out=t.out});function Oi(e,t){return new E_({type:"pipe",in:e,out:t})}const k_=A("ZodReadonly",(e,t)=>{Mg.init(e,t),Re.init(e,t)});function I_(e){return new k_({type:"readonly",innerType:e})}const T_=A("ZodLazy",(e,t)=>{Ag.init(e,t),Re.init(e,t),e.unwrap=()=>e._zod.def.getter()});function md(e){return new T_({type:"lazy",getter:e})}const Ni=A("ZodCustom",(e,t)=>{Lg.init(e,t),Re.init(e,t)});function x_(e){const t=new ut({check:"custom"});return t._zod.check=e,t}function gd(e,t){return Iv(Ni,e??(()=>!0),t)}function P_(e,t={}){return Tv(Ni,e,t)}function R_(e){const t=x_(n=>(n.addIssue=r=>{if(typeof r=="string")n.issues.push(Ur(r,n.value,t._zod.def));else{const o=r;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=n.value),o.inst??(o.inst=t),o.continue??(o.continue=!t._zod.def.abort),n.issues.push(Ur(o))}},e(n.value,n)));return t}function Vo(e,t={error:`Input not instance of ${e.name}`}){const n=new Ni({type:"custom",check:"custom",fn:r=>r instanceof e,abort:!0,...W(t)});return n._zod.bag.Class=e,n}function O_(e,t){return Oi(dd(e),t)}const N_={custom:"custom"};function M_(e){return cv(xi,e)}var Z;(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"})(Z||(Z={}));function Mi(...e){return e.reduce((t,n)=>({...t,...n??{}}),{})}async function A_(e,t){if(e==null)return Promise.resolve();const n=t==null?void 0:t.abortSignal;return new Promise((r,o)=>{if(n!=null&&n.aborted){o(vd());return}const s=setTimeout(()=>{i(),r()},e),i=()=>{clearTimeout(s),n==null||n.removeEventListener("abort",a)},a=()=>{i(),o(vd())};n==null||n.addEventListener("abort",a)})}function vd(){return new DOMException("Delay was aborted","AbortError")}function Fr(e){return Object.fromEntries([...e.headers])}var Vr=({prefix:e,size:t=16,alphabet:n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:r="-"}={})=>{const o=()=>{const s=n.length,i=new Array(t);for(let a=0;a<t;a++)i[a]=n[Math.random()*s|0];return i.join("")};if(e==null)return o;if(n.includes(r))throw new vi({argument:"separator",message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${o()}`},L_=Vr();function Ai(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}function zn(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}var j_=["fetch failed","failed to fetch"];function _d({error:e,url:t,requestBodyValues:n}){if(zn(e))return e;if(e instanceof TypeError&&j_.includes(e.message.toLowerCase())){const r=e.cause;if(r!=null)return new Ie({message:`Cannot connect to API: ${r.message}`,cause:r,url:t,requestBodyValues:n,isRetryable:!0})}return e}function Br(e=globalThis){var t,n,r;return e.window?"runtime/browser":(t=e.navigator)!=null&&t.userAgent?`runtime/${e.navigator.userAgent.toLowerCase()}`:(r=(n=e.process)==null?void 0:n.versions)!=null&&r.node?`runtime/node.js/${e.process.version.substring(0)}`:e.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function z_(e){return Object.fromEntries(Object.entries(e).filter(([t,n])=>n!=null))}function Dn(e,...t){const n=z_(e??{}),r=new Headers(n),o=r.get("user-agent")||"";return r.set("user-agent",[o,...t].filter(Boolean).join(" ")),Object.fromEntries(r)}var yd="3.0.12",D_=()=>globalThis.fetch,wd=async({url:e,headers:t={},successfulResponseHandler:n,failedResponseHandler:r,abortSignal:o,fetch:s=D_()})=>{try{const i=await s(e,{method:"GET",headers:Dn(t,`ai-sdk/provider-utils/${yd}`,Br()),signal:o}),a=Fr(i);if(!i.ok){let l;try{l=await r({response:i,url:e,requestBodyValues:{}})}catch(c){throw zn(c)||Ie.isInstance(c)?c:new Ie({message:"Failed to process error response",cause:c,statusCode:i.status,url:e,responseHeaders:a,requestBodyValues:{}})}throw l.value}try{return await n({response:i,url:e,requestBodyValues:{}})}catch(l){throw l instanceof Error&&(zn(l)||Ie.isInstance(l))?l:new Ie({message:"Failed to process successful response",cause:l,statusCode:i.status,url:e,responseHeaders:a,requestBodyValues:{}})}}catch(i){throw _d({error:i,url:e,requestBodyValues:{}})}};function U_({mediaType:e,url:t,supportedUrls:n}){return t=t.toLowerCase(),e=e.toLowerCase(),Object.entries(n).map(([r,o])=>{const s=r.toLowerCase();return s==="*"||s==="*/*"?{mediaTypePrefix:"",regexes:o}:{mediaTypePrefix:s.replace(/\*/,""),regexes:o}}).filter(({mediaTypePrefix:r})=>e.startsWith(r)).flatMap(({regexes:r})=>r).some(r=>r.test(t))}function Bo({settingValue:e,environmentVariableName:t}){if(typeof e=="string")return e;if(!(e!=null||typeof process>"u")&&(e=process.env[t],!(e==null||typeof e!="string")))return e}var q_=/"__proto__"\s*:/,Z_=/"constructor"\s*:/;function F_(e){const t=JSON.parse(e);return t===null||typeof t!="object"||q_.test(e)===!1&&Z_.test(e)===!1?t:V_(t)}function V_(e){let t=[e];for(;t.length;){const n=t;t=[];for(const r of n){if(Object.prototype.hasOwnProperty.call(r,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(r,"constructor")&&Object.prototype.hasOwnProperty.call(r.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const o in r){const s=r[o];s&&typeof s=="object"&&t.push(s)}}}return e}function bd(e){const{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return F_(e)}finally{Error.stackTraceLimit=t}}var Ho=Symbol.for("vercel.ai.validator");function B_(e){return{[Ho]:!0,validate:e}}function H_(e){return typeof e=="object"&&e!==null&&Ho in e&&e[Ho]===!0&&"validate"in e}function ir(e){let t;return()=>(t==null&&(t=e()),t)}function J_(e){return H_(e)?e:typeof e=="function"?e():G_(e)}function G_(e){return B_(async t=>{const n=await e["~standard"].validate(t);return n.issues==null?{success:!0,value:n.value}:{success:!1,error:new Gt({value:t,cause:n.issues})}})}async function Li({value:e,schema:t}){const n=await $n({value:e,schema:t});if(!n.success)throw Gt.wrap({value:e,cause:n.error});return n.value}async function $n({value:e,schema:t}){const n=J_(t);try{if(n.validate==null)return{success:!0,value:e,rawValue:e};const r=await n.validate(e);return r.success?{success:!0,value:r.value,rawValue:e}:{success:!1,error:Gt.wrap({value:e,cause:r.error}),rawValue:e}}catch(r){return{success:!1,error:Gt.wrap({value:e,cause:r}),rawValue:e}}}async function W_({text:e,schema:t}){try{const n=bd(e);return t==null?n:Li({value:n,schema:t})}catch(n){throw yn.isInstance(n)||Gt.isInstance(n)?n:new yn({text:e,cause:n})}}async function Un({text:e,schema:t}){try{const n=bd(e);return t==null?{success:!0,value:n,rawValue:n}:await $n({value:n,schema:t})}catch(n){return{success:!1,error:yn.isInstance(n)?n:new yn({text:e,cause:n}),rawValue:void 0}}}function K_({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new Mo).pipeThrough(new TransformStream({async transform({data:n},r){n!=="[DONE]"&&r.enqueue(await Un({text:n,schema:t}))}}))}var Y_=()=>globalThis.fetch,ji=async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:o,abortSignal:s,fetch:i})=>Q_({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:o,abortSignal:s,fetch:i}),Q_=async({url:e,headers:t={},body:n,successfulResponseHandler:r,failedResponseHandler:o,abortSignal:s,fetch:i=Y_()})=>{try{const a=await i(e,{method:"POST",headers:Dn(t,`ai-sdk/provider-utils/${yd}`,Br()),body:n.content,signal:s}),l=Fr(a);if(!a.ok){let c;try{c=await o({response:a,url:e,requestBodyValues:n.values})}catch(u){throw zn(u)||Ie.isInstance(u)?u:new Ie({message:"Failed to process error response",cause:u,statusCode:a.status,url:e,responseHeaders:l,requestBodyValues:n.values})}throw c.value}try{return await r({response:a,url:e,requestBodyValues:n.values})}catch(c){throw c instanceof Error&&(zn(c)||Ie.isInstance(c))?c:new Ie({message:"Failed to process successful response",cause:c,statusCode:a.status,url:e,responseHeaders:l,requestBodyValues:n.values})}}catch(a){throw _d({error:a,url:e,requestBodyValues:n.values})}};function vI(e){return e}function $d(e){return{...e,type:"dynamic"}}async function Sn(e){return typeof e=="function"&&(e=e()),Promise.resolve(e)}var Hr=({errorSchema:e,errorToMessage:t,isRetryable:n})=>async({response:r,url:o,requestBodyValues:s})=>{const i=await r.text(),a=Fr(r);if(i.trim()==="")return{responseHeaders:a,value:new Ie({message:r.statusText,url:o,requestBodyValues:s,statusCode:r.status,responseHeaders:a,responseBody:i,isRetryable:n==null?void 0:n(r)})};try{const l=await W_({text:i,schema:e});return{responseHeaders:a,value:new Ie({message:t(l),url:o,requestBodyValues:s,statusCode:r.status,responseHeaders:a,responseBody:i,data:l,isRetryable:n==null?void 0:n(r,l)})}}catch{return{responseHeaders:a,value:new Ie({message:r.statusText,url:o,requestBodyValues:s,statusCode:r.status,responseHeaders:a,responseBody:i,isRetryable:n==null?void 0:n(r)})}}},X_=e=>async({response:t})=>{const n=Fr(t);if(t.body==null)throw new Zc({});return{responseHeaders:n,value:K_({stream:t.body,schema:e})}},Jo=e=>async({response:t,url:n,requestBodyValues:r})=>{const o=await t.text(),s=await Un({text:o,schema:e}),i=Fr(t);if(!s.success)throw new Ie({message:"Invalid JSON response",cause:s.error,statusCode:t.status,responseHeaders:i,responseBody:o,url:n,requestBodyValues:r});return{responseHeaders:i,value:s.value,rawValue:s.rawValue}},ey=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join("/")},ty=Symbol("Let zodToJsonSchema decide on which parser to use"),Sd={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",strictUnions:!1,definitions:{},errorMessages:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},ny=e=>typeof e=="string"?{...Sd,name:e}:{...Sd,...e};function wt(){return{}}function ry(e,t){var n,r,o;const s={type:"array"};return(n=e.type)!=null&&n._def&&((o=(r=e.type)==null?void 0:r._def)==null?void 0:o.typeName)!==Z.ZodAny&&(s.items=Ce(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&(s.minItems=e.minLength.value),e.maxLength&&(s.maxItems=e.maxLength.value),e.exactLength&&(s.minItems=e.exactLength.value,s.maxItems=e.exactLength.value),s}function oy(e){const t={type:"integer",format:"int64"};if(!e.checks)return t;for(const n of e.checks)switch(n.kind){case"min":n.inclusive?t.minimum=n.value:t.exclusiveMinimum=n.value;break;case"max":n.inclusive?t.maximum=n.value:t.exclusiveMaximum=n.value;break;case"multipleOf":t.multipleOf=n.value;break}return t}function sy(){return{type:"boolean"}}function Cd(e,t){return Ce(e.type._def,t)}var iy=(e,t)=>Ce(e.innerType._def,t);function Ed(e,t,n){const r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((o,s)=>Ed(e,t,o))};switch(r){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return ay(e)}}var ay=e=>{const t={type:"integer",format:"unix-time"};for(const n of e.checks)switch(n.kind){case"min":t.minimum=n.value;break;case"max":t.maximum=n.value;break}return t};function ly(e,t){return{...Ce(e.innerType._def,t),default:e.defaultValue()}}function cy(e,t){return t.effectStrategy==="input"?Ce(e.schema._def,t):wt()}function uy(e){return{type:"string",enum:Array.from(e.values)}}var dy=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function py(e,t){const n=[Ce(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),Ce(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(o=>!!o),r=[];return n.forEach(o=>{if(dy(o))r.push(...o.allOf);else{let s=o;if("additionalProperties"in o&&o.additionalProperties===!1){const{additionalProperties:i,...a}=o;s=a}r.push(s)}}),r.length?{allOf:r}:void 0}function fy(e){const t=typeof e.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(e.value)?"array":"object"}:{type:t==="bigint"?"integer":t,const:e.value}}var zi=void 0,At={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:()=>(zi===void 0&&(zi=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),zi),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 kd(e,t){const n={type:"string"};if(e.checks)for(const r of e.checks)switch(r.kind){case"min":n.minLength=typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value;break;case"max":n.maxLength=typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value;break;case"email":switch(t.emailStrategy){case"format:email":Lt(n,"email",r.message,t);break;case"format:idn-email":Lt(n,"idn-email",r.message,t);break;case"pattern:zod":rt(n,At.email,r.message,t);break}break;case"url":Lt(n,"uri",r.message,t);break;case"uuid":Lt(n,"uuid",r.message,t);break;case"regex":rt(n,r.regex,r.message,t);break;case"cuid":rt(n,At.cuid,r.message,t);break;case"cuid2":rt(n,At.cuid2,r.message,t);break;case"startsWith":rt(n,RegExp(`^${Di(r.value,t)}`),r.message,t);break;case"endsWith":rt(n,RegExp(`${Di(r.value,t)}$`),r.message,t);break;case"datetime":Lt(n,"date-time",r.message,t);break;case"date":Lt(n,"date",r.message,t);break;case"time":Lt(n,"time",r.message,t);break;case"duration":Lt(n,"duration",r.message,t);break;case"length":n.minLength=typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,n.maxLength=typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value;break;case"includes":{rt(n,RegExp(Di(r.value,t)),r.message,t);break}case"ip":{r.version!=="v6"&&Lt(n,"ipv4",r.message,t),r.version!=="v4"&&Lt(n,"ipv6",r.message,t);break}case"base64url":rt(n,At.base64url,r.message,t);break;case"jwt":rt(n,At.jwt,r.message,t);break;case"cidr":{r.version!=="v6"&&rt(n,At.ipv4Cidr,r.message,t),r.version!=="v4"&&rt(n,At.ipv6Cidr,r.message,t);break}case"emoji":rt(n,At.emoji(),r.message,t);break;case"ulid":{rt(n,At.ulid,r.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{Lt(n,"binary",r.message,t);break}case"contentEncoding:base64":{n.contentEncoding="base64";break}case"pattern:zod":{rt(n,At.base64,r.message,t);break}}break}case"nanoid":rt(n,At.nanoid,r.message,t)}return n}function Di(e,t){return t.patternStrategy==="escape"?my(e):e}var hy=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function my(e){let t="";for(let n=0;n<e.length;n++)hy.has(e[n])||(t+="\\"),t+=e[n];return t}function Lt(e,t,n,r){var o;e.format||(o=e.anyOf)!=null&&o.some(s=>s.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format}),delete e.format),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):e.format=t}function rt(e,t,n,r){var o;e.pattern||(o=e.allOf)!=null&&o.some(s=>s.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern}),delete e.pattern),e.allOf.push({pattern:Id(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):e.pattern=Id(t,r)}function Id(e,t){var n;if(!t.applyRegexFlags||!e.flags)return e.source;const r={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},o=r.i?e.source.toLowerCase():e.source;let s="",i=!1,a=!1,l=!1;for(let c=0;c<o.length;c++){if(i){s+=o[c],i=!1;continue}if(r.i){if(a){if(o[c].match(/[a-z]/)){l?(s+=o[c],s+=`${o[c-2]}-${o[c]}`.toUpperCase(),l=!1):o[c+1]==="-"&&((n=o[c+2])!=null&&n.match(/[a-z]/))?(s+=o[c],l=!0):s+=`${o[c]}${o[c].toUpperCase()}`;continue}}else if(o[c].match(/[a-z]/)){s+=`[${o[c]}${o[c].toUpperCase()}]`;continue}}if(r.m){if(o[c]==="^"){s+=`(^|(?<=[\r
35
+ ]))`;continue}else if(o[c]==="$"){s+=`($|(?=[\r
36
+ ]))`;continue}}if(r.s&&o[c]==="."){s+=a?`${o[c]}\r
37
+ `:`[${o[c]}\r
38
+ ]`;continue}s+=o[c],o[c]==="\\"?i=!0:a&&o[c]==="]"?a=!1:!a&&o[c]==="["&&(a=!0)}try{new RegExp(s)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return s}function Td(e,t){var n,r,o,s,i,a;const l={type:"object",additionalProperties:(n=Ce(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]}))!=null?n:t.allowedAdditionalProperties};if(((r=e.keyType)==null?void 0:r._def.typeName)===Z.ZodString&&((o=e.keyType._def.checks)!=null&&o.length)){const{type:c,...u}=kd(e.keyType._def,t);return{...l,propertyNames:u}}else{if(((s=e.keyType)==null?void 0:s._def.typeName)===Z.ZodEnum)return{...l,propertyNames:{enum:e.keyType._def.values}};if(((i=e.keyType)==null?void 0:i._def.typeName)===Z.ZodBranded&&e.keyType._def.type._def.typeName===Z.ZodString&&((a=e.keyType._def.type._def.checks)!=null&&a.length)){const{type:c,...u}=Cd(e.keyType._def,t);return{...l,propertyNames:u}}}return l}function gy(e,t){if(t.mapStrategy==="record")return Td(e,t);const n=Ce(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||wt(),r=Ce(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||wt();return{type:"array",maxItems:125,items:{type:"array",items:[n,r],minItems:2,maxItems:2}}}function vy(e){const t=e.values,r=Object.keys(e.values).filter(s=>typeof t[t[s]]!="number").map(s=>t[s]),o=Array.from(new Set(r.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:r}}function _y(){return{not:wt()}}function yy(){return{type:"null"}}var Ui={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function wy(e,t){const n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(r=>r._def.typeName in Ui&&(!r._def.checks||!r._def.checks.length))){const r=n.reduce((o,s)=>{const i=Ui[s._def.typeName];return i&&!o.includes(i)?[...o,i]:o},[]);return{type:r.length>1?r:r[0]}}else if(n.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){const r=n.reduce((o,s)=>{const i=typeof s._def.value;switch(i){case"string":case"number":case"boolean":return[...o,i];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];case"symbol":case"undefined":case"function":default:return o}},[]);if(r.length===n.length){const o=r.filter((s,i,a)=>a.indexOf(s)===i);return{type:o.length>1?o:o[0],enum:n.reduce((s,i)=>s.includes(i._def.value)?s:[...s,i._def.value],[])}}}else if(n.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((r,o)=>[...r,...o._def.values.filter(s=>!r.includes(s))],[])};return by(e,t)}var by=(e,t)=>{const n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((r,o)=>Ce(r._def,{...t,currentPath:[...t.currentPath,"anyOf",`${o}`]})).filter(r=>!!r&&(!t.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return n.length?{anyOf:n}:void 0};function $y(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[Ui[e.innerType._def.typeName],"null"]};const n=Ce(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}function Sy(e){const t={type:"number"};if(!e.checks)return t;for(const n of e.checks)switch(n.kind){case"int":t.type="integer";break;case"min":n.inclusive?t.minimum=n.value:t.exclusiveMinimum=n.value;break;case"max":n.inclusive?t.maximum=n.value:t.exclusiveMaximum=n.value;break;case"multipleOf":t.multipleOf=n.value;break}return t}function Cy(e,t){const n={type:"object",properties:{}},r=[],o=e.shape();for(const i in o){let a=o[i];if(a===void 0||a._def===void 0)continue;const l=ky(a),c=Ce(a._def,{...t,currentPath:[...t.currentPath,"properties",i],propertyPath:[...t.currentPath,"properties",i]});c!==void 0&&(n.properties[i]=c,l||r.push(i))}r.length&&(n.required=r);const s=Ey(e,t);return s!==void 0&&(n.additionalProperties=s),n}function Ey(e,t){if(e.catchall._def.typeName!=="ZodNever")return Ce(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 ky(e){try{return e.isOptional()}catch{return!0}}var Iy=(e,t)=>{var n;if(t.currentPath.toString()===((n=t.propertyPath)==null?void 0:n.toString()))return Ce(e.innerType._def,t);const r=Ce(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:wt()},r]}:wt()},Ty=(e,t)=>{if(t.pipeStrategy==="input")return Ce(e.in._def,t);if(t.pipeStrategy==="output")return Ce(e.out._def,t);const n=Ce(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),r=Ce(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,r].filter(o=>o!==void 0)}};function xy(e,t){return Ce(e.type._def,t)}function Py(e,t){const r={type:"array",uniqueItems:!0,items:Ce(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&(r.minItems=e.minSize.value),e.maxSize&&(r.maxItems=e.maxSize.value),r}function Ry(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((n,r)=>Ce(n._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[]),additionalItems:Ce(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((n,r)=>Ce(n._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[])}}function Oy(){return{not:wt()}}function Ny(){return wt()}var My=(e,t)=>Ce(e.innerType._def,t),Ay=(e,t,n)=>{switch(t){case Z.ZodString:return kd(e,n);case Z.ZodNumber:return Sy(e);case Z.ZodObject:return Cy(e,n);case Z.ZodBigInt:return oy(e);case Z.ZodBoolean:return sy();case Z.ZodDate:return Ed(e,n);case Z.ZodUndefined:return Oy();case Z.ZodNull:return yy();case Z.ZodArray:return ry(e,n);case Z.ZodUnion:case Z.ZodDiscriminatedUnion:return wy(e,n);case Z.ZodIntersection:return py(e,n);case Z.ZodTuple:return Ry(e,n);case Z.ZodRecord:return Td(e,n);case Z.ZodLiteral:return fy(e);case Z.ZodEnum:return uy(e);case Z.ZodNativeEnum:return vy(e);case Z.ZodNullable:return $y(e,n);case Z.ZodOptional:return Iy(e,n);case Z.ZodMap:return gy(e,n);case Z.ZodSet:return Py(e,n);case Z.ZodLazy:return()=>e.getter()._def;case Z.ZodPromise:return xy(e,n);case Z.ZodNaN:case Z.ZodNever:return _y();case Z.ZodEffects:return cy(e,n);case Z.ZodAny:return wt();case Z.ZodUnknown:return Ny();case Z.ZodDefault:return ly(e,n);case Z.ZodBranded:return Cd(e,n);case Z.ZodReadonly:return My(e,n);case Z.ZodCatch:return iy(e,n);case Z.ZodPipeline:return Ty(e,n);case Z.ZodFunction:case Z.ZodVoid:case Z.ZodSymbol:return;default:return(r=>{})()}};function Ce(e,t,n=!1){var r;const o=t.seen.get(e);if(t.override){const l=(r=t.override)==null?void 0:r.call(t,e,t,o,n);if(l!==ty)return l}if(o&&!n){const l=Ly(o,t);if(l!==void 0)return l}const s={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,s);const i=Ay(e,e.typeName,t),a=typeof i=="function"?Ce(i(),t):i;if(a&&jy(e,t,a),t.postProcess){const l=t.postProcess(a,e,t);return s.jsonSchema=a,l}return s.jsonSchema=a,a}var Ly=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:ey(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((n,r)=>t.currentPath[r]===n)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),wt()):t.$refStrategy==="seen"?wt():void 0}},jy=(e,t,n)=>(e.description&&(n.description=e.description),n),zy=e=>{const t=ny(e),n=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([r,o])=>[o._def,{def:o._def,path:[...t.basePath,t.definitionPath,r],jsonSchema:void 0}]))}},Dy=(e,t)=>{var n;const r=zy(t);let o=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[u,h])=>{var _;return{...c,[u]:(_=Ce(h._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0))!=null?_:wt()}},{}):void 0;const s=typeof t=="string"?t:(t==null?void 0:t.nameStrategy)==="title"||t==null?void 0:t.name,i=(n=Ce(e._def,s===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,s]},!1))!=null?n:wt(),a=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;a!==void 0&&(i.title=a);const l=s===void 0?o?{...i,[r.definitionPath]:o}:i:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,s].join("/"),[r.definitionPath]:{...o,[s]:i}};return l.$schema="http://json-schema.org/draft-07/schema#",l},Uy=Dy;function qy(e,t){var n;const r=(n=void 0)!=null?n:!1;return Jr(()=>Uy(e,{$refStrategy:r?"root":"none"}),{validate:async o=>{const s=await e.safeParseAsync(o);return s.success?{success:!0,value:s.data}:{success:!1,error:s.error}}})}function Zy(e,t){var n;const r=(n=void 0)!=null?n:!1;return Jr(()=>nd(e,{target:"draft-7",io:"output",reused:r?"ref":"inline"}),{validate:async o=>{const s=await Ti(e,o);return s.success?{success:!0,value:s.data}:{success:!1,error:s.error}}})}function Fy(e){return"_zod"in e}function qn(e,t){return Fy(e)?Zy(e):qy(e)}var qi=Symbol.for("vercel.ai.schema");function Jr(e,{validate:t}={}){return{[qi]:!0,_type:void 0,[Ho]:!0,get jsonSchema(){return typeof e=="function"&&(e=e()),e},validate:t}}function Vy(e){return typeof e=="object"&&e!==null&&qi in e&&e[qi]===!0&&"jsonSchema"in e&&"validate"in e}function Go(e){return e==null?Jr({properties:{},additionalProperties:!1}):Vy(e)?e:typeof e=="function"?e():qn(e)}var{btoa:By,atob:Hy}=globalThis;function Zi(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=Hy(t);return Uint8Array.from(n,r=>r.codePointAt(0))}function Fi(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return By(t)}function Jy(e){return e==null?void 0:e.replace(/\/$/,"")}function Gy(e){return e!=null&&typeof e[Symbol.asyncIterator]=="function"}async function*xd({execute:e,input:t,options:n}){const r=e(t,n);if(Gy(r)){let o;for await(const s of r)o=s,yield{type:"preliminary",output:s};yield{type:"final",output:o}}else yield{type:"final",output:await r}}function Wy(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Vi=Object.defineProperty,Ky=Object.getOwnPropertyDescriptor,Yy=Object.getOwnPropertyNames,Qy=Object.prototype.hasOwnProperty,Xy=(e,t)=>{for(var n in t)Vi(e,n,{get:t[n],enumerable:!0})},ew=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Yy(t))!Qy.call(e,o)&&o!==n&&Vi(e,o,{get:()=>t[o],enumerable:!(r=Ky(t,o))||r.enumerable});return e},tw=e=>ew(Vi({},"__esModule",{value:!0}),e),Pd={};Xy(Pd,{SYMBOL_FOR_REQ_CONTEXT:()=>Rd,getContext:()=>rw});var nw=tw(Pd);const Rd=Symbol.for("@vercel/request-context");function rw(){var t,n;return((n=(t=globalThis[Rd])==null?void 0:t.get)==null?void 0:n.call(t))??{}}var Bi=Object.defineProperty,ow=Object.getOwnPropertyDescriptor,sw=Object.getOwnPropertyNames,iw=Object.prototype.hasOwnProperty,aw=(e,t)=>{for(var n in t)Bi(e,n,{get:t[n],enumerable:!0})},lw=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of sw(t))!iw.call(e,o)&&o!==n&&Bi(e,o,{get:()=>t[o],enumerable:!(r=ow(t,o))||r.enumerable});return e},cw=e=>lw(Bi({},"__esModule",{value:!0}),e),Od={};aw(Od,{getContext:()=>uw.getContext,getVercelOidcToken:()=>dw,getVercelOidcTokenSync:()=>pw});var Nd=cw(Od),uw=nw;async function dw(){return""}function pw(){return""}var fw="vercel.ai.gateway.error",Hi=Symbol.for(fw),Md,Ad,bt=class _m extends(Ad=Error,Md=Hi,Ad){constructor({message:t,statusCode:n=500,cause:r}){super(t),this[Md]=!0,this.statusCode=n,this.cause=r}static isInstance(t){return _m.hasMarker(t)}static hasMarker(t){return typeof t=="object"&&t!==null&&Hi in t&&t[Hi]===!0}},Ld="GatewayAuthenticationError",hw=`vercel.ai.gateway.error.${Ld}`,jd=Symbol.for(hw),zd,Dd,Ji=class ym extends(Dd=bt,zd=jd,Dd){constructor({message:t="Authentication failed",statusCode:n=401,cause:r}={}){super({message:t,statusCode:n,cause:r}),this[zd]=!0,this.name=Ld,this.type="authentication_error"}static isInstance(t){return bt.hasMarker(t)&&jd in t}static createContextualError({apiKeyProvided:t,oidcTokenProvided:n,message:r="Authentication failed",statusCode:o=401,cause:s}){let i;return t?i=`AI Gateway authentication failed: Invalid API key.
39
39
 
40
40
  Create a new API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
41
41
 
42
- Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.`:r?o=`AI Gateway authentication failed: Invalid OIDC token.
42
+ Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.`:n?i=`AI Gateway authentication failed: Invalid OIDC token.
43
43
 
44
44
  Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.
45
45
 
46
- Alternatively, use an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys`:o=`AI Gateway authentication failed: No authentication provided.
46
+ Alternatively, use an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys`:i=`AI Gateway authentication failed: No authentication provided.
47
47
 
48
48
  Option 1 - API key:
49
49
  Create an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
50
50
  Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.
51
51
 
52
52
  Option 2 - OIDC token:
53
- Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`,new zm({message:o,statusCode:n,cause:s})}},cd="GatewayInvalidRequestError",hb=`vercel.ai.gateway.error.${cd}`,dd=Symbol.for(hb),pd,hd,fb=class extends(hd=jt,pd=dd,hd){constructor({message:t="Invalid request",statusCode:e=400,cause:r}={}){super({message:t,statusCode:e,cause:r}),this[pd]=!0,this.name=cd,this.type="invalid_request_error"}static isInstance(t){return jt.hasMarker(t)&&dd in t}},fd="GatewayRateLimitError",mb=`vercel.ai.gateway.error.${fd}`,md=Symbol.for(mb),vd,gd,vb=class extends(gd=jt,vd=md,gd){constructor({message:t="Rate limit exceeded",statusCode:e=429,cause:r}={}){super({message:t,statusCode:e,cause:r}),this[vd]=!0,this.name=fd,this.type="rate_limit_exceeded"}static isInstance(t){return jt.hasMarker(t)&&md in t}},yd="GatewayModelNotFoundError",gb=`vercel.ai.gateway.error.${yd}`,_d=Symbol.for(gb),yb=rt(()=>Ie(E({modelId:w()}))),wd,bd,xd=class extends(bd=jt,wd=_d,bd){constructor({message:t="Model not found",statusCode:e=404,modelId:r,cause:a}={}){super({message:t,statusCode:e,cause:a}),this[wd]=!0,this.name=yd,this.type="model_not_found",this.modelId=r}static isInstance(t){return jt.hasMarker(t)&&_d in t}},Ed="GatewayInternalServerError",_b=`vercel.ai.gateway.error.${Ed}`,Sd=Symbol.for(_b),Id,kd,Td=class extends(kd=jt,Id=Sd,kd){constructor({message:t="Internal server error",statusCode:e=500,cause:r}={}){super({message:t,statusCode:e,cause:r}),this[Id]=!0,this.name=Ed,this.type="internal_server_error"}static isInstance(t){return jt.hasMarker(t)&&Sd in t}},Pd="GatewayResponseError",wb=`vercel.ai.gateway.error.${Pd}`,Cd=Symbol.for(wb),Rd,Od,bb=class extends(Od=jt,Rd=Cd,Od){constructor({message:t="Invalid response from Gateway",statusCode:e=502,response:r,validationError:a,cause:n}={}){super({message:t,statusCode:e,cause:n}),this[Rd]=!0,this.name=Pd,this.type="response_error",this.response=r,this.validationError=a}static isInstance(t){return jt.hasMarker(t)&&Cd in t}};async function $d({response:t,statusCode:e,defaultMessage:r="Gateway request failed",cause:a,authMethod:n}){const s=await er({value:t,schema:xb});if(!s.success)return new bb({message:`Invalid error response format: ${r}`,statusCode:e,response:t,validationError:s.error,cause:a});const o=s.value,i=o.error.type,l=o.error.message;switch(i){case"authentication_error":return ni.createContextualError({apiKeyProvided:n==="api-key",oidcTokenProvided:n==="oidc",statusCode:e,cause:a});case"invalid_request_error":return new fb({message:l,statusCode:e,cause:a});case"rate_limit_exceeded":return new vb({message:l,statusCode:e,cause:a});case"model_not_found":{const u=await er({value:o.error.param,schema:yb});return new xd({message:l,statusCode:e,modelId:u.success?u.value.modelId:void 0,cause:a})}case"internal_server_error":return new Td({message:l,statusCode:e,cause:a});default:return new Td({message:l,statusCode:e,cause:a})}}var xb=rt(()=>Ie(E({error:E({message:w(),type:w().nullish(),param:Xt().nullish(),code:Ne([w(),D()]).nullish()})})));function un(t,e){var r;return jt.isInstance(t)?t:ft.isInstance(t)?$d({response:Eb(t),statusCode:(r=t.statusCode)!=null?r:500,defaultMessage:"Gateway request failed",cause:t,authMethod:e}):$d({response:{},statusCode:500,defaultMessage:t instanceof Error?`Gateway request failed: ${t.message}`:"Unknown Gateway error",cause:t,authMethod:e})}function Eb(t){if(t.data!==void 0)return t.data;if(t.responseBody!=null)try{return JSON.parse(t.responseBody)}catch{return t.responseBody}return{}}var Ad="ai-gateway-auth-method";async function da(t){const e=await er({value:t[Ad],schema:Sb});return e.success?e.value:void 0}var Sb=rt(()=>Ie(Ne([q("api-key"),q("oidc")]))),Nd=class{constructor(t){this.config=t}async getAvailableModels(){try{const{value:t}=await Vc({url:`${this.config.baseURL}/config`,headers:await zr(this.config.headers()),successfulResponseHandler:tr(Ib),failedResponseHandler:on({errorSchema:Ft(),errorToMessage:e=>e}),fetch:this.config.fetch});return t}catch(t){throw await un(t)}}async getCredits(){try{const t=new URL(this.config.baseURL),{value:e}=await Vc({url:`${t.origin}/v1/credits`,headers:await zr(this.config.headers()),successfulResponseHandler:tr(kb),failedResponseHandler:on({errorSchema:Ft(),errorToMessage:r=>r}),fetch:this.config.fetch});return e}catch(t){throw await un(t)}}},Ib=rt(()=>Ie(E({models:K(E({id:w(),name:w(),description:w().nullish(),pricing:E({input:w(),output:w(),input_cache_read:w().nullish(),input_cache_write:w().nullish()}).transform(({input:t,output:e,input_cache_read:r,input_cache_write:a})=>({input:t,output:e,...r?{cachedInputTokens:r}:{},...a?{cacheCreationInputTokens:a}:{}})).nullish(),specification:E({specificationVersion:q("v2"),provider:w(),modelId:w()}),modelType:Xe(["language","embedding","image"]).nullish()}))}))),kb=rt(()=>Ie(E({balance:w(),total_used:w()}).transform(({balance:t,total_used:e})=>({balance:t,totalUsed:e})))),Tb=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v2",this.supportedUrls={"*/*":[/.*/]}}get provider(){return this.config.provider}async getArgs(t){const{abortSignal:e,...r}=t;return{args:this.maybeEncodeFileParts(r),warnings:[]}}async doGenerate(t){const{args:e,warnings:r}=await this.getArgs(t),{abortSignal:a}=t,n=await zr(this.config.headers());try{const{responseHeaders:s,value:o,rawValue:i}=await $t({url:this.getUrl(),headers:It(n,t.headers,this.getModelConfigHeaders(this.modelId,!1),await zr(this.config.o11yHeaders)),body:e,successfulResponseHandler:tr(Ft()),failedResponseHandler:on({errorSchema:Ft(),errorToMessage:l=>l}),...a&&{abortSignal:a},fetch:this.config.fetch});return{...o,request:{body:e},response:{headers:s,body:i},warnings:r}}catch(s){throw await un(s,await da(n))}}async doStream(t){const{args:e,warnings:r}=await this.getArgs(t),{abortSignal:a}=t,n=await zr(this.config.headers());try{const{value:s,responseHeaders:o}=await $t({url:this.getUrl(),headers:It(n,t.headers,this.getModelConfigHeaders(this.modelId,!0),await zr(this.config.o11yHeaders)),body:e,successfulResponseHandler:ca(Ft()),failedResponseHandler:on({errorSchema:Ft(),errorToMessage:i=>i}),...a&&{abortSignal:a},fetch:this.config.fetch});return{stream:s.pipeThrough(new TransformStream({start(i){r.length>0&&i.enqueue({type:"stream-start",warnings:r})},transform(i,l){if(i.success){const u=i.value;if(u.type==="raw"&&!t.includeRawChunks)return;u.type==="response-metadata"&&u.timestamp&&typeof u.timestamp=="string"&&(u.timestamp=new Date(u.timestamp)),l.enqueue(u)}else l.error(i.error)}})),request:{body:e},response:{headers:o}}}catch(s){throw await un(s,await da(n))}}isFilePart(t){return t&&typeof t=="object"&&"type"in t&&t.type==="file"}maybeEncodeFileParts(t){for(const e of t.prompt)for(const r of e.content)if(this.isFilePart(r)){const a=r;if(a.data instanceof Uint8Array){const n=Uint8Array.from(a.data),s=Buffer.from(n).toString("base64");a.data=new URL(`data:${a.mediaType||"application/octet-stream"};base64,${s}`)}}return t}getUrl(){return`${this.config.baseURL}/language-model`}getModelConfigHeaders(t,e){return{"ai-language-model-specification-version":"2","ai-language-model-id":t,"ai-language-model-streaming":String(e)}}},Pb=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v2",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0}get provider(){return this.config.provider}async doEmbed({values:t,headers:e,abortSignal:r,providerOptions:a}){var n;const s=await zr(this.config.headers());try{const{responseHeaders:o,value:i,rawValue:l}=await $t({url:this.getUrl(),headers:It(s,e??{},this.getModelConfigHeaders(),await zr(this.config.o11yHeaders)),body:{input:t.length===1?t[0]:t,...a?{providerOptions:a}:{}},successfulResponseHandler:tr(Cb),failedResponseHandler:on({errorSchema:Ft(),errorToMessage:u=>u}),...r&&{abortSignal:r},fetch:this.config.fetch});return{embeddings:i.embeddings,usage:(n=i.usage)!=null?n:void 0,providerMetadata:i.providerMetadata,response:{headers:o,body:l}}}catch(o){throw await un(o,await da(s))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":"2","ai-model-id":this.modelId}}},Cb=rt(()=>Ie(E({embeddings:K(K(D())),usage:E({tokens:D()}).nullish(),providerMetadata:ot(w(),ot(w(),Xt())).optional()})));async function Rb(){var t;return(t=nd.getContext().headers)==null?void 0:t["x-vercel-id"]}var Ob="2.0.0",$b="0.0.1";function Ab(t={}){var e,r;let a=null,n=null;const s=(e=t.metadataCacheRefreshMillis)!=null?e:1e3*60*5;let o=0;const i=(r=Xo(t.baseURL))!=null?r:"https://ai-gateway.vercel.sh/v1/ai",l=async()=>{const h=await Mb(t);if(h)return an({Authorization:`Bearer ${h.token}`,"ai-gateway-protocol-version":$b,[Ad]:h.authMethod,...t.headers},`ai-sdk/gateway/${Ob}`);throw ni.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401})},u=()=>{const h=ua({settingValue:void 0,environmentVariableName:"VERCEL_DEPLOYMENT_ID"}),g=ua({settingValue:void 0,environmentVariableName:"VERCEL_ENV"}),f=ua({settingValue:void 0,environmentVariableName:"VERCEL_REGION"});return async()=>{const p=await Rb();return{...h&&{"ai-o11y-deployment-id":h},...g&&{"ai-o11y-environment":g},...f&&{"ai-o11y-region":f},...p&&{"ai-o11y-request-id":p}}}},d=h=>new Tb(h,{provider:"gateway",baseURL:i,headers:l,fetch:t.fetch,o11yHeaders:u()}),v=async()=>{var h,g,f;const p=(f=(g=(h=t._internal)==null?void 0:h.currentDate)==null?void 0:g.call(h).getTime())!=null?f:Date.now();return(!a||p-o>s)&&(o=p,a=new Nd({baseURL:i,headers:l,fetch:t.fetch}).getAvailableModels().then(b=>(n=b,b)).catch(async b=>{throw await un(b,await da(await l()))})),n?Promise.resolve(n):a},m=async()=>new Nd({baseURL:i,headers:l,fetch:t.fetch}).getCredits().catch(async h=>{throw await un(h,await da(await l()))}),c=function(h){if(new.target)throw new Error("The Gateway Provider model function cannot be called with the new keyword.");return d(h)};return c.getAvailableModels=v,c.getCredits=m,c.imageModel=h=>{throw new bo({modelId:h,modelType:"imageModel"})},c.languageModel=d,c.textEmbeddingModel=h=>new Pb(h,{provider:"gateway",baseURL:i,headers:l,fetch:t.fetch,o11yHeaders:u()}),c}var Nb=Ab();async function Mb(t){const e=ua({settingValue:t.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});if(e)return{token:e,authMethod:"api-key"};try{return{token:await nd.getVercelOidcToken(),authMethod:"oidc"}}catch{return null}}var Db=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{},cn="1.9.0",Md=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function jb(t){var e=new Set([t]),r=new Set,a=t.match(Md);if(!a)return function(){return!1};var n={major:+a[1],minor:+a[2],patch:+a[3],prerelease:a[4]};if(n.prerelease!=null)return function(l){return l===t};function s(i){return r.add(i),!1}function o(i){return e.add(i),!0}return function(l){if(e.has(l))return!0;if(r.has(l))return!1;var u=l.match(Md);if(!u)return s(l);var d={major:+u[1],minor:+u[2],patch:+u[3],prerelease:u[4]};return d.prerelease!=null||n.major!==d.major?s(l):n.major===0?n.minor===d.minor&&n.patch<=d.patch?o(l):s(l):n.minor<=d.minor?o(l):s(l)}}var zb=jb(cn),Lb=cn.split(".")[0],pa=Symbol.for("opentelemetry.js.api."+Lb),ha=Db;function fa(t,e,r,a){var n;a===void 0&&(a=!1);var s=ha[pa]=(n=ha[pa])!==null&&n!==void 0?n:{version:cn};if(!a&&s[t]){var o=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+t);return r.error(o.stack||o.message),!1}if(s.version!==cn){var o=new Error("@opentelemetry/api: Registration of version v"+s.version+" for "+t+" does not match previously registered API v"+cn);return r.error(o.stack||o.message),!1}return s[t]=e,r.debug("@opentelemetry/api: Registered a global for "+t+" v"+cn+"."),!0}function dn(t){var e,r,a=(e=ha[pa])===null||e===void 0?void 0:e.version;if(!(!a||!zb(a)))return(r=ha[pa])===null||r===void 0?void 0:r[t]}function ma(t,e){e.debug("@opentelemetry/api: Unregistering a global for "+t+" v"+cn+".");var r=ha[pa];r&&delete r[t]}var Ub=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var a=r.call(t),n,s=[],o;try{for(;(e===void 0||e-- >0)&&!(n=a.next()).done;)s.push(n.value)}catch(i){o={error:i}}finally{try{n&&!n.done&&(r=a.return)&&r.call(a)}finally{if(o)throw o.error}}return s},Fb=function(t,e,r){if(r||arguments.length===2)for(var a=0,n=e.length,s;a<n;a++)(s||!(a in e))&&(s||(s=Array.prototype.slice.call(e,0,a)),s[a]=e[a]);return t.concat(s||Array.prototype.slice.call(e))},qb=function(){function t(e){this._namespace=e.namespace||"DiagComponentLogger"}return t.prototype.debug=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return va("debug",this._namespace,e)},t.prototype.error=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return va("error",this._namespace,e)},t.prototype.info=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return va("info",this._namespace,e)},t.prototype.warn=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return va("warn",this._namespace,e)},t.prototype.verbose=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return va("verbose",this._namespace,e)},t}();function va(t,e,r){var a=dn("diag");if(a)return r.unshift(e),a[t].apply(a,Fb([],Ub(r),!1))}var zt;(function(t){t[t.NONE=0]="NONE",t[t.ERROR=30]="ERROR",t[t.WARN=50]="WARN",t[t.INFO=60]="INFO",t[t.DEBUG=70]="DEBUG",t[t.VERBOSE=80]="VERBOSE",t[t.ALL=9999]="ALL"})(zt||(zt={}));function Zb(t,e){t<zt.NONE?t=zt.NONE:t>zt.ALL&&(t=zt.ALL),e=e||{};function r(a,n){var s=e[a];return typeof s=="function"&&t>=n?s.bind(e):function(){}}return{error:r("error",zt.ERROR),warn:r("warn",zt.WARN),info:r("info",zt.INFO),debug:r("debug",zt.DEBUG),verbose:r("verbose",zt.VERBOSE)}}var Vb=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var a=r.call(t),n,s=[],o;try{for(;(e===void 0||e-- >0)&&!(n=a.next()).done;)s.push(n.value)}catch(i){o={error:i}}finally{try{n&&!n.done&&(r=a.return)&&r.call(a)}finally{if(o)throw o.error}}return s},Bb=function(t,e,r){if(r||arguments.length===2)for(var a=0,n=e.length,s;a<n;a++)(s||!(a in e))&&(s||(s=Array.prototype.slice.call(e,0,a)),s[a]=e[a]);return t.concat(s||Array.prototype.slice.call(e))},Hb="diag",pr=function(){function t(){function e(n){return function(){for(var s=[],o=0;o<arguments.length;o++)s[o]=arguments[o];var i=dn("diag");if(i)return i[n].apply(i,Bb([],Vb(s),!1))}}var r=this,a=function(n,s){var o,i,l;if(s===void 0&&(s={logLevel:zt.INFO}),n===r){var u=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return r.error((o=u.stack)!==null&&o!==void 0?o:u.message),!1}typeof s=="number"&&(s={logLevel:s});var d=dn("diag"),v=Zb((i=s.logLevel)!==null&&i!==void 0?i:zt.INFO,n);if(d&&!s.suppressOverrideMessage){var m=(l=new Error().stack)!==null&&l!==void 0?l:"<failed to generate stacktrace>";d.warn("Current logger will be overwritten from "+m),v.warn("Current logger will overwrite one already registered from "+m)}return fa("diag",v,r,!0)};r.setLogger=a,r.disable=function(){ma(Hb,r)},r.createComponentLogger=function(n){return new qb(n)},r.verbose=e("verbose"),r.debug=e("debug"),r.info=e("info"),r.warn=e("warn"),r.error=e("error")}return t.instance=function(){return this._instance||(this._instance=new t),this._instance},t}(),Jb=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var a=r.call(t),n,s=[],o;try{for(;(e===void 0||e-- >0)&&!(n=a.next()).done;)s.push(n.value)}catch(i){o={error:i}}finally{try{n&&!n.done&&(r=a.return)&&r.call(a)}finally{if(o)throw o.error}}return s},Wb=function(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],a=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&a>=t.length&&(t=void 0),{value:t&&t[a++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},Gb=function(){function t(e){this._entries=e?new Map(e):new Map}return t.prototype.getEntry=function(e){var r=this._entries.get(e);if(r)return Object.assign({},r)},t.prototype.getAllEntries=function(){return Array.from(this._entries.entries()).map(function(e){var r=Jb(e,2),a=r[0],n=r[1];return[a,n]})},t.prototype.setEntry=function(e,r){var a=new t(this._entries);return a._entries.set(e,r),a},t.prototype.removeEntry=function(e){var r=new t(this._entries);return r._entries.delete(e),r},t.prototype.removeEntries=function(){for(var e,r,a=[],n=0;n<arguments.length;n++)a[n]=arguments[n];var s=new t(this._entries);try{for(var o=Wb(a),i=o.next();!i.done;i=o.next()){var l=i.value;s._entries.delete(l)}}catch(u){e={error:u}}finally{try{i&&!i.done&&(r=o.return)&&r.call(o)}finally{if(e)throw e.error}}return s},t.prototype.clear=function(){return new t},t}();pr.instance();function Kb(t){return t===void 0&&(t={}),new Gb(new Map(Object.entries(t)))}function Dd(t){return Symbol.for(t)}var Qb=function(){function t(e){var r=this;r._currentContext=e?new Map(e):new Map,r.getValue=function(a){return r._currentContext.get(a)},r.setValue=function(a,n){var s=new t(r._currentContext);return s._currentContext.set(a,n),s},r.deleteValue=function(a){var n=new t(r._currentContext);return n._currentContext.delete(a),n}}return t}(),Yb=new Qb,pn=function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(a,n){a.__proto__=n}||function(a,n){for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(a[s]=n[s])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function a(){this.constructor=e}e.prototype=r===null?Object.create(r):(a.prototype=r.prototype,new a)}}(),Xb=function(){function t(){}return t.prototype.createGauge=function(e,r){return u1},t.prototype.createHistogram=function(e,r){return c1},t.prototype.createCounter=function(e,r){return l1},t.prototype.createUpDownCounter=function(e,r){return d1},t.prototype.createObservableGauge=function(e,r){return h1},t.prototype.createObservableCounter=function(e,r){return p1},t.prototype.createObservableUpDownCounter=function(e,r){return f1},t.prototype.addBatchObservableCallback=function(e,r){},t.prototype.removeBatchObservableCallback=function(e){},t}(),vs=function(){function t(){}return t}(),e1=function(t){pn(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.add=function(r,a){},e}(vs),t1=function(t){pn(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.add=function(r,a){},e}(vs),r1=function(t){pn(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.record=function(r,a){},e}(vs),n1=function(t){pn(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.record=function(r,a){},e}(vs),ai=function(){function t(){}return t.prototype.addCallback=function(e){},t.prototype.removeCallback=function(e){},t}(),a1=function(t){pn(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(ai),s1=function(t){pn(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(ai),o1=function(t){pn(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(ai),i1=new Xb,l1=new e1,u1=new r1,c1=new n1,d1=new t1,p1=new a1,h1=new s1,f1=new o1,m1={get:function(t,e){if(t!=null)return t[e]},keys:function(t){return t==null?[]:Object.keys(t)}},v1={set:function(t,e,r){t!=null&&(t[e]=r)}},g1=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var a=r.call(t),n,s=[],o;try{for(;(e===void 0||e-- >0)&&!(n=a.next()).done;)s.push(n.value)}catch(i){o={error:i}}finally{try{n&&!n.done&&(r=a.return)&&r.call(a)}finally{if(o)throw o.error}}return s},y1=function(t,e,r){if(r||arguments.length===2)for(var a=0,n=e.length,s;a<n;a++)(s||!(a in e))&&(s||(s=Array.prototype.slice.call(e,0,a)),s[a]=e[a]);return t.concat(s||Array.prototype.slice.call(e))},_1=function(){function t(){}return t.prototype.active=function(){return Yb},t.prototype.with=function(e,r,a){for(var n=[],s=3;s<arguments.length;s++)n[s-3]=arguments[s];return r.call.apply(r,y1([a],g1(n),!1))},t.prototype.bind=function(e,r){return r},t.prototype.enable=function(){return this},t.prototype.disable=function(){return this},t}(),w1=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var a=r.call(t),n,s=[],o;try{for(;(e===void 0||e-- >0)&&!(n=a.next()).done;)s.push(n.value)}catch(i){o={error:i}}finally{try{n&&!n.done&&(r=a.return)&&r.call(a)}finally{if(o)throw o.error}}return s},b1=function(t,e,r){if(r||arguments.length===2)for(var a=0,n=e.length,s;a<n;a++)(s||!(a in e))&&(s||(s=Array.prototype.slice.call(e,0,a)),s[a]=e[a]);return t.concat(s||Array.prototype.slice.call(e))},si="context",x1=new _1,gs=function(){function t(){}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalContextManager=function(e){return fa(si,e,pr.instance())},t.prototype.active=function(){return this._getContextManager().active()},t.prototype.with=function(e,r,a){for(var n,s=[],o=3;o<arguments.length;o++)s[o-3]=arguments[o];return(n=this._getContextManager()).with.apply(n,b1([e,r,a],w1(s),!1))},t.prototype.bind=function(e,r){return this._getContextManager().bind(e,r)},t.prototype._getContextManager=function(){return dn(si)||x1},t.prototype.disable=function(){this._getContextManager().disable(),ma(si,pr.instance())},t}(),oi;(function(t){t[t.NONE=0]="NONE",t[t.SAMPLED=1]="SAMPLED"})(oi||(oi={}));var jd="0000000000000000",zd="00000000000000000000000000000000",E1={traceId:zd,spanId:jd,traceFlags:oi.NONE},ga=function(){function t(e){e===void 0&&(e=E1),this._spanContext=e}return t.prototype.spanContext=function(){return this._spanContext},t.prototype.setAttribute=function(e,r){return this},t.prototype.setAttributes=function(e){return this},t.prototype.addEvent=function(e,r){return this},t.prototype.addLink=function(e){return this},t.prototype.addLinks=function(e){return this},t.prototype.setStatus=function(e){return this},t.prototype.updateName=function(e){return this},t.prototype.end=function(e){},t.prototype.isRecording=function(){return!1},t.prototype.recordException=function(e,r){},t}(),ii=Dd("OpenTelemetry Context Key SPAN");function li(t){return t.getValue(ii)||void 0}function S1(){return li(gs.getInstance().active())}function ui(t,e){return t.setValue(ii,e)}function I1(t){return t.deleteValue(ii)}function k1(t,e){return ui(t,new ga(e))}function Ld(t){var e;return(e=li(t))===null||e===void 0?void 0:e.spanContext()}var T1=/^([0-9a-f]{32})$/i,P1=/^[0-9a-f]{16}$/i;function C1(t){return T1.test(t)&&t!==zd}function R1(t){return P1.test(t)&&t!==jd}function Ud(t){return C1(t.traceId)&&R1(t.spanId)}function O1(t){return new ga(t)}var ci=gs.getInstance(),Fd=function(){function t(){}return t.prototype.startSpan=function(e,r,a){a===void 0&&(a=ci.active());var n=!!(r!=null&&r.root);if(n)return new ga;var s=a&&Ld(a);return $1(s)&&Ud(s)?new ga(s):new ga},t.prototype.startActiveSpan=function(e,r,a,n){var s,o,i;if(!(arguments.length<2)){arguments.length===2?i=r:arguments.length===3?(s=r,i=a):(s=r,o=a,i=n);var l=o??ci.active(),u=this.startSpan(e,s,l),d=ui(l,u);return ci.with(d,i,void 0,u)}},t}();function $1(t){return typeof t=="object"&&typeof t.spanId=="string"&&typeof t.traceId=="string"&&typeof t.traceFlags=="number"}var A1=new Fd,N1=function(){function t(e,r,a,n){this._provider=e,this.name=r,this.version=a,this.options=n}return t.prototype.startSpan=function(e,r,a){return this._getTracer().startSpan(e,r,a)},t.prototype.startActiveSpan=function(e,r,a,n){var s=this._getTracer();return Reflect.apply(s.startActiveSpan,s,arguments)},t.prototype._getTracer=function(){if(this._delegate)return this._delegate;var e=this._provider.getDelegateTracer(this.name,this.version,this.options);return e?(this._delegate=e,this._delegate):A1},t}(),M1=function(){function t(){}return t.prototype.getTracer=function(e,r,a){return new Fd},t}(),D1=new M1,qd=function(){function t(){}return t.prototype.getTracer=function(e,r,a){var n;return(n=this.getDelegateTracer(e,r,a))!==null&&n!==void 0?n:new N1(this,e,r,a)},t.prototype.getDelegate=function(){var e;return(e=this._delegate)!==null&&e!==void 0?e:D1},t.prototype.setDelegate=function(e){this._delegate=e},t.prototype.getDelegateTracer=function(e,r,a){var n;return(n=this._delegate)===null||n===void 0?void 0:n.getTracer(e,r,a)},t}(),ys;(function(t){t[t.UNSET=0]="UNSET",t[t.OK=1]="OK",t[t.ERROR=2]="ERROR"})(ys||(ys={})),gs.getInstance(),pr.instance();var j1=function(){function t(){}return t.prototype.getMeter=function(e,r,a){return i1},t}(),z1=new j1,di="metrics",L1=function(){function t(){}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalMeterProvider=function(e){return fa(di,e,pr.instance())},t.prototype.getMeterProvider=function(){return dn(di)||z1},t.prototype.getMeter=function(e,r,a){return this.getMeterProvider().getMeter(e,r,a)},t.prototype.disable=function(){ma(di,pr.instance())},t}();L1.getInstance();var U1=function(){function t(){}return t.prototype.inject=function(e,r){},t.prototype.extract=function(e,r){return e},t.prototype.fields=function(){return[]},t}(),pi=Dd("OpenTelemetry Baggage Key");function Zd(t){return t.getValue(pi)||void 0}function F1(){return Zd(gs.getInstance().active())}function q1(t,e){return t.setValue(pi,e)}function Z1(t){return t.deleteValue(pi)}var hi="propagation",V1=new U1,B1=function(){function t(){this.createBaggage=Kb,this.getBaggage=Zd,this.getActiveBaggage=F1,this.setBaggage=q1,this.deleteBaggage=Z1}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalPropagator=function(e){return fa(hi,e,pr.instance())},t.prototype.inject=function(e,r,a){return a===void 0&&(a=v1),this._getGlobalPropagator().inject(e,r,a)},t.prototype.extract=function(e,r,a){return a===void 0&&(a=m1),this._getGlobalPropagator().extract(e,r,a)},t.prototype.fields=function(){return this._getGlobalPropagator().fields()},t.prototype.disable=function(){ma(hi,pr.instance())},t.prototype._getGlobalPropagator=function(){return dn(hi)||V1},t}();B1.getInstance();var fi="trace",H1=function(){function t(){this._proxyTracerProvider=new qd,this.wrapSpanContext=O1,this.isSpanContextValid=Ud,this.deleteSpan=I1,this.getSpan=li,this.getActiveSpan=S1,this.getSpanContext=Ld,this.setSpan=ui,this.setSpanContext=k1}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalTracerProvider=function(e){var r=fa(fi,this._proxyTracerProvider,pr.instance());return r&&this._proxyTracerProvider.setDelegate(e),r},t.prototype.getTracerProvider=function(){return dn(fi)||this._proxyTracerProvider},t.prototype.getTracer=function(e,r){return this.getTracerProvider().getTracer(e,r)},t.prototype.disable=function(){ma(fi,pr.instance()),this._proxyTracerProvider=new qd},t}(),J1=H1.getInstance(),W1=Object.defineProperty,G1=(t,e)=>{for(var r in e)W1(t,r,{get:e[r],enumerable:!0})},Vd="AI_NoOutputSpecifiedError",Bd=`vercel.ai.error.${Vd}`,K1=Symbol.for(Bd),Hd,Jd=class extends ve{constructor({message:t="No output specified."}={}){super({name:Vd,message:t}),this[Hd]=!0}static isInstance(t){return ve.hasMarker(t,Bd)}};Hd=K1;function Q1(t){const e="AI SDK Warning:";switch(t.type){case"unsupported-setting":{let r=`${e} The "${t.setting}" setting is not supported by this model`;return t.details&&(r+=` - ${t.details}`),r}case"unsupported-tool":{const r="name"in t.tool?t.tool.name:"unknown tool";let a=`${e} The tool "${r}" is not supported by this model`;return t.details&&(a+=` - ${t.details}`),a}case"other":return`${e} ${t.message}`;default:return`${e} ${JSON.stringify(t,null,2)}`}}var Y1="AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.",Wd=!1,Gd=t=>{if(t.length===0)return;const e=globalThis.AI_SDK_LOG_WARNINGS;if(e!==!1){if(typeof e=="function"){e(t);return}Wd||(Wd=!0,console.info(Y1));for(const r of t)console.warn(Q1(r))}},Kd="AI_InvalidArgumentError",Qd=`vercel.ai.error.${Kd}`,X1=Symbol.for(Qd),Yd,hr=class extends ve{constructor({parameter:t,value:e,message:r}){super({name:Kd,message:`Invalid argument for parameter ${t}: ${r}`}),this[Yd]=!0,this.parameter=t,this.value=e}static isInstance(t){return ve.hasMarker(t,Qd)}};Yd=X1;var Xd="AI_InvalidToolInputError",ep=`vercel.ai.error.${Xd}`,ex=Symbol.for(ep),tp,rp=class extends ve{constructor({toolInput:t,toolName:e,cause:r,message:a=`Invalid input for tool ${e}: ${En(r)}`}){super({name:Xd,message:a,cause:r}),this[tp]=!0,this.toolInput=t,this.toolName=e}static isInstance(t){return ve.hasMarker(t,ep)}};tp=ex;var np="AI_NoObjectGeneratedError",ap=`vercel.ai.error.${np}`,tx=Symbol.for(ap),sp,op=class extends ve{constructor({message:t="No object generated.",cause:e,text:r,response:a,usage:n,finishReason:s}){super({name:np,message:t,cause:e}),this[sp]=!0,this.text=r,this.response=a,this.usage=n,this.finishReason=s}static isInstance(t){return ve.hasMarker(t,ap)}};sp=tx;var ip="AI_NoOutputGeneratedError",lp=`vercel.ai.error.${ip}`,rx=Symbol.for(lp),up,nx=class extends ve{constructor({message:t="No output generated.",cause:e}={}){super({name:ip,message:t,cause:e}),this[up]=!0}static isInstance(t){return ve.hasMarker(t,lp)}};up=rx;var cp="AI_NoSuchToolError",dp=`vercel.ai.error.${cp}`,ax=Symbol.for(dp),pp,mi=class extends ve{constructor({toolName:t,availableTools:e=void 0,message:r=`Model tried to call unavailable tool '${t}'. ${e===void 0?"No tools are available.":`Available tools: ${e.join(", ")}.`}`}){super({name:cp,message:r}),this[pp]=!0,this.toolName=t,this.availableTools=e}static isInstance(t){return ve.hasMarker(t,dp)}};pp=ax;var hp="AI_ToolCallRepairError",fp=`vercel.ai.error.${hp}`,sx=Symbol.for(fp),mp,ox=class extends ve{constructor({cause:t,originalError:e,message:r=`Error repairing tool call: ${En(t)}`}){super({name:hp,message:r,cause:t}),this[mp]=!0,this.originalError=e}static isInstance(t){return ve.hasMarker(t,fp)}};mp=sx;var ix=class extends ve{constructor(t){super({name:"AI_UnsupportedModelVersionError",message:`Unsupported model version ${t.version} for provider "${t.provider}" and model "${t.modelId}". AI SDK 5 only supports models that implement specification version "v2".`}),this.version=t.version,this.provider=t.provider,this.modelId=t.modelId}},vp="AI_InvalidMessageRoleError",gp=`vercel.ai.error.${vp}`,lx=Symbol.for(gp),yp,ux=class extends ve{constructor({role:t,message:e=`Invalid message role: '${t}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:vp,message:e}),this[yp]=!0,this.role=t}static isInstance(t){return ve.hasMarker(t,gp)}};yp=lx;var _p="AI_DownloadError",wp=`vercel.ai.error.${_p}`,cx=Symbol.for(wp),bp,vi=class extends ve{constructor({url:t,statusCode:e,statusText:r,cause:a,message:n=a==null?`Failed to download ${t}: ${e} ${r}`:`Failed to download ${t}: ${a}`}){super({name:_p,message:n,cause:a}),this[bp]=!0,this.url=t,this.statusCode=e,this.statusText=r}static isInstance(t){return ve.hasMarker(t,wp)}};bp=cx;var xp="AI_RetryError",Ep=`vercel.ai.error.${xp}`,dx=Symbol.for(Ep),Sp,Ip=class extends ve{constructor({message:t,reason:e,errors:r}){super({name:xp,message:t}),this[Sp]=!0,this.reason=e,this.errors=r,this.lastError=r[r.length-1]}static isInstance(t){return ve.hasMarker(t,Ep)}};Sp=dx;function _s(t){if(typeof t!="string"){if(t.specificationVersion!=="v2")throw new ix({version:t.specificationVersion,provider:t.provider,modelId:t.modelId});return t}return px().languageModel(t)}function px(){var t;return(t=globalThis.AI_SDK_DEFAULT_PROVIDER)!=null?t:Nb}var hx=[{mediaType:"image/gif",bytesPrefix:[71,73,70]},{mediaType:"image/png",bytesPrefix:[137,80,78,71]},{mediaType:"image/jpeg",bytesPrefix:[255,216]},{mediaType:"image/webp",bytesPrefix:[82,73,70,70,null,null,null,null,87,69,66,80]},{mediaType:"image/bmp",bytesPrefix:[66,77]},{mediaType:"image/tiff",bytesPrefix:[73,73,42,0]},{mediaType:"image/tiff",bytesPrefix:[77,77,0,42]},{mediaType:"image/avif",bytesPrefix:[0,0,0,32,102,116,121,112,97,118,105,102]},{mediaType:"image/heic",bytesPrefix:[0,0,0,32,102,116,121,112,104,101,105,99]}],fx=t=>{const e=typeof t=="string"?fs(t):t,r=(e[6]&127)<<21|(e[7]&127)<<14|(e[8]&127)<<7|e[9]&127;return e.slice(r+10)};function mx(t){return typeof t=="string"&&t.startsWith("SUQz")||typeof t!="string"&&t.length>10&&t[0]===73&&t[1]===68&&t[2]===51?fx(t):t}function vx({data:t,signatures:e}){const r=mx(t),a=typeof r=="string"?fs(r.substring(0,Math.min(r.length,24))):r;for(const n of e)if(a.length>=n.bytesPrefix.length&&n.bytesPrefix.every((s,o)=>s===null||a[o]===s))return n.mediaType}var kp="5.0.76",gx=async({url:t})=>{var e;const r=t.toString();try{const a=await fetch(r,{headers:an({},`ai-sdk/${kp}`,Jo())});if(!a.ok)throw new vi({url:r,statusCode:a.status,statusText:a.statusText});return{data:new Uint8Array(await a.arrayBuffer()),mediaType:(e=a.headers.get("content-type"))!=null?e:void 0}}catch(a){throw vi.isInstance(a)?a:new vi({url:r,cause:a})}},yx=(t=gx)=>e=>Promise.all(e.map(async r=>r.isUrlSupportedByModel?null:t(r)));function _x(t){try{const[e,r]=t.split(",");return{mediaType:e.split(";")[0].split(":")[1],base64Content:r}}catch{return{mediaType:void 0,base64Content:void 0}}}var Tp=Ne([w(),Xa(Uint8Array),Xa(ArrayBuffer),e0(t=>{var e,r;return(r=(e=globalThis.Buffer)==null?void 0:e.isBuffer(t))!=null?r:!1},{message:"Must be a Buffer"})]);function Pp(t){if(t instanceof Uint8Array)return{data:t,mediaType:void 0};if(t instanceof ArrayBuffer)return{data:new Uint8Array(t),mediaType:void 0};if(typeof t=="string")try{t=new URL(t)}catch{}if(t instanceof URL&&t.protocol==="data:"){const{mediaType:e,base64Content:r}=_x(t.toString());if(e==null||r==null)throw new ve({name:"InvalidDataContentError",message:`Invalid data URL format in content ${t.toString()}`});return{data:r,mediaType:e}}return{data:t,mediaType:void 0}}function wx(t){return typeof t=="string"?t:t instanceof ArrayBuffer?ms(new Uint8Array(t)):ms(t)}async function Cp({prompt:t,supportedUrls:e,download:r=yx()}){const a=await xx(t.messages,r,e);return[...t.system!=null?[{role:"system",content:t.system}]:[],...t.messages.map(n=>bx({message:n,downloadedAssets:a}))]}function bx({message:t,downloadedAssets:e}){const r=t.role;switch(r){case"system":return{role:"system",content:t.content,providerOptions:t.providerOptions};case"user":return typeof t.content=="string"?{role:"user",content:[{type:"text",text:t.content}],providerOptions:t.providerOptions}:{role:"user",content:t.content.map(a=>Ex(a,e)).filter(a=>a.type!=="text"||a.text!==""),providerOptions:t.providerOptions};case"assistant":return typeof t.content=="string"?{role:"assistant",content:[{type:"text",text:t.content}],providerOptions:t.providerOptions}:{role:"assistant",content:t.content.filter(a=>a.type!=="text"||a.text!==""||a.providerOptions!=null).map(a=>{const n=a.providerOptions;switch(a.type){case"file":{const{data:s,mediaType:o}=Pp(a.data);return{type:"file",data:s,filename:a.filename,mediaType:o??a.mediaType,providerOptions:n}}case"reasoning":return{type:"reasoning",text:a.text,providerOptions:n};case"text":return{type:"text",text:a.text,providerOptions:n};case"tool-call":return{type:"tool-call",toolCallId:a.toolCallId,toolName:a.toolName,input:a.input,providerExecuted:a.providerExecuted,providerOptions:n};case"tool-result":return{type:"tool-result",toolCallId:a.toolCallId,toolName:a.toolName,output:a.output,providerOptions:n}}}),providerOptions:t.providerOptions};case"tool":return{role:"tool",content:t.content.map(a=>({type:"tool-result",toolCallId:a.toolCallId,toolName:a.toolName,output:a.output,providerOptions:a.providerOptions})),providerOptions:t.providerOptions};default:{const a=r;throw new ux({role:a})}}}async function xx(t,e,r){const a=t.filter(s=>s.role==="user").map(s=>s.content).filter(s=>Array.isArray(s)).flat().filter(s=>s.type==="image"||s.type==="file").map(s=>{var o;const i=(o=s.mediaType)!=null?o:s.type==="image"?"image/*":void 0;let l=s.type==="image"?s.image:s.data;if(typeof l=="string")try{l=new URL(l)}catch{}return{mediaType:i,data:l}}).filter(s=>s.data instanceof URL).map(s=>({url:s.data,isUrlSupportedByModel:s.mediaType!=null&&D0({url:s.data.toString(),mediaType:s.mediaType,supportedUrls:r})})),n=await e(a);return Object.fromEntries(n.map((s,o)=>s==null?null:[a[o].url.toString(),{data:s.data,mediaType:s.mediaType}]).filter(s=>s!=null))}function Ex(t,e){var r;if(t.type==="text")return{type:"text",text:t.text,providerOptions:t.providerOptions};let a;const n=t.type;switch(n){case"image":a=t.image;break;case"file":a=t.data;break;default:throw new Error(`Unsupported part type: ${n}`)}const{data:s,mediaType:o}=Pp(a);let i=o??t.mediaType,l=s;if(l instanceof URL){const u=e[l.toString()];u&&(l=u.data,i??(i=u.mediaType))}switch(n){case"image":return(l instanceof Uint8Array||typeof l=="string")&&(i=(r=vx({data:l,signatures:hx}))!=null?r:i),{type:"file",mediaType:i??"image/*",filename:void 0,data:l,providerOptions:t.providerOptions};case"file":{if(i==null)throw new Error("Media type is missing for file part");return{type:"file",mediaType:i,filename:t.filename,data:l,providerOptions:t.providerOptions}}}}function gi({maxOutputTokens:t,temperature:e,topP:r,topK:a,presencePenalty:n,frequencyPenalty:s,seed:o,stopSequences:i}){if(t!=null){if(!Number.isInteger(t))throw new hr({parameter:"maxOutputTokens",value:t,message:"maxOutputTokens must be an integer"});if(t<1)throw new hr({parameter:"maxOutputTokens",value:t,message:"maxOutputTokens must be >= 1"})}if(e!=null&&typeof e!="number")throw new hr({parameter:"temperature",value:e,message:"temperature must be a number"});if(r!=null&&typeof r!="number")throw new hr({parameter:"topP",value:r,message:"topP must be a number"});if(a!=null&&typeof a!="number")throw new hr({parameter:"topK",value:a,message:"topK must be a number"});if(n!=null&&typeof n!="number")throw new hr({parameter:"presencePenalty",value:n,message:"presencePenalty must be a number"});if(s!=null&&typeof s!="number")throw new hr({parameter:"frequencyPenalty",value:s,message:"frequencyPenalty must be a number"});if(o!=null&&!Number.isInteger(o))throw new hr({parameter:"seed",value:o,message:"seed must be an integer"});return{maxOutputTokens:t,temperature:e,topP:r,topK:a,presencePenalty:n,frequencyPenalty:s,stopSequences:i,seed:o}}function Sx(t){return t!=null&&Object.keys(t).length>0}function Rp({tools:t,toolChoice:e,activeTools:r}){return Sx(t)?{tools:(r!=null?Object.entries(t).filter(([n])=>r.includes(n)):Object.entries(t)).map(([n,s])=>{const o=s.type;switch(o){case void 0:case"dynamic":case"function":return{type:"function",name:n,description:s.description,inputSchema:hs(s.inputSchema).jsonSchema,providerOptions:s.providerOptions};case"provider-defined":return{type:"provider-defined",name:n,id:s.id,args:s.args};default:{const i=o;throw new Error(`Unsupported tool type: ${i}`)}}}),toolChoice:e==null?{type:"auto"}:typeof e=="string"?{type:e}:{type:"tool",toolName:e.toolName}}:{tools:void 0,toolChoice:void 0}}var ya=Pc(()=>Ne([P_(),w(),D(),st(),ot(w(),ya),K(ya)])),fr=ot(w(),ot(w(),ya)),Op=E({type:q("text"),text:w(),providerOptions:fr.optional()}),Ix=E({type:q("image"),image:Ne([Tp,Xa(URL)]),mediaType:w().optional(),providerOptions:fr.optional()}),$p=E({type:q("file"),data:Ne([Tp,Xa(URL)]),filename:w().optional(),mediaType:w(),providerOptions:fr.optional()}),kx=E({type:q("reasoning"),text:w(),providerOptions:fr.optional()}),Tx=E({type:q("tool-call"),toolCallId:w(),toolName:w(),input:Xt(),providerOptions:fr.optional(),providerExecuted:st().optional()}),Px=Rt("type",[E({type:q("text"),value:w()}),E({type:q("json"),value:ya}),E({type:q("error-text"),value:w()}),E({type:q("error-json"),value:ya}),E({type:q("content"),value:K(Ne([E({type:q("text"),text:w()}),E({type:q("media"),data:w(),mediaType:w()})]))})]),Ap=E({type:q("tool-result"),toolCallId:w(),toolName:w(),output:Px,providerOptions:fr.optional()}),Cx=E({role:q("system"),content:w(),providerOptions:fr.optional()}),Rx=E({role:q("user"),content:Ne([w(),K(Ne([Op,Ix,$p]))]),providerOptions:fr.optional()}),Ox=E({role:q("assistant"),content:Ne([w(),K(Ne([Op,$p,kx,Tx,Ap]))]),providerOptions:fr.optional()}),$x=E({role:q("tool"),content:K(Ap),providerOptions:fr.optional()}),Ax=Ne([Cx,Rx,Ox,$x]);async function Np(t){if(t.prompt==null&&t.messages==null)throw new Kr({prompt:t,message:"prompt or messages must be defined"});if(t.prompt!=null&&t.messages!=null)throw new Kr({prompt:t,message:"prompt and messages cannot be defined at the same time"});if(t.system!=null&&typeof t.system!="string")throw new Kr({prompt:t,message:"system must be a string"});let e;if(t.prompt!=null&&typeof t.prompt=="string")e=[{role:"user",content:t.prompt}];else if(t.prompt!=null&&Array.isArray(t.prompt))e=t.prompt;else if(t.messages!=null)e=t.messages;else throw new Kr({prompt:t,message:"prompt or messages must be defined"});if(e.length===0)throw new Kr({prompt:t,message:"messages must not be empty"});const r=await er({value:e,schema:K(Ax)});if(!r.success)throw new Kr({prompt:t,message:"The messages must be a ModelMessage[]. If you have passed a UIMessage[], you can use convertToModelMessages to convert them.",cause:r.error});return{messages:e,system:t.system}}function Mp(t){return ni.isInstance(t)||xd.isInstance(t)?new ve({name:"GatewayError",message:"Vercel AI Gateway access failed. If you want to use AI SDK providers directly, use the providers, e.g. @ai-sdk/openai, or register a different global default provider.",cause:t}):t}function Rn({operationId:t,telemetry:e}){return{"operation.name":`${t}${(e==null?void 0:e.functionId)!=null?` ${e.functionId}`:""}`,"resource.name":e==null?void 0:e.functionId,"ai.operationId":t,"ai.telemetry.functionId":e==null?void 0:e.functionId}}function Dp({model:t,settings:e,telemetry:r,headers:a}){var n;return{"ai.model.provider":t.provider,"ai.model.id":t.modelId,...Object.entries(e).reduce((s,[o,i])=>(s[`ai.settings.${o}`]=i,s),{}),...Object.entries((n=r==null?void 0:r.metadata)!=null?n:{}).reduce((s,[o,i])=>(s[`ai.telemetry.metadata.${o}`]=i,s),{}),...Object.entries(a??{}).reduce((s,[o,i])=>(i!==void 0&&(s[`ai.request.headers.${o}`]=i),s),{})}}var Nx={startSpan(){return ws},startActiveSpan(t,e,r,a){if(typeof e=="function")return e(ws);if(typeof r=="function")return r(ws);if(typeof a=="function")return a(ws)}},ws={spanContext(){return Mx},setAttribute(){return this},setAttributes(){return this},addEvent(){return this},addLink(){return this},addLinks(){return this},setStatus(){return this},updateName(){return this},end(){return this},isRecording(){return!1},recordException(){return this}},Mx={traceId:"",spanId:"",traceFlags:0};function jp({isEnabled:t=!1,tracer:e}={}){return t?e||J1.getTracer("ai"):Nx}function On({name:t,tracer:e,attributes:r,fn:a,endWhenDone:n=!0}){return e.startActiveSpan(t,{attributes:r},async s=>{try{const o=await a(s);return n&&s.end(),o}catch(o){try{yi(s,o)}finally{s.end()}throw o}})}function yi(t,e){e instanceof Error?(t.recordException({name:e.name,message:e.message,stack:e.stack}),t.setStatus({code:ys.ERROR,message:e.message})):t.setStatus({code:ys.ERROR})}function Zt({telemetry:t,attributes:e}){return(t==null?void 0:t.isEnabled)!==!0?{}:Object.entries(e).reduce((r,[a,n])=>{if(n==null)return r;if(typeof n=="object"&&"input"in n&&typeof n.input=="function"){if((t==null?void 0:t.recordInputs)===!1)return r;const s=n.input();return s==null?r:{...r,[a]:s}}if(typeof n=="object"&&"output"in n&&typeof n.output=="function"){if((t==null?void 0:t.recordOutputs)===!1)return r;const s=n.output();return s==null?r:{...r,[a]:s}}return{...r,[a]:n}},{})}function zp(t){return JSON.stringify(t.map(e=>({...e,content:typeof e.content=="string"?e.content:e.content.map(r=>r.type==="file"?{...r,data:r.data instanceof Uint8Array?wx(r.data):r.data}:r)})))}function Lp(t,e){return{inputTokens:_a(t.inputTokens,e.inputTokens),outputTokens:_a(t.outputTokens,e.outputTokens),totalTokens:_a(t.totalTokens,e.totalTokens),reasoningTokens:_a(t.reasoningTokens,e.reasoningTokens),cachedInputTokens:_a(t.cachedInputTokens,e.cachedInputTokens)}}function _a(t,e){return t==null&&e==null?void 0:(t??0)+(e??0)}function _i(t){return t===void 0?[]:Array.isArray(t)?t:[t]}function Dx({error:t,exponentialBackoffDelay:e}){const r=t.responseHeaders;if(!r)return e;let a;const n=r["retry-after-ms"];if(n){const o=parseFloat(n);Number.isNaN(o)||(a=o)}const s=r["retry-after"];if(s&&a===void 0){const o=parseFloat(s);Number.isNaN(o)?a=Date.parse(s)-Date.now():a=o*1e3}return a!=null&&!Number.isNaN(a)&&0<=a&&(a<60*1e3||a<e)?a:e}var jx=({maxRetries:t=2,initialDelayInMs:e=2e3,backoffFactor:r=2,abortSignal:a}={})=>async n=>Up(n,{maxRetries:t,delayInMs:e,backoffFactor:r,abortSignal:a});async function Up(t,{maxRetries:e,delayInMs:r,backoffFactor:a,abortSignal:n},s=[]){try{return await t()}catch(o){if(nn(o)||e===0)throw o;const i=Ho(o),l=[...s,o],u=l.length;if(u>e)throw new Ip({message:`Failed after ${u} attempts. Last error: ${i}`,reason:"maxRetriesExceeded",errors:l});if(o instanceof Error&&ft.isInstance(o)&&o.isRetryable===!0&&u<=e)return await $0(Dx({error:o,exponentialBackoffDelay:r}),{abortSignal:n}),Up(t,{maxRetries:e,delayInMs:a*r,backoffFactor:a,abortSignal:n},l);throw u===1?o:new Ip({message:`Failed after ${u} attempts with non-retryable error: '${i}'`,reason:"errorNotRetryable",errors:l})}}function Fp({maxRetries:t,abortSignal:e}){if(t!=null){if(!Number.isInteger(t))throw new hr({parameter:"maxRetries",value:t,message:"maxRetries must be an integer"});if(t<0)throw new hr({parameter:"maxRetries",value:t,message:"maxRetries must be >= 0"})}const r=t??2;return{maxRetries:r,retry:jx({maxRetries:r,abortSignal:e})}}function qp(t){const e=t.filter(r=>r.type==="text");if(e.length!==0)return e.map(r=>r.text).join("")}var Zp=class{constructor({data:t,mediaType:e}){const r=t instanceof Uint8Array;this.base64Data=r?void 0:t,this.uint8ArrayData=r?t:void 0,this.mediaType=e}get base64(){return this.base64Data==null&&(this.base64Data=ms(this.uint8ArrayData)),this.base64Data}get uint8Array(){return this.uint8ArrayData==null&&(this.uint8ArrayData=fs(this.base64Data)),this.uint8ArrayData}},zx=class extends Zp{constructor(t){super(t),this.type="file"}};async function Vp({toolCall:t,tools:e,repairToolCall:r,system:a,messages:n}){try{if(e==null)throw new mi({toolName:t.toolName});try{return await Bp({toolCall:t,tools:e})}catch(s){if(r==null||!(mi.isInstance(s)||rp.isInstance(s)))throw s;let o=null;try{o=await r({toolCall:t,tools:e,inputSchema:({toolName:i})=>{const{inputSchema:l}=e[i];return hs(l).jsonSchema},system:a,messages:n,error:s})}catch(i){throw new ox({cause:i,originalError:s})}if(o==null)throw s;return await Bp({toolCall:o,tools:e})}}catch(s){const o=await sn({text:t.input}),i=o.success?o.value:t.input;return{type:"tool-call",toolCallId:t.toolCallId,toolName:t.toolName,input:i,dynamic:!0,invalid:!0,error:s}}}async function Bp({toolCall:t,tools:e}){const r=t.toolName,a=e[r];if(a==null)throw new mi({toolName:t.toolName,availableTools:Object.keys(e)});const n=hs(a.inputSchema),s=t.input.trim()===""?await er({value:{},schema:n}):await sn({text:t.input,schema:n});if(s.success===!1)throw new rp({toolName:r,toolInput:t.input,cause:s.error});return a.type==="dynamic"?{type:"tool-call",toolCallId:t.toolCallId,toolName:t.toolName,input:s.value,providerExecuted:t.providerExecuted,providerMetadata:t.providerMetadata,dynamic:!0}:{type:"tool-call",toolCallId:t.toolCallId,toolName:r,input:s.value,providerExecuted:t.providerExecuted,providerMetadata:t.providerMetadata}}var Hp=class{constructor({content:t,finishReason:e,usage:r,warnings:a,request:n,response:s,providerMetadata:o}){this.content=t,this.finishReason=e,this.usage=r,this.warnings=a,this.request=n,this.response=s,this.providerMetadata=o}get text(){return this.content.filter(t=>t.type==="text").map(t=>t.text).join("")}get reasoning(){return this.content.filter(t=>t.type==="reasoning")}get reasoningText(){return this.reasoning.length===0?void 0:this.reasoning.map(t=>t.text).join("")}get files(){return this.content.filter(t=>t.type==="file").map(t=>t.file)}get sources(){return this.content.filter(t=>t.type==="source")}get toolCalls(){return this.content.filter(t=>t.type==="tool-call")}get staticToolCalls(){return this.toolCalls.filter(t=>t.dynamic!==!0)}get dynamicToolCalls(){return this.toolCalls.filter(t=>t.dynamic===!0)}get toolResults(){return this.content.filter(t=>t.type==="tool-result")}get staticToolResults(){return this.toolResults.filter(t=>t.dynamic!==!0)}get dynamicToolResults(){return this.toolResults.filter(t=>t.dynamic===!0)}};function wi(t){return({steps:e})=>e.length===t}async function Jp({stopConditions:t,steps:e}){return(await Promise.all(t.map(r=>r({steps:e})))).some(r=>r)}function bi({output:t,tool:e,errorMode:r}){return r==="text"?{type:"error-text",value:En(t)}:r==="json"?{type:"error-json",value:Wp(t)}:e!=null&&e.toModelOutput?e.toModelOutput(t):typeof t=="string"?{type:"text",value:t}:{type:"json",value:Wp(t)}}function Wp(t){return t===void 0?null:t}function xi({content:t,tools:e}){const r=[],a=t.filter(s=>s.type!=="source").filter(s=>(s.type!=="tool-result"||s.providerExecuted)&&(s.type!=="tool-error"||s.providerExecuted)).filter(s=>s.type!=="text"||s.text.length>0).map(s=>{switch(s.type){case"text":return{type:"text",text:s.text,providerOptions:s.providerMetadata};case"reasoning":return{type:"reasoning",text:s.text,providerOptions:s.providerMetadata};case"file":return{type:"file",data:s.file.base64,mediaType:s.file.mediaType,providerOptions:s.providerMetadata};case"tool-call":return{type:"tool-call",toolCallId:s.toolCallId,toolName:s.toolName,input:s.input,providerExecuted:s.providerExecuted,providerOptions:s.providerMetadata};case"tool-result":return{type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:bi({tool:e==null?void 0:e[s.toolName],output:s.output,errorMode:"none"}),providerExecuted:!0,providerOptions:s.providerMetadata};case"tool-error":return{type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:bi({tool:e==null?void 0:e[s.toolName],output:s.error,errorMode:"json"}),providerOptions:s.providerMetadata}}});a.length>0&&r.push({role:"assistant",content:a});const n=t.filter(s=>s.type==="tool-result"||s.type==="tool-error").filter(s=>!s.providerExecuted).map(s=>({type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:bi({tool:e==null?void 0:e[s.toolName],output:s.type==="tool-result"?s.output:s.error,errorMode:s.type==="tool-error"?"text":"none"})}));return n.length>0&&r.push({role:"tool",content:n}),r}var Lx=la({prefix:"aitxt",size:24});async function Ux({model:t,tools:e,toolChoice:r,system:a,prompt:n,messages:s,maxRetries:o,abortSignal:i,headers:l,stopWhen:u=wi(1),experimental_output:d,experimental_telemetry:v,providerOptions:m,experimental_activeTools:c,activeTools:h=c,experimental_prepareStep:g,prepareStep:f=g,experimental_repairToolCall:p,experimental_download:b,experimental_context:y,_internal:{generateId:_=Lx,currentDate:S=()=>new Date}={},onStepFinish:T,...I}){const O=_s(t),R=_i(u),{maxRetries:L,retry:U}=Fp({maxRetries:o,abortSignal:i}),Z=gi(I),M=an(l??{},`ai/${kp}`),j=Dp({model:O,telemetry:v,headers:M,settings:{...Z,maxRetries:L}}),F=await Np({system:a,prompt:n,messages:s}),X=jp(v);try{return await On({name:"ai.generateText",attributes:Zt({telemetry:v,attributes:{...Rn({operationId:"ai.generateText",telemetry:v}),...j,"ai.model.provider":O.provider,"ai.model.id":O.modelId,"ai.prompt":{input:()=>JSON.stringify({system:a,prompt:n,messages:s})}}}),tracer:X,fn:async Y=>{var te,oe,J,pe,ie,xe,C;const ae=gi(I);let ge,fe=[],ke=[];const vt=[],Me=[];do{const Se=[...F.messages,...vt],ue=await(f==null?void 0:f({model:O,steps:Me,stepNumber:Me.length,messages:Se})),Pe=_s((te=ue==null?void 0:ue.model)!=null?te:O),Ce=await Cp({prompt:{system:(oe=ue==null?void 0:ue.system)!=null?oe:F.system,messages:(J=ue==null?void 0:ue.messages)!=null?J:Se},supportedUrls:await Pe.supportedUrls,download:b}),{toolChoice:be,tools:et}=Rp({tools:e,toolChoice:(pe=ue==null?void 0:ue.toolChoice)!=null?pe:r,activeTools:(ie=ue==null?void 0:ue.activeTools)!=null?ie:h});ge=await U(()=>{var me;return On({name:"ai.generateText.doGenerate",attributes:Zt({telemetry:v,attributes:{...Rn({operationId:"ai.generateText.doGenerate",telemetry:v}),...j,"ai.model.provider":Pe.provider,"ai.model.id":Pe.modelId,"ai.prompt.messages":{input:()=>zp(Ce)},"ai.prompt.tools":{input:()=>et==null?void 0:et.map(Be=>JSON.stringify(Be))},"ai.prompt.toolChoice":{input:()=>be!=null?JSON.stringify(be):void 0},"gen_ai.system":Pe.provider,"gen_ai.request.model":Pe.modelId,"gen_ai.request.frequency_penalty":I.frequencyPenalty,"gen_ai.request.max_tokens":I.maxOutputTokens,"gen_ai.request.presence_penalty":I.presencePenalty,"gen_ai.request.stop_sequences":I.stopSequences,"gen_ai.request.temperature":(me=I.temperature)!=null?me:void 0,"gen_ai.request.top_k":I.topK,"gen_ai.request.top_p":I.topP}}),tracer:X,fn:async Be=>{var br,Ht,wt,or,Pt,Jt,$r,gn;const Ge=await Pe.doGenerate({...ae,tools:et,toolChoice:be,responseFormat:d==null?void 0:d.responseFormat,prompt:Ce,providerOptions:m,abortSignal:i,headers:M}),Wt={id:(Ht=(br=Ge.response)==null?void 0:br.id)!=null?Ht:_(),timestamp:(or=(wt=Ge.response)==null?void 0:wt.timestamp)!=null?or:S(),modelId:(Jt=(Pt=Ge.response)==null?void 0:Pt.modelId)!=null?Jt:Pe.modelId,headers:($r=Ge.response)==null?void 0:$r.headers,body:(gn=Ge.response)==null?void 0:gn.body};return Be.setAttributes(Zt({telemetry:v,attributes:{"ai.response.finishReason":Ge.finishReason,"ai.response.text":{output:()=>qp(Ge.content)},"ai.response.toolCalls":{output:()=>{const ir=Gp(Ge.content);return ir==null?void 0:JSON.stringify(ir)}},"ai.response.id":Wt.id,"ai.response.model":Wt.modelId,"ai.response.timestamp":Wt.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(Ge.providerMetadata),"ai.usage.promptTokens":Ge.usage.inputTokens,"ai.usage.completionTokens":Ge.usage.outputTokens,"gen_ai.response.finish_reasons":[Ge.finishReason],"gen_ai.response.id":Wt.id,"gen_ai.response.model":Wt.modelId,"gen_ai.usage.input_tokens":Ge.usage.inputTokens,"gen_ai.usage.output_tokens":Ge.usage.outputTokens}})),{...Ge,response:Wt}}})});const Le=await Promise.all(ge.content.filter(me=>me.type==="tool-call").map(me=>Vp({toolCall:me,tools:e,repairToolCall:p,system:a,messages:Se})));for(const me of Le){if(me.invalid)continue;const Be=e[me.toolName];(Be==null?void 0:Be.onInputAvailable)!=null&&await Be.onInputAvailable({input:me.input,toolCallId:me.toolCallId,messages:Se,abortSignal:i,experimental_context:y})}const G=Le.filter(me=>me.invalid&&me.dynamic);ke=[];for(const me of G)ke.push({type:"tool-error",toolCallId:me.toolCallId,toolName:me.toolName,input:me.input,error:Ho(me.error),dynamic:!0});fe=Le.filter(me=>!me.providerExecuted),e!=null&&ke.push(...await Fx({toolCalls:fe.filter(me=>!me.invalid),tools:e,tracer:X,telemetry:v,messages:Se,abortSignal:i,experimental_context:y}));const De=Zx({content:ge.content,toolCalls:Le,toolOutputs:ke});vt.push(...xi({content:De,tools:e}));const Ue=new Hp({content:De,finishReason:ge.finishReason,usage:ge.usage,warnings:ge.warnings,providerMetadata:ge.providerMetadata,request:(xe=ge.request)!=null?xe:{},response:{...ge.response,messages:structuredClone(vt)}});Gd((C=ge.warnings)!=null?C:[]),Me.push(Ue),await(T==null?void 0:T(Ue))}while(fe.length>0&&ke.length===fe.length&&!await Jp({stopConditions:R,steps:Me}));Y.setAttributes(Zt({telemetry:v,attributes:{"ai.response.finishReason":ge.finishReason,"ai.response.text":{output:()=>qp(ge.content)},"ai.response.toolCalls":{output:()=>{const Se=Gp(ge.content);return Se==null?void 0:JSON.stringify(Se)}},"ai.response.providerMetadata":JSON.stringify(ge.providerMetadata),"ai.usage.promptTokens":ge.usage.inputTokens,"ai.usage.completionTokens":ge.usage.outputTokens}}));const Ee=Me[Me.length-1];let Tt;return Ee.finishReason==="stop"&&(Tt=await(d==null?void 0:d.parseOutput({text:Ee.text},{response:Ee.response,usage:Ee.usage,finishReason:Ee.finishReason}))),new qx({steps:Me,resolvedOutput:Tt})}})}catch(Y){throw Mp(Y)}}async function Fx({toolCalls:t,tools:e,tracer:r,telemetry:a,messages:n,abortSignal:s,experimental_context:o}){return(await Promise.all(t.map(async({toolCallId:l,toolName:u,input:d})=>{const v=e[u];if((v==null?void 0:v.execute)!=null)return On({name:"ai.toolCall",attributes:Zt({telemetry:a,attributes:{...Rn({operationId:"ai.toolCall",telemetry:a}),"ai.toolCall.name":u,"ai.toolCall.id":l,"ai.toolCall.args":{output:()=>JSON.stringify(d)}}}),tracer:r,fn:async m=>{try{const c=Xc({execute:v.execute.bind(v),input:d,options:{toolCallId:l,messages:n,abortSignal:s,experimental_context:o}});let h;for await(const g of c)g.type==="final"&&(h=g.output);try{m.setAttributes(Zt({telemetry:a,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(h)}}}))}catch{}return{type:"tool-result",toolCallId:l,toolName:u,input:d,output:h,dynamic:v.type==="dynamic"}}catch(c){return yi(m,c),{type:"tool-error",toolCallId:l,toolName:u,input:d,error:c,dynamic:v.type==="dynamic"}}}})}))).filter(l=>l!=null)}var qx=class{constructor(t){this.steps=t.steps,this.resolvedOutput=t.resolvedOutput}get finalStep(){return this.steps[this.steps.length-1]}get content(){return this.finalStep.content}get text(){return this.finalStep.text}get files(){return this.finalStep.files}get reasoningText(){return this.finalStep.reasoningText}get reasoning(){return this.finalStep.reasoning}get toolCalls(){return this.finalStep.toolCalls}get staticToolCalls(){return this.finalStep.staticToolCalls}get dynamicToolCalls(){return this.finalStep.dynamicToolCalls}get toolResults(){return this.finalStep.toolResults}get staticToolResults(){return this.finalStep.staticToolResults}get dynamicToolResults(){return this.finalStep.dynamicToolResults}get sources(){return this.finalStep.sources}get finishReason(){return this.finalStep.finishReason}get warnings(){return this.finalStep.warnings}get providerMetadata(){return this.finalStep.providerMetadata}get response(){return this.finalStep.response}get request(){return this.finalStep.request}get usage(){return this.finalStep.usage}get totalUsage(){return this.steps.reduce((t,e)=>Lp(t,e.usage),{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0,reasoningTokens:void 0,cachedInputTokens:void 0})}get experimental_output(){if(this.resolvedOutput==null)throw new Jd;return this.resolvedOutput}};function Gp(t){const e=t.filter(r=>r.type==="tool-call");if(e.length!==0)return e.map(r=>({toolCallId:r.toolCallId,toolName:r.toolName,input:r.input}))}function Zx({content:t,toolCalls:e,toolOutputs:r}){return[...t.map(a=>{switch(a.type){case"text":case"reasoning":case"source":return a;case"file":return{type:"file",file:new Zp(a)};case"tool-call":return e.find(n=>n.toolCallId===a.toolCallId);case"tool-result":{const n=e.find(s=>s.toolCallId===a.toolCallId);if(n==null)throw new Error(`Tool call ${a.toolCallId} not found.`);return a.isError?{type:"tool-error",toolCallId:a.toolCallId,toolName:a.toolName,input:n.input,error:a.result,providerExecuted:!0,dynamic:n.dynamic}:{type:"tool-result",toolCallId:a.toolCallId,toolName:a.toolName,input:n.input,output:a.result,providerExecuted:!0,dynamic:n.dynamic}}}}),...r]}function bs(t,e){const r=new Headers(t??{});for(const[a,n]of Object.entries(e))r.has(a)||r.set(a,n);return r}function Vx({status:t,statusText:e,headers:r,textStream:a}){return new Response(a.pipeThrough(new TextEncoderStream),{status:t??200,statusText:e,headers:bs(r,{"content-type":"text/plain; charset=utf-8"})})}function Kp({response:t,status:e,statusText:r,headers:a,stream:n}){t.writeHead(e??200,r,a);const s=n.getReader();(async()=>{try{for(;;){const{done:i,value:l}=await s.read();if(i)break;t.write(l)||await new Promise(d=>{t.once("drain",d)})}}catch(i){throw i}finally{t.end()}})()}function Bx({response:t,status:e,statusText:r,headers:a,textStream:n}){Kp({response:t,status:e,statusText:r,headers:Object.fromEntries(bs(a,{"content-type":"text/plain; charset=utf-8"}).entries()),stream:n.pipeThrough(new TextEncoderStream)})}var Qp=class extends TransformStream{constructor(){super({transform(t,e){e.enqueue(`data: ${JSON.stringify(t)}
54
-
55
- `)},flush(t){t.enqueue(`data: [DONE]
56
-
57
- `)}})}},Yp={"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive","x-vercel-ai-ui-message-stream":"v1","x-accel-buffering":"no"};function Hx({status:t,statusText:e,headers:r,stream:a,consumeSseStream:n}){let s=a.pipeThrough(new Qp);if(n){const[o,i]=s.tee();s=o,n({stream:i})}return new Response(s.pipeThrough(new TextEncoderStream),{status:t,statusText:e,headers:bs(r,Yp)})}function Jx({originalMessages:t,responseMessageId:e}){if(t==null)return;const r=t[t.length-1];return(r==null?void 0:r.role)==="assistant"?r.id:typeof e=="function"?e():e}function Wx(t){return t.type.startsWith("data-")}function Xp(t,e){if(t===void 0&&e===void 0)return;if(t===void 0)return e;if(e===void 0)return t;const r={...t};for(const a in e)if(Object.prototype.hasOwnProperty.call(e,a)){const n=e[a];if(n===void 0)continue;const s=a in t?t[a]:void 0,o=n!==null&&typeof n=="object"&&!Array.isArray(n)&&!(n instanceof Date)&&!(n instanceof RegExp),i=s!=null&&typeof s=="object"&&!Array.isArray(s)&&!(s instanceof Date)&&!(s instanceof RegExp);o&&i?r[a]=Xp(s,n):r[a]=n}return r}function Gx(t){const e=["ROOT"];let r=-1,a=null;function n(l,u,d){switch(l){case'"':{r=u,e.pop(),e.push(d),e.push("INSIDE_STRING");break}case"f":case"t":case"n":{r=u,a=u,e.pop(),e.push(d),e.push("INSIDE_LITERAL");break}case"-":{e.pop(),e.push(d),e.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{r=u,e.pop(),e.push(d),e.push("INSIDE_NUMBER");break}case"{":{r=u,e.pop(),e.push(d),e.push("INSIDE_OBJECT_START");break}case"[":{r=u,e.pop(),e.push(d),e.push("INSIDE_ARRAY_START");break}}}function s(l,u){switch(l){case",":{e.pop(),e.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{r=u,e.pop();break}}}function o(l,u){switch(l){case",":{e.pop(),e.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{r=u,e.pop();break}}}for(let l=0;l<t.length;l++){const u=t[l];switch(e[e.length-1]){case"ROOT":n(u,l,"FINISH");break;case"INSIDE_OBJECT_START":{switch(u){case'"':{e.pop(),e.push("INSIDE_OBJECT_KEY");break}case"}":{r=l,e.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(u){case'"':{e.pop(),e.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(u){case'"':{e.pop(),e.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(u){case":":{e.pop(),e.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{n(u,l,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{s(u,l);break}case"INSIDE_STRING":{switch(u){case'"':{e.pop(),r=l;break}case"\\":{e.push("INSIDE_STRING_ESCAPE");break}default:r=l}break}case"INSIDE_ARRAY_START":{switch(u){case"]":{r=l,e.pop();break}default:{r=l,n(u,l,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(u){case",":{e.pop(),e.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{r=l,e.pop();break}default:{r=l;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{n(u,l,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{e.pop(),r=l;break}case"INSIDE_NUMBER":{switch(u){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{r=l;break}case"e":case"E":case"-":case".":break;case",":{e.pop(),e[e.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&o(u,l),e[e.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&s(u,l);break}case"}":{e.pop(),e[e.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&s(u,l);break}case"]":{e.pop(),e[e.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&o(u,l);break}default:{e.pop();break}}break}case"INSIDE_LITERAL":{const v=t.substring(a,l+1);!"false".startsWith(v)&&!"true".startsWith(v)&&!"null".startsWith(v)?(e.pop(),e[e.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?s(u,l):e[e.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&o(u,l)):r=l;break}}}let i=t.slice(0,r+1);for(let l=e.length-1;l>=0;l--)switch(e[l]){case"INSIDE_STRING":{i+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{i+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{i+="]";break}case"INSIDE_LITERAL":{const d=t.substring(a,t.length);"true".startsWith(d)?i+="true".slice(d.length):"false".startsWith(d)?i+="false".slice(d.length):"null".startsWith(d)&&(i+="null".slice(d.length))}}return i}async function eh(t){if(t===void 0)return{value:void 0,state:"undefined-input"};let e=await sn({text:t});return e.success?{value:e.value,state:"successful-parse"}:(e=await sn({text:Gx(t)}),e.success?{value:e.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function Ei(t){return t.type.startsWith("tool-")}function th(t){return t.type.split("-").slice(1).join("-")}function Kx({lastMessage:t,messageId:e}){return{message:(t==null?void 0:t.role)==="assistant"?t:{id:e,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function Qx({stream:t,messageMetadataSchema:e,dataPartSchemas:r,runUpdateMessageJob:a,onError:n,onToolCall:s,onData:o}){return t.pipeThrough(new TransformStream({async transform(i,l){await a(async({state:u,write:d})=>{var v,m,c,h;function g(_){const T=u.message.parts.filter(Ei).find(I=>I.toolCallId===_);if(T==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return T}function f(_){const T=u.message.parts.filter(I=>I.type==="dynamic-tool").find(I=>I.toolCallId===_);if(T==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return T}function p(_){var S;const T=u.message.parts.find(R=>Ei(R)&&R.toolCallId===_.toolCallId),I=_,O=T;T!=null?(T.state=_.state,O.input=I.input,O.output=I.output,O.errorText=I.errorText,O.rawInput=I.rawInput,O.preliminary=I.preliminary,O.providerExecuted=(S=I.providerExecuted)!=null?S:T.providerExecuted,I.providerMetadata!=null&&T.state==="input-available"&&(T.callProviderMetadata=I.providerMetadata)):u.message.parts.push({type:`tool-${_.toolName}`,toolCallId:_.toolCallId,state:_.state,input:I.input,output:I.output,rawInput:I.rawInput,errorText:I.errorText,providerExecuted:I.providerExecuted,preliminary:I.preliminary,...I.providerMetadata!=null?{callProviderMetadata:I.providerMetadata}:{}})}function b(_){var S;const T=u.message.parts.find(R=>R.type==="dynamic-tool"&&R.toolCallId===_.toolCallId),I=_,O=T;T!=null?(T.state=_.state,O.toolName=_.toolName,O.input=I.input,O.output=I.output,O.errorText=I.errorText,O.rawInput=(S=I.rawInput)!=null?S:O.rawInput,O.preliminary=I.preliminary,I.providerMetadata!=null&&T.state==="input-available"&&(T.callProviderMetadata=I.providerMetadata)):u.message.parts.push({type:"dynamic-tool",toolName:_.toolName,toolCallId:_.toolCallId,state:_.state,input:I.input,output:I.output,errorText:I.errorText,preliminary:I.preliminary,...I.providerMetadata!=null?{callProviderMetadata:I.providerMetadata}:{}})}async function y(_){if(_!=null){const S=u.message.metadata!=null?Xp(u.message.metadata,_):_;e!=null&&await cr({value:S,schema:e}),u.message.metadata=S}}switch(i.type){case"text-start":{const _={type:"text",text:"",providerMetadata:i.providerMetadata,state:"streaming"};u.activeTextParts[i.id]=_,u.message.parts.push(_),d();break}case"text-delta":{const _=u.activeTextParts[i.id];_.text+=i.delta,_.providerMetadata=(v=i.providerMetadata)!=null?v:_.providerMetadata,d();break}case"text-end":{const _=u.activeTextParts[i.id];_.state="done",_.providerMetadata=(m=i.providerMetadata)!=null?m:_.providerMetadata,delete u.activeTextParts[i.id],d();break}case"reasoning-start":{const _={type:"reasoning",text:"",providerMetadata:i.providerMetadata,state:"streaming"};u.activeReasoningParts[i.id]=_,u.message.parts.push(_),d();break}case"reasoning-delta":{const _=u.activeReasoningParts[i.id];_.text+=i.delta,_.providerMetadata=(c=i.providerMetadata)!=null?c:_.providerMetadata,d();break}case"reasoning-end":{const _=u.activeReasoningParts[i.id];_.providerMetadata=(h=i.providerMetadata)!=null?h:_.providerMetadata,_.state="done",delete u.activeReasoningParts[i.id],d();break}case"file":{u.message.parts.push({type:"file",mediaType:i.mediaType,url:i.url}),d();break}case"source-url":{u.message.parts.push({type:"source-url",sourceId:i.sourceId,url:i.url,title:i.title,providerMetadata:i.providerMetadata}),d();break}case"source-document":{u.message.parts.push({type:"source-document",sourceId:i.sourceId,mediaType:i.mediaType,title:i.title,filename:i.filename,providerMetadata:i.providerMetadata}),d();break}case"tool-input-start":{const _=u.message.parts.filter(Ei);u.partialToolCalls[i.toolCallId]={text:"",toolName:i.toolName,index:_.length,dynamic:i.dynamic},i.dynamic?b({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-streaming",input:void 0}):p({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-streaming",input:void 0,providerExecuted:i.providerExecuted}),d();break}case"tool-input-delta":{const _=u.partialToolCalls[i.toolCallId];_.text+=i.inputTextDelta;const{value:S}=await eh(_.text);_.dynamic?b({toolCallId:i.toolCallId,toolName:_.toolName,state:"input-streaming",input:S}):p({toolCallId:i.toolCallId,toolName:_.toolName,state:"input-streaming",input:S}),d();break}case"tool-input-available":{i.dynamic?b({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-available",input:i.input,providerMetadata:i.providerMetadata}):p({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-available",input:i.input,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata}),d(),s&&!i.providerExecuted&&await s({toolCall:i});break}case"tool-input-error":{i.dynamic?b({toolCallId:i.toolCallId,toolName:i.toolName,state:"output-error",input:i.input,errorText:i.errorText,providerMetadata:i.providerMetadata}):p({toolCallId:i.toolCallId,toolName:i.toolName,state:"output-error",input:void 0,rawInput:i.input,errorText:i.errorText,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata}),d();break}case"tool-output-available":{if(i.dynamic){const _=f(i.toolCallId);b({toolCallId:i.toolCallId,toolName:_.toolName,state:"output-available",input:_.input,output:i.output,preliminary:i.preliminary})}else{const _=g(i.toolCallId);p({toolCallId:i.toolCallId,toolName:th(_),state:"output-available",input:_.input,output:i.output,providerExecuted:i.providerExecuted,preliminary:i.preliminary})}d();break}case"tool-output-error":{if(i.dynamic){const _=f(i.toolCallId);b({toolCallId:i.toolCallId,toolName:_.toolName,state:"output-error",input:_.input,errorText:i.errorText})}else{const _=g(i.toolCallId);p({toolCallId:i.toolCallId,toolName:th(_),state:"output-error",input:_.input,rawInput:_.rawInput,errorText:i.errorText})}d();break}case"start-step":{u.message.parts.push({type:"step-start"});break}case"finish-step":{u.activeTextParts={},u.activeReasoningParts={};break}case"start":{i.messageId!=null&&(u.message.id=i.messageId),await y(i.messageMetadata),(i.messageId!=null||i.messageMetadata!=null)&&d();break}case"finish":{await y(i.messageMetadata),i.messageMetadata!=null&&d();break}case"message-metadata":{await y(i.messageMetadata),i.messageMetadata!=null&&d();break}case"error":{n==null||n(new Error(i.errorText));break}default:if(Wx(i)){(r==null?void 0:r[i.type])!=null&&await cr({value:i.data,schema:r[i.type]});const _=i;if(_.transient){o==null||o(_);break}const S=_.id!=null?u.message.parts.find(T=>_.type===T.type&&_.id===T.id):void 0;S!=null?S.data=_.data:u.message.parts.push(_),o==null||o(_),d()}}l.enqueue(i)})}}))}function Yx({messageId:t,originalMessages:e=[],onFinish:r,onError:a,stream:n}){let s=e==null?void 0:e[e.length-1];(s==null?void 0:s.role)!=="assistant"?s=void 0:t=s.id;let o=!1;const i=n.pipeThrough(new TransformStream({transform(m,c){if(m.type==="start"){const h=m;h.messageId==null&&t!=null&&(h.messageId=t)}m.type==="abort"&&(o=!0),c.enqueue(m)}}));if(r==null)return i;const l=Kx({lastMessage:s?structuredClone(s):void 0,messageId:t??""}),u=async m=>{await m({state:l,write:()=>{}})};let d=!1;const v=async()=>{if(d||!r)return;d=!0;const m=l.message.id===(s==null?void 0:s.id);await r({isAborted:o,isContinuation:m,responseMessage:l.message,messages:[...m?e.slice(0,-1):e,l.message]})};return Qx({stream:i,runUpdateMessageJob:u,onError:a}).pipeThrough(new TransformStream({transform(m,c){c.enqueue(m)},async cancel(){await v()},async flush(){await v()}}))}function Xx({response:t,status:e,statusText:r,headers:a,stream:n,consumeSseStream:s}){let o=n.pipeThrough(new Qp);if(s){const[i,l]=o.tee();o=i,s({stream:l})}Kp({response:t,status:e,statusText:r,headers:Object.fromEntries(bs(a,Yp).entries()),stream:o.pipeThrough(new TextEncoderStream)})}function xs(t){const e=t.pipeThrough(new TransformStream);return e[Symbol.asyncIterator]=function(){const r=this.getReader();let a=!1;async function n(s){var o;a=!0;try{s&&await((o=r.cancel)==null?void 0:o.call(r))}finally{try{r.releaseLock()}catch{}}}return{async next(){if(a)return{done:!0,value:void 0};const{done:s,value:o}=await r.read();return s?(await n(!0),{done:!0,value:void 0}):{done:!1,value:o}},async return(){return await n(!0),{done:!0,value:void 0}},async throw(s){throw await n(!0),s}}},e}async function eE({stream:t,onError:e}){const r=t.getReader();try{for(;;){const{done:a}=await r.read();if(a)break}}catch(a){e==null||e(a)}finally{r.releaseLock()}}function rh(){let t,e;return{promise:new Promise((a,n)=>{t=a,e=n}),resolve:t,reject:e}}function tE(){let t=[],e=null,r=!1,a=rh();const n=()=>{r=!0,a.resolve(),t.forEach(o=>o.cancel()),t=[],e==null||e.close()},s=async()=>{if(r&&t.length===0){e==null||e.close();return}if(t.length===0)return a=rh(),await a.promise,s();try{const{value:o,done:i}=await t[0].read();i?(t.shift(),t.length>0?await s():r&&(e==null||e.close())):e==null||e.enqueue(o)}catch(o){e==null||e.error(o),t.shift(),n()}};return{stream:new ReadableStream({start(o){e=o},pull:s,async cancel(){for(const o of t)await o.cancel();t=[],r=!0}}),addStream:o=>{if(r)throw new Error("Cannot add inner stream: outer stream is closed");t.push(o.getReader()),a.resolve()},close:()=>{r=!0,a.resolve(),t.length===0&&(e==null||e.close())},terminate:n}}var Es=class{constructor(){this.status={type:"pending"},this._resolve=void 0,this._reject=void 0}get promise(){return this._promise?this._promise:(this._promise=new Promise((t,e)=>{this.status.type==="resolved"?t(this.status.value):this.status.type==="rejected"&&e(this.status.error),this._resolve=t,this._reject=e}),this._promise)}resolve(t){var e;this.status={type:"resolved",value:t},this._promise&&((e=this._resolve)==null||e.call(this,t))}reject(t){var e;this.status={type:"rejected",error:t},this._promise&&((e=this._reject)==null||e.call(this,t))}};function rE(){var t,e;return(e=(t=globalThis==null?void 0:globalThis.performance)==null?void 0:t.now())!=null?e:Date.now()}function nE({tools:t,generatorStream:e,tracer:r,telemetry:a,system:n,messages:s,abortSignal:o,repairToolCall:i,experimental_context:l}){let u=null;const d=new ReadableStream({start(p){u=p}}),v=new Set,m=new Map;let c=!1,h;function g(){c&&v.size===0&&(h!=null&&u.enqueue(h),u.close())}const f=new TransformStream({async transform(p,b){const y=p.type;switch(y){case"stream-start":case"text-start":case"text-delta":case"text-end":case"reasoning-start":case"reasoning-delta":case"reasoning-end":case"tool-input-start":case"tool-input-delta":case"tool-input-end":case"source":case"response-metadata":case"error":case"raw":{b.enqueue(p);break}case"file":{b.enqueue({type:"file",file:new zx({data:p.data,mediaType:p.mediaType})});break}case"finish":{h={type:"finish",finishReason:p.finishReason,usage:p.usage,providerMetadata:p.providerMetadata};break}case"tool-call":{try{const _=await Vp({toolCall:p,tools:t,repairToolCall:i,system:n,messages:s});if(b.enqueue(_),_.invalid){u.enqueue({type:"tool-error",toolCallId:_.toolCallId,toolName:_.toolName,input:_.input,error:Ho(_.error),dynamic:!0});break}const S=t[_.toolName];if(m.set(_.toolCallId,_.input),S.onInputAvailable!=null&&await S.onInputAvailable({input:_.input,toolCallId:_.toolCallId,messages:s,abortSignal:o,experimental_context:l}),S.execute!=null&&_.providerExecuted!==!0){const T=Ot();v.add(T),On({name:"ai.toolCall",attributes:Zt({telemetry:a,attributes:{...Rn({operationId:"ai.toolCall",telemetry:a}),"ai.toolCall.name":_.toolName,"ai.toolCall.id":_.toolCallId,"ai.toolCall.args":{output:()=>JSON.stringify(_.input)}}}),tracer:r,fn:async I=>{let O;try{const R=Xc({execute:S.execute.bind(S),input:_.input,options:{toolCallId:_.toolCallId,messages:s,abortSignal:o,experimental_context:l}});for await(const L of R)u.enqueue({..._,type:"tool-result",output:L.output,...L.type==="preliminary"&&{preliminary:!0}}),L.type==="final"&&(O=L.output)}catch(R){yi(I,R),u.enqueue({..._,type:"tool-error",error:R}),v.delete(T),g();return}v.delete(T),g();try{I.setAttributes(Zt({telemetry:a,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(O)}}}))}catch{}}})}}catch(_){u.enqueue({type:"error",error:_})}break}case"tool-result":{const _=p.toolName;p.isError?u.enqueue({type:"tool-error",toolCallId:p.toolCallId,toolName:_,input:m.get(p.toolCallId),providerExecuted:p.providerExecuted,error:p.result}):b.enqueue({type:"tool-result",toolCallId:p.toolCallId,toolName:_,input:m.get(p.toolCallId),output:p.result,providerExecuted:p.providerExecuted});break}default:{const _=y;throw new Error(`Unhandled chunk type: ${_}`)}}},flush(){c=!0,g()}});return new ReadableStream({async start(p){return Promise.all([e.pipeThrough(f).pipeTo(new WritableStream({write(b){p.enqueue(b)},close(){}})),d.pipeTo(new WritableStream({write(b){p.enqueue(b)},close(){p.close()}}))])}})}var aE=la({prefix:"aitxt",size:24});function sE({model:t,tools:e,toolChoice:r,system:a,prompt:n,messages:s,maxRetries:o,abortSignal:i,headers:l,stopWhen:u=wi(1),experimental_output:d,experimental_telemetry:v,prepareStep:m,providerOptions:c,experimental_activeTools:h,activeTools:g=h,experimental_repairToolCall:f,experimental_transform:p,experimental_download:b,includeRawChunks:y=!1,onChunk:_,onError:S=({error:j})=>{console.error(j)},onFinish:T,onAbort:I,onStepFinish:O,experimental_context:R,_internal:{now:L=rE,generateId:U=aE,currentDate:Z=()=>new Date}={},...M}){return new iE({model:_s(t),telemetry:v,headers:l,settings:M,maxRetries:o,abortSignal:i,system:a,prompt:n,messages:s,tools:e,toolChoice:r,transforms:_i(p),activeTools:g,repairToolCall:f,stopConditions:_i(u),output:d,providerOptions:c,prepareStep:m,includeRawChunks:y,onChunk:_,onError:S,onFinish:T,onAbort:I,onStepFinish:O,now:L,currentDate:Z,generateId:U,experimental_context:R,download:b})}function oE(t){if(!t)return new TransformStream({transform(o,i){i.enqueue({part:o,partialOutput:void 0})}});let e,r="",a="",n="";function s({controller:o,partialOutput:i=void 0}){o.enqueue({part:{type:"text-delta",id:e,text:a},partialOutput:i}),a=""}return new TransformStream({async transform(o,i){if(o.type==="finish-step"&&a.length>0&&s({controller:i}),o.type!=="text-delta"&&o.type!=="text-start"&&o.type!=="text-end"){i.enqueue({part:o,partialOutput:void 0});return}if(e==null)e=o.id;else if(o.id!==e){i.enqueue({part:o,partialOutput:void 0});return}if(o.type==="text-start"){i.enqueue({part:o,partialOutput:void 0});return}if(o.type==="text-end"){a.length>0&&s({controller:i}),i.enqueue({part:o,partialOutput:void 0});return}r+=o.text,a+=o.text;const l=await t.parsePartial({text:r});if(l!=null){const u=JSON.stringify(l.partial);u!==n&&(s({controller:i,partialOutput:l.partial}),n=u)}}})}var iE=class{constructor({model:t,telemetry:e,headers:r,settings:a,maxRetries:n,abortSignal:s,system:o,prompt:i,messages:l,tools:u,toolChoice:d,transforms:v,activeTools:m,repairToolCall:c,stopConditions:h,output:g,providerOptions:f,prepareStep:p,includeRawChunks:b,now:y,currentDate:_,generateId:S,onChunk:T,onError:I,onFinish:O,onAbort:R,onStepFinish:L,experimental_context:U,download:Z}){this._totalUsage=new Es,this._finishReason=new Es,this._steps=new Es,this.output=g,this.includeRawChunks=b,this.tools=u;let M,j=[];const F=[];let X,Y,te={},oe=[];const J=[];let pe,ie={},xe={};const C=new TransformStream({async transform(ue,Pe){var Ce,be,et,Le;Pe.enqueue(ue);const{part:G}=ue;if((G.type==="text-delta"||G.type==="reasoning-delta"||G.type==="source"||G.type==="tool-call"||G.type==="tool-result"||G.type==="tool-input-start"||G.type==="tool-input-delta"||G.type==="raw")&&await(T==null?void 0:T({chunk:G})),G.type==="error"&&await I({error:Mp(G.error)}),G.type==="text-start"&&(ie[G.id]={type:"text",text:"",providerMetadata:G.providerMetadata},j.push(ie[G.id])),G.type==="text-delta"){const De=ie[G.id];if(De==null){Pe.enqueue({part:{type:"error",error:`text part ${G.id} not found`},partialOutput:void 0});return}De.text+=G.text,De.providerMetadata=(Ce=G.providerMetadata)!=null?Ce:De.providerMetadata}if(G.type==="text-end"){const De=ie[G.id];if(De==null){Pe.enqueue({part:{type:"error",error:`text part ${G.id} not found`},partialOutput:void 0});return}De.providerMetadata=(be=G.providerMetadata)!=null?be:De.providerMetadata,delete ie[G.id]}if(G.type==="reasoning-start"&&(xe[G.id]={type:"reasoning",text:"",providerMetadata:G.providerMetadata},j.push(xe[G.id])),G.type==="reasoning-delta"){const De=xe[G.id];if(De==null){Pe.enqueue({part:{type:"error",error:`reasoning part ${G.id} not found`},partialOutput:void 0});return}De.text+=G.text,De.providerMetadata=(et=G.providerMetadata)!=null?et:De.providerMetadata}if(G.type==="reasoning-end"){const De=xe[G.id];if(De==null){Pe.enqueue({part:{type:"error",error:`reasoning part ${G.id} not found`},partialOutput:void 0});return}De.providerMetadata=(Le=G.providerMetadata)!=null?Le:De.providerMetadata,delete xe[G.id]}if(G.type==="file"&&j.push({type:"file",file:G.file}),G.type==="source"&&j.push(G),G.type==="tool-call"&&j.push(G),G.type==="tool-result"&&!G.preliminary&&j.push(G),G.type==="tool-error"&&j.push(G),G.type==="start-step"&&(te=G.request,oe=G.warnings),G.type==="finish-step"){const De=xi({content:j,tools:u}),Ue=new Hp({content:j,finishReason:G.finishReason,usage:G.usage,warnings:oe,request:te,response:{...G.response,messages:[...F,...De]},providerMetadata:G.providerMetadata});await(L==null?void 0:L(Ue)),Gd(oe),J.push(Ue),j=[],xe={},ie={},F.push(...De),M.resolve()}G.type==="finish"&&(Y=G.totalUsage,X=G.finishReason)},async flush(ue){try{if(J.length===0){const et=new nx({message:"No output generated. Check the stream for errors."});Se._finishReason.reject(et),Se._totalUsage.reject(et),Se._steps.reject(et);return}const Pe=X??"unknown",Ce=Y??{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};Se._finishReason.resolve(Pe),Se._totalUsage.resolve(Ce),Se._steps.resolve(J);const be=J[J.length-1];await(O==null?void 0:O({finishReason:Pe,totalUsage:Ce,usage:be.usage,content:be.content,text:be.text,reasoningText:be.reasoningText,reasoning:be.reasoning,files:be.files,sources:be.sources,toolCalls:be.toolCalls,staticToolCalls:be.staticToolCalls,dynamicToolCalls:be.dynamicToolCalls,toolResults:be.toolResults,staticToolResults:be.staticToolResults,dynamicToolResults:be.dynamicToolResults,request:be.request,response:be.response,warnings:be.warnings,providerMetadata:be.providerMetadata,steps:J})),pe.setAttributes(Zt({telemetry:e,attributes:{"ai.response.finishReason":Pe,"ai.response.text":{output:()=>be.text},"ai.response.toolCalls":{output:()=>{var et;return(et=be.toolCalls)!=null&&et.length?JSON.stringify(be.toolCalls):void 0}},"ai.response.providerMetadata":JSON.stringify(be.providerMetadata),"ai.usage.inputTokens":Ce.inputTokens,"ai.usage.outputTokens":Ce.outputTokens,"ai.usage.totalTokens":Ce.totalTokens,"ai.usage.reasoningTokens":Ce.reasoningTokens,"ai.usage.cachedInputTokens":Ce.cachedInputTokens}}))}catch(Pe){ue.error(Pe)}finally{pe.end()}}}),ae=tE();this.addStream=ae.addStream,this.closeStream=ae.close;const ge=ae.stream.getReader();let fe=new ReadableStream({async start(ue){ue.enqueue({type:"start"})},async pull(ue){function Pe(){R==null||R({steps:J}),ue.enqueue({type:"abort"}),ue.close()}try{const{done:Ce,value:be}=await ge.read();if(Ce){ue.close();return}if(s!=null&&s.aborted){Pe();return}ue.enqueue(be)}catch(Ce){nn(Ce)&&(s!=null&&s.aborted)?Pe():ue.error(Ce)}},cancel(ue){return ae.stream.cancel(ue)}});for(const ue of v)fe=fe.pipeThrough(ue({tools:u,stopStream(){ae.terminate()}}));this.baseStream=fe.pipeThrough(oE(g)).pipeThrough(C);const{maxRetries:ke,retry:vt}=Fp({maxRetries:n,abortSignal:s}),Me=jp(e),Ee=gi(a),Tt=Dp({model:t,telemetry:e,headers:r,settings:{...Ee,maxRetries:ke}}),Se=this;On({name:"ai.streamText",attributes:Zt({telemetry:e,attributes:{...Rn({operationId:"ai.streamText",telemetry:e}),...Tt,"ai.prompt":{input:()=>JSON.stringify({system:o,prompt:i,messages:l})}}}),tracer:Me,endWhenDone:!1,fn:async ue=>{pe=ue;async function Pe({currentStep:Ce,responseMessages:be,usage:et}){var Le,G,De,Ue,me;const Be=Se.includeRawChunks;M=new Es;const br=await Np({system:o,prompt:i,messages:l}),Ht=[...br.messages,...be],wt=await(p==null?void 0:p({model:t,steps:J,stepNumber:J.length,messages:Ht})),or=_s((Le=wt==null?void 0:wt.model)!=null?Le:t),Pt=await Cp({prompt:{system:(G=wt==null?void 0:wt.system)!=null?G:br.system,messages:(De=wt==null?void 0:wt.messages)!=null?De:Ht},supportedUrls:await or.supportedUrls,download:Z}),{toolChoice:Jt,tools:$r}=Rp({tools:u,toolChoice:(Ue=wt==null?void 0:wt.toolChoice)!=null?Ue:d,activeTools:(me=wt==null?void 0:wt.activeTools)!=null?me:m}),{result:{stream:gn,response:Ge,request:Wt},doStreamSpan:ir,startTimestampMs:Na}=await vt(()=>On({name:"ai.streamText.doStream",attributes:Zt({telemetry:e,attributes:{...Rn({operationId:"ai.streamText.doStream",telemetry:e}),...Tt,"ai.model.provider":or.provider,"ai.model.id":or.modelId,"ai.prompt.messages":{input:()=>zp(Pt)},"ai.prompt.tools":{input:()=>$r==null?void 0:$r.map(de=>JSON.stringify(de))},"ai.prompt.toolChoice":{input:()=>Jt!=null?JSON.stringify(Jt):void 0},"gen_ai.system":or.provider,"gen_ai.request.model":or.modelId,"gen_ai.request.frequency_penalty":Ee.frequencyPenalty,"gen_ai.request.max_tokens":Ee.maxOutputTokens,"gen_ai.request.presence_penalty":Ee.presencePenalty,"gen_ai.request.stop_sequences":Ee.stopSequences,"gen_ai.request.temperature":Ee.temperature,"gen_ai.request.top_k":Ee.topK,"gen_ai.request.top_p":Ee.topP}}),tracer:Me,endWhenDone:!1,fn:async de=>({startTimestampMs:y(),doStreamSpan:de,result:await or.doStream({...Ee,tools:$r,toolChoice:Jt,responseFormat:g==null?void 0:g.responseFormat,prompt:Pt,providerOptions:f,abortSignal:s,headers:r,includeRawChunks:Be})})})),Gt=nE({tools:u,generatorStream:gn,tracer:Me,telemetry:e,system:o,messages:Ht,repairToolCall:c,abortSignal:s,experimental_context:U}),Wl=Wt??{},Bn=[],Ma=[];let Da;const ja={};let Jr="unknown",gt={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},za,La=!0,Kt={id:S(),timestamp:_(),modelId:t.modelId},Hn="";Se.addStream(Gt.pipeThrough(new TransformStream({async transform(de,ht){var Wr,yn,_n,k;if(de.type==="stream-start"){Da=de.warnings;return}if(La){const P=y()-Na;La=!1,ir.addEvent("ai.stream.firstChunk",{"ai.response.msToFirstChunk":P}),ir.setAttributes({"ai.response.msToFirstChunk":P}),ht.enqueue({type:"start-step",request:Wl,warnings:Da??[]})}const x=de.type;switch(x){case"text-start":case"text-end":{ht.enqueue(de);break}case"text-delta":{de.delta.length>0&&(ht.enqueue({type:"text-delta",id:de.id,text:de.delta,providerMetadata:de.providerMetadata}),Hn+=de.delta);break}case"reasoning-start":case"reasoning-end":{ht.enqueue(de);break}case"reasoning-delta":{ht.enqueue({type:"reasoning-delta",id:de.id,text:de.delta,providerMetadata:de.providerMetadata});break}case"tool-call":{ht.enqueue(de),Bn.push(de);break}case"tool-result":{ht.enqueue(de),de.preliminary||Ma.push(de);break}case"tool-error":{ht.enqueue(de),Ma.push(de);break}case"response-metadata":{Kt={id:(Wr=de.id)!=null?Wr:Kt.id,timestamp:(yn=de.timestamp)!=null?yn:Kt.timestamp,modelId:(_n=de.modelId)!=null?_n:Kt.modelId};break}case"finish":{gt=de.usage,Jr=de.finishReason,za=de.providerMetadata;const P=y()-Na;ir.addEvent("ai.stream.finish"),ir.setAttributes({"ai.response.msToFinish":P,"ai.response.avgOutputTokensPerSecond":1e3*((k=gt.outputTokens)!=null?k:0)/P});break}case"file":{ht.enqueue(de);break}case"source":{ht.enqueue(de);break}case"tool-input-start":{ja[de.id]=de.toolName;const P=u==null?void 0:u[de.toolName];(P==null?void 0:P.onInputStart)!=null&&await P.onInputStart({toolCallId:de.id,messages:Ht,abortSignal:s,experimental_context:U}),ht.enqueue({...de,dynamic:(P==null?void 0:P.type)==="dynamic"});break}case"tool-input-end":{delete ja[de.id],ht.enqueue(de);break}case"tool-input-delta":{const P=ja[de.id],A=u==null?void 0:u[P];(A==null?void 0:A.onInputDelta)!=null&&await A.onInputDelta({inputTextDelta:de.delta,toolCallId:de.id,messages:Ht,abortSignal:s,experimental_context:U}),ht.enqueue(de);break}case"error":{ht.enqueue(de),Jr="error";break}case"raw":{Be&&ht.enqueue(de);break}default:{const P=x;throw new Error(`Unknown chunk type: ${P}`)}}},async flush(de){const ht=Bn.length>0?JSON.stringify(Bn):void 0;try{ir.setAttributes(Zt({telemetry:e,attributes:{"ai.response.finishReason":Jr,"ai.response.text":{output:()=>Hn},"ai.response.toolCalls":{output:()=>ht},"ai.response.id":Kt.id,"ai.response.model":Kt.modelId,"ai.response.timestamp":Kt.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(za),"ai.usage.inputTokens":gt.inputTokens,"ai.usage.outputTokens":gt.outputTokens,"ai.usage.totalTokens":gt.totalTokens,"ai.usage.reasoningTokens":gt.reasoningTokens,"ai.usage.cachedInputTokens":gt.cachedInputTokens,"gen_ai.response.finish_reasons":[Jr],"gen_ai.response.id":Kt.id,"gen_ai.response.model":Kt.modelId,"gen_ai.usage.input_tokens":gt.inputTokens,"gen_ai.usage.output_tokens":gt.outputTokens}}))}catch{}finally{ir.end()}de.enqueue({type:"finish-step",finishReason:Jr,usage:gt,providerMetadata:za,response:{...Kt,headers:Ge==null?void 0:Ge.headers}});const Wr=Lp(et,gt);await M.promise;const yn=Bn.filter(k=>k.providerExecuted!==!0),_n=Ma.filter(k=>k.providerExecuted!==!0);if(yn.length>0&&_n.length===yn.length&&!await Jp({stopConditions:h,steps:J})){be.push(...xi({content:J[J.length-1].content,tools:u}));try{await Pe({currentStep:Ce+1,responseMessages:be,usage:Wr})}catch(k){de.enqueue({type:"error",error:k}),Se.closeStream()}}else de.enqueue({type:"finish",finishReason:Jr,totalUsage:Wr}),Se.closeStream()}})))}await Pe({currentStep:0,responseMessages:[],usage:{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0}})}}).catch(ue=>{Se.addStream(new ReadableStream({start(Pe){Pe.enqueue({type:"error",error:ue}),Pe.close()}})),Se.closeStream()})}get steps(){return this.consumeStream(),this._steps.promise}get finalStep(){return this.steps.then(t=>t[t.length-1])}get content(){return this.finalStep.then(t=>t.content)}get warnings(){return this.finalStep.then(t=>t.warnings)}get providerMetadata(){return this.finalStep.then(t=>t.providerMetadata)}get text(){return this.finalStep.then(t=>t.text)}get reasoningText(){return this.finalStep.then(t=>t.reasoningText)}get reasoning(){return this.finalStep.then(t=>t.reasoning)}get sources(){return this.finalStep.then(t=>t.sources)}get files(){return this.finalStep.then(t=>t.files)}get toolCalls(){return this.finalStep.then(t=>t.toolCalls)}get staticToolCalls(){return this.finalStep.then(t=>t.staticToolCalls)}get dynamicToolCalls(){return this.finalStep.then(t=>t.dynamicToolCalls)}get toolResults(){return this.finalStep.then(t=>t.toolResults)}get staticToolResults(){return this.finalStep.then(t=>t.staticToolResults)}get dynamicToolResults(){return this.finalStep.then(t=>t.dynamicToolResults)}get usage(){return this.finalStep.then(t=>t.usage)}get request(){return this.finalStep.then(t=>t.request)}get response(){return this.finalStep.then(t=>t.response)}get totalUsage(){return this.consumeStream(),this._totalUsage.promise}get finishReason(){return this.consumeStream(),this._finishReason.promise}teeStream(){const[t,e]=this.baseStream.tee();return this.baseStream=e,t}get textStream(){return xs(this.teeStream().pipeThrough(new TransformStream({transform({part:t},e){t.type==="text-delta"&&e.enqueue(t.text)}})))}get fullStream(){return xs(this.teeStream().pipeThrough(new TransformStream({transform({part:t},e){e.enqueue(t)}})))}async consumeStream(t){var e;try{await eE({stream:this.fullStream,onError:t==null?void 0:t.onError})}catch(r){(e=t==null?void 0:t.onError)==null||e.call(t,r)}}get experimental_partialOutputStream(){if(this.output==null)throw new Jd;return xs(this.teeStream().pipeThrough(new TransformStream({transform({partialOutput:t},e){t!=null&&e.enqueue(t)}})))}toUIMessageStream({originalMessages:t,generateMessageId:e,onFinish:r,messageMetadata:a,sendReasoning:n=!0,sendSources:s=!1,sendStart:o=!0,sendFinish:i=!0,onError:l=En}={}){const u=e!=null?Jx({originalMessages:t,responseMessageId:e}):void 0,d={},v=c=>{var h,g;const f=d[c];return((g=(h=this.tools)==null?void 0:h[f])==null?void 0:g.type)==="dynamic"?!0:void 0},m=this.fullStream.pipeThrough(new TransformStream({transform:async(c,h)=>{const g=a==null?void 0:a({part:c}),f=c.type;switch(f){case"text-start":{h.enqueue({type:"text-start",id:c.id,...c.providerMetadata!=null?{providerMetadata:c.providerMetadata}:{}});break}case"text-delta":{h.enqueue({type:"text-delta",id:c.id,delta:c.text,...c.providerMetadata!=null?{providerMetadata:c.providerMetadata}:{}});break}case"text-end":{h.enqueue({type:"text-end",id:c.id,...c.providerMetadata!=null?{providerMetadata:c.providerMetadata}:{}});break}case"reasoning-start":{h.enqueue({type:"reasoning-start",id:c.id,...c.providerMetadata!=null?{providerMetadata:c.providerMetadata}:{}});break}case"reasoning-delta":{n&&h.enqueue({type:"reasoning-delta",id:c.id,delta:c.text,...c.providerMetadata!=null?{providerMetadata:c.providerMetadata}:{}});break}case"reasoning-end":{h.enqueue({type:"reasoning-end",id:c.id,...c.providerMetadata!=null?{providerMetadata:c.providerMetadata}:{}});break}case"file":{h.enqueue({type:"file",mediaType:c.file.mediaType,url:`data:${c.file.mediaType};base64,${c.file.base64}`});break}case"source":{s&&c.sourceType==="url"&&h.enqueue({type:"source-url",sourceId:c.id,url:c.url,title:c.title,...c.providerMetadata!=null?{providerMetadata:c.providerMetadata}:{}}),s&&c.sourceType==="document"&&h.enqueue({type:"source-document",sourceId:c.id,mediaType:c.mediaType,title:c.title,filename:c.filename,...c.providerMetadata!=null?{providerMetadata:c.providerMetadata}:{}});break}case"tool-input-start":{d[c.id]=c.toolName;const p=v(c.id);h.enqueue({type:"tool-input-start",toolCallId:c.id,toolName:c.toolName,...c.providerExecuted!=null?{providerExecuted:c.providerExecuted}:{},...p!=null?{dynamic:p}:{}});break}case"tool-input-delta":{h.enqueue({type:"tool-input-delta",toolCallId:c.id,inputTextDelta:c.delta});break}case"tool-call":{d[c.toolCallId]=c.toolName;const p=v(c.toolCallId);c.invalid?h.enqueue({type:"tool-input-error",toolCallId:c.toolCallId,toolName:c.toolName,input:c.input,...c.providerExecuted!=null?{providerExecuted:c.providerExecuted}:{},...c.providerMetadata!=null?{providerMetadata:c.providerMetadata}:{},...p!=null?{dynamic:p}:{},errorText:l(c.error)}):h.enqueue({type:"tool-input-available",toolCallId:c.toolCallId,toolName:c.toolName,input:c.input,...c.providerExecuted!=null?{providerExecuted:c.providerExecuted}:{},...c.providerMetadata!=null?{providerMetadata:c.providerMetadata}:{},...p!=null?{dynamic:p}:{}});break}case"tool-result":{const p=v(c.toolCallId);h.enqueue({type:"tool-output-available",toolCallId:c.toolCallId,output:c.output,...c.providerExecuted!=null?{providerExecuted:c.providerExecuted}:{},...c.preliminary!=null?{preliminary:c.preliminary}:{},...p!=null?{dynamic:p}:{}});break}case"tool-error":{const p=v(c.toolCallId);h.enqueue({type:"tool-output-error",toolCallId:c.toolCallId,errorText:l(c.error),...c.providerExecuted!=null?{providerExecuted:c.providerExecuted}:{},...p!=null?{dynamic:p}:{}});break}case"error":{h.enqueue({type:"error",errorText:l(c.error)});break}case"start-step":{h.enqueue({type:"start-step"});break}case"finish-step":{h.enqueue({type:"finish-step"});break}case"start":{o&&h.enqueue({type:"start",...g!=null?{messageMetadata:g}:{},...u!=null?{messageId:u}:{}});break}case"finish":{i&&h.enqueue({type:"finish",...g!=null?{messageMetadata:g}:{}});break}case"abort":{h.enqueue(c);break}case"tool-input-end":break;case"raw":break;default:{const p=f;throw new Error(`Unknown chunk type: ${p}`)}}g!=null&&f!=="start"&&f!=="finish"&&h.enqueue({type:"message-metadata",messageMetadata:g})}}));return xs(Yx({stream:m,messageId:u??(e==null?void 0:e()),originalMessages:t,onFinish:r,onError:l}))}pipeUIMessageStreamToResponse(t,{originalMessages:e,generateMessageId:r,onFinish:a,messageMetadata:n,sendReasoning:s,sendSources:o,sendFinish:i,sendStart:l,onError:u,...d}={}){Xx({response:t,stream:this.toUIMessageStream({originalMessages:e,generateMessageId:r,onFinish:a,messageMetadata:n,sendReasoning:s,sendSources:o,sendFinish:i,sendStart:l,onError:u}),...d})}pipeTextStreamToResponse(t,e){Bx({response:t,textStream:this.textStream,...e})}toUIMessageStreamResponse({originalMessages:t,generateMessageId:e,onFinish:r,messageMetadata:a,sendReasoning:n,sendSources:s,sendFinish:o,sendStart:i,onError:l,...u}={}){return Hx({stream:this.toUIMessageStream({originalMessages:t,generateMessageId:e,onFinish:r,messageMetadata:a,sendReasoning:n,sendSources:s,sendFinish:o,sendStart:i,onError:l}),...u})}toTextStreamResponse(t){return Vx({textStream:this.textStream,...t})}};la({prefix:"aiobj",size:24}),la({prefix:"aiobj",size:24});var lE={};G1(lE,{object:()=>cE,text:()=>uE});var uE=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:t}){return{partial:t}},async parseOutput({text:t}){return t}}),cE=({schema:t})=>{const e=hs(t);return{type:"object",responseFormat:{type:"json",schema:e.jsonSchema},async parsePartial({text:r}){const a=await eh(r);switch(a.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:a.value};default:{const n=a.state;throw new Error(`Unsupported parse state: ${n}`)}}},async parseOutput({text:r},a){const n=await sn({text:r});if(!n.success)throw new op({message:"No object generated: could not parse the response.",cause:n.error,text:r,response:a.response,usage:a.usage,finishReason:a.finishReason});const s=await er({value:n.value,schema:e});if(!s.success)throw new op({message:"No object generated: response did not match schema.",cause:s.error,text:r,response:a.response,usage:a.usage,finishReason:a.finishReason});return s.value}}},dE=Sn({name:w(),version:w()}),Si=Sn({_meta:it(E({}).loose())}),wa=Si,pE=E({method:w(),params:it(Si)}),hE=Sn({experimental:it(E({}).loose()),logging:it(E({}).loose()),prompts:it(Sn({listChanged:it(st())})),resources:it(Sn({subscribe:it(st()),listChanged:it(st())})),tools:it(Sn({listChanged:it(st())}))});wa.extend({protocolVersion:w(),capabilities:hE,serverInfo:dE,instructions:it(w())});var fE=wa.extend({nextCursor:it(w())}),mE=E({name:w(),description:it(w()),inputSchema:E({type:q("object"),properties:it(E({}).loose())}).loose()}).loose();fE.extend({tools:K(mE)});var vE=E({type:q("text"),text:w()}).loose(),gE=E({type:q("image"),data:wc(),mimeType:w()}).loose(),nh=E({uri:w(),mimeType:it(w())}).loose(),yE=nh.extend({text:w()}),_E=nh.extend({blob:wc()}),wE=E({type:q("resource"),resource:Ne([yE,_E])}).loose();wa.extend({content:K(Ne([vE,gE,wE])),isError:st().default(!1).optional()}).or(wa.extend({toolResult:Xt()}));var Ss="2.0",bE=E({jsonrpc:q(Ss),id:Ne([w(),D().int()])}).merge(pE).strict(),xE=E({jsonrpc:q(Ss),id:Ne([w(),D().int()]),result:wa}).strict(),EE=E({jsonrpc:q(Ss),id:Ne([w(),D().int()]),error:E({code:D().int(),message:w(),data:it(Xt())})}).strict(),SE=E({jsonrpc:q(Ss)}).merge(E({method:w(),params:it(Si)})).strict();Ne([bE,SE,xE,EE]);const Is="2025-06-18",IE=[Is,"2025-03-26","2024-11-05","2024-10-07"],ks="2.0",ah=St([$(),mt().int()]),sh=$(),kE=W({progressToken:V(ah)}).passthrough(),Vt=W({_meta:V(kE)}).passthrough(),At=W({method:$(),params:V(Vt)}),ba=W({_meta:V(W({}).passthrough())}).passthrough(),mr=W({method:$(),params:V(ba)}),Bt=W({_meta:V(W({}).passthrough())}).passthrough(),Ts=St([$(),mt().int()]),oh=W({jsonrpc:_e(ks),id:Ts}).merge(At).strict(),ih=t=>oh.safeParse(t).success,lh=W({jsonrpc:_e(ks)}).merge(mr).strict(),TE=t=>lh.safeParse(t).success,uh=W({jsonrpc:_e(ks),id:Ts,result:Bt}).strict(),Ii=t=>uh.safeParse(t).success;var vr;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError"})(vr||(vr={}));const ch=W({jsonrpc:_e(ks),id:Ts,error:W({code:mt().int(),message:$(),data:V(oa())})}).strict(),PE=t=>ch.safeParse(t).success,hn=St([oh,lh,uh,ch]),fn=Bt.strict(),ki=mr.extend({method:_e("notifications/cancelled"),params:ba.extend({requestId:Ts,reason:$().optional()})}),CE=W({src:$(),mimeType:V($()),sizes:V(re($()))}).passthrough(),xa=W({icons:re(CE).optional()}).passthrough(),Ea=W({name:$(),title:V($())}).passthrough(),dh=Ea.extend({version:$(),websiteUrl:V($())}).merge(xa),RE=W({experimental:V(W({}).passthrough()),sampling:V(W({}).passthrough()),elicitation:V(W({}).passthrough()),roots:V(W({listChanged:V(dt())}).passthrough())}).passthrough(),OE=At.extend({method:_e("initialize"),params:Vt.extend({protocolVersion:$(),capabilities:RE,clientInfo:dh})}),$E=W({experimental:V(W({}).passthrough()),logging:V(W({}).passthrough()),completions:V(W({}).passthrough()),prompts:V(W({listChanged:V(dt())}).passthrough()),resources:V(W({subscribe:V(dt()),listChanged:V(dt())}).passthrough()),tools:V(W({listChanged:V(dt())}).passthrough())}).passthrough(),ph=Bt.extend({protocolVersion:$(),capabilities:$E,serverInfo:dh,instructions:V($())}),hh=mr.extend({method:_e("notifications/initialized")}),AE=t=>hh.safeParse(t).success,Ti=At.extend({method:_e("ping")}),NE=W({progress:mt(),total:V(mt()),message:V($())}).passthrough(),Pi=mr.extend({method:_e("notifications/progress"),params:ba.merge(NE).extend({progressToken:ah})}),Ps=At.extend({params:Vt.extend({cursor:V(sh)}).optional()}),Cs=Bt.extend({nextCursor:V(sh)}),fh=W({uri:$(),mimeType:V($()),_meta:V(W({}).passthrough())}).passthrough(),mh=fh.extend({text:$()}),Ci=$().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),vh=fh.extend({blob:Ci}),gh=Ea.extend({uri:$(),description:V($()),mimeType:V($()),_meta:V(W({}).passthrough())}).merge(xa),ME=Ea.extend({uriTemplate:$(),description:V($()),mimeType:V($()),_meta:V(W({}).passthrough())}).merge(xa),DE=Ps.extend({method:_e("resources/list")}),yh=Cs.extend({resources:re(gh)}),jE=Ps.extend({method:_e("resources/templates/list")}),_h=Cs.extend({resourceTemplates:re(ME)}),zE=At.extend({method:_e("resources/read"),params:Vt.extend({uri:$()})}),wh=Bt.extend({contents:re(St([mh,vh]))}),bh=mr.extend({method:_e("notifications/resources/list_changed")}),LE=At.extend({method:_e("resources/subscribe"),params:Vt.extend({uri:$()})}),UE=At.extend({method:_e("resources/unsubscribe"),params:Vt.extend({uri:$()})}),xh=mr.extend({method:_e("notifications/resources/updated"),params:ba.extend({uri:$()})}),FE=W({name:$(),description:V($()),required:V(dt())}).passthrough(),qE=Ea.extend({description:V($()),arguments:V(re(FE)),_meta:V(W({}).passthrough())}).merge(xa),ZE=Ps.extend({method:_e("prompts/list")}),Eh=Cs.extend({prompts:re(qE)}),VE=At.extend({method:_e("prompts/get"),params:Vt.extend({name:$(),arguments:V(ia($()))})}),Ri=W({type:_e("text"),text:$(),_meta:V(W({}).passthrough())}).passthrough(),Oi=W({type:_e("image"),data:Ci,mimeType:$(),_meta:V(W({}).passthrough())}).passthrough(),$i=W({type:_e("audio"),data:Ci,mimeType:$(),_meta:V(W({}).passthrough())}).passthrough(),BE=W({type:_e("resource"),resource:St([mh,vh]),_meta:V(W({}).passthrough())}).passthrough(),HE=gh.extend({type:_e("resource_link")}),Sh=St([Ri,Oi,$i,HE,BE]),JE=W({role:Rr(["user","assistant"]),content:Sh}).passthrough(),Ih=Bt.extend({description:V($()),messages:re(JE)}),kh=mr.extend({method:_e("notifications/prompts/list_changed")}),WE=W({title:V($()),readOnlyHint:V(dt()),destructiveHint:V(dt()),idempotentHint:V(dt()),openWorldHint:V(dt())}).passthrough(),GE=Ea.extend({description:V($()),inputSchema:W({type:_e("object"),properties:V(W({}).passthrough()),required:V(re($()))}).passthrough(),outputSchema:V(W({type:_e("object"),properties:V(W({}).passthrough()),required:V(re($()))}).passthrough()),annotations:V(WE),_meta:V(W({}).passthrough())}).merge(xa),KE=Ps.extend({method:_e("tools/list")}),Th=Cs.extend({tools:re(GE)}),Rs=Bt.extend({content:re(Sh).default([]),structuredContent:W({}).passthrough().optional(),isError:V(dt())});Rs.or(Bt.extend({toolResult:oa()}));const QE=At.extend({method:_e("tools/call"),params:Vt.extend({name:$(),arguments:V(ia(oa()))})}),Ph=mr.extend({method:_e("notifications/tools/list_changed")}),Ch=Rr(["debug","info","notice","warning","error","critical","alert","emergency"]),YE=At.extend({method:_e("logging/setLevel"),params:Vt.extend({level:Ch})}),Rh=mr.extend({method:_e("notifications/message"),params:ba.extend({level:Ch,logger:V($()),data:oa()})}),XE=W({name:$().optional()}).passthrough(),eS=W({hints:V(re(XE)),costPriority:V(mt().min(0).max(1)),speedPriority:V(mt().min(0).max(1)),intelligencePriority:V(mt().min(0).max(1))}).passthrough(),tS=W({role:Rr(["user","assistant"]),content:St([Ri,Oi,$i])}).passthrough(),Oh=At.extend({method:_e("sampling/createMessage"),params:Vt.extend({messages:re(tS),systemPrompt:V($()),includeContext:V(Rr(["none","thisServer","allServers"])),temperature:V(mt()),maxTokens:mt().int(),stopSequences:V(re($())),metadata:V(W({}).passthrough()),modelPreferences:V(eS)})}),$h=Bt.extend({model:$(),stopReason:V(Rr(["endTurn","stopSequence","maxTokens"]).or($())),role:Rr(["user","assistant"]),content:R0("type",[Ri,Oi,$i])}),rS=W({type:_e("boolean"),title:V($()),description:V($()),default:V(dt())}).passthrough(),nS=W({type:_e("string"),title:V($()),description:V($()),minLength:V(mt()),maxLength:V(mt()),format:V(Rr(["email","uri","date","date-time"]))}).passthrough(),aS=W({type:Rr(["number","integer"]),title:V($()),description:V($()),minimum:V(mt()),maximum:V(mt())}).passthrough(),sS=W({type:_e("string"),title:V($()),description:V($()),enum:re($()),enumNames:V(re($()))}).passthrough(),oS=St([rS,nS,aS,sS]),Ah=At.extend({method:_e("elicitation/create"),params:Vt.extend({message:$(),requestedSchema:W({type:_e("object"),properties:ia($(),oS),required:V(re($()))}).passthrough()})}),Nh=Bt.extend({action:Rr(["accept","decline","cancel"]),content:V(ia($(),oa()))}),iS=W({type:_e("ref/resource"),uri:$()}).passthrough(),lS=W({type:_e("ref/prompt"),name:$()}).passthrough(),uS=At.extend({method:_e("completion/complete"),params:Vt.extend({ref:St([lS,iS]),argument:W({name:$(),value:$()}).passthrough(),context:V(W({arguments:V(ia($(),$()))}))})}),Mh=Bt.extend({completion:W({values:re($()).max(100),total:V(mt().int()),hasMore:V(dt())}).passthrough()}),cS=W({uri:$().startsWith("file://"),name:V($()),_meta:V(W({}).passthrough())}).passthrough(),Dh=At.extend({method:_e("roots/list")}),jh=Bt.extend({roots:re(cS)}),dS=mr.extend({method:_e("notifications/roots/list_changed")});St([Ti,OE,uS,YE,VE,ZE,DE,jE,zE,LE,UE,QE,KE]),St([ki,Pi,hh,dS]),St([fn,$h,Nh,jh]),St([Ti,Oh,Ah,Dh]),St([ki,Pi,Rh,xh,bh,Ph,kh]),St([fn,ph,Mh,Ih,Eh,yh,_h,wh,Rs,Th]);class Lr extends Error{constructor(e,r,a){super(`MCP error ${e}: ${r}`),this.code=e,this.data=a,this.name="McpError"}}let Ai;Ai=globalThis.crypto;async function pS(t){return(await Ai).getRandomValues(new Uint8Array(t))}async function hS(t){const e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~";let r="";const a=await pS(t);for(let n=0;n<t;n++){const s=a[n]%e.length;r+=e[s]}return r}async function fS(t){return await hS(t)}async function mS(t){const e=await(await Ai).subtle.digest("SHA-256",new TextEncoder().encode(t));return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function vS(t){if(t||(t=43),t<43||t>128)throw`Expected a length between 43 and 128. Received ${t}.`;const e=await fS(t),r=await mS(e);return{code_verifier:e,code_challenge:r}}const yt=$().url().superRefine((t,e)=>{if(!URL.canParse(t))return e.addIssue({code:B.custom,message:"URL must be parseable",fatal:!0}),O0}).refine(t=>{const e=new URL(t);return e.protocol!=="javascript:"&&e.protocol!=="data:"&&e.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),gS=W({resource:$().url(),authorization_servers:re(yt).optional(),jwks_uri:$().url().optional(),scopes_supported:re($()).optional(),bearer_methods_supported:re($()).optional(),resource_signing_alg_values_supported:re($()).optional(),resource_name:$().optional(),resource_documentation:$().optional(),resource_policy_uri:$().url().optional(),resource_tos_uri:$().url().optional(),tls_client_certificate_bound_access_tokens:dt().optional(),authorization_details_types_supported:re($()).optional(),dpop_signing_alg_values_supported:re($()).optional(),dpop_bound_access_tokens_required:dt().optional()}).passthrough(),zh=W({issuer:$(),authorization_endpoint:yt,token_endpoint:yt,registration_endpoint:yt.optional(),scopes_supported:re($()).optional(),response_types_supported:re($()),response_modes_supported:re($()).optional(),grant_types_supported:re($()).optional(),token_endpoint_auth_methods_supported:re($()).optional(),token_endpoint_auth_signing_alg_values_supported:re($()).optional(),service_documentation:yt.optional(),revocation_endpoint:yt.optional(),revocation_endpoint_auth_methods_supported:re($()).optional(),revocation_endpoint_auth_signing_alg_values_supported:re($()).optional(),introspection_endpoint:$().optional(),introspection_endpoint_auth_methods_supported:re($()).optional(),introspection_endpoint_auth_signing_alg_values_supported:re($()).optional(),code_challenge_methods_supported:re($()).optional()}).passthrough(),yS=W({issuer:$(),authorization_endpoint:yt,token_endpoint:yt,userinfo_endpoint:yt.optional(),jwks_uri:yt,registration_endpoint:yt.optional(),scopes_supported:re($()).optional(),response_types_supported:re($()),response_modes_supported:re($()).optional(),grant_types_supported:re($()).optional(),acr_values_supported:re($()).optional(),subject_types_supported:re($()),id_token_signing_alg_values_supported:re($()),id_token_encryption_alg_values_supported:re($()).optional(),id_token_encryption_enc_values_supported:re($()).optional(),userinfo_signing_alg_values_supported:re($()).optional(),userinfo_encryption_alg_values_supported:re($()).optional(),userinfo_encryption_enc_values_supported:re($()).optional(),request_object_signing_alg_values_supported:re($()).optional(),request_object_encryption_alg_values_supported:re($()).optional(),request_object_encryption_enc_values_supported:re($()).optional(),token_endpoint_auth_methods_supported:re($()).optional(),token_endpoint_auth_signing_alg_values_supported:re($()).optional(),display_values_supported:re($()).optional(),claim_types_supported:re($()).optional(),claims_supported:re($()).optional(),service_documentation:$().optional(),claims_locales_supported:re($()).optional(),ui_locales_supported:re($()).optional(),claims_parameter_supported:dt().optional(),request_parameter_supported:dt().optional(),request_uri_parameter_supported:dt().optional(),require_request_uri_registration:dt().optional(),op_policy_uri:yt.optional(),op_tos_uri:yt.optional()}).passthrough().merge(zh.pick({code_challenge_methods_supported:!0})),Lh=W({access_token:$(),id_token:$().optional(),token_type:$(),expires_in:mt().optional(),scope:$().optional(),refresh_token:$().optional()}).strip(),_S=W({error:$(),error_description:$().optional(),error_uri:$().optional()}),Uh=yt.optional().or(_e("").transform(()=>{})),wS=W({redirect_uris:re(yt),token_endpoint_auth_method:$().optional(),grant_types:re($()).optional(),response_types:re($()).optional(),client_name:$().optional(),client_uri:yt.optional(),logo_uri:Uh,scope:$().optional(),contacts:re($()).optional(),tos_uri:Uh,policy_uri:$().optional(),jwks_uri:yt.optional(),jwks:C0().optional(),software_id:$().optional(),software_version:$().optional(),software_statement:$().optional()}).strip(),bS=W({client_id:$(),client_secret:$().optional(),client_id_issued_at:mt().optional(),client_secret_expires_at:mt().optional()}).strip(),xS=wS.merge(bS);W({error:$(),error_description:$().optional()}).strip(),W({token:$(),token_type_hint:$().optional()}).strip();function ES(t){const e=typeof t=="string"?new URL(t):new URL(t.href);return e.hash="",e}function SS({requestedResource:t,configuredResource:e}){const r=typeof t=="string"?new URL(t):new URL(t.href),a=typeof e=="string"?new URL(e):new URL(e.href);if(r.origin!==a.origin||r.pathname.length<a.pathname.length)return!1;const n=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",s=a.pathname.endsWith("/")?a.pathname:a.pathname+"/";return n.startsWith(s)}class _t extends Error{constructor(e,r){super(e),this.errorUri=r,this.name=this.constructor.name}toResponseObject(){const e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}}class Ni extends _t{}Ni.errorCode="invalid_request";class Os extends _t{}Os.errorCode="invalid_client";class $s extends _t{}$s.errorCode="invalid_grant";class As extends _t{}As.errorCode="unauthorized_client";class Mi extends _t{}Mi.errorCode="unsupported_grant_type";class Di extends _t{}Di.errorCode="invalid_scope";class ji extends _t{}ji.errorCode="access_denied";class $n extends _t{}$n.errorCode="server_error";class zi extends _t{}zi.errorCode="temporarily_unavailable";class Li extends _t{}Li.errorCode="unsupported_response_type";class Ui extends _t{}Ui.errorCode="unsupported_token_type";class Fi extends _t{}Fi.errorCode="invalid_token";class qi extends _t{}qi.errorCode="method_not_allowed";class Zi extends _t{}Zi.errorCode="too_many_requests";class Vi extends _t{}Vi.errorCode="invalid_client_metadata";class Bi extends _t{}Bi.errorCode="insufficient_scope";const IS={[Ni.errorCode]:Ni,[Os.errorCode]:Os,[$s.errorCode]:$s,[As.errorCode]:As,[Mi.errorCode]:Mi,[Di.errorCode]:Di,[ji.errorCode]:ji,[$n.errorCode]:$n,[zi.errorCode]:zi,[Li.errorCode]:Li,[Ui.errorCode]:Ui,[Fi.errorCode]:Fi,[qi.errorCode]:qi,[Zi.errorCode]:Zi,[Vi.errorCode]:Vi,[Bi.errorCode]:Bi};class ar extends Error{constructor(e){super(e??"Unauthorized")}}const Hi="code",Ji="S256";function Fh(t,e){const r=t.client_secret!==void 0;return e.length===0?r?"client_secret_post":"none":r&&e.includes("client_secret_basic")?"client_secret_basic":r&&e.includes("client_secret_post")?"client_secret_post":e.includes("none")?"none":r?"client_secret_post":"none"}function qh(t,e,r,a){const{client_id:n,client_secret:s}=e;switch(t){case"client_secret_basic":kS(n,s,r);return;case"client_secret_post":TS(n,s,a);return;case"none":PS(n,a);return;default:throw new Error(`Unsupported client authentication method: ${t}`)}}function kS(t,e,r){if(!e)throw new Error("client_secret_basic authentication requires a client_secret");const a=btoa(`${t}:${e}`);r.set("Authorization",`Basic ${a}`)}function TS(t,e,r){r.set("client_id",t),e&&r.set("client_secret",e)}function PS(t,e){e.set("client_id",t)}async function Wi(t){const e=t instanceof Response?t.status:void 0,r=t instanceof Response?await t.text():t;try{const a=_S.parse(JSON.parse(r)),{error:n,error_description:s,error_uri:o}=a,i=IS[n]||$n;return new i(s||"",o)}catch(a){const n=`${e?`HTTP ${e}: `:""}Invalid OAuth error response: ${a}. Raw body: ${r}`;return new $n(n)}}async function An(t,e){var r,a;try{return await Gi(t,e)}catch(n){if(n instanceof Os||n instanceof As)return await((r=t.invalidateCredentials)===null||r===void 0?void 0:r.call(t,"all")),await Gi(t,e);if(n instanceof $s)return await((a=t.invalidateCredentials)===null||a===void 0?void 0:a.call(t,"tokens")),await Gi(t,e);throw n}}async function Gi(t,{serverUrl:e,authorizationCode:r,scope:a,resourceMetadataUrl:n,fetchFn:s}){let o,i;try{o=await RS(e,{resourceMetadataUrl:n},s),o.authorization_servers&&o.authorization_servers.length>0&&(i=o.authorization_servers[0])}catch{}i||(i=e);const l=await CS(e,t,o),u=await MS(i,{fetchFn:s});let d=await Promise.resolve(t.clientInformation());if(!d){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");if(!t.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");const g=await LS(i,{metadata:u,clientMetadata:t.clientMetadata,fetchFn:s});await t.saveClientInformation(g),d=g}if(r!==void 0){const g=await t.codeVerifier(),f=await jS(i,{metadata:u,clientInformation:d,authorizationCode:r,codeVerifier:g,redirectUri:t.redirectUrl,resource:l,addClientAuthentication:t.addClientAuthentication,fetchFn:s});return await t.saveTokens(f),"AUTHORIZED"}const v=await t.tokens();if(v!=null&&v.refresh_token)try{const g=await zS(i,{metadata:u,clientInformation:d,refreshToken:v.refresh_token,resource:l,addClientAuthentication:t.addClientAuthentication,fetchFn:s});return await t.saveTokens(g),"AUTHORIZED"}catch(g){if(!(!(g instanceof _t)||g instanceof $n))throw g}const m=t.state?await t.state():void 0,{authorizationUrl:c,codeVerifier:h}=await DS(i,{metadata:u,clientInformation:d,state:m,redirectUrl:t.redirectUrl,scope:a||t.clientMetadata.scope,resource:l});return await t.saveCodeVerifier(h),await t.redirectToAuthorization(c),"REDIRECT"}async function CS(t,e,r){const a=ES(t);if(e.validateResourceURL)return await e.validateResourceURL(a,r==null?void 0:r.resource);if(r){if(!SS({requestedResource:a,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${a} (or origin)`);return new URL(r.resource)}}function Ki(t){const e=t.headers.get("WWW-Authenticate");if(!e)return;const[r,a]=e.split(" ");if(r.toLowerCase()!=="bearer"||!a)return;const s=/resource_metadata="([^"]*)"/.exec(e);if(s)try{return new URL(s[1])}catch{return}}async function RS(t,e,r=fetch){const a=await AS(t,"oauth-protected-resource",r,{protocolVersion:e==null?void 0:e.protocolVersion,metadataUrl:e==null?void 0:e.resourceMetadataUrl});if(!a||a.status===404)throw new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!a.ok)throw new Error(`HTTP ${a.status} trying to load well-known OAuth protected resource metadata.`);return gS.parse(await a.json())}async function Qi(t,e,r=fetch){try{return await r(t,{headers:e})}catch(a){if(a instanceof TypeError)return e?Qi(t,void 0,r):void 0;throw a}}function OS(t,e="",r={}){return e.endsWith("/")&&(e=e.slice(0,-1)),r.prependPathname?`${e}/.well-known/${t}`:`/.well-known/${t}${e}`}async function Zh(t,e,r=fetch){return await Qi(t,{"MCP-Protocol-Version":e},r)}function $S(t,e){return!t||t.status>=400&&t.status<500&&e!=="/"}async function AS(t,e,r,a){var n,s;const o=new URL(t),i=(n=a==null?void 0:a.protocolVersion)!==null&&n!==void 0?n:Is;let l;if(a!=null&&a.metadataUrl)l=new URL(a.metadataUrl);else{const d=OS(e,o.pathname);l=new URL(d,(s=a==null?void 0:a.metadataServerUrl)!==null&&s!==void 0?s:o),l.search=o.search}let u=await Zh(l,i,r);if(!(a!=null&&a.metadataUrl)&&$S(u,o.pathname)){const d=new URL(`/.well-known/${e}`,o);u=await Zh(d,i,r)}return u}function NS(t){const e=typeof t=="string"?new URL(t):t,r=e.pathname!=="/",a=[];if(!r)return a.push({url:new URL("/.well-known/oauth-authorization-server",e.origin),type:"oauth"}),a.push({url:new URL("/.well-known/openid-configuration",e.origin),type:"oidc"}),a;let n=e.pathname;return n.endsWith("/")&&(n=n.slice(0,-1)),a.push({url:new URL(`/.well-known/oauth-authorization-server${n}`,e.origin),type:"oauth"}),a.push({url:new URL("/.well-known/oauth-authorization-server",e.origin),type:"oauth"}),a.push({url:new URL(`/.well-known/openid-configuration${n}`,e.origin),type:"oidc"}),a.push({url:new URL(`${n}/.well-known/openid-configuration`,e.origin),type:"oidc"}),a}async function MS(t,{fetchFn:e=fetch,protocolVersion:r=Is}={}){const a={"MCP-Protocol-Version":r,Accept:"application/json"},n=NS(t);for(const{url:s,type:o}of n){const i=await Qi(s,a,e);if(i){if(!i.ok){if(i.status>=400&&i.status<500)continue;throw new Error(`HTTP ${i.status} trying to load ${o==="oauth"?"OAuth":"OpenID provider"} metadata from ${s}`)}return o==="oauth"?zh.parse(await i.json()):yS.parse(await i.json())}}}async function DS(t,{metadata:e,clientInformation:r,redirectUrl:a,scope:n,state:s,resource:o}){let i;if(e){if(i=new URL(e.authorization_endpoint),!e.response_types_supported.includes(Hi))throw new Error(`Incompatible auth server: does not support response type ${Hi}`);if(e.code_challenge_methods_supported&&!e.code_challenge_methods_supported.includes(Ji))throw new Error(`Incompatible auth server: does not support code challenge method ${Ji}`)}else i=new URL("/authorize",t);const l=await vS(),u=l.code_verifier,d=l.code_challenge;return i.searchParams.set("response_type",Hi),i.searchParams.set("client_id",r.client_id),i.searchParams.set("code_challenge",d),i.searchParams.set("code_challenge_method",Ji),i.searchParams.set("redirect_uri",String(a)),s&&i.searchParams.set("state",s),n&&i.searchParams.set("scope",n),n!=null&&n.includes("offline_access")&&i.searchParams.append("prompt","consent"),o&&i.searchParams.set("resource",o.href),{authorizationUrl:i,codeVerifier:u}}async function jS(t,{metadata:e,clientInformation:r,authorizationCode:a,codeVerifier:n,redirectUri:s,resource:o,addClientAuthentication:i,fetchFn:l}){var u;const d="authorization_code",v=e!=null&&e.token_endpoint?new URL(e.token_endpoint):new URL("/token",t);if(e!=null&&e.grant_types_supported&&!e.grant_types_supported.includes(d))throw new Error(`Incompatible auth server: does not support grant type ${d}`);const m=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),c=new URLSearchParams({grant_type:d,code:a,code_verifier:n,redirect_uri:String(s)});if(i)i(m,c,t,e);else{const g=(u=e==null?void 0:e.token_endpoint_auth_methods_supported)!==null&&u!==void 0?u:[],f=Fh(r,g);qh(f,r,m,c)}o&&c.set("resource",o.href);const h=await(l??fetch)(v,{method:"POST",headers:m,body:c});if(!h.ok)throw await Wi(h);return Lh.parse(await h.json())}async function zS(t,{metadata:e,clientInformation:r,refreshToken:a,resource:n,addClientAuthentication:s,fetchFn:o}){var i;const l="refresh_token";let u;if(e){if(u=new URL(e.token_endpoint),e.grant_types_supported&&!e.grant_types_supported.includes(l))throw new Error(`Incompatible auth server: does not support grant type ${l}`)}else u=new URL("/token",t);const d=new Headers({"Content-Type":"application/x-www-form-urlencoded"}),v=new URLSearchParams({grant_type:l,refresh_token:a});if(s)s(d,v,t,e);else{const c=(i=e==null?void 0:e.token_endpoint_auth_methods_supported)!==null&&i!==void 0?i:[],h=Fh(r,c);qh(h,r,d,v)}n&&v.set("resource",n.href);const m=await(o??fetch)(u,{method:"POST",headers:d,body:v});if(!m.ok)throw await Wi(m);return Lh.parse({refresh_token:a,...await m.json()})}async function LS(t,{metadata:e,clientMetadata:r,fetchFn:a}){let n;if(e){if(!e.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");n=new URL(e.registration_endpoint)}else n=new URL("/register",t);const s=await(a??fetch)(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok)throw await Wi(s);return xS.parse(await s.json())}const US={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class Ns extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}}class Ms{constructor(e,r){var a;this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._requestInit=r==null?void 0:r.requestInit,this._authProvider=r==null?void 0:r.authProvider,this._fetch=r==null?void 0:r.fetch,this._sessionId=r==null?void 0:r.sessionId,this._reconnectionOptions=(a=r==null?void 0:r.reconnectionOptions)!==null&&a!==void 0?a:US}async _authThenStart(){var e;if(!this._authProvider)throw new ar("No auth provider");let r;try{r=await An(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(a){throw(e=this.onerror)===null||e===void 0||e.call(this,a),a}if(r!=="AUTHORIZED")throw new ar;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var e;const r={};if(this._authProvider){const n=await this._authProvider.tokens();n&&(r.Authorization=`Bearer ${n.access_token}`)}this._sessionId&&(r["mcp-session-id"]=this._sessionId),this._protocolVersion&&(r["mcp-protocol-version"]=this._protocolVersion);const a=this._normalizeHeaders((e=this._requestInit)===null||e===void 0?void 0:e.headers);return new Headers({...r,...a})}async _startOrAuthSse(e){var r,a,n;const{resumptionToken:s}=e;try{const o=await this._commonHeaders();o.set("Accept","text/event-stream"),s&&o.set("last-event-id",s);const i=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._url,{method:"GET",headers:o,signal:(a=this._abortController)===null||a===void 0?void 0:a.signal});if(!i.ok){if(i.status===401&&this._authProvider)return await this._authThenStart();if(i.status===405)return;throw new Ns(i.status,`Failed to open SSE stream: ${i.statusText}`)}this._handleSseStream(i.body,e,!0)}catch(o){throw(n=this.onerror)===null||n===void 0||n.call(this,o),o}}_getNextReconnectionDelay(e){const r=this._reconnectionOptions.initialReconnectionDelay,a=this._reconnectionOptions.reconnectionDelayGrowFactor,n=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(a,e),n)}_normalizeHeaders(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}_scheduleReconnection(e,r=0){var a;const n=this._reconnectionOptions.maxRetries;if(n>0&&r>=n){(a=this.onerror)===null||a===void 0||a.call(this,new Error(`Maximum reconnection attempts (${n}) exceeded.`));return}const s=this._getNextReconnectionDelay(r);setTimeout(()=>{this._startOrAuthSse(e).catch(o=>{var i;(i=this.onerror)===null||i===void 0||i.call(this,new Error(`Failed to reconnect SSE stream: ${o instanceof Error?o.message:String(o)}`)),this._scheduleReconnection(e,r+1)})},s)}_handleSseStream(e,r,a){if(!e)return;const{onresumptiontoken:n,replayMessageId:s}=r;let o;(async()=>{var l,u,d,v;try{const m=e.pipeThrough(new TextDecoderStream).pipeThrough(new Au).getReader();for(;;){const{value:c,done:h}=await m.read();if(h)break;if(c.id&&(o=c.id,n==null||n(c.id)),!c.event||c.event==="message")try{const g=hn.parse(JSON.parse(c.data));s!==void 0&&Ii(g)&&(g.id=s),(l=this.onmessage)===null||l===void 0||l.call(this,g)}catch(g){(u=this.onerror)===null||u===void 0||u.call(this,g)}}}catch(m){if((d=this.onerror)===null||d===void 0||d.call(this,new Error(`SSE stream disconnected: ${m}`)),a&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:o,onresumptiontoken:n,replayMessageId:s},0)}catch(c){(v=this.onerror)===null||v===void 0||v.call(this,new Error(`Failed to reconnect: ${c instanceof Error?c.message:String(c)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new ar("No auth provider");if(await An(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new ar("Failed to authorize")}async close(){var e,r;(e=this._abortController)===null||e===void 0||e.abort(),(r=this.onclose)===null||r===void 0||r.call(this)}async send(e,r){var a,n,s,o;try{const{resumptionToken:i,onresumptiontoken:l}=r||{};if(i){this._startOrAuthSse({resumptionToken:i,replayMessageId:ih(e)?e.id:void 0}).catch(f=>{var p;return(p=this.onerror)===null||p===void 0?void 0:p.call(this,f)});return}const u=await this._commonHeaders();u.set("content-type","application/json"),u.set("accept","application/json, text/event-stream");const d={...this._requestInit,method:"POST",headers:u,body:JSON.stringify(e),signal:(a=this._abortController)===null||a===void 0?void 0:a.signal},v=await((n=this._fetch)!==null&&n!==void 0?n:fetch)(this._url,d),m=v.headers.get("mcp-session-id");if(m&&(this._sessionId=m),!v.ok){if(v.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new Ns(401,"Server returned 401 after successful authentication");if(this._resourceMetadataUrl=Ki(v),await An(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new ar;return this._hasCompletedAuthFlow=!0,this.send(e)}const f=await v.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${v.status}): ${f}`)}if(this._hasCompletedAuthFlow=!1,v.status===202){AE(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(f=>{var p;return(p=this.onerror)===null||p===void 0?void 0:p.call(this,f)});return}const h=(Array.isArray(e)?e:[e]).filter(f=>"method"in f&&"id"in f&&f.id!==void 0).length>0,g=v.headers.get("content-type");if(h)if(g!=null&&g.includes("text/event-stream"))this._handleSseStream(v.body,{onresumptiontoken:l},!1);else if(g!=null&&g.includes("application/json")){const f=await v.json(),p=Array.isArray(f)?f.map(b=>hn.parse(b)):[hn.parse(f)];for(const b of p)(s=this.onmessage)===null||s===void 0||s.call(this,b)}else throw new Ns(-1,`Unexpected content type: ${g}`)}catch(i){throw(o=this.onerror)===null||o===void 0||o.call(this,i),i}}get sessionId(){return this._sessionId}async terminateSession(){var e,r,a;if(this._sessionId)try{const n=await this._commonHeaders(),s={...this._requestInit,method:"DELETE",headers:n,signal:(e=this._abortController)===null||e===void 0?void 0:e.signal},o=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._url,s);if(!o.ok&&o.status!==405)throw new Ns(o.status,`Failed to terminate session: ${o.statusText}`);this._sessionId=void 0}catch(n){throw(a=this.onerror)===null||a===void 0||a.call(this,n),n}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}}class Ds{constructor(){this._messageQueue=[]}static createLinkedPair(){const e=new Ds,r=new Ds;return e._otherTransport=r,r._otherTransport=e,[e,r]}async start(){for(var e;this._messageQueue.length>0;){const r=this._messageQueue.shift();(e=this.onmessage)===null||e===void 0||e.call(this,r.message,r.extra)}}async close(){var e;const r=this._otherTransport;this._otherTransport=void 0,await(r==null?void 0:r.close()),(e=this.onclose)===null||e===void 0||e.call(this)}async send(e,r){if(!this._otherTransport)throw new Error("Not connected");this._otherTransport.onmessage?this._otherTransport.onmessage(e,{authInfo:r==null?void 0:r.authInfo}):this._otherTransport._messageQueue.push({message:e,extra:{authInfo:r==null?void 0:r.authInfo}})}}var Yi=E({error:E({message:w(),type:w().nullish(),param:Ft().nullish(),code:Ne([w(),D()]).nullish()})}),gr=on({errorSchema:Yi,errorToMessage:t=>t.error.message});function FS({prompt:t,systemMessageMode:e="system"}){const r=[],a=[];for(const{role:n,content:s}of t)switch(n){case"system":{switch(e){case"system":{r.push({role:"system",content:s});break}case"developer":{r.push({role:"developer",content:s});break}case"remove":{a.push({type:"other",message:"system messages are removed for this model"});break}default:{const o=e;throw new Error(`Unsupported system message mode: ${o}`)}}break}case"user":{if(s.length===1&&s[0].type==="text"){r.push({role:"user",content:s[0].text});break}r.push({role:"user",content:s.map((o,i)=>{var l,u,d;switch(o.type){case"text":return{type:"text",text:o.text};case"file":if(o.mediaType.startsWith("image/")){const v=o.mediaType==="image/*"?"image/jpeg":o.mediaType;return{type:"image_url",image_url:{url:o.data instanceof URL?o.data.toString():`data:${v};base64,${ln(o.data)}`,detail:(u=(l=o.providerOptions)==null?void 0:l.openai)==null?void 0:u.imageDetail}}}else if(o.mediaType.startsWith("audio/")){if(o.data instanceof URL)throw new Yt({functionality:"audio file parts with URLs"});switch(o.mediaType){case"audio/wav":return{type:"input_audio",input_audio:{data:ln(o.data),format:"wav"}};case"audio/mp3":case"audio/mpeg":return{type:"input_audio",input_audio:{data:ln(o.data),format:"mp3"}};default:throw new Yt({functionality:`audio content parts with media type ${o.mediaType}`})}}else if(o.mediaType==="application/pdf"){if(o.data instanceof URL)throw new Yt({functionality:"PDF file parts with URLs"});return{type:"file",file:typeof o.data=="string"&&o.data.startsWith("file-")?{file_id:o.data}:{filename:(d=o.filename)!=null?d:`part-${i}.pdf`,file_data:`data:application/pdf;base64,${ln(o.data)}`}}}else throw new Yt({functionality:`file part media type ${o.mediaType}`})}})});break}case"assistant":{let o="";const i=[];for(const l of s)switch(l.type){case"text":{o+=l.text;break}case"tool-call":{i.push({id:l.toolCallId,type:"function",function:{name:l.toolName,arguments:JSON.stringify(l.input)}});break}}r.push({role:"assistant",content:o,tool_calls:i.length>0?i:void 0});break}case"tool":{for(const o of s){const i=o.output;let l;switch(i.type){case"text":case"error-text":l=i.value;break;case"content":case"json":case"error-json":l=JSON.stringify(i.value);break}r.push({role:"tool",tool_call_id:o.toolCallId,content:l})}break}default:{const o=n;throw new Error(`Unsupported role: ${o}`)}}return{messages:r,warnings:a}}function Vh({id:t,model:e,created:r}){return{id:t??void 0,modelId:e??void 0,timestamp:r!=null?new Date(r*1e3):void 0}}function Bh(t){switch(t){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"unknown"}}var qS=rt(()=>Ie(E({id:w().nullish(),created:D().nullish(),model:w().nullish(),choices:K(E({message:E({role:q("assistant").nullish(),content:w().nullish(),tool_calls:K(E({id:w().nullish(),type:q("function"),function:E({name:w(),arguments:w()})})).nullish(),annotations:K(E({type:q("url_citation"),start_index:D(),end_index:D(),url:w(),title:w()})).nullish()}),index:D(),logprobs:E({content:K(E({token:w(),logprob:D(),top_logprobs:K(E({token:w(),logprob:D()}))})).nullish()}).nullish(),finish_reason:w().nullish()})),usage:E({prompt_tokens:D().nullish(),completion_tokens:D().nullish(),total_tokens:D().nullish(),prompt_tokens_details:E({cached_tokens:D().nullish()}).nullish(),completion_tokens_details:E({reasoning_tokens:D().nullish(),accepted_prediction_tokens:D().nullish(),rejected_prediction_tokens:D().nullish()}).nullish()}).nullish()}))),ZS=rt(()=>Ie(Ne([E({id:w().nullish(),created:D().nullish(),model:w().nullish(),choices:K(E({delta:E({role:Xe(["assistant"]).nullish(),content:w().nullish(),tool_calls:K(E({index:D(),id:w().nullish(),type:q("function").nullish(),function:E({name:w().nullish(),arguments:w().nullish()})})).nullish(),annotations:K(E({type:q("url_citation"),start_index:D(),end_index:D(),url:w(),title:w()})).nullish()}).nullish(),logprobs:E({content:K(E({token:w(),logprob:D(),top_logprobs:K(E({token:w(),logprob:D()}))})).nullish()}).nullish(),finish_reason:w().nullish(),index:D()})),usage:E({prompt_tokens:D().nullish(),completion_tokens:D().nullish(),total_tokens:D().nullish(),prompt_tokens_details:E({cached_tokens:D().nullish()}).nullish(),completion_tokens_details:E({reasoning_tokens:D().nullish(),accepted_prediction_tokens:D().nullish(),rejected_prediction_tokens:D().nullish()}).nullish()}).nullish()}),Yi]))),VS=rt(()=>Ie(E({logitBias:ot(n0(),D()).optional(),logprobs:Ne([st(),D()]).optional(),parallelToolCalls:st().optional(),user:w().optional(),reasoningEffort:Xe(["minimal","low","medium","high"]).optional(),maxCompletionTokens:D().optional(),store:st().optional(),metadata:ot(w().max(64),w().max(512)).optional(),prediction:ot(w(),Ft()).optional(),structuredOutputs:st().optional(),serviceTier:Xe(["auto","flex","priority","default"]).optional(),strictJsonSchema:st().optional(),textVerbosity:Xe(["low","medium","high"]).optional(),promptCacheKey:w().optional(),safetyIdentifier:w().optional()})));function BS({tools:t,toolChoice:e,structuredOutputs:r,strictJsonSchema:a}){t=t!=null&&t.length?t:void 0;const n=[];if(t==null)return{tools:void 0,toolChoice:void 0,toolWarnings:n};const s=[];for(const i of t)switch(i.type){case"function":s.push({type:"function",function:{name:i.name,description:i.description,parameters:i.inputSchema,strict:r?a:void 0}});break;default:n.push({type:"unsupported-tool",tool:i});break}if(e==null)return{tools:s,toolChoice:void 0,toolWarnings:n};const o=e.type;switch(o){case"auto":case"none":case"required":return{tools:s,toolChoice:o,toolWarnings:n};case"tool":return{tools:s,toolChoice:{type:"function",function:{name:e.toolName}},toolWarnings:n};default:{const i=o;throw new Yt({functionality:`tool choice type: ${i}`})}}}var HS=class{constructor(t,e){this.specificationVersion="v2",this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=t,this.config=e}get provider(){return this.config.provider}async getArgs({prompt:t,maxOutputTokens:e,temperature:r,topP:a,topK:n,frequencyPenalty:s,presencePenalty:o,stopSequences:i,responseFormat:l,seed:u,tools:d,toolChoice:v,providerOptions:m}){var c,h,g,f;const p=[],b=(c=await dr({provider:"openai",providerOptions:m,schema:VS}))!=null?c:{},y=(h=b.structuredOutputs)!=null?h:!0;n!=null&&p.push({type:"unsupported-setting",setting:"topK"}),(l==null?void 0:l.type)==="json"&&l.schema!=null&&!y&&p.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{messages:_,warnings:S}=FS({prompt:t,systemMessageMode:GS(this.modelId)});p.push(...S);const T=(g=b.strictJsonSchema)!=null?g:!1,I={model:this.modelId,logit_bias:b.logitBias,logprobs:b.logprobs===!0||typeof b.logprobs=="number"?!0:void 0,top_logprobs:typeof b.logprobs=="number"?b.logprobs:typeof b.logprobs=="boolean"&&b.logprobs?0:void 0,user:b.user,parallel_tool_calls:b.parallelToolCalls,max_tokens:e,temperature:r,top_p:a,frequency_penalty:s,presence_penalty:o,response_format:(l==null?void 0:l.type)==="json"?y&&l.schema!=null?{type:"json_schema",json_schema:{schema:l.schema,strict:T,name:(f=l.name)!=null?f:"response",description:l.description}}:{type:"json_object"}:void 0,stop:i,seed:u,verbosity:b.textVerbosity,max_completion_tokens:b.maxCompletionTokens,store:b.store,metadata:b.metadata,prediction:b.prediction,reasoning_effort:b.reasoningEffort,service_tier:b.serviceTier,prompt_cache_key:b.promptCacheKey,safety_identifier:b.safetyIdentifier,messages:_};Hh(this.modelId)?(I.temperature!=null&&(I.temperature=void 0,p.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"})),I.top_p!=null&&(I.top_p=void 0,p.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"})),I.frequency_penalty!=null&&(I.frequency_penalty=void 0,p.push({type:"unsupported-setting",setting:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"})),I.presence_penalty!=null&&(I.presence_penalty=void 0,p.push({type:"unsupported-setting",setting:"presencePenalty",details:"presencePenalty is not supported for reasoning models"})),I.logit_bias!=null&&(I.logit_bias=void 0,p.push({type:"other",message:"logitBias is not supported for reasoning models"})),I.logprobs!=null&&(I.logprobs=void 0,p.push({type:"other",message:"logprobs is not supported for reasoning models"})),I.top_logprobs!=null&&(I.top_logprobs=void 0,p.push({type:"other",message:"topLogprobs is not supported for reasoning models"})),I.max_tokens!=null&&(I.max_completion_tokens==null&&(I.max_completion_tokens=I.max_tokens),I.max_tokens=void 0)):(this.modelId.startsWith("gpt-4o-search-preview")||this.modelId.startsWith("gpt-4o-mini-search-preview"))&&I.temperature!=null&&(I.temperature=void 0,p.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for the search preview models and has been removed."})),b.serviceTier==="flex"&&!JS(this.modelId)&&(p.push({type:"unsupported-setting",setting:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),I.service_tier=void 0),b.serviceTier==="priority"&&!WS(this.modelId)&&(p.push({type:"unsupported-setting",setting:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),I.service_tier=void 0);const{tools:O,toolChoice:R,toolWarnings:L}=BS({tools:d,toolChoice:v,structuredOutputs:y,strictJsonSchema:T});return{args:{...I,tools:O,tool_choice:R},warnings:[...p,...L]}}async doGenerate(t){var e,r,a,n,s,o,i,l,u,d,v,m,c,h;const{args:g,warnings:f}=await this.getArgs(t),{responseHeaders:p,value:b,rawValue:y}=await $t({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:It(this.config.headers(),t.headers),body:g,failedResponseHandler:gr,successfulResponseHandler:tr(qS),abortSignal:t.abortSignal,fetch:this.config.fetch}),_=b.choices[0],S=[],T=_.message.content;T!=null&&T.length>0&&S.push({type:"text",text:T});for(const L of(e=_.message.tool_calls)!=null?e:[])S.push({type:"tool-call",toolCallId:(r=L.id)!=null?r:Ot(),toolName:L.function.name,input:L.function.arguments});for(const L of(a=_.message.annotations)!=null?a:[])S.push({type:"source",sourceType:"url",id:Ot(),url:L.url,title:L.title});const I=(n=b.usage)==null?void 0:n.completion_tokens_details,O=(s=b.usage)==null?void 0:s.prompt_tokens_details,R={openai:{}};return(I==null?void 0:I.accepted_prediction_tokens)!=null&&(R.openai.acceptedPredictionTokens=I==null?void 0:I.accepted_prediction_tokens),(I==null?void 0:I.rejected_prediction_tokens)!=null&&(R.openai.rejectedPredictionTokens=I==null?void 0:I.rejected_prediction_tokens),((o=_.logprobs)==null?void 0:o.content)!=null&&(R.openai.logprobs=_.logprobs.content),{content:S,finishReason:Bh(_.finish_reason),usage:{inputTokens:(l=(i=b.usage)==null?void 0:i.prompt_tokens)!=null?l:void 0,outputTokens:(d=(u=b.usage)==null?void 0:u.completion_tokens)!=null?d:void 0,totalTokens:(m=(v=b.usage)==null?void 0:v.total_tokens)!=null?m:void 0,reasoningTokens:(c=I==null?void 0:I.reasoning_tokens)!=null?c:void 0,cachedInputTokens:(h=O==null?void 0:O.cached_tokens)!=null?h:void 0},request:{body:g},response:{...Vh(b),headers:p,body:y},warnings:f,providerMetadata:R}}async doStream(t){const{args:e,warnings:r}=await this.getArgs(t),a={...e,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:n,value:s}=await $t({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:It(this.config.headers(),t.headers),body:a,failedResponseHandler:gr,successfulResponseHandler:ca(ZS),abortSignal:t.abortSignal,fetch:this.config.fetch}),o=[];let i="unknown";const l={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};let u=!0,d=!1;const v={openai:{}};return{stream:s.pipeThrough(new TransformStream({start(m){m.enqueue({type:"stream-start",warnings:r})},transform(m,c){var h,g,f,p,b,y,_,S,T,I,O,R,L,U,Z,M,j,F,X,Y,te,oe,J,pe;if(t.includeRawChunks&&c.enqueue({type:"raw",rawValue:m.rawValue}),!m.success){i="error",c.enqueue({type:"error",error:m.error});return}const ie=m.value;if("error"in ie){i="error",c.enqueue({type:"error",error:ie.error});return}u&&(u=!1,c.enqueue({type:"response-metadata",...Vh(ie)})),ie.usage!=null&&(l.inputTokens=(h=ie.usage.prompt_tokens)!=null?h:void 0,l.outputTokens=(g=ie.usage.completion_tokens)!=null?g:void 0,l.totalTokens=(f=ie.usage.total_tokens)!=null?f:void 0,l.reasoningTokens=(b=(p=ie.usage.completion_tokens_details)==null?void 0:p.reasoning_tokens)!=null?b:void 0,l.cachedInputTokens=(_=(y=ie.usage.prompt_tokens_details)==null?void 0:y.cached_tokens)!=null?_:void 0,((S=ie.usage.completion_tokens_details)==null?void 0:S.accepted_prediction_tokens)!=null&&(v.openai.acceptedPredictionTokens=(T=ie.usage.completion_tokens_details)==null?void 0:T.accepted_prediction_tokens),((I=ie.usage.completion_tokens_details)==null?void 0:I.rejected_prediction_tokens)!=null&&(v.openai.rejectedPredictionTokens=(O=ie.usage.completion_tokens_details)==null?void 0:O.rejected_prediction_tokens));const xe=ie.choices[0];if((xe==null?void 0:xe.finish_reason)!=null&&(i=Bh(xe.finish_reason)),((R=xe==null?void 0:xe.logprobs)==null?void 0:R.content)!=null&&(v.openai.logprobs=xe.logprobs.content),(xe==null?void 0:xe.delta)==null)return;const C=xe.delta;if(C.content!=null&&(d||(c.enqueue({type:"text-start",id:"0"}),d=!0),c.enqueue({type:"text-delta",id:"0",delta:C.content})),C.tool_calls!=null)for(const ae of C.tool_calls){const ge=ae.index;if(o[ge]==null){if(ae.type!=="function")throw new Wn({data:ae,message:"Expected 'function' type."});if(ae.id==null)throw new Wn({data:ae,message:"Expected 'id' to be a string."});if(((L=ae.function)==null?void 0:L.name)==null)throw new Wn({data:ae,message:"Expected 'function.name' to be a string."});c.enqueue({type:"tool-input-start",id:ae.id,toolName:ae.function.name}),o[ge]={id:ae.id,type:"function",function:{name:ae.function.name,arguments:(U=ae.function.arguments)!=null?U:""},hasFinished:!1};const ke=o[ge];((Z=ke.function)==null?void 0:Z.name)!=null&&((M=ke.function)==null?void 0:M.arguments)!=null&&(ke.function.arguments.length>0&&c.enqueue({type:"tool-input-delta",id:ke.id,delta:ke.function.arguments}),ds(ke.function.arguments)&&(c.enqueue({type:"tool-input-end",id:ke.id}),c.enqueue({type:"tool-call",toolCallId:(j=ke.id)!=null?j:Ot(),toolName:ke.function.name,input:ke.function.arguments}),ke.hasFinished=!0));continue}const fe=o[ge];fe.hasFinished||(((F=ae.function)==null?void 0:F.arguments)!=null&&(fe.function.arguments+=(Y=(X=ae.function)==null?void 0:X.arguments)!=null?Y:""),c.enqueue({type:"tool-input-delta",id:fe.id,delta:(te=ae.function.arguments)!=null?te:""}),((oe=fe.function)==null?void 0:oe.name)!=null&&((J=fe.function)==null?void 0:J.arguments)!=null&&ds(fe.function.arguments)&&(c.enqueue({type:"tool-input-end",id:fe.id}),c.enqueue({type:"tool-call",toolCallId:(pe=fe.id)!=null?pe:Ot(),toolName:fe.function.name,input:fe.function.arguments}),fe.hasFinished=!0))}if(C.annotations!=null)for(const ae of C.annotations)c.enqueue({type:"source",sourceType:"url",id:Ot(),url:ae.url,title:ae.title})},flush(m){d&&m.enqueue({type:"text-end",id:"0"}),m.enqueue({type:"finish",finishReason:i,usage:l,...v!=null?{providerMetadata:v}:{}})}})),request:{body:a},response:{headers:n}}}};function Hh(t){return(t.startsWith("o")||t.startsWith("gpt-5"))&&!t.startsWith("gpt-5-chat")}function JS(t){return t.startsWith("o3")||t.startsWith("o4-mini")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-chat")}function WS(t){return t.startsWith("gpt-4")||t.startsWith("gpt-5-mini")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-nano")&&!t.startsWith("gpt-5-chat")||t.startsWith("o3")||t.startsWith("o4-mini")}function GS(t){var e,r;return Hh(t)?(r=(e=KS[t])==null?void 0:e.systemMessageMode)!=null?r:"developer":"system"}var KS={"o1-mini":{systemMessageMode:"remove"},"o1-mini-2024-09-12":{systemMessageMode:"remove"},"o1-preview":{systemMessageMode:"remove"},"o1-preview-2024-09-12":{systemMessageMode:"remove"},o3:{systemMessageMode:"developer"},"o3-2025-04-16":{systemMessageMode:"developer"},"o3-mini":{systemMessageMode:"developer"},"o3-mini-2025-01-31":{systemMessageMode:"developer"},"o4-mini":{systemMessageMode:"developer"},"o4-mini-2025-04-16":{systemMessageMode:"developer"}};function QS({prompt:t,user:e="user",assistant:r="assistant"}){let a="";t[0].role==="system"&&(a+=`${t[0].content}
58
-
59
- `,t=t.slice(1));for(const{role:n,content:s}of t)switch(n){case"system":throw new Kr({message:"Unexpected system message in prompt: ${content}",prompt:t});case"user":{const o=s.map(i=>{switch(i.type){case"text":return i.text}}).filter(Boolean).join("");a+=`${e}:
60
- ${o}
61
-
62
- `;break}case"assistant":{const o=s.map(i=>{switch(i.type){case"text":return i.text;case"tool-call":throw new Yt({functionality:"tool-call messages"})}}).join("");a+=`${r}:
63
- ${o}
64
-
65
- `;break}case"tool":throw new Yt({functionality:"tool messages"});default:{const o=n;throw new Error(`Unsupported role: ${o}`)}}return a+=`${r}:
66
- `,{prompt:a,stopSequences:[`
67
- ${e}:`]}}function Jh({id:t,model:e,created:r}){return{id:t??void 0,modelId:e??void 0,timestamp:r!=null?new Date(r*1e3):void 0}}function Wh(t){switch(t){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"unknown"}}var YS=rt(()=>Ie(E({id:w().nullish(),created:D().nullish(),model:w().nullish(),choices:K(E({text:w(),finish_reason:w(),logprobs:E({tokens:K(w()),token_logprobs:K(D()),top_logprobs:K(ot(w(),D())).nullish()}).nullish()})),usage:E({prompt_tokens:D(),completion_tokens:D(),total_tokens:D()}).nullish()}))),XS=rt(()=>Ie(Ne([E({id:w().nullish(),created:D().nullish(),model:w().nullish(),choices:K(E({text:w(),finish_reason:w().nullish(),index:D(),logprobs:E({tokens:K(w()),token_logprobs:K(D()),top_logprobs:K(ot(w(),D())).nullish()}).nullish()})),usage:E({prompt_tokens:D(),completion_tokens:D(),total_tokens:D()}).nullish()}),Yi]))),Gh=rt(()=>Ie(E({echo:st().optional(),logitBias:ot(w(),D()).optional(),suffix:w().optional(),user:w().optional(),logprobs:Ne([st(),D()]).optional()}))),eI=class{constructor(t,e){this.specificationVersion="v2",this.supportedUrls={},this.modelId=t,this.config=e}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get provider(){return this.config.provider}async getArgs({prompt:t,maxOutputTokens:e,temperature:r,topP:a,topK:n,frequencyPenalty:s,presencePenalty:o,stopSequences:i,responseFormat:l,tools:u,toolChoice:d,seed:v,providerOptions:m}){const c=[],h={...await dr({provider:"openai",providerOptions:m,schema:Gh}),...await dr({provider:this.providerOptionsName,providerOptions:m,schema:Gh})};n!=null&&c.push({type:"unsupported-setting",setting:"topK"}),u!=null&&u.length&&c.push({type:"unsupported-setting",setting:"tools"}),d!=null&&c.push({type:"unsupported-setting",setting:"toolChoice"}),l!=null&&l.type!=="text"&&c.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format is not supported."});const{prompt:g,stopSequences:f}=QS({prompt:t}),p=[...f??[],...i??[]];return{args:{model:this.modelId,echo:h.echo,logit_bias:h.logitBias,logprobs:(h==null?void 0:h.logprobs)===!0?0:(h==null?void 0:h.logprobs)===!1||h==null?void 0:h.logprobs,suffix:h.suffix,user:h.user,max_tokens:e,temperature:r,top_p:a,frequency_penalty:s,presence_penalty:o,seed:v,prompt:g,stop:p.length>0?p:void 0},warnings:c}}async doGenerate(t){var e,r,a;const{args:n,warnings:s}=await this.getArgs(t),{responseHeaders:o,value:i,rawValue:l}=await $t({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:It(this.config.headers(),t.headers),body:n,failedResponseHandler:gr,successfulResponseHandler:tr(YS),abortSignal:t.abortSignal,fetch:this.config.fetch}),u=i.choices[0],d={openai:{}};return u.logprobs!=null&&(d.openai.logprobs=u.logprobs),{content:[{type:"text",text:u.text}],usage:{inputTokens:(e=i.usage)==null?void 0:e.prompt_tokens,outputTokens:(r=i.usage)==null?void 0:r.completion_tokens,totalTokens:(a=i.usage)==null?void 0:a.total_tokens},finishReason:Wh(u.finish_reason),request:{body:n},response:{...Jh(i),headers:o,body:l},providerMetadata:d,warnings:s}}async doStream(t){const{args:e,warnings:r}=await this.getArgs(t),a={...e,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:n,value:s}=await $t({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:It(this.config.headers(),t.headers),body:a,failedResponseHandler:gr,successfulResponseHandler:ca(XS),abortSignal:t.abortSignal,fetch:this.config.fetch});let o="unknown";const i={openai:{}},l={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};let u=!0;return{stream:s.pipeThrough(new TransformStream({start(d){d.enqueue({type:"stream-start",warnings:r})},transform(d,v){if(t.includeRawChunks&&v.enqueue({type:"raw",rawValue:d.rawValue}),!d.success){o="error",v.enqueue({type:"error",error:d.error});return}const m=d.value;if("error"in m){o="error",v.enqueue({type:"error",error:m.error});return}u&&(u=!1,v.enqueue({type:"response-metadata",...Jh(m)}),v.enqueue({type:"text-start",id:"0"})),m.usage!=null&&(l.inputTokens=m.usage.prompt_tokens,l.outputTokens=m.usage.completion_tokens,l.totalTokens=m.usage.total_tokens);const c=m.choices[0];(c==null?void 0:c.finish_reason)!=null&&(o=Wh(c.finish_reason)),(c==null?void 0:c.logprobs)!=null&&(i.openai.logprobs=c.logprobs),(c==null?void 0:c.text)!=null&&c.text.length>0&&v.enqueue({type:"text-delta",id:"0",delta:c.text})},flush(d){u||d.enqueue({type:"text-end",id:"0"}),d.enqueue({type:"finish",finishReason:o,providerMetadata:i,usage:l})}})),request:{body:a},response:{headers:n}}}},tI=rt(()=>Ie(E({dimensions:D().optional(),user:w().optional()}))),rI=rt(()=>Ie(E({data:K(E({embedding:K(D())})),usage:E({prompt_tokens:D()}).nullish()}))),nI=class{constructor(t,e){this.specificationVersion="v2",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=t,this.config=e}get provider(){return this.config.provider}async doEmbed({values:t,headers:e,abortSignal:r,providerOptions:a}){var n;if(t.length>this.maxEmbeddingsPerCall)throw new Qm({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:t});const s=(n=await dr({provider:"openai",providerOptions:a,schema:tI}))!=null?n:{},{responseHeaders:o,value:i,rawValue:l}=await $t({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:It(this.config.headers(),e),body:{model:this.modelId,input:t,encoding_format:"float",dimensions:s.dimensions,user:s.user},failedResponseHandler:gr,successfulResponseHandler:tr(rI),abortSignal:r,fetch:this.config.fetch});return{embeddings:i.data.map(u=>u.embedding),usage:i.usage?{tokens:i.usage.prompt_tokens}:void 0,response:{headers:o,body:l}}}},aI=rt(()=>Ie(E({data:K(E({b64_json:w(),revised_prompt:w().optional()}))}))),sI={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10,"gpt-image-1-mini":10},oI=new Set(["gpt-image-1","gpt-image-1-mini"]),iI=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v2"}get maxImagesPerCall(){var t;return(t=sI[this.modelId])!=null?t:1}get provider(){return this.config.provider}async doGenerate({prompt:t,n:e,size:r,aspectRatio:a,seed:n,providerOptions:s,headers:o,abortSignal:i}){var l,u,d,v;const m=[];a!=null&&m.push({type:"unsupported-setting",setting:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),n!=null&&m.push({type:"unsupported-setting",setting:"seed"});const c=(d=(u=(l=this.config._internal)==null?void 0:l.currentDate)==null?void 0:u.call(l))!=null?d:new Date,{value:h,responseHeaders:g}=await $t({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:It(this.config.headers(),o),body:{model:this.modelId,prompt:t,n:e,size:r,...(v=s.openai)!=null?v:{},...oI.has(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:gr,successfulResponseHandler:tr(aI),abortSignal:i,fetch:this.config.fetch});return{images:h.data.map(f=>f.b64_json),warnings:m,response:{timestamp:c,modelId:this.modelId,headers:g},providerMetadata:{openai:{images:h.data.map(f=>f.revised_prompt?{revisedPrompt:f.revised_prompt}:null)}}}}},lI=bt(()=>Ie(E({code:w().nullish(),containerId:w()}))),uI=bt(()=>Ie(E({outputs:K(Rt("type",[E({type:q("logs"),logs:w()}),E({type:q("image"),url:w()})])).nullish()}))),cI=bt(()=>Ie(E({container:Ne([w(),E({fileIds:K(w()).optional()})]).optional()}))),dI=Cn({id:"openai.code_interpreter",name:"code_interpreter",inputSchema:lI,outputSchema:uI}),pI=(t={})=>dI(t),Kh=E({key:w(),type:Xe(["eq","ne","gt","gte","lt","lte"]),value:Ne([w(),D(),st()])}),Qh=E({type:Xe(["and","or"]),filters:K(Ne([Kh,Pc(()=>Qh)]))}),hI=bt(()=>Ie(E({vectorStoreIds:K(w()),maxNumResults:D().optional(),ranking:E({ranker:w().optional(),scoreThreshold:D().optional()}).optional(),filters:Ne([Kh,Qh]).optional()}))),fI=bt(()=>Ie(E({queries:K(w()),results:K(E({attributes:ot(w(),Xt()),fileId:w(),filename:w(),score:D(),text:w()})).nullable()}))),mI=Cn({id:"openai.file_search",name:"file_search",inputSchema:E({}),outputSchema:fI}),vI=bt(()=>Ie(E({background:Xe(["auto","opaque","transparent"]).optional(),inputFidelity:Xe(["low","high"]).optional(),inputImageMask:E({fileId:w().optional(),imageUrl:w().optional()}).optional(),model:w().optional(),moderation:Xe(["auto"]).optional(),outputCompression:D().int().min(0).max(100).optional(),outputFormat:Xe(["png","jpeg","webp"]).optional(),partialImages:D().int().min(0).max(3).optional(),quality:Xe(["auto","low","medium","high"]).optional(),size:Xe(["1024x1024","1024x1536","1536x1024","auto"]).optional()}).strict())),gI=bt(()=>Ie(E({}))),yI=bt(()=>Ie(E({result:w()}))),_I=Cn({id:"openai.image_generation",name:"image_generation",inputSchema:gI,outputSchema:yI}),wI=(t={})=>_I(t),Yh=bt(()=>Ie(E({action:E({type:q("exec"),command:K(w()),timeoutMs:D().optional(),user:w().optional(),workingDirectory:w().optional(),env:ot(w(),w()).optional()})}))),Xh=bt(()=>Ie(E({output:w()}))),bI=Cn({id:"openai.local_shell",name:"local_shell",inputSchema:Yh,outputSchema:Xh}),xI=bt(()=>Ie(E({filters:E({allowedDomains:K(w()).optional()}).optional(),searchContextSize:Xe(["low","medium","high"]).optional(),userLocation:E({type:q("approximate"),country:w().optional(),city:w().optional(),region:w().optional(),timezone:w().optional()}).optional()}))),EI=bt(()=>Ie(E({}))),SI=bt(()=>Ie(E({action:Rt("type",[E({type:q("search"),query:w().optional()}),E({type:q("openPage"),url:w()}),E({type:q("find"),url:w(),pattern:w()})])}))),II=Cn({id:"openai.web_search",name:"web_search",inputSchema:EI,outputSchema:SI}),kI=(t={})=>II(t),TI=bt(()=>Ie(E({searchContextSize:Xe(["low","medium","high"]).optional(),userLocation:E({type:q("approximate"),country:w().optional(),city:w().optional(),region:w().optional(),timezone:w().optional()}).optional()}))),PI=bt(()=>Ie(E({}))),CI=bt(()=>Ie(E({action:Rt("type",[E({type:q("search"),query:w().optional()}),E({type:q("openPage"),url:w()}),E({type:q("find"),url:w(),pattern:w()})])}))),RI=Cn({id:"openai.web_search_preview",name:"web_search_preview",inputSchema:PI,outputSchema:CI}),OI={codeInterpreter:pI,fileSearch:mI,imageGeneration:wI,localShell:bI,webSearchPreview:RI,webSearch:kI};function ef(t,e){return e?e.some(r=>t.startsWith(r)):!1}async function $I({prompt:t,systemMessageMode:e,fileIdPrefixes:r,store:a,hasLocalShellTool:n=!1}){var s,o,i,l;const u=[],d=[];for(const{role:v,content:m}of t)switch(v){case"system":{switch(e){case"system":{u.push({role:"system",content:m});break}case"developer":{u.push({role:"developer",content:m});break}case"remove":{d.push({type:"other",message:"system messages are removed for this model"});break}default:{const c=e;throw new Error(`Unsupported system message mode: ${c}`)}}break}case"user":{u.push({role:"user",content:m.map((c,h)=>{var g,f,p;switch(c.type){case"text":return{type:"input_text",text:c.text};case"file":if(c.mediaType.startsWith("image/")){const b=c.mediaType==="image/*"?"image/jpeg":c.mediaType;return{type:"input_image",...c.data instanceof URL?{image_url:c.data.toString()}:typeof c.data=="string"&&ef(c.data,r)?{file_id:c.data}:{image_url:`data:${b};base64,${ln(c.data)}`},detail:(f=(g=c.providerOptions)==null?void 0:g.openai)==null?void 0:f.imageDetail}}else{if(c.mediaType==="application/pdf")return c.data instanceof URL?{type:"input_file",file_url:c.data.toString()}:{type:"input_file",...typeof c.data=="string"&&ef(c.data,r)?{file_id:c.data}:{filename:(p=c.filename)!=null?p:`part-${h}.pdf`,file_data:`data:application/pdf;base64,${ln(c.data)}`}};throw new Yt({functionality:`file part media type ${c.mediaType}`})}}})});break}case"assistant":{const c={},h={};for(const g of m)switch(g.type){case"text":{const f=(o=(s=g.providerOptions)==null?void 0:s.openai)==null?void 0:o.itemId;if(a&&f!=null){u.push({type:"item_reference",id:f});break}u.push({role:"assistant",content:[{type:"output_text",text:g.text}],id:f});break}case"tool-call":{if(h[g.toolCallId]=g,g.providerExecuted)break;const f=(l=(i=g.providerOptions)==null?void 0:i.openai)==null?void 0:l.itemId;if(a&&f!=null){u.push({type:"item_reference",id:f});break}if(n&&g.toolName==="local_shell"){const p=await cr({value:g.input,schema:Yh});u.push({type:"local_shell_call",call_id:g.toolCallId,id:f,action:{type:"exec",command:p.action.command,timeout_ms:p.action.timeoutMs,user:p.action.user,working_directory:p.action.workingDirectory,env:p.action.env}});break}u.push({type:"function_call",call_id:g.toolCallId,name:g.toolName,arguments:JSON.stringify(g.input),id:f});break}case"tool-result":{a?u.push({type:"item_reference",id:g.toolCallId}):d.push({type:"other",message:`Results for OpenAI tool ${g.toolName} are not sent to the API when store is false`});break}case"reasoning":{const f=await dr({provider:"openai",providerOptions:g.providerOptions,schema:AI}),p=f==null?void 0:f.itemId;if(p!=null){const b=c[p];if(a)b===void 0&&(u.push({type:"item_reference",id:p}),c[p]={type:"reasoning",id:p,summary:[]});else{const y=[];g.text.length>0?y.push({type:"summary_text",text:g.text}):b!==void 0&&d.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(g)}.`}),b===void 0?(c[p]={type:"reasoning",id:p,encrypted_content:f==null?void 0:f.reasoningEncryptedContent,summary:y},u.push(c[p])):(b.summary.push(...y),(f==null?void 0:f.reasoningEncryptedContent)!=null&&(b.encrypted_content=f.reasoningEncryptedContent))}}else d.push({type:"other",message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(g)}.`});break}}break}case"tool":{for(const c of m){const h=c.output;if(n&&c.toolName==="local_shell"&&h.type==="json"){const f=await cr({value:h.value,schema:Xh});u.push({type:"local_shell_call_output",call_id:c.toolCallId,output:f.output});break}let g;switch(h.type){case"text":case"error-text":g=h.value;break;case"json":case"error-json":g=JSON.stringify(h.value);break;case"content":g=h.value.map(f=>{switch(f.type){case"text":return{type:"input_text",text:f.text};case"media":return f.mediaType.startsWith("image/")?{type:"input_image",image_url:`data:${f.mediaType};base64,${f.data}`}:{type:"input_file",filename:"data",file_data:`data:${f.mediaType};base64,${f.data}`}}});break}u.push({type:"function_call_output",call_id:c.toolCallId,output:g})}break}default:{const c=v;throw new Error(`Unsupported role: ${c}`)}}return{input:u,warnings:d}}var AI=E({itemId:w().nullish(),reasoningEncryptedContent:w().nullish()});function tf({finishReason:t,hasFunctionCall:e}){switch(t){case void 0:case null:return e?"tool-calls":"stop";case"max_output_tokens":return"length";case"content_filter":return"content-filter";default:return e?"tool-calls":"unknown"}}var NI=rt(()=>Ie(Ne([E({type:q("response.output_text.delta"),item_id:w(),delta:w(),logprobs:K(E({token:w(),logprob:D(),top_logprobs:K(E({token:w(),logprob:D()}))})).nullish()}),E({type:Xe(["response.completed","response.incomplete"]),response:E({incomplete_details:E({reason:w()}).nullish(),usage:E({input_tokens:D(),input_tokens_details:E({cached_tokens:D().nullish()}).nullish(),output_tokens:D(),output_tokens_details:E({reasoning_tokens:D().nullish()}).nullish()}),service_tier:w().nullish()})}),E({type:q("response.created"),response:E({id:w(),created_at:D(),model:w(),service_tier:w().nullish()})}),E({type:q("response.output_item.added"),output_index:D(),item:Rt("type",[E({type:q("message"),id:w()}),E({type:q("reasoning"),id:w(),encrypted_content:w().nullish()}),E({type:q("function_call"),id:w(),call_id:w(),name:w(),arguments:w()}),E({type:q("web_search_call"),id:w(),status:w()}),E({type:q("computer_call"),id:w(),status:w()}),E({type:q("file_search_call"),id:w()}),E({type:q("image_generation_call"),id:w()}),E({type:q("code_interpreter_call"),id:w(),container_id:w(),code:w().nullable(),outputs:K(Rt("type",[E({type:q("logs"),logs:w()}),E({type:q("image"),url:w()})])).nullable(),status:w()})])}),E({type:q("response.output_item.done"),output_index:D(),item:Rt("type",[E({type:q("message"),id:w()}),E({type:q("reasoning"),id:w(),encrypted_content:w().nullish()}),E({type:q("function_call"),id:w(),call_id:w(),name:w(),arguments:w(),status:q("completed")}),E({type:q("code_interpreter_call"),id:w(),code:w().nullable(),container_id:w(),outputs:K(Rt("type",[E({type:q("logs"),logs:w()}),E({type:q("image"),url:w()})])).nullable()}),E({type:q("image_generation_call"),id:w(),result:w()}),E({type:q("web_search_call"),id:w(),status:w(),action:Rt("type",[E({type:q("search"),query:w().nullish()}),E({type:q("open_page"),url:w()}),E({type:q("find"),url:w(),pattern:w()})])}),E({type:q("file_search_call"),id:w(),queries:K(w()),results:K(E({attributes:ot(w(),Xt()),file_id:w(),filename:w(),score:D(),text:w()})).nullish()}),E({type:q("local_shell_call"),id:w(),call_id:w(),action:E({type:q("exec"),command:K(w()),timeout_ms:D().optional(),user:w().optional(),working_directory:w().optional(),env:ot(w(),w()).optional()})}),E({type:q("computer_call"),id:w(),status:q("completed")})])}),E({type:q("response.function_call_arguments.delta"),item_id:w(),output_index:D(),delta:w()}),E({type:q("response.image_generation_call.partial_image"),item_id:w(),output_index:D(),partial_image_b64:w()}),E({type:q("response.code_interpreter_call_code.delta"),item_id:w(),output_index:D(),delta:w()}),E({type:q("response.code_interpreter_call_code.done"),item_id:w(),output_index:D(),code:w()}),E({type:q("response.output_text.annotation.added"),annotation:Rt("type",[E({type:q("url_citation"),url:w(),title:w()}),E({type:q("file_citation"),file_id:w(),filename:w().nullish(),index:D().nullish(),start_index:D().nullish(),end_index:D().nullish(),quote:w().nullish()})])}),E({type:q("response.reasoning_summary_part.added"),item_id:w(),summary_index:D()}),E({type:q("response.reasoning_summary_text.delta"),item_id:w(),summary_index:D(),delta:w()}),E({type:q("response.reasoning_summary_part.done"),item_id:w(),summary_index:D()}),E({type:q("error"),code:w(),message:w(),param:w().nullish(),sequence_number:D()}),E({type:w()}).loose().transform(t=>({type:"unknown_chunk",message:t.type}))]))),MI=rt(()=>Ie(E({id:w(),created_at:D(),error:E({code:w(),message:w()}).nullish(),model:w(),output:K(Rt("type",[E({type:q("message"),role:q("assistant"),id:w(),content:K(E({type:q("output_text"),text:w(),logprobs:K(E({token:w(),logprob:D(),top_logprobs:K(E({token:w(),logprob:D()}))})).nullish(),annotations:K(Rt("type",[E({type:q("url_citation"),start_index:D(),end_index:D(),url:w(),title:w()}),E({type:q("file_citation"),file_id:w(),filename:w().nullish(),index:D().nullish(),start_index:D().nullish(),end_index:D().nullish(),quote:w().nullish()}),E({type:q("container_file_citation")})]))}))}),E({type:q("web_search_call"),id:w(),status:w(),action:Rt("type",[E({type:q("search"),query:w().nullish()}),E({type:q("open_page"),url:w()}),E({type:q("find"),url:w(),pattern:w()})])}),E({type:q("file_search_call"),id:w(),queries:K(w()),results:K(E({attributes:ot(w(),Xt()),file_id:w(),filename:w(),score:D(),text:w()})).nullish()}),E({type:q("code_interpreter_call"),id:w(),code:w().nullable(),container_id:w(),outputs:K(Rt("type",[E({type:q("logs"),logs:w()}),E({type:q("image"),url:w()})])).nullable()}),E({type:q("image_generation_call"),id:w(),result:w()}),E({type:q("local_shell_call"),id:w(),call_id:w(),action:E({type:q("exec"),command:K(w()),timeout_ms:D().optional(),user:w().optional(),working_directory:w().optional(),env:ot(w(),w()).optional()})}),E({type:q("function_call"),call_id:w(),name:w(),arguments:w(),id:w()}),E({type:q("computer_call"),id:w(),status:w().optional()}),E({type:q("reasoning"),id:w(),encrypted_content:w().nullish(),summary:K(E({type:q("summary_text"),text:w()}))})])),service_tier:w().nullish(),incomplete_details:E({reason:w()}).nullish(),usage:E({input_tokens:D(),input_tokens_details:E({cached_tokens:D().nullish()}).nullish(),output_tokens:D(),output_tokens_details:E({reasoning_tokens:D().nullish()}).nullish()})}))),rf=20,DI=rt(()=>Ie(E({include:K(Xe(["reasoning.encrypted_content","file_search_call.results","message.output_text.logprobs"])).nullish(),instructions:w().nullish(),logprobs:Ne([st(),D().min(1).max(rf)]).optional(),maxToolCalls:D().nullish(),metadata:Ft().nullish(),parallelToolCalls:st().nullish(),previousResponseId:w().nullish(),promptCacheKey:w().nullish(),reasoningEffort:w().nullish(),reasoningSummary:w().nullish(),safetyIdentifier:w().nullish(),serviceTier:Xe(["auto","flex","priority","default"]).nullish(),store:st().nullish(),strictJsonSchema:st().nullish(),textVerbosity:Xe(["low","medium","high"]).nullish(),truncation:Xe(["auto","disabled"]).nullish(),user:w().nullish()})));async function jI({tools:t,toolChoice:e,strictJsonSchema:r}){t=t!=null&&t.length?t:void 0;const a=[];if(t==null)return{tools:void 0,toolChoice:void 0,toolWarnings:a};const n=[];for(const o of t)switch(o.type){case"function":n.push({type:"function",name:o.name,description:o.description,parameters:o.inputSchema,strict:r});break;case"provider-defined":{switch(o.id){case"openai.file_search":{const i=await cr({value:o.args,schema:hI});n.push({type:"file_search",vector_store_ids:i.vectorStoreIds,max_num_results:i.maxNumResults,ranking_options:i.ranking?{ranker:i.ranking.ranker,score_threshold:i.ranking.scoreThreshold}:void 0,filters:i.filters});break}case"openai.local_shell":{n.push({type:"local_shell"});break}case"openai.web_search_preview":{const i=await cr({value:o.args,schema:TI});n.push({type:"web_search_preview",search_context_size:i.searchContextSize,user_location:i.userLocation});break}case"openai.web_search":{const i=await cr({value:o.args,schema:xI});n.push({type:"web_search",filters:i.filters!=null?{allowed_domains:i.filters.allowedDomains}:void 0,search_context_size:i.searchContextSize,user_location:i.userLocation});break}case"openai.code_interpreter":{const i=await cr({value:o.args,schema:cI});n.push({type:"code_interpreter",container:i.container==null?{type:"auto",file_ids:void 0}:typeof i.container=="string"?i.container:{type:"auto",file_ids:i.container.fileIds}});break}case"openai.image_generation":{const i=await cr({value:o.args,schema:vI});n.push({type:"image_generation",background:i.background,input_fidelity:i.inputFidelity,input_image_mask:i.inputImageMask?{file_id:i.inputImageMask.fileId,image_url:i.inputImageMask.imageUrl}:void 0,model:i.model,size:i.size,quality:i.quality,moderation:i.moderation,output_format:i.outputFormat,output_compression:i.outputCompression});break}}break}default:a.push({type:"unsupported-tool",tool:o});break}if(e==null)return{tools:n,toolChoice:void 0,toolWarnings:a};const s=e.type;switch(s){case"auto":case"none":case"required":return{tools:n,toolChoice:s,toolWarnings:a};case"tool":return{tools:n,toolChoice:e.toolName==="code_interpreter"||e.toolName==="file_search"||e.toolName==="image_generation"||e.toolName==="web_search_preview"||e.toolName==="web_search"?{type:e.toolName}:{type:"function",name:e.toolName},toolWarnings:a};default:{const o=s;throw new Yt({functionality:`tool choice type: ${o}`})}}}var zI=class{constructor(t,e){this.specificationVersion="v2",this.supportedUrls={"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]},this.modelId=t,this.config=e}get provider(){return this.config.provider}async getArgs({maxOutputTokens:t,temperature:e,stopSequences:r,topP:a,topK:n,presencePenalty:s,frequencyPenalty:o,seed:i,prompt:l,providerOptions:u,tools:d,toolChoice:v,responseFormat:m}){var c,h,g,f;const p=[],b=WI(this.modelId);n!=null&&p.push({type:"unsupported-setting",setting:"topK"}),i!=null&&p.push({type:"unsupported-setting",setting:"seed"}),s!=null&&p.push({type:"unsupported-setting",setting:"presencePenalty"}),o!=null&&p.push({type:"unsupported-setting",setting:"frequencyPenalty"}),r!=null&&p.push({type:"unsupported-setting",setting:"stopSequences"});const y=await dr({provider:"openai",providerOptions:u,schema:DI}),{input:_,warnings:S}=await $I({prompt:l,systemMessageMode:b.systemMessageMode,fileIdPrefixes:this.config.fileIdPrefixes,store:(c=y==null?void 0:y.store)!=null?c:!0,hasLocalShellTool:R("openai.local_shell")});p.push(...S);const T=(h=y==null?void 0:y.strictJsonSchema)!=null?h:!1;let I=y==null?void 0:y.include;function O(Y){I==null?I=[Y]:I.includes(Y)||(I=[...I,Y])}function R(Y){return(d==null?void 0:d.find(te=>te.type==="provider-defined"&&te.id===Y))!=null}const L=typeof(y==null?void 0:y.logprobs)=="number"?y==null?void 0:y.logprobs:(y==null?void 0:y.logprobs)===!0?rf:void 0;L&&O("message.output_text.logprobs");const U=(g=d==null?void 0:d.find(Y=>Y.type==="provider-defined"&&(Y.id==="openai.web_search"||Y.id==="openai.web_search_preview")))==null?void 0:g.name;U&&O("web_search_call.action.sources"),R("openai.code_interpreter")&&O("code_interpreter_call.outputs");const Z=y==null?void 0:y.store;Z===!1&&b.isReasoningModel&&O("reasoning.encrypted_content");const M={model:this.modelId,input:_,temperature:e,top_p:a,max_output_tokens:t,...((m==null?void 0:m.type)==="json"||(y==null?void 0:y.textVerbosity))&&{text:{...(m==null?void 0:m.type)==="json"&&{format:m.schema!=null?{type:"json_schema",strict:T,name:(f=m.name)!=null?f:"response",description:m.description,schema:m.schema}:{type:"json_object"}},...(y==null?void 0:y.textVerbosity)&&{verbosity:y.textVerbosity}}},max_tool_calls:y==null?void 0:y.maxToolCalls,metadata:y==null?void 0:y.metadata,parallel_tool_calls:y==null?void 0:y.parallelToolCalls,previous_response_id:y==null?void 0:y.previousResponseId,store:Z,user:y==null?void 0:y.user,instructions:y==null?void 0:y.instructions,service_tier:y==null?void 0:y.serviceTier,include:I,prompt_cache_key:y==null?void 0:y.promptCacheKey,safety_identifier:y==null?void 0:y.safetyIdentifier,top_logprobs:L,truncation:y==null?void 0:y.truncation,...b.isReasoningModel&&((y==null?void 0:y.reasoningEffort)!=null||(y==null?void 0:y.reasoningSummary)!=null)&&{reasoning:{...(y==null?void 0:y.reasoningEffort)!=null&&{effort:y.reasoningEffort},...(y==null?void 0:y.reasoningSummary)!=null&&{summary:y.reasoningSummary}}}};b.isReasoningModel?(M.temperature!=null&&(M.temperature=void 0,p.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"})),M.top_p!=null&&(M.top_p=void 0,p.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"}))):((y==null?void 0:y.reasoningEffort)!=null&&p.push({type:"unsupported-setting",setting:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"}),(y==null?void 0:y.reasoningSummary)!=null&&p.push({type:"unsupported-setting",setting:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"})),(y==null?void 0:y.serviceTier)==="flex"&&!b.supportsFlexProcessing&&(p.push({type:"unsupported-setting",setting:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete M.service_tier),(y==null?void 0:y.serviceTier)==="priority"&&!b.supportsPriorityProcessing&&(p.push({type:"unsupported-setting",setting:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),delete M.service_tier);const{tools:j,toolChoice:F,toolWarnings:X}=await jI({tools:d,toolChoice:v,strictJsonSchema:T});return{webSearchToolName:U,args:{...M,tools:j,tool_choice:F},warnings:[...p,...X],store:Z}}async doGenerate(t){var e,r,a,n,s,o,i,l,u,d,v,m,c,h,g,f,p,b,y;const{args:_,warnings:S,webSearchToolName:T}=await this.getArgs(t),I=this.config.url({path:"/responses",modelId:this.modelId}),{responseHeaders:O,value:R,rawValue:L}=await $t({url:I,headers:It(this.config.headers(),t.headers),body:_,failedResponseHandler:gr,successfulResponseHandler:tr(MI),abortSignal:t.abortSignal,fetch:this.config.fetch});if(R.error)throw new ft({message:R.error.message,url:I,requestBodyValues:_,statusCode:400,responseHeaders:O,responseBody:L,isRetryable:!1});const U=[],Z=[];let M=!1;for(const F of R.output)switch(F.type){case"reasoning":{F.summary.length===0&&F.summary.push({type:"summary_text",text:""});for(const X of F.summary)U.push({type:"reasoning",text:X.text,providerMetadata:{openai:{itemId:F.id,reasoningEncryptedContent:(e=F.encrypted_content)!=null?e:null}}});break}case"image_generation_call":{U.push({type:"tool-call",toolCallId:F.id,toolName:"image_generation",input:"{}",providerExecuted:!0}),U.push({type:"tool-result",toolCallId:F.id,toolName:"image_generation",result:{result:F.result},providerExecuted:!0});break}case"local_shell_call":{U.push({type:"tool-call",toolCallId:F.call_id,toolName:"local_shell",input:JSON.stringify({action:F.action}),providerMetadata:{openai:{itemId:F.id}}});break}case"message":{for(const X of F.content){(a=(r=t.providerOptions)==null?void 0:r.openai)!=null&&a.logprobs&&X.logprobs&&Z.push(X.logprobs),U.push({type:"text",text:X.text,providerMetadata:{openai:{itemId:F.id}}});for(const Y of X.annotations)Y.type==="url_citation"?U.push({type:"source",sourceType:"url",id:(o=(s=(n=this.config).generateId)==null?void 0:s.call(n))!=null?o:Ot(),url:Y.url,title:Y.title}):Y.type==="file_citation"&&U.push({type:"source",sourceType:"document",id:(u=(l=(i=this.config).generateId)==null?void 0:l.call(i))!=null?u:Ot(),mediaType:"text/plain",title:(v=(d=Y.quote)!=null?d:Y.filename)!=null?v:"Document",filename:(m=Y.filename)!=null?m:Y.file_id})}break}case"function_call":{M=!0,U.push({type:"tool-call",toolCallId:F.call_id,toolName:F.name,input:F.arguments,providerMetadata:{openai:{itemId:F.id}}});break}case"web_search_call":{U.push({type:"tool-call",toolCallId:F.id,toolName:T??"web_search",input:JSON.stringify({}),providerExecuted:!0}),U.push({type:"tool-result",toolCallId:F.id,toolName:T??"web_search",result:af(F.action),providerExecuted:!0});break}case"computer_call":{U.push({type:"tool-call",toolCallId:F.id,toolName:"computer_use",input:"",providerExecuted:!0}),U.push({type:"tool-result",toolCallId:F.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:F.status||"completed"},providerExecuted:!0});break}case"file_search_call":{U.push({type:"tool-call",toolCallId:F.id,toolName:"file_search",input:"{}",providerExecuted:!0}),U.push({type:"tool-result",toolCallId:F.id,toolName:"file_search",result:{queries:F.queries,results:(h=(c=F.results)==null?void 0:c.map(X=>({attributes:X.attributes,fileId:X.file_id,filename:X.filename,score:X.score,text:X.text})))!=null?h:null},providerExecuted:!0});break}case"code_interpreter_call":{U.push({type:"tool-call",toolCallId:F.id,toolName:"code_interpreter",input:JSON.stringify({code:F.code,containerId:F.container_id}),providerExecuted:!0}),U.push({type:"tool-result",toolCallId:F.id,toolName:"code_interpreter",result:{outputs:F.outputs},providerExecuted:!0});break}}const j={openai:{responseId:R.id}};return Z.length>0&&(j.openai.logprobs=Z),typeof R.service_tier=="string"&&(j.openai.serviceTier=R.service_tier),{content:U,finishReason:tf({finishReason:(g=R.incomplete_details)==null?void 0:g.reason,hasFunctionCall:M}),usage:{inputTokens:R.usage.input_tokens,outputTokens:R.usage.output_tokens,totalTokens:R.usage.input_tokens+R.usage.output_tokens,reasoningTokens:(p=(f=R.usage.output_tokens_details)==null?void 0:f.reasoning_tokens)!=null?p:void 0,cachedInputTokens:(y=(b=R.usage.input_tokens_details)==null?void 0:b.cached_tokens)!=null?y:void 0},request:{body:_},response:{id:R.id,timestamp:new Date(R.created_at*1e3),modelId:R.model,headers:O,body:L},providerMetadata:j,warnings:S}}async doStream(t){const{args:e,warnings:r,webSearchToolName:a,store:n}=await this.getArgs(t),{responseHeaders:s,value:o}=await $t({url:this.config.url({path:"/responses",modelId:this.modelId}),headers:It(this.config.headers(),t.headers),body:{...e,stream:!0},failedResponseHandler:gr,successfulResponseHandler:ca(NI),abortSignal:t.abortSignal,fetch:this.config.fetch}),i=this;let l="unknown";const u={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},d=[];let v=null;const m={};let c=!1;const h={};let g;return{stream:o.pipeThrough(new TransformStream({start(f){f.enqueue({type:"stream-start",warnings:r})},transform(f,p){var b,y,_,S,T,I,O,R,L,U,Z,M,j,F,X,Y,te,oe,J,pe,ie,xe;if(t.includeRawChunks&&p.enqueue({type:"raw",rawValue:f.rawValue}),!f.success){l="error",p.enqueue({type:"error",error:f.error});return}const C=f.value;if(nf(C))C.item.type==="function_call"?(m[C.output_index]={toolName:C.item.name,toolCallId:C.item.call_id},p.enqueue({type:"tool-input-start",id:C.item.call_id,toolName:C.item.name})):C.item.type==="web_search_call"?(m[C.output_index]={toolName:a??"web_search",toolCallId:C.item.id},p.enqueue({type:"tool-input-start",id:C.item.id,toolName:a??"web_search",providerExecuted:!0}),p.enqueue({type:"tool-input-end",id:C.item.id}),p.enqueue({type:"tool-call",toolCallId:C.item.id,toolName:"web_search",input:JSON.stringify({}),providerExecuted:!0})):C.item.type==="computer_call"?(m[C.output_index]={toolName:"computer_use",toolCallId:C.item.id},p.enqueue({type:"tool-input-start",id:C.item.id,toolName:"computer_use",providerExecuted:!0})):C.item.type==="code_interpreter_call"?(m[C.output_index]={toolName:"code_interpreter",toolCallId:C.item.id,codeInterpreter:{containerId:C.item.container_id}},p.enqueue({type:"tool-input-start",id:C.item.id,toolName:"code_interpreter",providerExecuted:!0}),p.enqueue({type:"tool-input-delta",id:C.item.id,delta:`{"containerId":"${C.item.container_id}","code":"`})):C.item.type==="file_search_call"?p.enqueue({type:"tool-call",toolCallId:C.item.id,toolName:"file_search",input:"{}",providerExecuted:!0}):C.item.type==="image_generation_call"?p.enqueue({type:"tool-call",toolCallId:C.item.id,toolName:"image_generation",input:"{}",providerExecuted:!0}):C.item.type==="message"?p.enqueue({type:"text-start",id:C.item.id,providerMetadata:{openai:{itemId:C.item.id}}}):nf(C)&&C.item.type==="reasoning"&&(h[C.item.id]={encryptedContent:C.item.encrypted_content,summaryParts:{0:"active"}},p.enqueue({type:"reasoning-start",id:`${C.item.id}:0`,providerMetadata:{openai:{itemId:C.item.id,reasoningEncryptedContent:(b=C.item.encrypted_content)!=null?b:null}}}));else if(UI(C)){if(C.item.type==="function_call")m[C.output_index]=void 0,c=!0,p.enqueue({type:"tool-input-end",id:C.item.call_id}),p.enqueue({type:"tool-call",toolCallId:C.item.call_id,toolName:C.item.name,input:C.item.arguments,providerMetadata:{openai:{itemId:C.item.id}}});else if(C.item.type==="web_search_call")m[C.output_index]=void 0,p.enqueue({type:"tool-result",toolCallId:C.item.id,toolName:"web_search",result:af(C.item.action),providerExecuted:!0});else if(C.item.type==="computer_call")m[C.output_index]=void 0,p.enqueue({type:"tool-input-end",id:C.item.id}),p.enqueue({type:"tool-call",toolCallId:C.item.id,toolName:"computer_use",input:"",providerExecuted:!0}),p.enqueue({type:"tool-result",toolCallId:C.item.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:C.item.status||"completed"},providerExecuted:!0});else if(C.item.type==="file_search_call")m[C.output_index]=void 0,p.enqueue({type:"tool-result",toolCallId:C.item.id,toolName:"file_search",result:{queries:C.item.queries,results:(_=(y=C.item.results)==null?void 0:y.map(ae=>({attributes:ae.attributes,fileId:ae.file_id,filename:ae.filename,score:ae.score,text:ae.text})))!=null?_:null},providerExecuted:!0});else if(C.item.type==="code_interpreter_call")m[C.output_index]=void 0,p.enqueue({type:"tool-result",toolCallId:C.item.id,toolName:"code_interpreter",result:{outputs:C.item.outputs},providerExecuted:!0});else if(C.item.type==="image_generation_call")p.enqueue({type:"tool-result",toolCallId:C.item.id,toolName:"image_generation",result:{result:C.item.result},providerExecuted:!0});else if(C.item.type==="local_shell_call")m[C.output_index]=void 0,p.enqueue({type:"tool-call",toolCallId:C.item.call_id,toolName:"local_shell",input:JSON.stringify({action:{type:"exec",command:C.item.action.command,timeoutMs:C.item.action.timeout_ms,user:C.item.action.user,workingDirectory:C.item.action.working_directory,env:C.item.action.env}}),providerMetadata:{openai:{itemId:C.item.id}}});else if(C.item.type==="message")p.enqueue({type:"text-end",id:C.item.id});else if(C.item.type==="reasoning"){const ae=h[C.item.id],ge=Object.entries(ae.summaryParts).filter(([fe,ke])=>ke==="active"||ke==="can-conclude").map(([fe])=>fe);for(const fe of ge)p.enqueue({type:"reasoning-end",id:`${C.item.id}:${fe}`,providerMetadata:{openai:{itemId:C.item.id,reasoningEncryptedContent:(S=C.item.encrypted_content)!=null?S:null}}});delete h[C.item.id]}}else if(ZI(C)){const ae=m[C.output_index];ae!=null&&p.enqueue({type:"tool-input-delta",id:ae.toolCallId,delta:C.delta})}else if(VI(C)){const ae=m[C.output_index];ae!=null&&p.enqueue({type:"tool-input-delta",id:ae.toolCallId,delta:JSON.stringify(C.delta).slice(1,-1)})}else if(BI(C)){const ae=m[C.output_index];ae!=null&&(p.enqueue({type:"tool-input-delta",id:ae.toolCallId,delta:'"}'}),p.enqueue({type:"tool-input-end",id:ae.toolCallId}),p.enqueue({type:"tool-call",toolCallId:ae.toolCallId,toolName:"code_interpreter",input:JSON.stringify({code:C.code,containerId:ae.codeInterpreter.containerId}),providerExecuted:!0}))}else if(qI(C))v=C.response.id,p.enqueue({type:"response-metadata",id:C.response.id,timestamp:new Date(C.response.created_at*1e3),modelId:C.response.model});else if(LI(C))p.enqueue({type:"text-delta",id:C.item_id,delta:C.delta}),(I=(T=t.providerOptions)==null?void 0:T.openai)!=null&&I.logprobs&&C.logprobs&&d.push(C.logprobs);else if(C.type==="response.reasoning_summary_part.added"){if(C.summary_index>0){const ae=h[C.item_id];ae.summaryParts[C.summary_index]="active";for(const ge of Object.keys(ae.summaryParts))ae.summaryParts[ge]==="can-conclude"&&(p.enqueue({type:"reasoning-end",id:`${C.item_id}:${ge}`,providerMetadata:{openai:{itemId:C.item_id}}}),ae.summaryParts[ge]="concluded");p.enqueue({type:"reasoning-start",id:`${C.item_id}:${C.summary_index}`,providerMetadata:{openai:{itemId:C.item_id,reasoningEncryptedContent:(R=(O=h[C.item_id])==null?void 0:O.encryptedContent)!=null?R:null}}})}}else C.type==="response.reasoning_summary_text.delta"?p.enqueue({type:"reasoning-delta",id:`${C.item_id}:${C.summary_index}`,delta:C.delta,providerMetadata:{openai:{itemId:C.item_id}}}):C.type==="response.reasoning_summary_part.done"?n?(p.enqueue({type:"reasoning-end",id:`${C.item_id}:${C.summary_index}`,providerMetadata:{openai:{itemId:C.item_id}}}),h[C.item_id].summaryParts[C.summary_index]="concluded"):h[C.item_id].summaryParts[C.summary_index]="can-conclude":FI(C)?(l=tf({finishReason:(L=C.response.incomplete_details)==null?void 0:L.reason,hasFunctionCall:c}),u.inputTokens=C.response.usage.input_tokens,u.outputTokens=C.response.usage.output_tokens,u.totalTokens=C.response.usage.input_tokens+C.response.usage.output_tokens,u.reasoningTokens=(Z=(U=C.response.usage.output_tokens_details)==null?void 0:U.reasoning_tokens)!=null?Z:void 0,u.cachedInputTokens=(j=(M=C.response.usage.input_tokens_details)==null?void 0:M.cached_tokens)!=null?j:void 0,typeof C.response.service_tier=="string"&&(g=C.response.service_tier)):HI(C)?C.annotation.type==="url_citation"?p.enqueue({type:"source",sourceType:"url",id:(Y=(X=(F=i.config).generateId)==null?void 0:X.call(F))!=null?Y:Ot(),url:C.annotation.url,title:C.annotation.title}):C.annotation.type==="file_citation"&&p.enqueue({type:"source",sourceType:"document",id:(J=(oe=(te=i.config).generateId)==null?void 0:oe.call(te))!=null?J:Ot(),mediaType:"text/plain",title:(ie=(pe=C.annotation.quote)!=null?pe:C.annotation.filename)!=null?ie:"Document",filename:(xe=C.annotation.filename)!=null?xe:C.annotation.file_id}):JI(C)&&p.enqueue({type:"error",error:C})},flush(f){const p={openai:{responseId:v}};d.length>0&&(p.openai.logprobs=d),g!==void 0&&(p.openai.serviceTier=g),f.enqueue({type:"finish",finishReason:l,usage:u,providerMetadata:p})}})),request:{body:e},response:{headers:s}}}};function LI(t){return t.type==="response.output_text.delta"}function UI(t){return t.type==="response.output_item.done"}function FI(t){return t.type==="response.completed"||t.type==="response.incomplete"}function qI(t){return t.type==="response.created"}function ZI(t){return t.type==="response.function_call_arguments.delta"}function VI(t){return t.type==="response.code_interpreter_call_code.delta"}function BI(t){return t.type==="response.code_interpreter_call_code.done"}function nf(t){return t.type==="response.output_item.added"}function HI(t){return t.type==="response.output_text.annotation.added"}function JI(t){return t.type==="error"}function WI(t){const e=t.startsWith("o3")||t.startsWith("o4-mini")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-chat"),r=t.startsWith("gpt-4")||t.startsWith("gpt-5-mini")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-nano")&&!t.startsWith("gpt-5-chat")||t.startsWith("o3")||t.startsWith("o4-mini"),a={systemMessageMode:"system",supportsFlexProcessing:e,supportsPriorityProcessing:r};return t.startsWith("gpt-5-chat")?{...a,isReasoningModel:!1}:t.startsWith("o")||t.startsWith("gpt-5")||t.startsWith("codex-")||t.startsWith("computer-use")?t.startsWith("o1-mini")||t.startsWith("o1-preview")?{...a,isReasoningModel:!0,systemMessageMode:"remove"}:{...a,isReasoningModel:!0,systemMessageMode:"developer"}:{...a,isReasoningModel:!1}}function af(t){var e;switch(t.type){case"search":return{action:{type:"search",query:(e=t.query)!=null?e:void 0}};case"open_page":return{action:{type:"openPage",url:t.url}};case"find":return{action:{type:"find",url:t.url,pattern:t.pattern}}}}var GI=rt(()=>Ie(E({instructions:w().nullish(),speed:D().min(.25).max(4).default(1).nullish()}))),KI=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v2"}get provider(){return this.config.provider}async getArgs({text:t,voice:e="alloy",outputFormat:r="mp3",speed:a,instructions:n,language:s,providerOptions:o}){const i=[],l=await dr({provider:"openai",providerOptions:o,schema:GI}),u={model:this.modelId,input:t,voice:e,response_format:"mp3",speed:a,instructions:n};if(r&&(["mp3","opus","aac","flac","wav","pcm"].includes(r)?u.response_format=r:i.push({type:"unsupported-setting",setting:"outputFormat",details:`Unsupported output format: ${r}. Using mp3 instead.`})),l){const d={};for(const v in d){const m=d[v];m!==void 0&&(u[v]=m)}}return s&&i.push({type:"unsupported-setting",setting:"language",details:`OpenAI speech models do not support language selection. Language parameter "${s}" was ignored.`}),{requestBody:u,warnings:i}}async doGenerate(t){var e,r,a;const n=(a=(r=(e=this.config._internal)==null?void 0:e.currentDate)==null?void 0:r.call(e))!=null?a:new Date,{requestBody:s,warnings:o}=await this.getArgs(t),{value:i,responseHeaders:l,rawValue:u}=await $t({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:It(this.config.headers(),t.headers),body:s,failedResponseHandler:gr,successfulResponseHandler:Q0(),abortSignal:t.abortSignal,fetch:this.config.fetch});return{audio:i,warnings:o,request:{body:JSON.stringify(s)},response:{timestamp:n,modelId:this.modelId,headers:l,body:u}}}},QI=rt(()=>Ie(E({text:w(),language:w().nullish(),duration:D().nullish(),words:K(E({word:w(),start:D(),end:D()})).nullish(),segments:K(E({id:D(),seek:D(),start:D(),end:D(),text:w(),tokens:K(D()),temperature:D(),avg_logprob:D(),compression_ratio:D(),no_speech_prob:D()})).nullish()}))),YI=rt(()=>Ie(E({include:K(w()).optional(),language:w().optional(),prompt:w().optional(),temperature:D().min(0).max(1).default(0).optional(),timestampGranularities:K(Xe(["word","segment"])).default(["segment"]).optional()}))),sf={afrikaans:"af",arabic:"ar",armenian:"hy",azerbaijani:"az",belarusian:"be",bosnian:"bs",bulgarian:"bg",catalan:"ca",chinese:"zh",croatian:"hr",czech:"cs",danish:"da",dutch:"nl",english:"en",estonian:"et",finnish:"fi",french:"fr",galician:"gl",german:"de",greek:"el",hebrew:"he",hindi:"hi",hungarian:"hu",icelandic:"is",indonesian:"id",italian:"it",japanese:"ja",kannada:"kn",kazakh:"kk",korean:"ko",latvian:"lv",lithuanian:"lt",macedonian:"mk",malay:"ms",marathi:"mr",maori:"mi",nepali:"ne",norwegian:"no",persian:"fa",polish:"pl",portuguese:"pt",romanian:"ro",russian:"ru",serbian:"sr",slovak:"sk",slovenian:"sl",spanish:"es",swahili:"sw",swedish:"sv",tagalog:"tl",tamil:"ta",thai:"th",turkish:"tr",ukrainian:"uk",urdu:"ur",vietnamese:"vi",welsh:"cy"},XI=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v2"}get provider(){return this.config.provider}async getArgs({audio:t,mediaType:e,providerOptions:r}){const a=[],n=await dr({provider:"openai",providerOptions:r,schema:YI}),s=new FormData,o=t instanceof Uint8Array?new Blob([t]):new Blob([fs(t)]);s.append("model",this.modelId);const i=j0(e);if(s.append("file",new File([o],"audio",{type:e}),`audio.${i}`),n){const l={include:n.include,language:n.language,prompt:n.prompt,response_format:["gpt-4o-transcribe","gpt-4o-mini-transcribe"].includes(this.modelId)?"json":"verbose_json",temperature:n.temperature,timestamp_granularities:n.timestampGranularities};for(const[u,d]of Object.entries(l))if(d!=null)if(Array.isArray(d))for(const v of d)s.append(`${u}[]`,String(v));else s.append(u,String(d))}return{formData:s,warnings:a}}async doGenerate(t){var e,r,a,n,s,o,i,l;const u=(a=(r=(e=this.config._internal)==null?void 0:e.currentDate)==null?void 0:r.call(e))!=null?a:new Date,{formData:d,warnings:v}=await this.getArgs(t),{value:m,responseHeaders:c,rawValue:h}=await G0({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:It(this.config.headers(),t.headers),formData:d,failedResponseHandler:gr,successfulResponseHandler:tr(QI),abortSignal:t.abortSignal,fetch:this.config.fetch}),g=m.language!=null&&m.language in sf?sf[m.language]:void 0;return{text:m.text,segments:(i=(o=(n=m.segments)==null?void 0:n.map(f=>({text:f.text,startSecond:f.start,endSecond:f.end})))!=null?o:(s=m.words)==null?void 0:s.map(f=>({text:f.word,startSecond:f.start,endSecond:f.end})))!=null?i:[],language:g,durationInSeconds:(l=m.duration)!=null?l:void 0,warnings:v,response:{timestamp:u,modelId:this.modelId,headers:c,body:h}}}},ek="2.0.53";function of(t={}){var e,r;const a=(e=Xo(ua({settingValue:t.baseURL,environmentVariableName:"OPENAI_BASE_URL"})))!=null?e:"https://api.openai.com/v1",n=(r=t.name)!=null?r:"openai",s=()=>an({Authorization:`Bearer ${Bc({apiKey:t.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":t.organization,"OpenAI-Project":t.project,...t.headers},`ai-sdk/openai/${ek}`),o=g=>new HS(g,{provider:`${n}.chat`,url:({path:f})=>`${a}${f}`,headers:s,fetch:t.fetch}),i=g=>new eI(g,{provider:`${n}.completion`,url:({path:f})=>`${a}${f}`,headers:s,fetch:t.fetch}),l=g=>new nI(g,{provider:`${n}.embedding`,url:({path:f})=>`${a}${f}`,headers:s,fetch:t.fetch}),u=g=>new iI(g,{provider:`${n}.image`,url:({path:f})=>`${a}${f}`,headers:s,fetch:t.fetch}),d=g=>new XI(g,{provider:`${n}.transcription`,url:({path:f})=>`${a}${f}`,headers:s,fetch:t.fetch}),v=g=>new KI(g,{provider:`${n}.speech`,url:({path:f})=>`${a}${f}`,headers:s,fetch:t.fetch}),m=g=>{if(new.target)throw new Error("The OpenAI model function cannot be called with the new keyword.");return c(g)},c=g=>new zI(g,{provider:`${n}.responses`,url:({path:f})=>`${a}${f}`,headers:s,fetch:t.fetch,fileIdPrefixes:["file-"]}),h=function(g){return m(g)};return h.languageModel=m,h.chat=o,h.completion=i,h.responses=c,h.embedding=l,h.textEmbedding=l,h.textEmbeddingModel=l,h.image=u,h.imageModel=u,h.transcription=d,h.transcriptionModel=d,h.speech=v,h.speechModel=v,h.tools=OI,h}of();function Sa(t){var e,r;return(r=(e=t==null?void 0:t.providerOptions)==null?void 0:e.openaiCompatible)!=null?r:{}}function tk(t){const e=[];for(const{role:r,content:a,...n}of t){const s=Sa({...n});switch(r){case"system":{e.push({role:"system",content:a,...s});break}case"user":{if(a.length===1&&a[0].type==="text"){e.push({role:"user",content:a[0].text,...Sa(a[0])});break}e.push({role:"user",content:a.map(o=>{const i=Sa(o);switch(o.type){case"text":return{type:"text",text:o.text,...i};case"file":if(o.mediaType.startsWith("image/")){const l=o.mediaType==="image/*"?"image/jpeg":o.mediaType;return{type:"image_url",image_url:{url:o.data instanceof URL?o.data.toString():`data:${l};base64,${ln(o.data)}`},...i}}else throw new Yt({functionality:`file part media type ${o.mediaType}`})}}),...s});break}case"assistant":{let o="";const i=[];for(const l of a){const u=Sa(l);switch(l.type){case"text":{o+=l.text;break}case"tool-call":{i.push({id:l.toolCallId,type:"function",function:{name:l.toolName,arguments:JSON.stringify(l.input)},...u});break}}}e.push({role:"assistant",content:o,tool_calls:i.length>0?i:void 0,...s});break}case"tool":{for(const o of a){const i=o.output;let l;switch(i.type){case"text":case"error-text":l=i.value;break;case"content":case"json":case"error-json":l=JSON.stringify(i.value);break}const u=Sa(o);e.push({role:"tool",tool_call_id:o.toolCallId,content:l,...u})}break}default:{const o=r;throw new Error(`Unsupported role: ${o}`)}}}return e}function lf({id:t,model:e,created:r}){return{id:t??void 0,modelId:e??void 0,timestamp:r!=null?new Date(r*1e3):void 0}}function uf(t){switch(t){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"unknown"}}var Xi=E({user:w().optional(),reasoningEffort:w().optional(),textVerbosity:w().optional()}),rk=E({error:E({message:w(),type:w().nullish(),param:Ft().nullish(),code:Ne([w(),D()]).nullish()})}),nk={errorSchema:rk,errorToMessage:t=>t.error.message};function ak({tools:t,toolChoice:e}){t=t!=null&&t.length?t:void 0;const r=[];if(t==null)return{tools:void 0,toolChoice:void 0,toolWarnings:r};const a=[];for(const s of t)s.type==="provider-defined"?r.push({type:"unsupported-tool",tool:s}):a.push({type:"function",function:{name:s.name,description:s.description,parameters:s.inputSchema}});if(e==null)return{tools:a,toolChoice:void 0,toolWarnings:r};const n=e.type;switch(n){case"auto":case"none":case"required":return{tools:a,toolChoice:n,toolWarnings:r};case"tool":return{tools:a,toolChoice:{type:"function",function:{name:e.toolName}},toolWarnings:r};default:{const s=n;throw new Yt({functionality:`tool choice type: ${s}`})}}}var sk=class{constructor(t,e){this.specificationVersion="v2";var r,a;this.modelId=t,this.config=e;const n=(r=e.errorStructure)!=null?r:nk;this.chunkSchema=ik(n.errorSchema),this.failedResponseHandler=on(n),this.supportsStructuredOutputs=(a=e.supportsStructuredOutputs)!=null?a:!1}get provider(){return this.config.provider}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get supportedUrls(){var t,e,r;return(r=(e=(t=this.config).supportedUrls)==null?void 0:e.call(t))!=null?r:{}}async getArgs({prompt:t,maxOutputTokens:e,temperature:r,topP:a,topK:n,frequencyPenalty:s,presencePenalty:o,providerOptions:i,stopSequences:l,responseFormat:u,seed:d,toolChoice:v,tools:m}){var c,h,g,f;const p=[],b=Object.assign((c=await dr({provider:"openai-compatible",providerOptions:i,schema:Xi}))!=null?c:{},(h=await dr({provider:this.providerOptionsName,providerOptions:i,schema:Xi}))!=null?h:{});n!=null&&p.push({type:"unsupported-setting",setting:"topK"}),(u==null?void 0:u.type)==="json"&&u.schema!=null&&!this.supportsStructuredOutputs&&p.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{tools:y,toolChoice:_,toolWarnings:S}=ak({tools:m,toolChoice:v});return{args:{model:this.modelId,user:b.user,max_tokens:e,temperature:r,top_p:a,frequency_penalty:s,presence_penalty:o,response_format:(u==null?void 0:u.type)==="json"?this.supportsStructuredOutputs===!0&&u.schema!=null?{type:"json_schema",json_schema:{schema:u.schema,name:(g=u.name)!=null?g:"response",description:u.description}}:{type:"json_object"}:void 0,stop:l,seed:d,...Object.fromEntries(Object.entries((f=i==null?void 0:i[this.providerOptionsName])!=null?f:{}).filter(([T])=>!Object.keys(Xi.shape).includes(T))),reasoning_effort:b.reasoningEffort,verbosity:b.textVerbosity,messages:tk(t),tools:y,tool_choice:_},warnings:[...p,...S]}}async doGenerate(t){var e,r,a,n,s,o,i,l,u,d,v,m,c,h,g,f,p;const{args:b,warnings:y}=await this.getArgs({...t}),_=JSON.stringify(b),{responseHeaders:S,value:T,rawValue:I}=await $t({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:It(this.config.headers(),t.headers),body:b,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:tr(ok),abortSignal:t.abortSignal,fetch:this.config.fetch}),O=T.choices[0],R=[],L=O.message.content;L!=null&&L.length>0&&R.push({type:"text",text:L});const U=(e=O.message.reasoning_content)!=null?e:O.message.reasoning;if(U!=null&&U.length>0&&R.push({type:"reasoning",text:U}),O.message.tool_calls!=null)for(const j of O.message.tool_calls)R.push({type:"tool-call",toolCallId:(r=j.id)!=null?r:Ot(),toolName:j.function.name,input:j.function.arguments});const Z={[this.providerOptionsName]:{},...await((n=(a=this.config.metadataExtractor)==null?void 0:a.extractMetadata)==null?void 0:n.call(a,{parsedBody:I}))},M=(s=T.usage)==null?void 0:s.completion_tokens_details;return(M==null?void 0:M.accepted_prediction_tokens)!=null&&(Z[this.providerOptionsName].acceptedPredictionTokens=M==null?void 0:M.accepted_prediction_tokens),(M==null?void 0:M.rejected_prediction_tokens)!=null&&(Z[this.providerOptionsName].rejectedPredictionTokens=M==null?void 0:M.rejected_prediction_tokens),{content:R,finishReason:uf(O.finish_reason),usage:{inputTokens:(i=(o=T.usage)==null?void 0:o.prompt_tokens)!=null?i:void 0,outputTokens:(u=(l=T.usage)==null?void 0:l.completion_tokens)!=null?u:void 0,totalTokens:(v=(d=T.usage)==null?void 0:d.total_tokens)!=null?v:void 0,reasoningTokens:(h=(c=(m=T.usage)==null?void 0:m.completion_tokens_details)==null?void 0:c.reasoning_tokens)!=null?h:void 0,cachedInputTokens:(p=(f=(g=T.usage)==null?void 0:g.prompt_tokens_details)==null?void 0:f.cached_tokens)!=null?p:void 0},providerMetadata:Z,request:{body:_},response:{...lf(T),headers:S,body:I},warnings:y}}async doStream(t){var e;const{args:r,warnings:a}=await this.getArgs({...t}),n={...r,stream:!0,stream_options:this.config.includeUsage?{include_usage:!0}:void 0},s=(e=this.config.metadataExtractor)==null?void 0:e.createStreamExtractor(),{responseHeaders:o,value:i}=await $t({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:It(this.config.headers(),t.headers),body:n,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:ca(this.chunkSchema),abortSignal:t.abortSignal,fetch:this.config.fetch}),l=[];let u="unknown";const d={completionTokens:void 0,completionTokensDetails:{reasoningTokens:void 0,acceptedPredictionTokens:void 0,rejectedPredictionTokens:void 0},promptTokens:void 0,promptTokensDetails:{cachedTokens:void 0},totalTokens:void 0};let v=!0;const m=this.providerOptionsName;let c=!1,h=!1;return{stream:i.pipeThrough(new TransformStream({start(g){g.enqueue({type:"stream-start",warnings:a})},transform(g,f){var p,b,y,_,S,T,I,O,R,L,U,Z,M;if(t.includeRawChunks&&f.enqueue({type:"raw",rawValue:g.rawValue}),!g.success){u="error",f.enqueue({type:"error",error:g.error});return}const j=g.value;if(s==null||s.processChunk(g.rawValue),"error"in j){u="error",f.enqueue({type:"error",error:j.error.message});return}if(v&&(v=!1,f.enqueue({type:"response-metadata",...lf(j)})),j.usage!=null){const{prompt_tokens:te,completion_tokens:oe,total_tokens:J,prompt_tokens_details:pe,completion_tokens_details:ie}=j.usage;d.promptTokens=te??void 0,d.completionTokens=oe??void 0,d.totalTokens=J??void 0,(ie==null?void 0:ie.reasoning_tokens)!=null&&(d.completionTokensDetails.reasoningTokens=ie==null?void 0:ie.reasoning_tokens),(ie==null?void 0:ie.accepted_prediction_tokens)!=null&&(d.completionTokensDetails.acceptedPredictionTokens=ie==null?void 0:ie.accepted_prediction_tokens),(ie==null?void 0:ie.rejected_prediction_tokens)!=null&&(d.completionTokensDetails.rejectedPredictionTokens=ie==null?void 0:ie.rejected_prediction_tokens),(pe==null?void 0:pe.cached_tokens)!=null&&(d.promptTokensDetails.cachedTokens=pe==null?void 0:pe.cached_tokens)}const F=j.choices[0];if((F==null?void 0:F.finish_reason)!=null&&(u=uf(F.finish_reason)),(F==null?void 0:F.delta)==null)return;const X=F.delta,Y=(p=X.reasoning_content)!=null?p:X.reasoning;if(Y&&(c||(f.enqueue({type:"reasoning-start",id:"reasoning-0"}),c=!0),f.enqueue({type:"reasoning-delta",id:"reasoning-0",delta:Y})),X.content&&(h||(f.enqueue({type:"text-start",id:"txt-0"}),h=!0),f.enqueue({type:"text-delta",id:"txt-0",delta:X.content})),X.tool_calls!=null)for(const te of X.tool_calls){const oe=te.index;if(l[oe]==null){if(te.id==null)throw new Wn({data:te,message:"Expected 'id' to be a string."});if(((b=te.function)==null?void 0:b.name)==null)throw new Wn({data:te,message:"Expected 'function.name' to be a string."});f.enqueue({type:"tool-input-start",id:te.id,toolName:te.function.name}),l[oe]={id:te.id,type:"function",function:{name:te.function.name,arguments:(y=te.function.arguments)!=null?y:""},hasFinished:!1};const pe=l[oe];((_=pe.function)==null?void 0:_.name)!=null&&((S=pe.function)==null?void 0:S.arguments)!=null&&(pe.function.arguments.length>0&&f.enqueue({type:"tool-input-delta",id:pe.id,delta:pe.function.arguments}),ds(pe.function.arguments)&&(f.enqueue({type:"tool-input-end",id:pe.id}),f.enqueue({type:"tool-call",toolCallId:(T=pe.id)!=null?T:Ot(),toolName:pe.function.name,input:pe.function.arguments}),pe.hasFinished=!0));continue}const J=l[oe];J.hasFinished||(((I=te.function)==null?void 0:I.arguments)!=null&&(J.function.arguments+=(R=(O=te.function)==null?void 0:O.arguments)!=null?R:""),f.enqueue({type:"tool-input-delta",id:J.id,delta:(L=te.function.arguments)!=null?L:""}),((U=J.function)==null?void 0:U.name)!=null&&((Z=J.function)==null?void 0:Z.arguments)!=null&&ds(J.function.arguments)&&(f.enqueue({type:"tool-input-end",id:J.id}),f.enqueue({type:"tool-call",toolCallId:(M=J.id)!=null?M:Ot(),toolName:J.function.name,input:J.function.arguments}),J.hasFinished=!0))}},flush(g){var f,p,b,y,_,S;c&&g.enqueue({type:"reasoning-end",id:"reasoning-0"}),h&&g.enqueue({type:"text-end",id:"txt-0"});for(const I of l.filter(O=>!O.hasFinished))g.enqueue({type:"tool-input-end",id:I.id}),g.enqueue({type:"tool-call",toolCallId:(f=I.id)!=null?f:Ot(),toolName:I.function.name,input:I.function.arguments});const T={[m]:{},...s==null?void 0:s.buildMetadata()};d.completionTokensDetails.acceptedPredictionTokens!=null&&(T[m].acceptedPredictionTokens=d.completionTokensDetails.acceptedPredictionTokens),d.completionTokensDetails.rejectedPredictionTokens!=null&&(T[m].rejectedPredictionTokens=d.completionTokensDetails.rejectedPredictionTokens),g.enqueue({type:"finish",finishReason:u,usage:{inputTokens:(p=d.promptTokens)!=null?p:void 0,outputTokens:(b=d.completionTokens)!=null?b:void 0,totalTokens:(y=d.totalTokens)!=null?y:void 0,reasoningTokens:(_=d.completionTokensDetails.reasoningTokens)!=null?_:void 0,cachedInputTokens:(S=d.promptTokensDetails.cachedTokens)!=null?S:void 0},providerMetadata:T})}})),request:{body:n},response:{headers:o}}}},cf=E({prompt_tokens:D().nullish(),completion_tokens:D().nullish(),total_tokens:D().nullish(),prompt_tokens_details:E({cached_tokens:D().nullish()}).nullish(),completion_tokens_details:E({reasoning_tokens:D().nullish(),accepted_prediction_tokens:D().nullish(),rejected_prediction_tokens:D().nullish()}).nullish()}).nullish(),ok=E({id:w().nullish(),created:D().nullish(),model:w().nullish(),choices:K(E({message:E({role:q("assistant").nullish(),content:w().nullish(),reasoning_content:w().nullish(),reasoning:w().nullish(),tool_calls:K(E({id:w().nullish(),function:E({name:w(),arguments:w()})})).nullish()}),finish_reason:w().nullish()})),usage:cf}),ik=t=>Ne([E({id:w().nullish(),created:D().nullish(),model:w().nullish(),choices:K(E({delta:E({role:Xe(["assistant"]).nullish(),content:w().nullish(),reasoning_content:w().nullish(),reasoning:w().nullish(),tool_calls:K(E({index:D(),id:w().nullish(),function:E({name:w().nullish(),arguments:w().nullish()})})).nullish()}).nullish(),finish_reason:w().nullish()})),usage:cf}),t]);E({echo:st().optional(),logitBias:ot(w(),D()).optional(),suffix:w().optional(),user:w().optional()});var lk=E({prompt_tokens:D(),completion_tokens:D(),total_tokens:D()});E({id:w().nullish(),created:D().nullish(),model:w().nullish(),choices:K(E({text:w(),finish_reason:w()})),usage:lk.nullish()}),E({dimensions:D().optional(),user:w().optional()}),E({data:K(E({embedding:K(D())})),usage:E({prompt_tokens:D()}).nullish(),providerMetadata:ot(w(),ot(w(),Ft())).optional()}),E({data:K(E({b64_json:w()}))});var df=t=>{var e,r;return t==null?void 0:{deepseek:{promptCacheHitTokens:(e=t.prompt_cache_hit_tokens)!=null?e:NaN,promptCacheMissTokens:(r=t.prompt_cache_miss_tokens)!=null?r:NaN}}},uk={extractMetadata:async({parsedBody:t})=>{const e=await er({value:t,schema:ck});return!e.success||e.value.usage==null?void 0:df(e.value.usage)},createStreamExtractor:()=>{let t;return{processChunk:async e=>{var r,a;const n=await er({value:e,schema:dk});n.success&&((a=(r=n.value.choices)==null?void 0:r[0])==null?void 0:a.finish_reason)==="stop"&&n.value.usage&&(t=n.value.usage)},buildMetadata:()=>df(t)}}},pf=E({prompt_cache_hit_tokens:D().nullish(),prompt_cache_miss_tokens:D().nullish()}),ck=E({usage:pf.nullish()}),dk=E({choices:K(E({finish_reason:w().nullish()})).nullish(),usage:pf.nullish()}),pk="1.0.23";function hf(t={}){var e;const r=Xo((e=t.baseURL)!=null?e:"https://api.deepseek.com/v1"),a=()=>an({Authorization:`Bearer ${Bc({apiKey:t.apiKey,environmentVariableName:"DEEPSEEK_API_KEY",description:"DeepSeek API key"})}`,...t.headers},`ai-sdk/deepseek/${pk}`),n=o=>new sk(o,{provider:"deepseek.chat",url:({path:i})=>`${r}${i}`,headers:a,fetch:t.fetch,metadataExtractor:uk}),s=o=>n(o);return s.languageModel=n,s.chat=n,s.textEmbeddingModel=o=>{throw new bo({modelId:o,modelType:"textEmbeddingModel"})},s.imageModel=o=>{throw new bo({modelId:o,modelType:"imageModel"})},s}hf();const hk=(t,e,r)=>{if(r.endsWith("content"))chrome.tabs.query({},a=>{a.forEach(n=>{chrome.tabs.sendMessage(n.id,{type:t,data:e,direction:r,tabId:n.id})})});else return chrome.runtime.sendMessage({direction:r,type:t,data:e})},fk=(t,e,r,a)=>{const n=(s,o,i)=>{if(s.type===t&&s.direction===r){const{data:l}=s;e(l,o,i),i(o)}};return chrome.runtime.onMessage.addListener(n),()=>chrome.runtime.onMessage.removeListener(n)};class mk{constructor(e){this._isStarted=!1,this._isClosed=!1,this.targetSessionId=e,this._messageListener=fk("mcp-server-to-client",r=>{var a;try{if(r.sessionId!==this.targetSessionId)return;const n=hn.parse(r.mcpMessage);(a=this.onmessage)==null||a.call(this,n)}catch(n){console.log("【Client Transport】处理server消息错误:",n)}},"content->side")}_throwError(e,r){if(e()){const a=new Error(r);throw console.log(r,a),this.onerror&&this.onerror(a),a}}async start(){this._throwError(()=>this._isClosed,"【Client Transport】 未启动,无法重新启动"),this._isStarted=!0}async send(e,r){this._throwError(()=>!this._isStarted,"【Client Transport】 未启动,无法发送消息"),this._throwError(()=>this._isClosed,"【Client Transport】 已关闭,无法发送消息");const a=chrome.sessionRegistry.get(this.targetSessionId);this._throwError(()=>!a,`【Client Transport】sessionRegistry中未找到${this.targetSessionId}`);const n=a.tabIds[a.tabIds.length-1];hk("mcp-client-to-server",{sessionId:this.targetSessionId,tabId:n,mcpMessage:e},"side->content")}async close(){if(!this._isClosed)try{this._isClosed=!0,this._isStarted=!1,this._messageListener&&this._messageListener(),this.onclose&&this.onclose()}catch{this._throwError(()=>!0,"【Client Transport】 关闭时发生错误")}}}const vk=6e4;class gk{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this.setNotificationHandler(ki,r=>{const a=this._requestHandlerAbortControllers.get(r.params.requestId);a==null||a.abort(r.params.reason)}),this.setNotificationHandler(Pi,r=>{this._onprogress(r)}),this.setRequestHandler(Ti,r=>({}))}_setupTimeout(e,r,a,n,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(n,r),startTime:Date.now(),timeout:r,maxTotalTimeout:a,resetTimeoutOnProgress:s,onTimeout:n})}_resetTimeout(e){const r=this._timeoutInfo.get(e);if(!r)return!1;const a=Date.now()-r.startTime;if(r.maxTotalTimeout&&a>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),new Lr(vr.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:a});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){const r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){var r,a,n;this._transport=e;const s=(r=this.transport)===null||r===void 0?void 0:r.onclose;this._transport.onclose=()=>{s==null||s(),this._onclose()};const o=(a=this.transport)===null||a===void 0?void 0:a.onerror;this._transport.onerror=l=>{o==null||o(l),this._onerror(l)};const i=(n=this._transport)===null||n===void 0?void 0:n.onmessage;this._transport.onmessage=(l,u)=>{i==null||i(l,u),Ii(l)||PE(l)?this._onresponse(l):ih(l)?this._onrequest(l,u):TE(l)?this._onnotification(l):this._onerror(new Error(`Unknown message type: ${JSON.stringify(l)}`))},await this._transport.start()}_onclose(){var e;const r=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear(),this._transport=void 0,(e=this.onclose)===null||e===void 0||e.call(this);const a=new Lr(vr.ConnectionClosed,"Connection closed");for(const n of r.values())n(a)}_onerror(e){var r;(r=this.onerror)===null||r===void 0||r.call(this,e)}_onnotification(e){var r;const a=(r=this._notificationHandlers.get(e.method))!==null&&r!==void 0?r:this.fallbackNotificationHandler;a!==void 0&&Promise.resolve().then(()=>a(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){var a,n;const s=(a=this._requestHandlers.get(e.method))!==null&&a!==void 0?a:this.fallbackRequestHandler,o=this._transport;if(s===void 0){o==null||o.send({jsonrpc:"2.0",id:e.id,error:{code:vr.MethodNotFound,message:"Method not found"}}).catch(u=>this._onerror(new Error(`Failed to send an error response: ${u}`)));return}const i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);const l={signal:i.signal,sessionId:o==null?void 0:o.sessionId,_meta:(n=e.params)===null||n===void 0?void 0:n._meta,sendNotification:u=>this.notification(u,{relatedRequestId:e.id}),sendRequest:(u,d,v)=>this.request(u,d,{...v,relatedRequestId:e.id}),authInfo:r==null?void 0:r.authInfo,requestId:e.id,requestInfo:r==null?void 0:r.requestInfo};Promise.resolve().then(()=>s(e,l)).then(u=>{if(!i.signal.aborted)return o==null?void 0:o.send({result:u,jsonrpc:"2.0",id:e.id})},u=>{var d;if(!i.signal.aborted)return o==null?void 0:o.send({jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(u.code)?u.code:vr.InternalError,message:(d=u.message)!==null&&d!==void 0?d:"Internal error"}})}).catch(u=>this._onerror(new Error(`Failed to send response: ${u}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){const{progressToken:r,...a}=e.params,n=Number(r),s=this._progressHandlers.get(n);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}const o=this._responseHandlers.get(n),i=this._timeoutInfo.get(n);if(i&&o&&i.resetTimeoutOnProgress)try{this._resetTimeout(n)}catch(l){o(l);return}s(a)}_onresponse(e){const r=Number(e.id),a=this._responseHandlers.get(r);if(a===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}if(this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),Ii(e))a(e);else{const n=new Lr(e.error.code,e.error.message,e.error.data);a(n)}}get transport(){return this._transport}async close(){var e;await((e=this._transport)===null||e===void 0?void 0:e.close())}request(e,r,a){const{relatedRequestId:n,resumptionToken:s,onresumptiontoken:o}=a??{};return new Promise((i,l)=>{var u,d,v,m,c,h;if(!this._transport){l(new Error("Not connected"));return}((u=this._options)===null||u===void 0?void 0:u.enforceStrictCapabilities)===!0&&this.assertCapabilityForMethod(e.method),(d=a==null?void 0:a.signal)===null||d===void 0||d.throwIfAborted();const g=this._requestMessageId++,f={...e,jsonrpc:"2.0",id:g};a!=null&&a.onprogress&&(this._progressHandlers.set(g,a.onprogress),f.params={...e.params,_meta:{...((v=e.params)===null||v===void 0?void 0:v._meta)||{},progressToken:g}});const p=_=>{var S;this._responseHandlers.delete(g),this._progressHandlers.delete(g),this._cleanupTimeout(g),(S=this._transport)===null||S===void 0||S.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:g,reason:String(_)}},{relatedRequestId:n,resumptionToken:s,onresumptiontoken:o}).catch(T=>this._onerror(new Error(`Failed to send cancellation: ${T}`))),l(_)};this._responseHandlers.set(g,_=>{var S;if(!(!((S=a==null?void 0:a.signal)===null||S===void 0)&&S.aborted)){if(_ instanceof Error)return l(_);try{const T=r.parse(_.result);i(T)}catch(T){l(T)}}}),(m=a==null?void 0:a.signal)===null||m===void 0||m.addEventListener("abort",()=>{var _;p((_=a==null?void 0:a.signal)===null||_===void 0?void 0:_.reason)});const b=(c=a==null?void 0:a.timeout)!==null&&c!==void 0?c:vk,y=()=>p(new Lr(vr.RequestTimeout,"Request timed out",{timeout:b}));this._setupTimeout(g,b,a==null?void 0:a.maxTotalTimeout,y,(h=a==null?void 0:a.resetTimeoutOnProgress)!==null&&h!==void 0?h:!1),this._transport.send(f,{relatedRequestId:n,resumptionToken:s,onresumptiontoken:o}).catch(_=>{this._cleanupTimeout(g),l(_)})})}async notification(e,r){var a,n;if(!this._transport)throw new Error("Not connected");if(this.assertNotificationCapability(e.method),((n=(a=this._options)===null||a===void 0?void 0:a.debouncedNotificationMethods)!==null&&n!==void 0?n:[]).includes(e.method)&&!e.params&&!(r!=null&&r.relatedRequestId)){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{var l;if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;const u={...e,jsonrpc:"2.0"};(l=this._transport)===null||l===void 0||l.send(u,r).catch(d=>this._onerror(d))});return}const i={...e,jsonrpc:"2.0"};await this._transport.send(i,r)}setRequestHandler(e,r){const a=e.shape.method.value;this.assertRequestHandlerCapability(a),this._requestHandlers.set(a,(n,s)=>Promise.resolve(r(e.parse(n),s)))}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){this._notificationHandlers.set(e.shape.method.value,a=>Promise.resolve(r(e.parse(a))))}removeNotificationHandler(e){this._notificationHandlers.delete(e)}}function yk(t,e){return Object.entries(e).reduce((r,[a,n])=>(n&&typeof n=="object"?r[a]=r[a]?{...r[a],...n}:n:r[a]=n,r),{...t})}var el={exports:{}};/** @license URI.js v4.4.1 (c) 2011 Gary Court. License: http://github.com/garycourt/uri-js */(function(t,e){(function(r,a){a(e)})(Hw,function(r){function a(){for(var k=arguments.length,x=Array(k),P=0;P<k;P++)x[P]=arguments[P];if(x.length>1){x[0]=x[0].slice(0,-1);for(var A=x.length-1,N=1;N<A;++N)x[N]=x[N].slice(1,-1);return x[A]=x[A].slice(1),x.join("")}else return x[0]}function n(k){return"(?:"+k+")"}function s(k){return k===void 0?"undefined":k===null?"null":Object.prototype.toString.call(k).split(" ").pop().split("]").shift().toLowerCase()}function o(k){return k.toUpperCase()}function i(k){return k!=null?k instanceof Array?k:typeof k.length!="number"||k.split||k.setInterval||k.call?[k]:Array.prototype.slice.call(k):[]}function l(k,x){var P=k;if(x)for(var A in x)P[A]=x[A];return P}function u(k){var x="[A-Za-z]",P="[0-9]",A=a(P,"[A-Fa-f]"),N=n(n("%[EFef]"+A+"%"+A+A+"%"+A+A)+"|"+n("%[89A-Fa-f]"+A+"%"+A+A)+"|"+n("%"+A+A)),le="[\\:\\/\\?\\#\\[\\]\\@]",ce="[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]",$e=a(le,ce),He=k?"[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]":"[]",nt=k?"[\\uE000-\\uF8FF]":"[]",Oe=a(x,P,"[\\-\\.\\_\\~]",He);n(x+a(x,P,"[\\+\\-\\.]")+"*"),n(n(N+"|"+a(Oe,ce,"[\\:]"))+"*");var Ze=n(n("25[0-5]")+"|"+n("2[0-4]"+P)+"|"+n("1"+P+P)+"|"+n("0?[1-9]"+P)+"|0?0?"+P),at=n(Ze+"\\."+Ze+"\\."+Ze+"\\."+Ze),ye=n(A+"{1,4}"),Ke=n(n(ye+"\\:"+ye)+"|"+at),ut=n(n(ye+"\\:")+"{6}"+Ke),Qe=n("\\:\\:"+n(ye+"\\:")+"{5}"+Ke),Gr=n(n(ye)+"?\\:\\:"+n(ye+"\\:")+"{4}"+Ke),xr=n(n(n(ye+"\\:")+"{0,1}"+ye)+"?\\:\\:"+n(ye+"\\:")+"{3}"+Ke),Er=n(n(n(ye+"\\:")+"{0,2}"+ye)+"?\\:\\:"+n(ye+"\\:")+"{2}"+Ke),Jn=n(n(n(ye+"\\:")+"{0,3}"+ye)+"?\\:\\:"+ye+"\\:"+Ke),wn=n(n(n(ye+"\\:")+"{0,4}"+ye)+"?\\:\\:"+Ke),Qt=n(n(n(ye+"\\:")+"{0,5}"+ye)+"?\\:\\:"+ye),Sr=n(n(n(ye+"\\:")+"{0,6}"+ye)+"?\\:\\:"),bn=n([ut,Qe,Gr,xr,Er,Jn,wn,Qt,Sr].join("|")),Ar=n(n(Oe+"|"+N)+"+");n("[vV]"+A+"+\\."+a(Oe,ce,"[\\:]")+"+"),n(n(N+"|"+a(Oe,ce))+"*");var Ua=n(N+"|"+a(Oe,ce,"[\\:\\@]"));return n(n(N+"|"+a(Oe,ce,"[\\@]"))+"+"),n(n(Ua+"|"+a("[\\/\\?]",nt))+"*"),{NOT_SCHEME:new RegExp(a("[^]",x,P,"[\\+\\-\\.]"),"g"),NOT_USERINFO:new RegExp(a("[^\\%\\:]",Oe,ce),"g"),NOT_HOST:new RegExp(a("[^\\%\\[\\]\\:]",Oe,ce),"g"),NOT_PATH:new RegExp(a("[^\\%\\/\\:\\@]",Oe,ce),"g"),NOT_PATH_NOSCHEME:new RegExp(a("[^\\%\\/\\@]",Oe,ce),"g"),NOT_QUERY:new RegExp(a("[^\\%]",Oe,ce,"[\\:\\@\\/\\?]",nt),"g"),NOT_FRAGMENT:new RegExp(a("[^\\%]",Oe,ce,"[\\:\\@\\/\\?]"),"g"),ESCAPE:new RegExp(a("[^]",Oe,ce),"g"),UNRESERVED:new RegExp(Oe,"g"),OTHER_CHARS:new RegExp(a("[^\\%]",Oe,$e),"g"),PCT_ENCODED:new RegExp(N,"g"),IPV4ADDRESS:new RegExp("^("+at+")$"),IPV6ADDRESS:new RegExp("^\\[?("+bn+")"+n(n("\\%25|\\%(?!"+A+"{2})")+"("+Ar+")")+"?\\]?$")}}var d=u(!1),v=u(!0),m=function(){function k(x,P){var A=[],N=!0,le=!1,ce=void 0;try{for(var $e=x[Symbol.iterator](),He;!(N=(He=$e.next()).done)&&(A.push(He.value),!(P&&A.length===P));N=!0);}catch(nt){le=!0,ce=nt}finally{try{!N&&$e.return&&$e.return()}finally{if(le)throw ce}}return A}return function(x,P){if(Array.isArray(x))return x;if(Symbol.iterator in Object(x))return k(x,P);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),c=function(k){if(Array.isArray(k)){for(var x=0,P=Array(k.length);x<k.length;x++)P[x]=k[x];return P}else return Array.from(k)},h=2147483647,g=36,f=1,p=26,b=38,y=700,_=72,S=128,T="-",I=/^xn--/,O=/[^\0-\x7E]/,R=/[\x2E\u3002\uFF0E\uFF61]/g,L={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},U=g-f,Z=Math.floor,M=String.fromCharCode;function j(k){throw new RangeError(L[k])}function F(k,x){for(var P=[],A=k.length;A--;)P[A]=x(k[A]);return P}function X(k,x){var P=k.split("@"),A="";P.length>1&&(A=P[0]+"@",k=P[1]),k=k.replace(R,".");var N=k.split("."),le=F(N,x).join(".");return A+le}function Y(k){for(var x=[],P=0,A=k.length;P<A;){var N=k.charCodeAt(P++);if(N>=55296&&N<=56319&&P<A){var le=k.charCodeAt(P++);(le&64512)==56320?x.push(((N&1023)<<10)+(le&1023)+65536):(x.push(N),P--)}else x.push(N)}return x}var te=function(x){return String.fromCodePoint.apply(String,c(x))},oe=function(x){return x-48<10?x-22:x-65<26?x-65:x-97<26?x-97:g},J=function(x,P){return x+22+75*(x<26)-((P!=0)<<5)},pe=function(x,P,A){var N=0;for(x=A?Z(x/y):x>>1,x+=Z(x/P);x>U*p>>1;N+=g)x=Z(x/U);return Z(N+(U+1)*x/(x+b))},ie=function(x){var P=[],A=x.length,N=0,le=S,ce=_,$e=x.lastIndexOf(T);$e<0&&($e=0);for(var He=0;He<$e;++He)x.charCodeAt(He)>=128&&j("not-basic"),P.push(x.charCodeAt(He));for(var nt=$e>0?$e+1:0;nt<A;){for(var Oe=N,Ze=1,at=g;;at+=g){nt>=A&&j("invalid-input");var ye=oe(x.charCodeAt(nt++));(ye>=g||ye>Z((h-N)/Ze))&&j("overflow"),N+=ye*Ze;var Ke=at<=ce?f:at>=ce+p?p:at-ce;if(ye<Ke)break;var ut=g-Ke;Ze>Z(h/ut)&&j("overflow"),Ze*=ut}var Qe=P.length+1;ce=pe(N-Oe,Qe,Oe==0),Z(N/Qe)>h-le&&j("overflow"),le+=Z(N/Qe),N%=Qe,P.splice(N++,0,le)}return String.fromCodePoint.apply(String,P)},xe=function(x){var P=[];x=Y(x);var A=x.length,N=S,le=0,ce=_,$e=!0,He=!1,nt=void 0;try{for(var Oe=x[Symbol.iterator](),Ze;!($e=(Ze=Oe.next()).done);$e=!0){var at=Ze.value;at<128&&P.push(M(at))}}catch(Fa){He=!0,nt=Fa}finally{try{!$e&&Oe.return&&Oe.return()}finally{if(He)throw nt}}var ye=P.length,Ke=ye;for(ye&&P.push(T);Ke<A;){var ut=h,Qe=!0,Gr=!1,xr=void 0;try{for(var Er=x[Symbol.iterator](),Jn;!(Qe=(Jn=Er.next()).done);Qe=!0){var wn=Jn.value;wn>=N&&wn<ut&&(ut=wn)}}catch(Fa){Gr=!0,xr=Fa}finally{try{!Qe&&Er.return&&Er.return()}finally{if(Gr)throw xr}}var Qt=Ke+1;ut-N>Z((h-le)/Qt)&&j("overflow"),le+=(ut-N)*Qt,N=ut;var Sr=!0,bn=!1,Ar=void 0;try{for(var Ua=x[Symbol.iterator](),$m;!(Sr=($m=Ua.next()).done);Sr=!0){var Am=$m.value;if(Am<N&&++le>h&&j("overflow"),Am==N){for(var yo=le,_o=g;;_o+=g){var wo=_o<=ce?f:_o>=ce+p?p:_o-ce;if(yo<wo)break;var Nm=yo-wo,Mm=g-wo;P.push(M(J(wo+Nm%Mm,0))),yo=Z(Nm/Mm)}P.push(M(J(yo,0))),ce=pe(le,Qt,Ke==ye),le=0,++Ke}}}catch(Fa){bn=!0,Ar=Fa}finally{try{!Sr&&Ua.return&&Ua.return()}finally{if(bn)throw Ar}}++le,++N}return P.join("")},C=function(x){return X(x,function(P){return I.test(P)?ie(P.slice(4).toLowerCase()):P})},ae=function(x){return X(x,function(P){return O.test(P)?"xn--"+xe(P):P})},ge={version:"2.1.0",ucs2:{decode:Y,encode:te},decode:ie,encode:xe,toASCII:ae,toUnicode:C},fe={};function ke(k){var x=k.charCodeAt(0),P=void 0;return x<16?P="%0"+x.toString(16).toUpperCase():x<128?P="%"+x.toString(16).toUpperCase():x<2048?P="%"+(x>>6|192).toString(16).toUpperCase()+"%"+(x&63|128).toString(16).toUpperCase():P="%"+(x>>12|224).toString(16).toUpperCase()+"%"+(x>>6&63|128).toString(16).toUpperCase()+"%"+(x&63|128).toString(16).toUpperCase(),P}function vt(k){for(var x="",P=0,A=k.length;P<A;){var N=parseInt(k.substr(P+1,2),16);if(N<128)x+=String.fromCharCode(N),P+=3;else if(N>=194&&N<224){if(A-P>=6){var le=parseInt(k.substr(P+4,2),16);x+=String.fromCharCode((N&31)<<6|le&63)}else x+=k.substr(P,6);P+=6}else if(N>=224){if(A-P>=9){var ce=parseInt(k.substr(P+4,2),16),$e=parseInt(k.substr(P+7,2),16);x+=String.fromCharCode((N&15)<<12|(ce&63)<<6|$e&63)}else x+=k.substr(P,9);P+=9}else x+=k.substr(P,3),P+=3}return x}function Me(k,x){function P(A){var N=vt(A);return N.match(x.UNRESERVED)?N:A}return k.scheme&&(k.scheme=String(k.scheme).replace(x.PCT_ENCODED,P).toLowerCase().replace(x.NOT_SCHEME,"")),k.userinfo!==void 0&&(k.userinfo=String(k.userinfo).replace(x.PCT_ENCODED,P).replace(x.NOT_USERINFO,ke).replace(x.PCT_ENCODED,o)),k.host!==void 0&&(k.host=String(k.host).replace(x.PCT_ENCODED,P).toLowerCase().replace(x.NOT_HOST,ke).replace(x.PCT_ENCODED,o)),k.path!==void 0&&(k.path=String(k.path).replace(x.PCT_ENCODED,P).replace(k.scheme?x.NOT_PATH:x.NOT_PATH_NOSCHEME,ke).replace(x.PCT_ENCODED,o)),k.query!==void 0&&(k.query=String(k.query).replace(x.PCT_ENCODED,P).replace(x.NOT_QUERY,ke).replace(x.PCT_ENCODED,o)),k.fragment!==void 0&&(k.fragment=String(k.fragment).replace(x.PCT_ENCODED,P).replace(x.NOT_FRAGMENT,ke).replace(x.PCT_ENCODED,o)),k}function Ee(k){return k.replace(/^0*(.*)/,"$1")||"0"}function Tt(k,x){var P=k.match(x.IPV4ADDRESS)||[],A=m(P,2),N=A[1];return N?N.split(".").map(Ee).join("."):k}function Se(k,x){var P=k.match(x.IPV6ADDRESS)||[],A=m(P,3),N=A[1],le=A[2];if(N){for(var ce=N.toLowerCase().split("::").reverse(),$e=m(ce,2),He=$e[0],nt=$e[1],Oe=nt?nt.split(":").map(Ee):[],Ze=He.split(":").map(Ee),at=x.IPV4ADDRESS.test(Ze[Ze.length-1]),ye=at?7:8,Ke=Ze.length-ye,ut=Array(ye),Qe=0;Qe<ye;++Qe)ut[Qe]=Oe[Qe]||Ze[Ke+Qe]||"";at&&(ut[ye-1]=Tt(ut[ye-1],x));var Gr=ut.reduce(function(Qt,Sr,bn){if(!Sr||Sr==="0"){var Ar=Qt[Qt.length-1];Ar&&Ar.index+Ar.length===bn?Ar.length++:Qt.push({index:bn,length:1})}return Qt},[]),xr=Gr.sort(function(Qt,Sr){return Sr.length-Qt.length})[0],Er=void 0;if(xr&&xr.length>1){var Jn=ut.slice(0,xr.index),wn=ut.slice(xr.index+xr.length);Er=Jn.join(":")+"::"+wn.join(":")}else Er=ut.join(":");return le&&(Er+="%"+le),Er}else return k}var ue=/^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i,Pe="".match(/(){0}/)[1]===void 0;function Ce(k){var x=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},P={},A=x.iri!==!1?v:d;x.reference==="suffix"&&(k=(x.scheme?x.scheme+":":"")+"//"+k);var N=k.match(ue);if(N){Pe?(P.scheme=N[1],P.userinfo=N[3],P.host=N[4],P.port=parseInt(N[5],10),P.path=N[6]||"",P.query=N[7],P.fragment=N[8],isNaN(P.port)&&(P.port=N[5])):(P.scheme=N[1]||void 0,P.userinfo=k.indexOf("@")!==-1?N[3]:void 0,P.host=k.indexOf("//")!==-1?N[4]:void 0,P.port=parseInt(N[5],10),P.path=N[6]||"",P.query=k.indexOf("?")!==-1?N[7]:void 0,P.fragment=k.indexOf("#")!==-1?N[8]:void 0,isNaN(P.port)&&(P.port=k.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/)?N[4]:void 0)),P.host&&(P.host=Se(Tt(P.host,A),A)),P.scheme===void 0&&P.userinfo===void 0&&P.host===void 0&&P.port===void 0&&!P.path&&P.query===void 0?P.reference="same-document":P.scheme===void 0?P.reference="relative":P.fragment===void 0?P.reference="absolute":P.reference="uri",x.reference&&x.reference!=="suffix"&&x.reference!==P.reference&&(P.error=P.error||"URI is not a "+x.reference+" reference.");var le=fe[(x.scheme||P.scheme||"").toLowerCase()];if(!x.unicodeSupport&&(!le||!le.unicodeSupport)){if(P.host&&(x.domainHost||le&&le.domainHost))try{P.host=ge.toASCII(P.host.replace(A.PCT_ENCODED,vt).toLowerCase())}catch(ce){P.error=P.error||"Host's domain name can not be converted to ASCII via punycode: "+ce}Me(P,d)}else Me(P,A);le&&le.parse&&le.parse(P,x)}else P.error=P.error||"URI can not be parsed.";return P}function be(k,x){var P=x.iri!==!1?v:d,A=[];return k.userinfo!==void 0&&(A.push(k.userinfo),A.push("@")),k.host!==void 0&&A.push(Se(Tt(String(k.host),P),P).replace(P.IPV6ADDRESS,function(N,le,ce){return"["+le+(ce?"%25"+ce:"")+"]"})),(typeof k.port=="number"||typeof k.port=="string")&&(A.push(":"),A.push(String(k.port))),A.length?A.join(""):void 0}var et=/^\.\.?\//,Le=/^\/\.(\/|$)/,G=/^\/\.\.(\/|$)/,De=/^\/?(?:.|\n)*?(?=\/|$)/;function Ue(k){for(var x=[];k.length;)if(k.match(et))k=k.replace(et,"");else if(k.match(Le))k=k.replace(Le,"/");else if(k.match(G))k=k.replace(G,"/"),x.pop();else if(k==="."||k==="..")k="";else{var P=k.match(De);if(P){var A=P[0];k=k.slice(A.length),x.push(A)}else throw new Error("Unexpected dot segment condition")}return x.join("")}function me(k){var x=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},P=x.iri?v:d,A=[],N=fe[(x.scheme||k.scheme||"").toLowerCase()];if(N&&N.serialize&&N.serialize(k,x),k.host&&!P.IPV6ADDRESS.test(k.host)){if(x.domainHost||N&&N.domainHost)try{k.host=x.iri?ge.toUnicode(k.host):ge.toASCII(k.host.replace(P.PCT_ENCODED,vt).toLowerCase())}catch($e){k.error=k.error||"Host's domain name can not be converted to "+(x.iri?"Unicode":"ASCII")+" via punycode: "+$e}}Me(k,P),x.reference!=="suffix"&&k.scheme&&(A.push(k.scheme),A.push(":"));var le=be(k,x);if(le!==void 0&&(x.reference!=="suffix"&&A.push("//"),A.push(le),k.path&&k.path.charAt(0)!=="/"&&A.push("/")),k.path!==void 0){var ce=k.path;!x.absolutePath&&(!N||!N.absolutePath)&&(ce=Ue(ce)),le===void 0&&(ce=ce.replace(/^\/\//,"/%2F")),A.push(ce)}return k.query!==void 0&&(A.push("?"),A.push(k.query)),k.fragment!==void 0&&(A.push("#"),A.push(k.fragment)),A.join("")}function Be(k,x){var P=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},A=arguments[3],N={};return A||(k=Ce(me(k,P),P),x=Ce(me(x,P),P)),P=P||{},!P.tolerant&&x.scheme?(N.scheme=x.scheme,N.userinfo=x.userinfo,N.host=x.host,N.port=x.port,N.path=Ue(x.path||""),N.query=x.query):(x.userinfo!==void 0||x.host!==void 0||x.port!==void 0?(N.userinfo=x.userinfo,N.host=x.host,N.port=x.port,N.path=Ue(x.path||""),N.query=x.query):(x.path?(x.path.charAt(0)==="/"?N.path=Ue(x.path):((k.userinfo!==void 0||k.host!==void 0||k.port!==void 0)&&!k.path?N.path="/"+x.path:k.path?N.path=k.path.slice(0,k.path.lastIndexOf("/")+1)+x.path:N.path=x.path,N.path=Ue(N.path)),N.query=x.query):(N.path=k.path,x.query!==void 0?N.query=x.query:N.query=k.query),N.userinfo=k.userinfo,N.host=k.host,N.port=k.port),N.scheme=k.scheme),N.fragment=x.fragment,N}function br(k,x,P){var A=l({scheme:"null"},P);return me(Be(Ce(k,A),Ce(x,A),A,!0),A)}function Ht(k,x){return typeof k=="string"?k=me(Ce(k,x),x):s(k)==="object"&&(k=Ce(me(k,x),x)),k}function wt(k,x,P){return typeof k=="string"?k=me(Ce(k,P),P):s(k)==="object"&&(k=me(k,P)),typeof x=="string"?x=me(Ce(x,P),P):s(x)==="object"&&(x=me(x,P)),k===x}function or(k,x){return k&&k.toString().replace(!x||!x.iri?d.ESCAPE:v.ESCAPE,ke)}function Pt(k,x){return k&&k.toString().replace(!x||!x.iri?d.PCT_ENCODED:v.PCT_ENCODED,vt)}var Jt={scheme:"http",domainHost:!0,parse:function(x,P){return x.host||(x.error=x.error||"HTTP URIs must have a host."),x},serialize:function(x,P){var A=String(x.scheme).toLowerCase()==="https";return(x.port===(A?443:80)||x.port==="")&&(x.port=void 0),x.path||(x.path="/"),x}},$r={scheme:"https",domainHost:Jt.domainHost,parse:Jt.parse,serialize:Jt.serialize};function gn(k){return typeof k.secure=="boolean"?k.secure:String(k.scheme).toLowerCase()==="wss"}var Ge={scheme:"ws",domainHost:!0,parse:function(x,P){var A=x;return A.secure=gn(A),A.resourceName=(A.path||"/")+(A.query?"?"+A.query:""),A.path=void 0,A.query=void 0,A},serialize:function(x,P){if((x.port===(gn(x)?443:80)||x.port==="")&&(x.port=void 0),typeof x.secure=="boolean"&&(x.scheme=x.secure?"wss":"ws",x.secure=void 0),x.resourceName){var A=x.resourceName.split("?"),N=m(A,2),le=N[0],ce=N[1];x.path=le&&le!=="/"?le:void 0,x.query=ce,x.resourceName=void 0}return x.fragment=void 0,x}},Wt={scheme:"wss",domainHost:Ge.domainHost,parse:Ge.parse,serialize:Ge.serialize},ir={},Na="[A-Za-z0-9\\-\\.\\_\\~\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]",Gt="[0-9A-Fa-f]",Wl=n(n("%[EFef]"+Gt+"%"+Gt+Gt+"%"+Gt+Gt)+"|"+n("%[89A-Fa-f]"+Gt+"%"+Gt+Gt)+"|"+n("%"+Gt+Gt)),Bn="[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]",Ma="[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]",Da=a(Ma,'[\\"\\\\]'),ja="[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]",Jr=new RegExp(Na,"g"),gt=new RegExp(Wl,"g"),za=new RegExp(a("[^]",Bn,"[\\.]",'[\\"]',Da),"g"),La=new RegExp(a("[^]",Na,ja),"g"),Kt=La;function Hn(k){var x=vt(k);return x.match(Jr)?x:k}var de={scheme:"mailto",parse:function(x,P){var A=x,N=A.to=A.path?A.path.split(","):[];if(A.path=void 0,A.query){for(var le=!1,ce={},$e=A.query.split("&"),He=0,nt=$e.length;He<nt;++He){var Oe=$e[He].split("=");switch(Oe[0]){case"to":for(var Ze=Oe[1].split(","),at=0,ye=Ze.length;at<ye;++at)N.push(Ze[at]);break;case"subject":A.subject=Pt(Oe[1],P);break;case"body":A.body=Pt(Oe[1],P);break;default:le=!0,ce[Pt(Oe[0],P)]=Pt(Oe[1],P);break}}le&&(A.headers=ce)}A.query=void 0;for(var Ke=0,ut=N.length;Ke<ut;++Ke){var Qe=N[Ke].split("@");if(Qe[0]=Pt(Qe[0]),P.unicodeSupport)Qe[1]=Pt(Qe[1],P).toLowerCase();else try{Qe[1]=ge.toASCII(Pt(Qe[1],P).toLowerCase())}catch(Gr){A.error=A.error||"Email address's domain name can not be converted to ASCII via punycode: "+Gr}N[Ke]=Qe.join("@")}return A},serialize:function(x,P){var A=x,N=i(x.to);if(N){for(var le=0,ce=N.length;le<ce;++le){var $e=String(N[le]),He=$e.lastIndexOf("@"),nt=$e.slice(0,He).replace(gt,Hn).replace(gt,o).replace(za,ke),Oe=$e.slice(He+1);try{Oe=P.iri?ge.toUnicode(Oe):ge.toASCII(Pt(Oe,P).toLowerCase())}catch(Ke){A.error=A.error||"Email address's domain name can not be converted to "+(P.iri?"Unicode":"ASCII")+" via punycode: "+Ke}N[le]=nt+"@"+Oe}A.path=N.join(",")}var Ze=x.headers=x.headers||{};x.subject&&(Ze.subject=x.subject),x.body&&(Ze.body=x.body);var at=[];for(var ye in Ze)Ze[ye]!==ir[ye]&&at.push(ye.replace(gt,Hn).replace(gt,o).replace(La,ke)+"="+Ze[ye].replace(gt,Hn).replace(gt,o).replace(Kt,ke));return at.length&&(A.query=at.join("&")),A}},ht=/^([^\:]+)\:(.*)/,Wr={scheme:"urn",parse:function(x,P){var A=x.path&&x.path.match(ht),N=x;if(A){var le=P.scheme||N.scheme||"urn",ce=A[1].toLowerCase(),$e=A[2],He=le+":"+(P.nid||ce),nt=fe[He];N.nid=ce,N.nss=$e,N.path=void 0,nt&&(N=nt.parse(N,P))}else N.error=N.error||"URN can not be parsed.";return N},serialize:function(x,P){var A=P.scheme||x.scheme||"urn",N=x.nid,le=A+":"+(P.nid||N),ce=fe[le];ce&&(x=ce.serialize(x,P));var $e=x,He=x.nss;return $e.path=(N||P.nid)+":"+He,$e}},yn=/^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/,_n={scheme:"urn:uuid",parse:function(x,P){var A=x;return A.uuid=A.nss,A.nss=void 0,!P.tolerant&&(!A.uuid||!A.uuid.match(yn))&&(A.error=A.error||"UUID is not valid."),A},serialize:function(x,P){var A=x;return A.nss=(x.uuid||"").toLowerCase(),A}};fe[Jt.scheme]=Jt,fe[$r.scheme]=$r,fe[Ge.scheme]=Ge,fe[Wt.scheme]=Wt,fe[de.scheme]=de,fe[Wr.scheme]=Wr,fe[_n.scheme]=_n,r.SCHEMES=fe,r.pctEncChar=ke,r.pctDecChars=vt,r.parse=Ce,r.removeDotSegments=Ue,r.serialize=me,r.resolveComponents=Be,r.resolve=br,r.normalize=Ht,r.equal=wt,r.escapeComponent=or,r.unescapeComponent=Pt,Object.defineProperty(r,"__esModule",{value:!0})})})(el,el.exports);var _k=el.exports,tl=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var a,n,s;if(Array.isArray(e)){if(a=e.length,a!=r.length)return!1;for(n=a;n--!==0;)if(!t(e[n],r[n]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(s=Object.keys(e),a=s.length,a!==Object.keys(r).length)return!1;for(n=a;n--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[n]))return!1;for(n=a;n--!==0;){var o=s[n];if(!t(e[o],r[o]))return!1}return!0}return e!==e&&r!==r},wk=function(e){for(var r=0,a=e.length,n=0,s;n<a;)r++,s=e.charCodeAt(n++),s>=55296&&s<=56319&&n<a&&(s=e.charCodeAt(n),(s&64512)==56320&&n++);return r},Nn={copy:bk,checkDataType:rl,checkDataTypes:xk,coerceToTypes:Ek,toHash:nl,getProperty:al,escapeQuotes:sl,equal:tl,ucs2length:wk,varOccurences:kk,varReplace:Tk,schemaHasRules:Pk,schemaHasRulesExcept:Ck,schemaUnknownRules:Rk,toQuotedString:ol,getPathExpr:Ok,getPath:$k,getData:Mk,unescapeFragment:Dk,unescapeJsonPointer:ll,escapeFragment:jk,escapeJsonPointer:il};function bk(t,e){e=e||{};for(var r in t)e[r]=t[r];return e}function rl(t,e,r,a){var n=a?" !== ":" === ",s=a?" || ":" && ",o=a?"!":"",i=a?"":"!";switch(t){case"null":return e+n+"null";case"array":return o+"Array.isArray("+e+")";case"object":return"("+o+e+s+"typeof "+e+n+'"object"'+s+i+"Array.isArray("+e+"))";case"integer":return"(typeof "+e+n+'"number"'+s+i+"("+e+" % 1)"+s+e+n+e+(r?s+o+"isFinite("+e+")":"")+")";case"number":return"(typeof "+e+n+'"'+t+'"'+(r?s+o+"isFinite("+e+")":"")+")";default:return"typeof "+e+n+'"'+t+'"'}}function xk(t,e,r){switch(t.length){case 1:return rl(t[0],e,r,!0);default:var a="",n=nl(t);n.array&&n.object&&(a=n.null?"(":"(!"+e+" || ",a+="typeof "+e+' !== "object")',delete n.null,delete n.array,delete n.object),n.number&&delete n.integer;for(var s in n)a+=(a?" && ":"")+rl(s,e,r,!0);return a}}var ff=nl(["string","number","integer","boolean","null"]);function Ek(t,e){if(Array.isArray(e)){for(var r=[],a=0;a<e.length;a++){var n=e[a];(ff[n]||t==="array"&&n==="array")&&(r[r.length]=n)}if(r.length)return r}else{if(ff[e])return[e];if(t==="array"&&e==="array")return["array"]}}function nl(t){for(var e={},r=0;r<t.length;r++)e[t[r]]=!0;return e}var Sk=/^[a-z$_][a-z$_0-9]*$/i,Ik=/'|\\/g;function al(t){return typeof t=="number"?"["+t+"]":Sk.test(t)?"."+t:"['"+sl(t)+"']"}function sl(t){return t.replace(Ik,"\\$&").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\f/g,"\\f").replace(/\t/g,"\\t")}function kk(t,e){e+="[^0-9]";var r=t.match(new RegExp(e,"g"));return r?r.length:0}function Tk(t,e,r){return e+="([^0-9])",r=r.replace(/\$/g,"$$$$"),t.replace(new RegExp(e,"g"),r+"$1")}function Pk(t,e){if(typeof t=="boolean")return!t;for(var r in t)if(e[r])return!0}function Ck(t,e,r){if(typeof t=="boolean")return!t&&r!="not";for(var a in t)if(a!=r&&e[a])return!0}function Rk(t,e){if(typeof t!="boolean"){for(var r in t)if(!e[r])return r}}function ol(t){return"'"+sl(t)+"'"}function Ok(t,e,r,a){var n=r?"'/' + "+e+(a?"":".replace(/~/g, '~0').replace(/\\//g, '~1')"):a?"'[' + "+e+" + ']'":"'[\\'' + "+e+" + '\\']'";return mf(t,n)}function $k(t,e,r){var a=ol(r?"/"+il(e):al(e));return mf(t,a)}var Ak=/^\/(?:[^~]|~0|~1)*$/,Nk=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Mk(t,e,r){var a,n,s,o;if(t==="")return"rootData";if(t[0]=="/"){if(!Ak.test(t))throw new Error("Invalid JSON-pointer: "+t);n=t,s="rootData"}else{if(o=t.match(Nk),!o)throw new Error("Invalid JSON-pointer: "+t);if(a=+o[1],n=o[2],n=="#"){if(a>=e)throw new Error("Cannot access property/index "+a+" levels up, current level is "+e);return r[e-a]}if(a>e)throw new Error("Cannot access data "+a+" levels up, current level is "+e);if(s="data"+(e-a||""),!n)return s}for(var i=s,l=n.split("/"),u=0;u<l.length;u++){var d=l[u];d&&(s+=al(ll(d)),i+=" && "+s)}return i}function mf(t,e){return t=='""'?e:(t+" + "+e).replace(/([^\\])' \+ '/g,"$1")}function Dk(t){return ll(decodeURIComponent(t))}function jk(t){return encodeURIComponent(il(t))}function il(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}function ll(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}var zk=Nn,vf=Lk;function Lk(t){zk.copy(t,this)}var gf={exports:{}},Ur=gf.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var a=typeof r=="function"?r:r.pre||function(){},n=r.post||function(){};js(e,a,n,t,"",t)};Ur.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0},Ur.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},Ur.propsKeywords={definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},Ur.skipKeywords={default:!0,enum:!0,const:!0,required:!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};function js(t,e,r,a,n,s,o,i,l,u){if(a&&typeof a=="object"&&!Array.isArray(a)){e(a,n,s,o,i,l,u);for(var d in a){var v=a[d];if(Array.isArray(v)){if(d in Ur.arrayKeywords)for(var m=0;m<v.length;m++)js(t,e,r,v[m],n+"/"+d+"/"+m,s,n,d,a,m)}else if(d in Ur.propsKeywords){if(v&&typeof v=="object")for(var c in v)js(t,e,r,v[c],n+"/"+d+"/"+Uk(c),s,n,d,a,c)}else(d in Ur.keywords||t.allKeys&&!(d in Ur.skipKeywords))&&js(t,e,r,v,n+"/"+d,s,n,d,a)}r(a,n,s,o,i,l,u)}}function Uk(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}var Fk=gf.exports,Ia=_k,yf=tl,zs=Nn,Ls=vf,qk=Fk,ul=Fr;Fr.normalizeId=qr,Fr.fullPath=Fs,Fr.url=qs,Fr.ids=Jk,Fr.inlineRef=cl,Fr.schema=Us;function Fr(t,e,r){var a=this._refs[r];if(typeof a=="string")if(this._refs[a])a=this._refs[a];else return Fr.call(this,t,e,a);if(a=a||this._schemas[r],a instanceof Ls)return cl(a.schema,this._opts.inlineRefs)?a.schema:a.validate||this._compile(a);var n=Us.call(this,e,r),s,o,i;return n&&(s=n.schema,e=n.root,i=n.baseId),s instanceof Ls?o=s.validate||t.call(this,s.schema,e,void 0,i):s!==void 0&&(o=cl(s,this._opts.inlineRefs)?s:t.call(this,s,e,void 0,i)),o}function Us(t,e){var r=Ia.parse(e),a=wf(r),n=Fs(this._getId(t.schema));if(Object.keys(t.schema).length===0||a!==n){var s=qr(a),o=this._refs[s];if(typeof o=="string")return Zk.call(this,t,o,r);if(o instanceof Ls)o.validate||this._compile(o),t=o;else if(o=this._schemas[s],o instanceof Ls){if(o.validate||this._compile(o),s==qr(e))return{schema:o,root:t,baseId:n};t=o}else return;if(!t.schema)return;n=Fs(this._getId(t.schema))}return _f.call(this,r,n,t.schema,t)}function Zk(t,e,r){var a=Us.call(this,t,e);if(a){var n=a.schema,s=a.baseId;t=a.root;var o=this._getId(n);return o&&(s=qs(s,o)),_f.call(this,r,s,n,t)}}var Vk=zs.toHash(["properties","patternProperties","enum","dependencies","definitions"]);function _f(t,e,r,a){if(t.fragment=t.fragment||"",t.fragment.slice(0,1)=="/"){for(var n=t.fragment.split("/"),s=1;s<n.length;s++){var o=n[s];if(o){if(o=zs.unescapeFragment(o),r=r[o],r===void 0)break;var i;if(!Vk[o]&&(i=this._getId(r),i&&(e=qs(e,i)),r.$ref)){var l=qs(e,r.$ref),u=Us.call(this,a,l);u&&(r=u.schema,a=u.root,e=u.baseId)}}}if(r!==void 0&&r!==a.schema)return{schema:r,root:a,baseId:e}}}var Bk=zs.toHash(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum"]);function cl(t,e){if(e===!1)return!1;if(e===void 0||e===!0)return dl(t);if(e)return pl(t)<=e}function dl(t){var e;if(Array.isArray(t)){for(var r=0;r<t.length;r++)if(e=t[r],typeof e=="object"&&!dl(e))return!1}else for(var a in t)if(a=="$ref"||(e=t[a],typeof e=="object"&&!dl(e)))return!1;return!0}function pl(t){var e=0,r;if(Array.isArray(t)){for(var a=0;a<t.length;a++)if(r=t[a],typeof r=="object"&&(e+=pl(r)),e==1/0)return 1/0}else for(var n in t){if(n=="$ref")return 1/0;if(Bk[n])e++;else if(r=t[n],typeof r=="object"&&(e+=pl(r)+1),e==1/0)return 1/0}return e}function Fs(t,e){e!==!1&&(t=qr(t));var r=Ia.parse(t);return wf(r)}function wf(t){return Ia.serialize(t).split("#")[0]+"#"}var Hk=/#\/?$/;function qr(t){return t?t.replace(Hk,""):""}function qs(t,e){return e=qr(e),Ia.resolve(t,e)}function Jk(t){var e=qr(this._getId(t)),r={"":e},a={"":Fs(e,!1)},n={},s=this;return qk(t,{allKeys:!0},function(o,i,l,u,d,v,m){if(i!==""){var c=s._getId(o),h=r[u],g=a[u]+"/"+d;if(m!==void 0&&(g+="/"+(typeof m=="number"?m:zs.escapeFragment(m))),typeof c=="string"){c=h=qr(h?Ia.resolve(h,c):c);var f=s._refs[c];if(typeof f=="string"&&(f=s._refs[f]),f&&f.schema){if(!yf(o,f.schema))throw new Error('id "'+c+'" resolves to more than one schema')}else if(c!=qr(g))if(c[0]=="#"){if(n[c]&&!yf(o,n[c]))throw new Error('id "'+c+'" resolves to more than one schema');n[c]=o}else s._refs[c]=g}r[i]=h,a[i]=g}}),n}var hl=ul,fl={Validation:bf(Wk),MissingRef:bf(ml)};function Wk(t){this.message="validation failed",this.errors=t,this.ajv=this.validation=!0}ml.message=function(t,e){return"can't resolve reference "+e+" from id "+t};function ml(t,e,r){this.message=r||ml.message(t,e),this.missingRef=hl.url(t,e),this.missingSchema=hl.normalizeId(hl.fullPath(this.missingRef))}function bf(t){return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}var xf=function(t,e){e||(e={}),typeof e=="function"&&(e={cmp:e});var r=typeof e.cycles=="boolean"?e.cycles:!1,a=e.cmp&&function(s){return function(o){return function(i,l){var u={key:i,value:o[i]},d={key:l,value:o[l]};return s(u,d)}}}(e.cmp),n=[];return function s(o){if(o&&o.toJSON&&typeof o.toJSON=="function"&&(o=o.toJSON()),o!==void 0){if(typeof o=="number")return isFinite(o)?""+o:"null";if(typeof o!="object")return JSON.stringify(o);var i,l;if(Array.isArray(o)){for(l="[",i=0;i<o.length;i++)i&&(l+=","),l+=s(o[i])||"null";return l+"]"}if(o===null)return"null";if(n.indexOf(o)!==-1){if(r)return JSON.stringify("__cycle__");throw new TypeError("Converting circular structure to JSON")}var u=n.push(o)-1,d=Object.keys(o).sort(a&&a(o));for(l="",i=0;i<d.length;i++){var v=d[i],m=s(o[v]);m&&(l&&(l+=","),l+=JSON.stringify(v)+":"+m)}return n.splice(u,1),"{"+l+"}"}}(t)},Ef=function(e,r,a){var n="",s=e.schema.$async===!0,o=e.util.schemaHasRulesExcept(e.schema,e.RULES.all,"$ref"),i=e.self._getId(e.schema);if(e.opts.strictKeywords){var l=e.util.schemaUnknownRules(e.schema,e.RULES.keywords);if(l){var u="unknown keyword: "+l;if(e.opts.strictKeywords==="log")e.logger.warn(u);else throw new Error(u)}}if(e.isTop&&(n+=" var validate = ",s&&(e.async=!0,n+="async "),n+="function(data, dataPath, parentData, parentDataProperty, rootData) { 'use strict'; ",i&&(e.opts.sourceCode||e.opts.processCode)&&(n+=" "+("/*# sourceURL="+i+" */")+" ")),typeof e.schema=="boolean"||!(o||e.schema.$ref)){var r="false schema",d=e.level,v=e.dataLevel,m=e.schema[r],c=e.schemaPath+e.util.getProperty(r),h=e.errSchemaPath+"/"+r,S=!e.opts.allErrors,O,g="data"+(v||""),_="valid"+d;if(e.schema===!1){e.isTop?S=!0:n+=" var "+_+" = false; ";var f=f||[];f.push(n),n="",e.createErrors!==!1?(n+=" { keyword: '"+(O||"false schema")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(h)+" , params: {} ",e.opts.messages!==!1&&(n+=" , message: 'boolean schema is false' "),e.opts.verbose&&(n+=" , schema: false , parentSchema: validate.schema"+e.schemaPath+" , data: "+g+" "),n+=" } "):n+=" {} ";var p=n;n=f.pop(),!e.compositeRule&&S?e.async?n+=" throw new ValidationError(["+p+"]); ":n+=" validate.errors = ["+p+"]; return false; ":n+=" var err = "+p+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}else e.isTop?s?n+=" return data; ":n+=" validate.errors = null; return true; ":n+=" var "+_+" = true; ";return e.isTop&&(n+=" }; return validate; "),n}if(e.isTop){var b=e.isTop,d=e.level=0,v=e.dataLevel=0,g="data";if(e.rootId=e.resolve.fullPath(e.self._getId(e.root.schema)),e.baseId=e.baseId||e.rootId,delete e.isTop,e.dataPathArr=[""],e.schema.default!==void 0&&e.opts.useDefaults&&e.opts.strictDefaults){var y="default is ignored in the schema root";if(e.opts.strictDefaults==="log")e.logger.warn(y);else throw new Error(y)}n+=" var vErrors = null; ",n+=" var errors = 0; ",n+=" if (rootData === undefined) rootData = data; "}else{var d=e.level,v=e.dataLevel,g="data"+(v||"");if(i&&(e.baseId=e.resolve.url(e.baseId,i)),s&&!e.async)throw new Error("async schema in sync schema");n+=" var errs_"+d+" = errors;"}var _="valid"+d,S=!e.opts.allErrors,T="",I="",O,R=e.schema.type,L=Array.isArray(R);if(R&&e.opts.nullable&&e.schema.nullable===!0&&(L?R.indexOf("null")==-1&&(R=R.concat("null")):R!="null"&&(R=[R,"null"],L=!0)),L&&R.length==1&&(R=R[0],L=!1),e.schema.$ref&&o){if(e.opts.extendRefs=="fail")throw new Error('$ref: validation keywords used in schema at path "'+e.errSchemaPath+'" (see option extendRefs)');e.opts.extendRefs!==!0&&(o=!1,e.logger.warn('$ref: keywords ignored in schema at path "'+e.errSchemaPath+'"'))}if(e.schema.$comment&&e.opts.$comment&&(n+=" "+e.RULES.all.$comment.code(e,"$comment")),R){if(e.opts.coerceTypes)var U=e.util.coerceToTypes(e.opts.coerceTypes,R);var Z=e.RULES.types[R];if(U||L||Z===!0||Z&&!Le(Z)){var c=e.schemaPath+".type",h=e.errSchemaPath+"/type",c=e.schemaPath+".type",h=e.errSchemaPath+"/type",M=L?"checkDataTypes":"checkDataType";if(n+=" if ("+e.util[M](R,g,e.opts.strictNumbers,!0)+") { ",U){var j="dataType"+d,F="coerced"+d;n+=" var "+j+" = typeof "+g+"; var "+F+" = undefined; ",e.opts.coerceTypes=="array"&&(n+=" if ("+j+" == 'object' && Array.isArray("+g+") && "+g+".length == 1) { "+g+" = "+g+"[0]; "+j+" = typeof "+g+"; if ("+e.util.checkDataType(e.schema.type,g,e.opts.strictNumbers)+") "+F+" = "+g+"; } "),n+=" if ("+F+" !== undefined) ; ";var X=U;if(X)for(var Y,te=-1,oe=X.length-1;te<oe;)Y=X[te+=1],Y=="string"?n+=" else if ("+j+" == 'number' || "+j+" == 'boolean') "+F+" = '' + "+g+"; else if ("+g+" === null) "+F+" = ''; ":Y=="number"||Y=="integer"?(n+=" else if ("+j+" == 'boolean' || "+g+" === null || ("+j+" == 'string' && "+g+" && "+g+" == +"+g+" ",Y=="integer"&&(n+=" && !("+g+" % 1)"),n+=")) "+F+" = +"+g+"; "):Y=="boolean"?n+=" else if ("+g+" === 'false' || "+g+" === 0 || "+g+" === null) "+F+" = false; else if ("+g+" === 'true' || "+g+" === 1) "+F+" = true; ":Y=="null"?n+=" else if ("+g+" === '' || "+g+" === 0 || "+g+" === false) "+F+" = null; ":e.opts.coerceTypes=="array"&&Y=="array"&&(n+=" else if ("+j+" == 'string' || "+j+" == 'number' || "+j+" == 'boolean' || "+g+" == null) "+F+" = ["+g+"]; ");n+=" else { ";var f=f||[];f.push(n),n="",e.createErrors!==!1?(n+=" { keyword: '"+(O||"type")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(h)+" , params: { type: '",L?n+=""+R.join(","):n+=""+R,n+="' } ",e.opts.messages!==!1&&(n+=" , message: 'should be ",L?n+=""+R.join(","):n+=""+R,n+="' "),e.opts.verbose&&(n+=" , schema: validate.schema"+c+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+g+" "),n+=" } "):n+=" {} ";var p=n;n=f.pop(),!e.compositeRule&&S?e.async?n+=" throw new ValidationError(["+p+"]); ":n+=" validate.errors = ["+p+"]; return false; ":n+=" var err = "+p+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } if ("+F+" !== undefined) { ";var J=v?"data"+(v-1||""):"parentData",pe=v?e.dataPathArr[v]:"parentDataProperty";n+=" "+g+" = "+F+"; ",v||(n+="if ("+J+" !== undefined)"),n+=" "+J+"["+pe+"] = "+F+"; } "}else{var f=f||[];f.push(n),n="",e.createErrors!==!1?(n+=" { keyword: '"+(O||"type")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(h)+" , params: { type: '",L?n+=""+R.join(","):n+=""+R,n+="' } ",e.opts.messages!==!1&&(n+=" , message: 'should be ",L?n+=""+R.join(","):n+=""+R,n+="' "),e.opts.verbose&&(n+=" , schema: validate.schema"+c+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+g+" "),n+=" } "):n+=" {} ";var p=n;n=f.pop(),!e.compositeRule&&S?e.async?n+=" throw new ValidationError(["+p+"]); ":n+=" validate.errors = ["+p+"]; return false; ":n+=" var err = "+p+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}n+=" } "}}if(e.schema.$ref&&!o)n+=" "+e.RULES.all.$ref.code(e,"$ref")+" ",S&&(n+=" } if (errors === ",b?n+="0":n+="errs_"+d,n+=") { ",I+="}");else{var ie=e.RULES;if(ie){for(var Z,xe=-1,C=ie.length-1;xe<C;)if(Z=ie[xe+=1],Le(Z)){if(Z.type&&(n+=" if ("+e.util.checkDataType(Z.type,g,e.opts.strictNumbers)+") { "),e.opts.useDefaults){if(Z.type=="object"&&e.schema.properties){var m=e.schema.properties,ae=Object.keys(m),ge=ae;if(ge)for(var fe,ke=-1,vt=ge.length-1;ke<vt;){fe=ge[ke+=1];var Me=m[fe];if(Me.default!==void 0){var Ee=g+e.util.getProperty(fe);if(e.compositeRule){if(e.opts.strictDefaults){var y="default is ignored for: "+Ee;if(e.opts.strictDefaults==="log")e.logger.warn(y);else throw new Error(y)}}else n+=" if ("+Ee+" === undefined ",e.opts.useDefaults=="empty"&&(n+=" || "+Ee+" === null || "+Ee+" === '' "),n+=" ) "+Ee+" = ",e.opts.useDefaults=="shared"?n+=" "+e.useDefault(Me.default)+" ":n+=" "+JSON.stringify(Me.default)+" ",n+="; "}}}else if(Z.type=="array"&&Array.isArray(e.schema.items)){var Tt=e.schema.items;if(Tt){for(var Me,te=-1,Se=Tt.length-1;te<Se;)if(Me=Tt[te+=1],Me.default!==void 0){var Ee=g+"["+te+"]";if(e.compositeRule){if(e.opts.strictDefaults){var y="default is ignored for: "+Ee;if(e.opts.strictDefaults==="log")e.logger.warn(y);else throw new Error(y)}}else n+=" if ("+Ee+" === undefined ",e.opts.useDefaults=="empty"&&(n+=" || "+Ee+" === null || "+Ee+" === '' "),n+=" ) "+Ee+" = ",e.opts.useDefaults=="shared"?n+=" "+e.useDefault(Me.default)+" ":n+=" "+JSON.stringify(Me.default)+" ",n+="; "}}}}var ue=Z.rules;if(ue){for(var Pe,Ce=-1,be=ue.length-1;Ce<be;)if(Pe=ue[Ce+=1],G(Pe)){var et=Pe.code(e,Pe.keyword,Z.type);et&&(n+=" "+et+" ",S&&(T+="}"))}}if(S&&(n+=" "+T+" ",T=""),Z.type&&(n+=" } ",R&&R===Z.type&&!U)){n+=" else { ";var c=e.schemaPath+".type",h=e.errSchemaPath+"/type",f=f||[];f.push(n),n="",e.createErrors!==!1?(n+=" { keyword: '"+(O||"type")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(h)+" , params: { type: '",L?n+=""+R.join(","):n+=""+R,n+="' } ",e.opts.messages!==!1&&(n+=" , message: 'should be ",L?n+=""+R.join(","):n+=""+R,n+="' "),e.opts.verbose&&(n+=" , schema: validate.schema"+c+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+g+" "),n+=" } "):n+=" {} ";var p=n;n=f.pop(),!e.compositeRule&&S?e.async?n+=" throw new ValidationError(["+p+"]); ":n+=" validate.errors = ["+p+"]; return false; ":n+=" var err = "+p+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } "}S&&(n+=" if (errors === ",b?n+="0":n+="errs_"+d,n+=") { ",I+="}")}}}S&&(n+=" "+I+" "),b?(s?(n+=" if (errors === 0) return data; ",n+=" else throw new ValidationError(vErrors); "):(n+=" validate.errors = vErrors; ",n+=" return errors === 0; "),n+=" }; return validate;"):n+=" var "+_+" = errors === errs_"+d+";";function Le(Ue){for(var me=Ue.rules,Be=0;Be<me.length;Be++)if(G(me[Be]))return!0}function G(Ue){return e.schema[Ue.keyword]!==void 0||Ue.implements&&De(Ue)}function De(Ue){for(var me=Ue.implements,Be=0;Be<me.length;Be++)if(e.schema[me[Be]]!==void 0)return!0}return n},Zs=ul,Vs=Nn,Sf=fl,Gk=xf,If=Ef,Kk=Vs.ucs2length,Qk=tl,Yk=Sf.Validation,Xk=vl;function vl(t,e,r,a){var n=this,s=this._opts,o=[void 0],i={},l=[],u={},d=[],v={},m=[];e=e||{schema:t,refVal:o,refs:i};var c=eT.call(this,t,e,a),h=this._compilations[c.index];if(c.compiling)return h.callValidate=y;var g=this._formats,f=this.RULES;try{var p=_(t,e,r,a);h.validate=p;var b=h.callValidate;return b&&(b.schema=p.schema,b.errors=null,b.refs=p.refs,b.refVal=p.refVal,b.root=p.root,b.$async=p.$async,s.sourceCode&&(b.source=p.source)),p}finally{tT.call(this,t,e,a)}function y(){var M=h.validate,j=M.apply(this,arguments);return y.errors=M.errors,j}function _(M,j,F,X){var Y=!j||j&&j.schema==M;if(j.schema!=e.schema)return vl.call(n,M,j,F,X);var te=M.$async===!0,oe=If({isTop:!0,schema:M,isRoot:Y,baseId:X,root:j,schemaPath:"",errSchemaPath:"#",errorPath:'""',MissingRefError:Sf.MissingRef,RULES:f,validate:If,util:Vs,resolve:Zs,resolveRef:S,usePattern:L,useDefault:U,useCustomRule:Z,opts:s,formats:g,logger:n.logger,self:n});oe=Bs(o,aT)+Bs(l,rT)+Bs(d,nT)+Bs(m,sT)+oe,s.processCode&&(oe=s.processCode(oe,M));var J;try{var pe=new Function("self","RULES","formats","root","refVal","defaults","customRules","equal","ucs2length","ValidationError",oe);J=pe(n,f,g,e,o,d,m,Qk,Kk,Yk),o[0]=J}catch(ie){throw n.logger.error("Error compiling schema, function code:",oe),ie}return J.schema=M,J.errors=null,J.refs=i,J.refVal=o,J.root=Y?J:j,te&&(J.$async=!0),s.sourceCode===!0&&(J.source={code:oe,patterns:l,defaults:d}),J}function S(M,j,F){j=Zs.url(M,j);var X=i[j],Y,te;if(X!==void 0)return Y=o[X],te="refVal["+X+"]",R(Y,te);if(!F&&e.refs){var oe=e.refs[j];if(oe!==void 0)return Y=e.refVal[oe],te=T(j,Y),R(Y,te)}te=T(j);var J=Zs.call(n,_,e,j);if(J===void 0){var pe=r&&r[j];pe&&(J=Zs.inlineRef(pe,s.inlineRefs)?pe:vl.call(n,pe,e,r,M))}if(J===void 0)I(j);else return O(j,J),R(J,te)}function T(M,j){var F=o.length;return o[F]=j,i[M]=F,"refVal"+F}function I(M){delete i[M]}function O(M,j){var F=i[M];o[F]=j}function R(M,j){return typeof M=="object"||typeof M=="boolean"?{code:j,schema:M,inline:!0}:{code:j,$async:M&&!!M.$async}}function L(M){var j=u[M];return j===void 0&&(j=u[M]=l.length,l[j]=M),"pattern"+j}function U(M){switch(typeof M){case"boolean":case"number":return""+M;case"string":return Vs.toQuotedString(M);case"object":if(M===null)return"null";var j=Gk(M),F=v[j];return F===void 0&&(F=v[j]=d.length,d[F]=M),"default"+F}}function Z(M,j,F,X){if(n._opts.validateSchema!==!1){var Y=M.definition.dependencies;if(Y&&!Y.every(function(ge){return Object.prototype.hasOwnProperty.call(F,ge)}))throw new Error("parent schema must have all required keywords: "+Y.join(","));var te=M.definition.validateSchema;if(te){var oe=te(j);if(!oe){var J="keyword schema is invalid: "+n.errorsText(te.errors);if(n._opts.validateSchema=="log")n.logger.error(J);else throw new Error(J)}}}var pe=M.definition.compile,ie=M.definition.inline,xe=M.definition.macro,C;if(pe)C=pe.call(n,j,F,X);else if(xe)C=xe.call(n,j,F,X),s.validateSchema!==!1&&n.validateSchema(C,!0);else if(ie)C=ie.call(n,X,M.keyword,j,F);else if(C=M.definition.validate,!C)return;if(C===void 0)throw new Error('custom keyword "'+M.keyword+'"failed to compile');var ae=m.length;return m[ae]=C,{code:"customRule"+ae,validate:C}}}function eT(t,e,r){var a=kf.call(this,t,e,r);return a>=0?{index:a,compiling:!0}:(a=this._compilations.length,this._compilations[a]={schema:t,root:e,baseId:r},{index:a,compiling:!1})}function tT(t,e,r){var a=kf.call(this,t,e,r);a>=0&&this._compilations.splice(a,1)}function kf(t,e,r){for(var a=0;a<this._compilations.length;a++){var n=this._compilations[a];if(n.schema==t&&n.root==e&&n.baseId==r)return a}return-1}function rT(t,e){return"var pattern"+t+" = new RegExp("+Vs.toQuotedString(e[t])+");"}function nT(t){return"var default"+t+" = defaults["+t+"];"}function aT(t,e){return e[t]===void 0?"":"var refVal"+t+" = refVal["+t+"];"}function sT(t){return"var customRule"+t+" = customRules["+t+"];"}function Bs(t,e){if(!t.length)return"";for(var r="",a=0;a<t.length;a++)r+=e(a,t);return r}var Tf={exports:{}},Hs=Tf.exports=function(){this._cache={}};Hs.prototype.put=function(e,r){this._cache[e]=r},Hs.prototype.get=function(e){return this._cache[e]},Hs.prototype.del=function(e){delete this._cache[e]},Hs.prototype.clear=function(){this._cache={}};var oT=Tf.exports,iT=Nn,lT=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,uT=[0,31,28,31,30,31,30,31,31,30,31,30,31],cT=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,Pf=/^(?=.{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,dT=/^(?:[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,pT=/^(?:[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,Cf=/^(?:(?:[^\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,Rf=/^(?:(?:http[s\u017F]?|ftp):\/\/)(?:(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+(?::(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?@)?(?:(?!10(?:\.[0-9]{1,3}){3})(?!127(?:\.[0-9]{1,3}){3})(?!169\.254(?:\.[0-9]{1,3}){2})(?!192\.168(?:\.[0-9]{1,3}){2})(?!172\.(?:1[6-9]|2[0-9]|3[01])(?:\.[0-9]{1,3}){2})(?:[1-9][0-9]?|1[0-9][0-9]|2[01][0-9]|22[0-3])(?:\.(?:1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){2}(?:\.(?:[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))|(?:(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)(?:\.(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)*(?:\.(?:(?:[a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]){2,})))(?::[0-9]{2,5})?(?:\/(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?$/i,Of=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,$f=/^(?:\/(?:[^~/]|~0|~1)*)*$/,Af=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,Nf=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,hT=Js;function Js(t){return t=t=="full"?"full":"fast",iT.copy(Js[t])}Js.fast={date:/^\d\d\d\d-[0-1]\d-[0-3]\d$/,time:/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,"date-time":/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,"uri-template":Cf,url:Rf,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i,hostname:Pf,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,ipv6:/^\s*(?:(?:(?:[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}))|:)))(?:%.+)?\s*$/i,regex:jf,uuid:Of,"json-pointer":$f,"json-pointer-uri-fragment":Af,"relative-json-pointer":Nf},Js.full={date:Mf,time:Df,"date-time":vT,uri:yT,"uri-reference":pT,"uri-template":Cf,url:Rf,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:Pf,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,ipv6:/^\s*(?:(?:(?:[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}))|:)))(?:%.+)?\s*$/i,regex:jf,uuid:Of,"json-pointer":$f,"json-pointer-uri-fragment":Af,"relative-json-pointer":Nf};function fT(t){return t%4===0&&(t%100!==0||t%400===0)}function Mf(t){var e=t.match(lT);if(!e)return!1;var r=+e[1],a=+e[2],n=+e[3];return a>=1&&a<=12&&n>=1&&n<=(a==2&&fT(r)?29:uT[a])}function Df(t,e){var r=t.match(cT);if(!r)return!1;var a=r[1],n=r[2],s=r[3],o=r[5];return(a<=23&&n<=59&&s<=59||a==23&&n==59&&s==60)&&(!e||o)}var mT=/t|\s/i;function vT(t){var e=t.split(mT);return e.length==2&&Mf(e[0])&&Df(e[1],!0)}var gT=/\/|:/;function yT(t){return gT.test(t)&&dT.test(t)}var _T=/[^\\]\\Z/;function jf(t){if(_T.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}var wT=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,d="data"+(o||""),v="valid"+s,m,c;if(i=="#"||i=="#/")e.isRoot?(m=e.async,c="validate"):(m=e.root.schema.$async===!0,c="root.refVal[0]");else{var h=e.resolveRef(e.baseId,i,e.isRoot);if(h===void 0){var g=e.MissingRefError.message(e.baseId,i);if(e.opts.missingRefs=="fail"){e.logger.error(g);var f=f||[];f.push(n),n="",e.createErrors!==!1?(n+=" { keyword: '$ref' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { ref: '"+e.util.escapeQuotes(i)+"' } ",e.opts.messages!==!1&&(n+=" , message: 'can\\'t resolve reference "+e.util.escapeQuotes(i)+"' "),e.opts.verbose&&(n+=" , schema: "+e.util.toQuotedString(i)+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),n+=" } "):n+=" {} ";var p=n;n=f.pop(),!e.compositeRule&&u?e.async?n+=" throw new ValidationError(["+p+"]); ":n+=" validate.errors = ["+p+"]; return false; ":n+=" var err = "+p+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",u&&(n+=" if (false) { ")}else if(e.opts.missingRefs=="ignore")e.logger.warn(g),u&&(n+=" if (true) { ");else throw new e.MissingRefError(e.baseId,i,g)}else if(h.inline){var b=e.util.copy(e);b.level++;var y="valid"+b.level;b.schema=h.schema,b.schemaPath="",b.errSchemaPath=i;var _=e.validate(b).replace(/validate\.schema/g,h.code);n+=" "+_+" ",u&&(n+=" if ("+y+") { ")}else m=h.$async===!0||e.async&&h.$async!==!1,c=h.code}if(c){var f=f||[];f.push(n),n="",e.opts.passContext?n+=" "+c+".call(this, ":n+=" "+c+"( ",n+=" "+d+", (dataPath || '')",e.errorPath!='""'&&(n+=" + "+e.errorPath);var S=o?"data"+(o-1||""):"parentData",T=o?e.dataPathArr[o]:"parentDataProperty";n+=" , "+S+" , "+T+", rootData) ";var I=n;if(n=f.pop(),m){if(!e.async)throw new Error("async schema referenced by sync schema");u&&(n+=" var "+v+"; "),n+=" try { await "+I+"; ",u&&(n+=" "+v+" = true; "),n+=" } catch (e) { if (!(e instanceof ValidationError)) throw e; if (vErrors === null) vErrors = e.errors; else vErrors = vErrors.concat(e.errors); errors = vErrors.length; ",u&&(n+=" "+v+" = false; "),n+=" } ",u&&(n+=" if ("+v+") { ")}else n+=" if (!"+I+") { if (vErrors === null) vErrors = "+c+".errors; else vErrors = vErrors.concat("+c+".errors); errors = vErrors.length; } ",u&&(n+=" else { ")}return n},bT=function(e,r,a){var n=" ",s=e.schema[r],o=e.schemaPath+e.util.getProperty(r),i=e.errSchemaPath+"/"+r,l=!e.opts.allErrors,u=e.util.copy(e),d="";u.level++;var v="valid"+u.level,m=u.baseId,c=!0,h=s;if(h)for(var g,f=-1,p=h.length-1;f<p;)g=h[f+=1],(e.opts.strictKeywords?typeof g=="object"&&Object.keys(g).length>0||g===!1:e.util.schemaHasRules(g,e.RULES.all))&&(c=!1,u.schema=g,u.schemaPath=o+"["+f+"]",u.errSchemaPath=i+"/"+f,n+=" "+e.validate(u)+" ",u.baseId=m,l&&(n+=" if ("+v+") { ",d+="}"));return l&&(c?n+=" if (true) { ":n+=" "+d.slice(0,-1)+" "),n},xT=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,v="data"+(o||""),m="valid"+s,c="errs__"+s,h=e.util.copy(e),g="";h.level++;var f="valid"+h.level,p=i.every(function(O){return e.opts.strictKeywords?typeof O=="object"&&Object.keys(O).length>0||O===!1:e.util.schemaHasRules(O,e.RULES.all)});if(p){var b=h.baseId;n+=" var "+c+" = errors; var "+m+" = false; ";var y=e.compositeRule;e.compositeRule=h.compositeRule=!0;var _=i;if(_)for(var S,T=-1,I=_.length-1;T<I;)S=_[T+=1],h.schema=S,h.schemaPath=l+"["+T+"]",h.errSchemaPath=u+"/"+T,n+=" "+e.validate(h)+" ",h.baseId=b,n+=" "+m+" = "+m+" || "+f+"; if (!"+m+") { ",g+="}";e.compositeRule=h.compositeRule=y,n+=" "+g+" if (!"+m+") { var err = ",e.createErrors!==!1?(n+=" { keyword: 'anyOf' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: {} ",e.opts.messages!==!1&&(n+=" , message: 'should match some schema in anyOf' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+v+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&d&&(e.async?n+=" throw new ValidationError(vErrors); ":n+=" validate.errors = vErrors; return false; "),n+=" } else { errors = "+c+"; if (vErrors !== null) { if ("+c+") vErrors.length = "+c+"; else vErrors = null; } ",e.opts.allErrors&&(n+=" } ")}else d&&(n+=" if (true) { ");return n},ET=function(e,r,a){var n=" ",s=e.schema[r],o=e.errSchemaPath+"/"+r;e.opts.allErrors;var i=e.util.toQuotedString(s);return e.opts.$comment===!0?n+=" console.log("+i+");":typeof e.opts.$comment=="function"&&(n+=" self._opts.$comment("+i+", "+e.util.toQuotedString(o)+", validate.root.schema);"),n},ST=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,v="data"+(o||""),m="valid"+s,c=e.opts.$data&&i&&i.$data;c&&(n+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; "),c||(n+=" var schema"+s+" = validate.schema"+l+";"),n+="var "+m+" = equal("+v+", schema"+s+"); if (!"+m+") { ";var h=h||[];h.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'const' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { allowedValue: schema"+s+" } ",e.opts.messages!==!1&&(n+=" , message: 'should be equal to constant' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+v+" "),n+=" } "):n+=" {} ";var g=n;return n=h.pop(),!e.compositeRule&&d?e.async?n+=" throw new ValidationError(["+g+"]); ":n+=" validate.errors = ["+g+"]; return false; ":n+=" var err = "+g+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" }",d&&(n+=" else { "),n},IT=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,v="data"+(o||""),m="valid"+s,c="errs__"+s,h=e.util.copy(e),g="";h.level++;var f="valid"+h.level,p="i"+s,b=h.dataLevel=e.dataLevel+1,y="data"+b,_=e.baseId,S=e.opts.strictKeywords?typeof i=="object"&&Object.keys(i).length>0||i===!1:e.util.schemaHasRules(i,e.RULES.all);if(n+="var "+c+" = errors;var "+m+";",S){var T=e.compositeRule;e.compositeRule=h.compositeRule=!0,h.schema=i,h.schemaPath=l,h.errSchemaPath=u,n+=" var "+f+" = false; for (var "+p+" = 0; "+p+" < "+v+".length; "+p+"++) { ",h.errorPath=e.util.getPathExpr(e.errorPath,p,e.opts.jsonPointers,!0);var I=v+"["+p+"]";h.dataPathArr[b]=p;var O=e.validate(h);h.baseId=_,e.util.varOccurences(O,y)<2?n+=" "+e.util.varReplace(O,y,I)+" ":n+=" var "+y+" = "+I+"; "+O+" ",n+=" if ("+f+") break; } ",e.compositeRule=h.compositeRule=T,n+=" "+g+" if (!"+f+") {"}else n+=" if ("+v+".length == 0) {";var R=R||[];R.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'contains' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: {} ",e.opts.messages!==!1&&(n+=" , message: 'should contain a valid item' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+v+" "),n+=" } "):n+=" {} ";var L=n;return n=R.pop(),!e.compositeRule&&d?e.async?n+=" throw new ValidationError(["+L+"]); ":n+=" validate.errors = ["+L+"]; return false; ":n+=" var err = "+L+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } else { ",S&&(n+=" errors = "+c+"; if (vErrors !== null) { if ("+c+") vErrors.length = "+c+"; else vErrors = null; } "),e.opts.allErrors&&(n+=" } "),n},kT=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,v="data"+(o||""),m="errs__"+s,c=e.util.copy(e),h="";c.level++;var g="valid"+c.level,f={},p={},b=e.opts.ownProperties;for(T in i)if(T!="__proto__"){var y=i[T],_=Array.isArray(y)?p:f;_[T]=y}n+="var "+m+" = errors;";var S=e.errorPath;n+="var missing"+s+";";for(var T in p)if(_=p[T],_.length){if(n+=" if ( "+v+e.util.getProperty(T)+" !== undefined ",b&&(n+=" && Object.prototype.hasOwnProperty.call("+v+", '"+e.util.escapeQuotes(T)+"') "),d){n+=" && ( ";var I=_;if(I)for(var O,R=-1,L=I.length-1;R<L;){O=I[R+=1],R&&(n+=" || ");var U=e.util.getProperty(O),Z=v+U;n+=" ( ( "+Z+" === undefined ",b&&(n+=" || ! Object.prototype.hasOwnProperty.call("+v+", '"+e.util.escapeQuotes(O)+"') "),n+=") && (missing"+s+" = "+e.util.toQuotedString(e.opts.jsonPointers?O:U)+") ) "}n+=")) { ";var M="missing"+s,j="' + "+M+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.opts.jsonPointers?e.util.getPathExpr(S,M,!0):S+" + "+M);var F=F||[];F.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'dependencies' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { property: '"+e.util.escapeQuotes(T)+"', missingProperty: '"+j+"', depsCount: "+_.length+", deps: '"+e.util.escapeQuotes(_.length==1?_[0]:_.join(", "))+"' } ",e.opts.messages!==!1&&(n+=" , message: 'should have ",_.length==1?n+="property "+e.util.escapeQuotes(_[0]):n+="properties "+e.util.escapeQuotes(_.join(", ")),n+=" when property "+e.util.escapeQuotes(T)+" is present' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+v+" "),n+=" } "):n+=" {} ";var X=n;n=F.pop(),!e.compositeRule&&d?e.async?n+=" throw new ValidationError(["+X+"]); ":n+=" validate.errors = ["+X+"]; return false; ":n+=" var err = "+X+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}else{n+=" ) { ";var Y=_;if(Y)for(var O,te=-1,oe=Y.length-1;te<oe;){O=Y[te+=1];var U=e.util.getProperty(O),j=e.util.escapeQuotes(O),Z=v+U;e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPath(S,O,e.opts.jsonPointers)),n+=" if ( "+Z+" === undefined ",b&&(n+=" || ! Object.prototype.hasOwnProperty.call("+v+", '"+e.util.escapeQuotes(O)+"') "),n+=") { var err = ",e.createErrors!==!1?(n+=" { keyword: 'dependencies' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { property: '"+e.util.escapeQuotes(T)+"', missingProperty: '"+j+"', depsCount: "+_.length+", deps: '"+e.util.escapeQuotes(_.length==1?_[0]:_.join(", "))+"' } ",e.opts.messages!==!1&&(n+=" , message: 'should have ",_.length==1?n+="property "+e.util.escapeQuotes(_[0]):n+="properties "+e.util.escapeQuotes(_.join(", ")),n+=" when property "+e.util.escapeQuotes(T)+" is present' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+v+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } "}}n+=" } ",d&&(h+="}",n+=" else { ")}e.errorPath=S;var J=c.baseId;for(var T in f){var y=f[T];(e.opts.strictKeywords?typeof y=="object"&&Object.keys(y).length>0||y===!1:e.util.schemaHasRules(y,e.RULES.all))&&(n+=" "+g+" = true; if ( "+v+e.util.getProperty(T)+" !== undefined ",b&&(n+=" && Object.prototype.hasOwnProperty.call("+v+", '"+e.util.escapeQuotes(T)+"') "),n+=") { ",c.schema=y,c.schemaPath=l+e.util.getProperty(T),c.errSchemaPath=u+"/"+e.util.escapeFragment(T),n+=" "+e.validate(c)+" ",c.baseId=J,n+=" } ",d&&(n+=" if ("+g+") { ",h+="}"))}return d&&(n+=" "+h+" if ("+m+" == errors) {"),n},TT=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,v="data"+(o||""),m="valid"+s,c=e.opts.$data&&i&&i.$data;c&&(n+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ");var h="i"+s,g="schema"+s;c||(n+=" var "+g+" = validate.schema"+l+";"),n+="var "+m+";",c&&(n+=" if (schema"+s+" === undefined) "+m+" = true; else if (!Array.isArray(schema"+s+")) "+m+" = false; else {"),n+=""+m+" = false;for (var "+h+"=0; "+h+"<"+g+".length; "+h+"++) if (equal("+v+", "+g+"["+h+"])) { "+m+" = true; break; }",c&&(n+=" } "),n+=" if (!"+m+") { ";var f=f||[];f.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'enum' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { allowedValues: schema"+s+" } ",e.opts.messages!==!1&&(n+=" , message: 'should be equal to one of the allowed values' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+v+" "),n+=" } "):n+=" {} ";var p=n;return n=f.pop(),!e.compositeRule&&d?e.async?n+=" throw new ValidationError(["+p+"]); ":n+=" validate.errors = ["+p+"]; return false; ":n+=" var err = "+p+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" }",d&&(n+=" else { "),n},PT=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,v="data"+(o||"");if(e.opts.format===!1)return d&&(n+=" if (true) { "),n;var m=e.opts.$data&&i&&i.$data,c;m?(n+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",c="schema"+s):c=i;var h=e.opts.unknownFormats,g=Array.isArray(h);if(m){var f="format"+s,p="isObject"+s,b="formatType"+s;n+=" var "+f+" = formats["+c+"]; var "+p+" = typeof "+f+" == 'object' && !("+f+" instanceof RegExp) && "+f+".validate; var "+b+" = "+p+" && "+f+".type || 'string'; if ("+p+") { ",e.async&&(n+=" var async"+s+" = "+f+".async; "),n+=" "+f+" = "+f+".validate; } if ( ",m&&(n+=" ("+c+" !== undefined && typeof "+c+" != 'string') || "),n+=" (",h!="ignore"&&(n+=" ("+c+" && !"+f+" ",g&&(n+=" && self._opts.unknownFormats.indexOf("+c+") == -1 "),n+=") || "),n+=" ("+f+" && "+b+" == '"+a+"' && !(typeof "+f+" == 'function' ? ",e.async?n+=" (async"+s+" ? await "+f+"("+v+") : "+f+"("+v+")) ":n+=" "+f+"("+v+") ",n+=" : "+f+".test("+v+"))))) {"}else{var f=e.formats[i];if(!f){if(h=="ignore")return e.logger.warn('unknown format "'+i+'" ignored in schema at path "'+e.errSchemaPath+'"'),d&&(n+=" if (true) { "),n;if(g&&h.indexOf(i)>=0)return d&&(n+=" if (true) { "),n;throw new Error('unknown format "'+i+'" is used in schema at path "'+e.errSchemaPath+'"')}var p=typeof f=="object"&&!(f instanceof RegExp)&&f.validate,b=p&&f.type||"string";if(p){var y=f.async===!0;f=f.validate}if(b!=a)return d&&(n+=" if (true) { "),n;if(y){if(!e.async)throw new Error("async format in sync schema");var _="formats"+e.util.getProperty(i)+".validate";n+=" if (!(await "+_+"("+v+"))) { "}else{n+=" if (! ";var _="formats"+e.util.getProperty(i);p&&(_+=".validate"),typeof f=="function"?n+=" "+_+"("+v+") ":n+=" "+_+".test("+v+") ",n+=") { "}}var S=S||[];S.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'format' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { format: ",m?n+=""+c:n+=""+e.util.toQuotedString(i),n+=" } ",e.opts.messages!==!1&&(n+=` , message: 'should match format "`,m?n+="' + "+c+" + '":n+=""+e.util.escapeQuotes(i),n+=`"' `),e.opts.verbose&&(n+=" , schema: ",m?n+="validate.schema"+l:n+=""+e.util.toQuotedString(i),n+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+v+" "),n+=" } "):n+=" {} ";var T=n;return n=S.pop(),!e.compositeRule&&d?e.async?n+=" throw new ValidationError(["+T+"]); ":n+=" validate.errors = ["+T+"]; return false; ":n+=" var err = "+T+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } ",d&&(n+=" else { "),n},CT=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,v="data"+(o||""),m="valid"+s,c="errs__"+s,h=e.util.copy(e);h.level++;var g="valid"+h.level,f=e.schema.then,p=e.schema.else,b=f!==void 0&&(e.opts.strictKeywords?typeof f=="object"&&Object.keys(f).length>0||f===!1:e.util.schemaHasRules(f,e.RULES.all)),y=p!==void 0&&(e.opts.strictKeywords?typeof p=="object"&&Object.keys(p).length>0||p===!1:e.util.schemaHasRules(p,e.RULES.all)),_=h.baseId;if(b||y){var S;h.createErrors=!1,h.schema=i,h.schemaPath=l,h.errSchemaPath=u,n+=" var "+c+" = errors; var "+m+" = true; ";var T=e.compositeRule;e.compositeRule=h.compositeRule=!0,n+=" "+e.validate(h)+" ",h.baseId=_,h.createErrors=!0,n+=" errors = "+c+"; if (vErrors !== null) { if ("+c+") vErrors.length = "+c+"; else vErrors = null; } ",e.compositeRule=h.compositeRule=T,b?(n+=" if ("+g+") { ",h.schema=e.schema.then,h.schemaPath=e.schemaPath+".then",h.errSchemaPath=e.errSchemaPath+"/then",n+=" "+e.validate(h)+" ",h.baseId=_,n+=" "+m+" = "+g+"; ",b&&y?(S="ifClause"+s,n+=" var "+S+" = 'then'; "):S="'then'",n+=" } ",y&&(n+=" else { ")):n+=" if (!"+g+") { ",y&&(h.schema=e.schema.else,h.schemaPath=e.schemaPath+".else",h.errSchemaPath=e.errSchemaPath+"/else",n+=" "+e.validate(h)+" ",h.baseId=_,n+=" "+m+" = "+g+"; ",b&&y?(S="ifClause"+s,n+=" var "+S+" = 'else'; "):S="'else'",n+=" } "),n+=" if (!"+m+") { var err = ",e.createErrors!==!1?(n+=" { keyword: 'if' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { failingKeyword: "+S+" } ",e.opts.messages!==!1&&(n+=` , message: 'should match "' + `+S+` + '" schema' `),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+v+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&d&&(e.async?n+=" throw new ValidationError(vErrors); ":n+=" validate.errors = vErrors; return false; "),n+=" } ",d&&(n+=" else { ")}else d&&(n+=" if (true) { ");return n},RT=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,v="data"+(o||""),m="valid"+s,c="errs__"+s,h=e.util.copy(e),g="";h.level++;var f="valid"+h.level,p="i"+s,b=h.dataLevel=e.dataLevel+1,y="data"+b,_=e.baseId;if(n+="var "+c+" = errors;var "+m+";",Array.isArray(i)){var S=e.schema.additionalItems;if(S===!1){n+=" "+m+" = "+v+".length <= "+i.length+"; ";var T=u;u=e.errSchemaPath+"/additionalItems",n+=" if (!"+m+") { ";var I=I||[];I.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'additionalItems' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { limit: "+i.length+" } ",e.opts.messages!==!1&&(n+=" , message: 'should NOT have more than "+i.length+" items' "),e.opts.verbose&&(n+=" , schema: false , parentSchema: validate.schema"+e.schemaPath+" , data: "+v+" "),n+=" } "):n+=" {} ";var O=n;n=I.pop(),!e.compositeRule&&d?e.async?n+=" throw new ValidationError(["+O+"]); ":n+=" validate.errors = ["+O+"]; return false; ":n+=" var err = "+O+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } ",u=T,d&&(g+="}",n+=" else { ")}var R=i;if(R){for(var L,U=-1,Z=R.length-1;U<Z;)if(L=R[U+=1],e.opts.strictKeywords?typeof L=="object"&&Object.keys(L).length>0||L===!1:e.util.schemaHasRules(L,e.RULES.all)){n+=" "+f+" = true; if ("+v+".length > "+U+") { ";var M=v+"["+U+"]";h.schema=L,h.schemaPath=l+"["+U+"]",h.errSchemaPath=u+"/"+U,h.errorPath=e.util.getPathExpr(e.errorPath,U,e.opts.jsonPointers,!0),h.dataPathArr[b]=U;var j=e.validate(h);h.baseId=_,e.util.varOccurences(j,y)<2?n+=" "+e.util.varReplace(j,y,M)+" ":n+=" var "+y+" = "+M+"; "+j+" ",n+=" } ",d&&(n+=" if ("+f+") { ",g+="}")}}if(typeof S=="object"&&(e.opts.strictKeywords?typeof S=="object"&&Object.keys(S).length>0||S===!1:e.util.schemaHasRules(S,e.RULES.all))){h.schema=S,h.schemaPath=e.schemaPath+".additionalItems",h.errSchemaPath=e.errSchemaPath+"/additionalItems",n+=" "+f+" = true; if ("+v+".length > "+i.length+") { for (var "+p+" = "+i.length+"; "+p+" < "+v+".length; "+p+"++) { ",h.errorPath=e.util.getPathExpr(e.errorPath,p,e.opts.jsonPointers,!0);var M=v+"["+p+"]";h.dataPathArr[b]=p;var j=e.validate(h);h.baseId=_,e.util.varOccurences(j,y)<2?n+=" "+e.util.varReplace(j,y,M)+" ":n+=" var "+y+" = "+M+"; "+j+" ",d&&(n+=" if (!"+f+") break; "),n+=" } } ",d&&(n+=" if ("+f+") { ",g+="}")}}else if(e.opts.strictKeywords?typeof i=="object"&&Object.keys(i).length>0||i===!1:e.util.schemaHasRules(i,e.RULES.all)){h.schema=i,h.schemaPath=l,h.errSchemaPath=u,n+=" for (var "+p+" = 0; "+p+" < "+v+".length; "+p+"++) { ",h.errorPath=e.util.getPathExpr(e.errorPath,p,e.opts.jsonPointers,!0);var M=v+"["+p+"]";h.dataPathArr[b]=p;var j=e.validate(h);h.baseId=_,e.util.varOccurences(j,y)<2?n+=" "+e.util.varReplace(j,y,M)+" ":n+=" var "+y+" = "+M+"; "+j+" ",d&&(n+=" if (!"+f+") break; "),n+=" }"}return d&&(n+=" "+g+" if ("+c+" == errors) {"),n},zf=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,_,v="data"+(o||""),m=e.opts.$data&&i&&i.$data,c;m?(n+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",c="schema"+s):c=i;var h=r=="maximum",g=h?"exclusiveMaximum":"exclusiveMinimum",f=e.schema[g],p=e.opts.$data&&f&&f.$data,b=h?"<":">",y=h?">":"<",_=void 0;if(!(m||typeof i=="number"||i===void 0))throw new Error(r+" must be number");if(!(p||f===void 0||typeof f=="number"||typeof f=="boolean"))throw new Error(g+" must be number or boolean");if(p){var S=e.util.getData(f.$data,o,e.dataPathArr),T="exclusive"+s,I="exclType"+s,O="exclIsNumber"+s,R="op"+s,L="' + "+R+" + '";n+=" var schemaExcl"+s+" = "+S+"; ",S="schemaExcl"+s,n+=" var "+T+"; var "+I+" = typeof "+S+"; if ("+I+" != 'boolean' && "+I+" != 'undefined' && "+I+" != 'number') { ";var _=g,U=U||[];U.push(n),n="",e.createErrors!==!1?(n+=" { keyword: '"+(_||"_exclusiveLimit")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: {} ",e.opts.messages!==!1&&(n+=" , message: '"+g+" should be boolean' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+v+" "),n+=" } "):n+=" {} ";var Z=n;n=U.pop(),!e.compositeRule&&d?e.async?n+=" throw new ValidationError(["+Z+"]); ":n+=" validate.errors = ["+Z+"]; return false; ":n+=" var err = "+Z+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } else if ( ",m&&(n+=" ("+c+" !== undefined && typeof "+c+" != 'number') || "),n+=" "+I+" == 'number' ? ( ("+T+" = "+c+" === undefined || "+S+" "+b+"= "+c+") ? "+v+" "+y+"= "+S+" : "+v+" "+y+" "+c+" ) : ( ("+T+" = "+S+" === true) ? "+v+" "+y+"= "+c+" : "+v+" "+y+" "+c+" ) || "+v+" !== "+v+") { var op"+s+" = "+T+" ? '"+b+"' : '"+b+"='; ",i===void 0&&(_=g,u=e.errSchemaPath+"/"+g,c=S,m=p)}else{var O=typeof f=="number",L=b;if(O&&m){var R="'"+L+"'";n+=" if ( ",m&&(n+=" ("+c+" !== undefined && typeof "+c+" != 'number') || "),n+=" ( "+c+" === undefined || "+f+" "+b+"= "+c+" ? "+v+" "+y+"= "+f+" : "+v+" "+y+" "+c+" ) || "+v+" !== "+v+") { "}else{O&&i===void 0?(T=!0,_=g,u=e.errSchemaPath+"/"+g,c=f,y+="="):(O&&(c=Math[h?"min":"max"](f,i)),f===(O?c:!0)?(T=!0,_=g,u=e.errSchemaPath+"/"+g,y+="="):(T=!1,L+="="));var R="'"+L+"'";n+=" if ( ",m&&(n+=" ("+c+" !== undefined && typeof "+c+" != 'number') || "),n+=" "+v+" "+y+" "+c+" || "+v+" !== "+v+") { "}}_=_||r;var U=U||[];U.push(n),n="",e.createErrors!==!1?(n+=" { keyword: '"+(_||"_limit")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { comparison: "+R+", limit: "+c+", exclusive: "+T+" } ",e.opts.messages!==!1&&(n+=" , message: 'should be "+L+" ",m?n+="' + "+c:n+=""+c+"'"),e.opts.verbose&&(n+=" , schema: ",m?n+="validate.schema"+l:n+=""+i,n+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+v+" "),n+=" } "):n+=" {} ";var Z=n;return n=U.pop(),!e.compositeRule&&d?e.async?n+=" throw new ValidationError(["+Z+"]); ":n+=" validate.errors = ["+Z+"]; return false; ":n+=" var err = "+Z+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } ",d&&(n+=" else { "),n},Lf=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,g,v="data"+(o||""),m=e.opts.$data&&i&&i.$data,c;if(m?(n+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",c="schema"+s):c=i,!(m||typeof i=="number"))throw new Error(r+" must be number");var h=r=="maxItems"?">":"<";n+="if ( ",m&&(n+=" ("+c+" !== undefined && typeof "+c+" != 'number') || "),n+=" "+v+".length "+h+" "+c+") { ";var g=r,f=f||[];f.push(n),n="",e.createErrors!==!1?(n+=" { keyword: '"+(g||"_limitItems")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { limit: "+c+" } ",e.opts.messages!==!1&&(n+=" , message: 'should NOT have ",r=="maxItems"?n+="more":n+="fewer",n+=" than ",m?n+="' + "+c+" + '":n+=""+i,n+=" items' "),e.opts.verbose&&(n+=" , schema: ",m?n+="validate.schema"+l:n+=""+i,n+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+v+" "),n+=" } "):n+=" {} ";var p=n;return n=f.pop(),!e.compositeRule&&d?e.async?n+=" throw new ValidationError(["+p+"]); ":n+=" validate.errors = ["+p+"]; return false; ":n+=" var err = "+p+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+="} ",d&&(n+=" else { "),n},Uf=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,g,v="data"+(o||""),m=e.opts.$data&&i&&i.$data,c;if(m?(n+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",c="schema"+s):c=i,!(m||typeof i=="number"))throw new Error(r+" must be number");var h=r=="maxLength"?">":"<";n+="if ( ",m&&(n+=" ("+c+" !== undefined && typeof "+c+" != 'number') || "),e.opts.unicode===!1?n+=" "+v+".length ":n+=" ucs2length("+v+") ",n+=" "+h+" "+c+") { ";var g=r,f=f||[];f.push(n),n="",e.createErrors!==!1?(n+=" { keyword: '"+(g||"_limitLength")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { limit: "+c+" } ",e.opts.messages!==!1&&(n+=" , message: 'should NOT be ",r=="maxLength"?n+="longer":n+="shorter",n+=" than ",m?n+="' + "+c+" + '":n+=""+i,n+=" characters' "),e.opts.verbose&&(n+=" , schema: ",m?n+="validate.schema"+l:n+=""+i,n+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+v+" "),n+=" } "):n+=" {} ";var p=n;return n=f.pop(),!e.compositeRule&&d?e.async?n+=" throw new ValidationError(["+p+"]); ":n+=" validate.errors = ["+p+"]; return false; ":n+=" var err = "+p+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+="} ",d&&(n+=" else { "),n},Ff=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,g,v="data"+(o||""),m=e.opts.$data&&i&&i.$data,c;if(m?(n+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",c="schema"+s):c=i,!(m||typeof i=="number"))throw new Error(r+" must be number");var h=r=="maxProperties"?">":"<";n+="if ( ",m&&(n+=" ("+c+" !== undefined && typeof "+c+" != 'number') || "),n+=" Object.keys("+v+").length "+h+" "+c+") { ";var g=r,f=f||[];f.push(n),n="",e.createErrors!==!1?(n+=" { keyword: '"+(g||"_limitProperties")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { limit: "+c+" } ",e.opts.messages!==!1&&(n+=" , message: 'should NOT have ",r=="maxProperties"?n+="more":n+="fewer",n+=" than ",m?n+="' + "+c+" + '":n+=""+i,n+=" properties' "),e.opts.verbose&&(n+=" , schema: ",m?n+="validate.schema"+l:n+=""+i,n+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+v+" "),n+=" } "):n+=" {} ";var p=n;return n=f.pop(),!e.compositeRule&&d?e.async?n+=" throw new ValidationError(["+p+"]); ":n+=" validate.errors = ["+p+"]; return false; ":n+=" var err = "+p+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+="} ",d&&(n+=" else { "),n},OT=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,v="data"+(o||""),m=e.opts.$data&&i&&i.$data,c;if(m?(n+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",c="schema"+s):c=i,!(m||typeof i=="number"))throw new Error(r+" must be number");n+="var division"+s+";if (",m&&(n+=" "+c+" !== undefined && ( typeof "+c+" != 'number' || "),n+=" (division"+s+" = "+v+" / "+c+", ",e.opts.multipleOfPrecision?n+=" Math.abs(Math.round(division"+s+") - division"+s+") > 1e-"+e.opts.multipleOfPrecision+" ":n+=" division"+s+" !== parseInt(division"+s+") ",n+=" ) ",m&&(n+=" ) "),n+=" ) { ";var h=h||[];h.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'multipleOf' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { multipleOf: "+c+" } ",e.opts.messages!==!1&&(n+=" , message: 'should be multiple of ",m?n+="' + "+c:n+=""+c+"'"),e.opts.verbose&&(n+=" , schema: ",m?n+="validate.schema"+l:n+=""+i,n+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+v+" "),n+=" } "):n+=" {} ";var g=n;return n=h.pop(),!e.compositeRule&&d?e.async?n+=" throw new ValidationError(["+g+"]); ":n+=" validate.errors = ["+g+"]; return false; ":n+=" var err = "+g+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+="} ",d&&(n+=" else { "),n},$T=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,v="data"+(o||""),m="errs__"+s,c=e.util.copy(e);c.level++;var h="valid"+c.level;if(e.opts.strictKeywords?typeof i=="object"&&Object.keys(i).length>0||i===!1:e.util.schemaHasRules(i,e.RULES.all)){c.schema=i,c.schemaPath=l,c.errSchemaPath=u,n+=" var "+m+" = errors; ";var g=e.compositeRule;e.compositeRule=c.compositeRule=!0,c.createErrors=!1;var f;c.opts.allErrors&&(f=c.opts.allErrors,c.opts.allErrors=!1),n+=" "+e.validate(c)+" ",c.createErrors=!0,f&&(c.opts.allErrors=f),e.compositeRule=c.compositeRule=g,n+=" if ("+h+") { ";var p=p||[];p.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'not' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: {} ",e.opts.messages!==!1&&(n+=" , message: 'should NOT be valid' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+v+" "),n+=" } "):n+=" {} ";var b=n;n=p.pop(),!e.compositeRule&&d?e.async?n+=" throw new ValidationError(["+b+"]); ":n+=" validate.errors = ["+b+"]; return false; ":n+=" var err = "+b+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } else { errors = "+m+"; if (vErrors !== null) { if ("+m+") vErrors.length = "+m+"; else vErrors = null; } ",e.opts.allErrors&&(n+=" } ")}else n+=" var err = ",e.createErrors!==!1?(n+=" { keyword: 'not' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: {} ",e.opts.messages!==!1&&(n+=" , message: 'should NOT be valid' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+v+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",d&&(n+=" if (false) { ");return n},AT=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,v="data"+(o||""),m="valid"+s,c="errs__"+s,h=e.util.copy(e),g="";h.level++;var f="valid"+h.level,p=h.baseId,b="prevValid"+s,y="passingSchemas"+s;n+="var "+c+" = errors , "+b+" = false , "+m+" = false , "+y+" = null; ";var _=e.compositeRule;e.compositeRule=h.compositeRule=!0;var S=i;if(S)for(var T,I=-1,O=S.length-1;I<O;)T=S[I+=1],(e.opts.strictKeywords?typeof T=="object"&&Object.keys(T).length>0||T===!1:e.util.schemaHasRules(T,e.RULES.all))?(h.schema=T,h.schemaPath=l+"["+I+"]",h.errSchemaPath=u+"/"+I,n+=" "+e.validate(h)+" ",h.baseId=p):n+=" var "+f+" = true; ",I&&(n+=" if ("+f+" && "+b+") { "+m+" = false; "+y+" = ["+y+", "+I+"]; } else { ",g+="}"),n+=" if ("+f+") { "+m+" = "+b+" = true; "+y+" = "+I+"; }";return e.compositeRule=h.compositeRule=_,n+=""+g+"if (!"+m+") { var err = ",e.createErrors!==!1?(n+=" { keyword: 'oneOf' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { passingSchemas: "+y+" } ",e.opts.messages!==!1&&(n+=" , message: 'should match exactly one schema in oneOf' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+v+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&d&&(e.async?n+=" throw new ValidationError(vErrors); ":n+=" validate.errors = vErrors; return false; "),n+="} else { errors = "+c+"; if (vErrors !== null) { if ("+c+") vErrors.length = "+c+"; else vErrors = null; }",e.opts.allErrors&&(n+=" } "),n},NT=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,v="data"+(o||""),m=e.opts.$data&&i&&i.$data,c;m?(n+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",c="schema"+s):c=i;var h=m?"(new RegExp("+c+"))":e.usePattern(i);n+="if ( ",m&&(n+=" ("+c+" !== undefined && typeof "+c+" != 'string') || "),n+=" !"+h+".test("+v+") ) { ";var g=g||[];g.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'pattern' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { pattern: ",m?n+=""+c:n+=""+e.util.toQuotedString(i),n+=" } ",e.opts.messages!==!1&&(n+=` , message: 'should match pattern "`,m?n+="' + "+c+" + '":n+=""+e.util.escapeQuotes(i),n+=`"' `),e.opts.verbose&&(n+=" , schema: ",m?n+="validate.schema"+l:n+=""+e.util.toQuotedString(i),n+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+v+" "),n+=" } "):n+=" {} ";var f=n;return n=g.pop(),!e.compositeRule&&d?e.async?n+=" throw new ValidationError(["+f+"]); ":n+=" validate.errors = ["+f+"]; return false; ":n+=" var err = "+f+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+="} ",d&&(n+=" else { "),n},MT=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,v="data"+(o||""),m="errs__"+s,c=e.util.copy(e),h="";c.level++;var g="valid"+c.level,f="key"+s,p="idx"+s,b=c.dataLevel=e.dataLevel+1,y="data"+b,_="dataProperties"+s,S=Object.keys(i||{}).filter(te),T=e.schema.patternProperties||{},I=Object.keys(T).filter(te),O=e.schema.additionalProperties,R=S.length||I.length,L=O===!1,U=typeof O=="object"&&Object.keys(O).length,Z=e.opts.removeAdditional,M=L||U||Z,j=e.opts.ownProperties,F=e.baseId,X=e.schema.required;if(X&&!(e.opts.$data&&X.$data)&&X.length<e.opts.loopRequired)var Y=e.util.toHash(X);function te(wt){return wt!=="__proto__"}if(n+="var "+m+" = errors;var "+g+" = true;",j&&(n+=" var "+_+" = undefined;"),M){if(j?n+=" "+_+" = "+_+" || Object.keys("+v+"); for (var "+p+"=0; "+p+"<"+_+".length; "+p+"++) { var "+f+" = "+_+"["+p+"]; ":n+=" for (var "+f+" in "+v+") { ",R){if(n+=" var isAdditional"+s+" = !(false ",S.length)if(S.length>8)n+=" || validate.schema"+l+".hasOwnProperty("+f+") ";else{var oe=S;if(oe)for(var J,pe=-1,ie=oe.length-1;pe<ie;)J=oe[pe+=1],n+=" || "+f+" == "+e.util.toQuotedString(J)+" "}if(I.length){var xe=I;if(xe)for(var C,ae=-1,ge=xe.length-1;ae<ge;)C=xe[ae+=1],n+=" || "+e.usePattern(C)+".test("+f+") "}n+=" ); if (isAdditional"+s+") { "}if(Z=="all")n+=" delete "+v+"["+f+"]; ";else{var fe=e.errorPath,ke="' + "+f+" + '";if(e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPathExpr(e.errorPath,f,e.opts.jsonPointers)),L)if(Z)n+=" delete "+v+"["+f+"]; ";else{n+=" "+g+" = false; ";var vt=u;u=e.errSchemaPath+"/additionalProperties";var Me=Me||[];Me.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'additionalProperties' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { additionalProperty: '"+ke+"' } ",e.opts.messages!==!1&&(n+=" , message: '",e.opts._errorDataPathProperty?n+="is an invalid additional property":n+="should NOT have additional properties",n+="' "),e.opts.verbose&&(n+=" , schema: false , parentSchema: validate.schema"+e.schemaPath+" , data: "+v+" "),n+=" } "):n+=" {} ";var Ee=n;n=Me.pop(),!e.compositeRule&&d?e.async?n+=" throw new ValidationError(["+Ee+"]); ":n+=" validate.errors = ["+Ee+"]; return false; ":n+=" var err = "+Ee+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",u=vt,d&&(n+=" break; ")}else if(U)if(Z=="failing"){n+=" var "+m+" = errors; ";var Tt=e.compositeRule;e.compositeRule=c.compositeRule=!0,c.schema=O,c.schemaPath=e.schemaPath+".additionalProperties",c.errSchemaPath=e.errSchemaPath+"/additionalProperties",c.errorPath=e.opts._errorDataPathProperty?e.errorPath:e.util.getPathExpr(e.errorPath,f,e.opts.jsonPointers);var Se=v+"["+f+"]";c.dataPathArr[b]=f;var ue=e.validate(c);c.baseId=F,e.util.varOccurences(ue,y)<2?n+=" "+e.util.varReplace(ue,y,Se)+" ":n+=" var "+y+" = "+Se+"; "+ue+" ",n+=" if (!"+g+") { errors = "+m+"; if (validate.errors !== null) { if (errors) validate.errors.length = errors; else validate.errors = null; } delete "+v+"["+f+"]; } ",e.compositeRule=c.compositeRule=Tt}else{c.schema=O,c.schemaPath=e.schemaPath+".additionalProperties",c.errSchemaPath=e.errSchemaPath+"/additionalProperties",c.errorPath=e.opts._errorDataPathProperty?e.errorPath:e.util.getPathExpr(e.errorPath,f,e.opts.jsonPointers);var Se=v+"["+f+"]";c.dataPathArr[b]=f;var ue=e.validate(c);c.baseId=F,e.util.varOccurences(ue,y)<2?n+=" "+e.util.varReplace(ue,y,Se)+" ":n+=" var "+y+" = "+Se+"; "+ue+" ",d&&(n+=" if (!"+g+") break; ")}e.errorPath=fe}R&&(n+=" } "),n+=" } ",d&&(n+=" if ("+g+") { ",h+="}")}var Pe=e.opts.useDefaults&&!e.compositeRule;if(S.length){var Ce=S;if(Ce)for(var J,be=-1,et=Ce.length-1;be<et;){J=Ce[be+=1];var Le=i[J];if(e.opts.strictKeywords?typeof Le=="object"&&Object.keys(Le).length>0||Le===!1:e.util.schemaHasRules(Le,e.RULES.all)){var G=e.util.getProperty(J),Se=v+G,De=Pe&&Le.default!==void 0;c.schema=Le,c.schemaPath=l+G,c.errSchemaPath=u+"/"+e.util.escapeFragment(J),c.errorPath=e.util.getPath(e.errorPath,J,e.opts.jsonPointers),c.dataPathArr[b]=e.util.toQuotedString(J);var ue=e.validate(c);if(c.baseId=F,e.util.varOccurences(ue,y)<2){ue=e.util.varReplace(ue,y,Se);var Ue=Se}else{var Ue=y;n+=" var "+y+" = "+Se+"; "}if(De)n+=" "+ue+" ";else{if(Y&&Y[J]){n+=" if ( "+Ue+" === undefined ",j&&(n+=" || ! Object.prototype.hasOwnProperty.call("+v+", '"+e.util.escapeQuotes(J)+"') "),n+=") { "+g+" = false; ";var fe=e.errorPath,vt=u,me=e.util.escapeQuotes(J);e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPath(fe,J,e.opts.jsonPointers)),u=e.errSchemaPath+"/required";var Me=Me||[];Me.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { missingProperty: '"+me+"' } ",e.opts.messages!==!1&&(n+=" , message: '",e.opts._errorDataPathProperty?n+="is a required property":n+="should have required property \\'"+me+"\\'",n+="' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+v+" "),n+=" } "):n+=" {} ";var Ee=n;n=Me.pop(),!e.compositeRule&&d?e.async?n+=" throw new ValidationError(["+Ee+"]); ":n+=" validate.errors = ["+Ee+"]; return false; ":n+=" var err = "+Ee+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",u=vt,e.errorPath=fe,n+=" } else { "}else d?(n+=" if ( "+Ue+" === undefined ",j&&(n+=" || ! Object.prototype.hasOwnProperty.call("+v+", '"+e.util.escapeQuotes(J)+"') "),n+=") { "+g+" = true; } else { "):(n+=" if ("+Ue+" !== undefined ",j&&(n+=" && Object.prototype.hasOwnProperty.call("+v+", '"+e.util.escapeQuotes(J)+"') "),n+=" ) { ");n+=" "+ue+" } "}}d&&(n+=" if ("+g+") { ",h+="}")}}if(I.length){var Be=I;if(Be)for(var C,br=-1,Ht=Be.length-1;br<Ht;){C=Be[br+=1];var Le=T[C];if(e.opts.strictKeywords?typeof Le=="object"&&Object.keys(Le).length>0||Le===!1:e.util.schemaHasRules(Le,e.RULES.all)){c.schema=Le,c.schemaPath=e.schemaPath+".patternProperties"+e.util.getProperty(C),c.errSchemaPath=e.errSchemaPath+"/patternProperties/"+e.util.escapeFragment(C),j?n+=" "+_+" = "+_+" || Object.keys("+v+"); for (var "+p+"=0; "+p+"<"+_+".length; "+p+"++) { var "+f+" = "+_+"["+p+"]; ":n+=" for (var "+f+" in "+v+") { ",n+=" if ("+e.usePattern(C)+".test("+f+")) { ",c.errorPath=e.util.getPathExpr(e.errorPath,f,e.opts.jsonPointers);var Se=v+"["+f+"]";c.dataPathArr[b]=f;var ue=e.validate(c);c.baseId=F,e.util.varOccurences(ue,y)<2?n+=" "+e.util.varReplace(ue,y,Se)+" ":n+=" var "+y+" = "+Se+"; "+ue+" ",d&&(n+=" if (!"+g+") break; "),n+=" } ",d&&(n+=" else "+g+" = true; "),n+=" } ",d&&(n+=" if ("+g+") { ",h+="}")}}}return d&&(n+=" "+h+" if ("+m+" == errors) {"),n},DT=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,v="data"+(o||""),m="errs__"+s,c=e.util.copy(e),h="";c.level++;var g="valid"+c.level;if(n+="var "+m+" = errors;",e.opts.strictKeywords?typeof i=="object"&&Object.keys(i).length>0||i===!1:e.util.schemaHasRules(i,e.RULES.all)){c.schema=i,c.schemaPath=l,c.errSchemaPath=u;var f="key"+s,p="idx"+s,b="i"+s,y="' + "+f+" + '",_=c.dataLevel=e.dataLevel+1,S="data"+_,T="dataProperties"+s,I=e.opts.ownProperties,O=e.baseId;I&&(n+=" var "+T+" = undefined; "),I?n+=" "+T+" = "+T+" || Object.keys("+v+"); for (var "+p+"=0; "+p+"<"+T+".length; "+p+"++) { var "+f+" = "+T+"["+p+"]; ":n+=" for (var "+f+" in "+v+") { ",n+=" var startErrs"+s+" = errors; ";var R=f,L=e.compositeRule;e.compositeRule=c.compositeRule=!0;var U=e.validate(c);c.baseId=O,e.util.varOccurences(U,S)<2?n+=" "+e.util.varReplace(U,S,R)+" ":n+=" var "+S+" = "+R+"; "+U+" ",e.compositeRule=c.compositeRule=L,n+=" if (!"+g+") { for (var "+b+"=startErrs"+s+"; "+b+"<errors; "+b+"++) { vErrors["+b+"].propertyName = "+f+"; } var err = ",e.createErrors!==!1?(n+=" { keyword: 'propertyNames' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { propertyName: '"+y+"' } ",e.opts.messages!==!1&&(n+=" , message: 'property name \\'"+y+"\\' is invalid' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+v+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&d&&(e.async?n+=" throw new ValidationError(vErrors); ":n+=" validate.errors = vErrors; return false; "),d&&(n+=" break; "),n+=" } }"}return d&&(n+=" "+h+" if ("+m+" == errors) {"),n},jT=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,v="data"+(o||""),m="valid"+s,c=e.opts.$data&&i&&i.$data;c&&(n+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ");var h="schema"+s;if(!c)if(i.length<e.opts.loopRequired&&e.schema.properties&&Object.keys(e.schema.properties).length){var g=[],f=i;if(f)for(var p,b=-1,y=f.length-1;b<y;){p=f[b+=1];var _=e.schema.properties[p];_&&(e.opts.strictKeywords?typeof _=="object"&&Object.keys(_).length>0||_===!1:e.util.schemaHasRules(_,e.RULES.all))||(g[g.length]=p)}}else var g=i;if(c||g.length){var S=e.errorPath,T=c||g.length>=e.opts.loopRequired,I=e.opts.ownProperties;if(d)if(n+=" var missing"+s+"; ",T){c||(n+=" var "+h+" = validate.schema"+l+"; ");var O="i"+s,R="schema"+s+"["+O+"]",L="' + "+R+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPathExpr(S,R,e.opts.jsonPointers)),n+=" var "+m+" = true; ",c&&(n+=" if (schema"+s+" === undefined) "+m+" = true; else if (!Array.isArray(schema"+s+")) "+m+" = false; else {"),n+=" for (var "+O+" = 0; "+O+" < "+h+".length; "+O+"++) { "+m+" = "+v+"["+h+"["+O+"]] !== undefined ",I&&(n+=" && Object.prototype.hasOwnProperty.call("+v+", "+h+"["+O+"]) "),n+="; if (!"+m+") break; } ",c&&(n+=" } "),n+=" if (!"+m+") { ";var U=U||[];U.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { missingProperty: '"+L+"' } ",e.opts.messages!==!1&&(n+=" , message: '",e.opts._errorDataPathProperty?n+="is a required property":n+="should have required property \\'"+L+"\\'",n+="' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+v+" "),n+=" } "):n+=" {} ";var Z=n;n=U.pop(),!e.compositeRule&&d?e.async?n+=" throw new ValidationError(["+Z+"]); ":n+=" validate.errors = ["+Z+"]; return false; ":n+=" var err = "+Z+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } else { "}else{n+=" if ( ";var M=g;if(M)for(var j,O=-1,F=M.length-1;O<F;){j=M[O+=1],O&&(n+=" || ");var X=e.util.getProperty(j),Y=v+X;n+=" ( ( "+Y+" === undefined ",I&&(n+=" || ! Object.prototype.hasOwnProperty.call("+v+", '"+e.util.escapeQuotes(j)+"') "),n+=") && (missing"+s+" = "+e.util.toQuotedString(e.opts.jsonPointers?j:X)+") ) "}n+=") { ";var R="missing"+s,L="' + "+R+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.opts.jsonPointers?e.util.getPathExpr(S,R,!0):S+" + "+R);var U=U||[];U.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { missingProperty: '"+L+"' } ",e.opts.messages!==!1&&(n+=" , message: '",e.opts._errorDataPathProperty?n+="is a required property":n+="should have required property \\'"+L+"\\'",n+="' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+v+" "),n+=" } "):n+=" {} ";var Z=n;n=U.pop(),!e.compositeRule&&d?e.async?n+=" throw new ValidationError(["+Z+"]); ":n+=" validate.errors = ["+Z+"]; return false; ":n+=" var err = "+Z+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } else { "}else if(T){c||(n+=" var "+h+" = validate.schema"+l+"; ");var O="i"+s,R="schema"+s+"["+O+"]",L="' + "+R+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPathExpr(S,R,e.opts.jsonPointers)),c&&(n+=" if ("+h+" && !Array.isArray("+h+")) { var err = ",e.createErrors!==!1?(n+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { missingProperty: '"+L+"' } ",e.opts.messages!==!1&&(n+=" , message: '",e.opts._errorDataPathProperty?n+="is a required property":n+="should have required property \\'"+L+"\\'",n+="' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+v+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else if ("+h+" !== undefined) { "),n+=" for (var "+O+" = 0; "+O+" < "+h+".length; "+O+"++) { if ("+v+"["+h+"["+O+"]] === undefined ",I&&(n+=" || ! Object.prototype.hasOwnProperty.call("+v+", "+h+"["+O+"]) "),n+=") { var err = ",e.createErrors!==!1?(n+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { missingProperty: '"+L+"' } ",e.opts.messages!==!1&&(n+=" , message: '",e.opts._errorDataPathProperty?n+="is a required property":n+="should have required property \\'"+L+"\\'",n+="' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+v+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } } ",c&&(n+=" } ")}else{var te=g;if(te)for(var j,oe=-1,J=te.length-1;oe<J;){j=te[oe+=1];var X=e.util.getProperty(j),L=e.util.escapeQuotes(j),Y=v+X;e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPath(S,j,e.opts.jsonPointers)),n+=" if ( "+Y+" === undefined ",I&&(n+=" || ! Object.prototype.hasOwnProperty.call("+v+", '"+e.util.escapeQuotes(j)+"') "),n+=") { var err = ",e.createErrors!==!1?(n+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { missingProperty: '"+L+"' } ",e.opts.messages!==!1&&(n+=" , message: '",e.opts._errorDataPathProperty?n+="is a required property":n+="should have required property \\'"+L+"\\'",n+="' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+v+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } "}}e.errorPath=S}else d&&(n+=" if (true) {");return n},zT=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,v="data"+(o||""),m="valid"+s,c=e.opts.$data&&i&&i.$data,h;if(c?(n+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",h="schema"+s):h=i,(i||c)&&e.opts.uniqueItems!==!1){c&&(n+=" var "+m+"; if ("+h+" === false || "+h+" === undefined) "+m+" = true; else if (typeof "+h+" != 'boolean') "+m+" = false; else { "),n+=" var i = "+v+".length , "+m+" = true , j; if (i > 1) { ";var g=e.schema.items&&e.schema.items.type,f=Array.isArray(g);if(!g||g=="object"||g=="array"||f&&(g.indexOf("object")>=0||g.indexOf("array")>=0))n+=" outer: for (;i--;) { for (j = i; j--;) { if (equal("+v+"[i], "+v+"[j])) { "+m+" = false; break outer; } } } ";else{n+=" var itemIndices = {}, item; for (;i--;) { var item = "+v+"[i]; ";var p="checkDataType"+(f?"s":"");n+=" if ("+e.util[p](g,"item",e.opts.strictNumbers,!0)+") continue; ",f&&(n+=` if (typeof item == 'string') item = '"' + item; `),n+=" if (typeof itemIndices[item] == 'number') { "+m+" = false; j = itemIndices[item]; break; } itemIndices[item] = i; } "}n+=" } ",c&&(n+=" } "),n+=" if (!"+m+") { ";var b=b||[];b.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'uniqueItems' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { i: i, j: j } ",e.opts.messages!==!1&&(n+=" , message: 'should NOT have duplicate items (items ## ' + j + ' and ' + i + ' are identical)' "),e.opts.verbose&&(n+=" , schema: ",c?n+="validate.schema"+l:n+=""+i,n+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+v+" "),n+=" } "):n+=" {} ";var y=n;n=b.pop(),!e.compositeRule&&d?e.async?n+=" throw new ValidationError(["+y+"]); ":n+=" validate.errors = ["+y+"]; return false; ":n+=" var err = "+y+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } ",d&&(n+=" else { ")}else d&&(n+=" if (true) { ");return n},LT={$ref:wT,allOf:bT,anyOf:xT,$comment:ET,const:ST,contains:IT,dependencies:kT,enum:TT,format:PT,if:CT,items:RT,maximum:zf,minimum:zf,maxItems:Lf,minItems:Lf,maxLength:Uf,minLength:Uf,maxProperties:Ff,minProperties:Ff,multipleOf:OT,not:$T,oneOf:AT,pattern:NT,properties:MT,propertyNames:DT,required:jT,uniqueItems:zT,validate:Ef},qf=LT,gl=Nn.toHash,UT=function(){var e=[{type:"number",rules:[{maximum:["exclusiveMaximum"]},{minimum:["exclusiveMinimum"]},"multipleOf","format"]},{type:"string",rules:["maxLength","minLength","pattern","format"]},{type:"array",rules:["maxItems","minItems","items","contains","uniqueItems"]},{type:"object",rules:["maxProperties","minProperties","required","dependencies","propertyNames",{properties:["additionalProperties","patternProperties"]}]},{rules:["$ref","const","enum","not","anyOf","oneOf","allOf","if"]}],r=["type","$comment"],a=["$schema","$id","id","$data","$async","title","description","default","definitions","examples","readOnly","writeOnly","contentMediaType","contentEncoding","additionalItems","then","else"],n=["number","integer","string","array","object","boolean","null"];return e.all=gl(r),e.types=gl(n),e.forEach(function(s){s.rules=s.rules.map(function(o){var i;if(typeof o=="object"){var l=Object.keys(o)[0];i=o[l],o=l,i.forEach(function(d){r.push(d),e.all[d]=!0})}r.push(o);var u=e.all[o]={keyword:o,code:qf[o],implements:i};return u}),e.all.$comment={keyword:"$comment",code:qf.$comment},s.type&&(e.types[s.type]=s)}),e.keywords=gl(r.concat(a)),e.custom={},e},Zf=["multipleOf","maximum","exclusiveMaximum","minimum","exclusiveMinimum","maxLength","minLength","pattern","additionalItems","maxItems","minItems","uniqueItems","maxProperties","minProperties","required","additionalProperties","enum","format","const"],FT=function(t,e){for(var r=0;r<e.length;r++){t=JSON.parse(JSON.stringify(t));var a=e[r].split("/"),n=t,s;for(s=1;s<a.length;s++)n=n[a[s]];for(s=0;s<Zf.length;s++){var o=Zf[s],i=n[o];i&&(n[o]={anyOf:[i,{$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"}]})}}return t},qT=fl.MissingRef,ZT=Vf;function Vf(t,e,r){var a=this;if(typeof this._opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");typeof e=="function"&&(r=e,e=void 0);var n=s(t).then(function(){var i=a._addSchema(t,void 0,e);return i.validate||o(i)});return r&&n.then(function(i){r(null,i)},r),n;function s(i){var l=i.$schema;return l&&!a.getSchema(l)?Vf.call(a,{$ref:l},!0):Promise.resolve()}function o(i){try{return a._compile(i)}catch(u){if(u instanceof qT)return l(u);throw u}function l(u){var d=u.missingSchema;if(c(d))throw new Error("Schema "+d+" is loaded but "+u.missingRef+" cannot be resolved");var v=a._loadingSchemas[d];return v||(v=a._loadingSchemas[d]=a._opts.loadSchema(d),v.then(m,m)),v.then(function(h){if(!c(d))return s(h).then(function(){c(d)||a.addSchema(h,d,void 0,e)})}).then(function(){return o(i)});function m(){delete a._loadingSchemas[d]}function c(h){return a._refs[h]||a._schemas[h]}}}}var VT=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,v,m="data"+(o||""),c="valid"+s,h="errs__"+s,g=e.opts.$data&&i&&i.$data,f;g?(n+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",f="schema"+s):f=i;var p=this,b="definition"+s,y=p.definition,_="",S,T,I,O,R;if(g&&y.$data){R="keywordValidate"+s;var L=y.validateSchema;n+=" var "+b+" = RULES.custom['"+r+"'].definition; var "+R+" = "+b+".validate;"}else{if(O=e.useCustomRule(p,i,e.schema,e),!O)return;f="validate.schema"+l,R=O.code,S=y.compile,T=y.inline,I=y.macro}var U=R+".errors",Z="i"+s,M="ruleErr"+s,j=y.async;if(j&&!e.async)throw new Error("async keyword in sync schema");if(T||I||(n+=""+U+" = null;"),n+="var "+h+" = errors;var "+c+";",g&&y.$data&&(_+="}",n+=" if ("+f+" === undefined) { "+c+" = true; } else { ",L&&(_+="}",n+=" "+c+" = "+b+".validateSchema("+f+"); if ("+c+") { ")),T)y.statements?n+=" "+O.validate+" ":n+=" "+c+" = "+O.validate+"; ";else if(I){var F=e.util.copy(e),_="";F.level++;var X="valid"+F.level;F.schema=O.validate,F.schemaPath="";var Y=e.compositeRule;e.compositeRule=F.compositeRule=!0;var te=e.validate(F).replace(/validate\.schema/g,R);e.compositeRule=F.compositeRule=Y,n+=" "+te}else{var oe=oe||[];oe.push(n),n="",n+=" "+R+".call( ",e.opts.passContext?n+="this":n+="self",S||y.schema===!1?n+=" , "+m+" ":n+=" , "+f+" , "+m+" , validate.schema"+e.schemaPath+" ",n+=" , (dataPath || '')",e.errorPath!='""'&&(n+=" + "+e.errorPath);var J=o?"data"+(o-1||""):"parentData",pe=o?e.dataPathArr[o]:"parentDataProperty";n+=" , "+J+" , "+pe+" , rootData ) ";var ie=n;n=oe.pop(),y.errors===!1?(n+=" "+c+" = ",j&&(n+="await "),n+=""+ie+"; "):j?(U="customErrors"+s,n+=" var "+U+" = null; try { "+c+" = await "+ie+"; } catch (e) { "+c+" = false; if (e instanceof ValidationError) "+U+" = e.errors; else throw e; } "):n+=" "+U+" = null; "+c+" = "+ie+"; "}if(y.modifying&&(n+=" if ("+J+") "+m+" = "+J+"["+pe+"];"),n+=""+_,y.valid)d&&(n+=" if (true) { ");else{n+=" if ( ",y.valid===void 0?(n+=" !",I?n+=""+X:n+=""+c):n+=" "+!y.valid+" ",n+=") { ",v=p.keyword;var oe=oe||[];oe.push(n),n="";var oe=oe||[];oe.push(n),n="",e.createErrors!==!1?(n+=" { keyword: '"+(v||"custom")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { keyword: '"+p.keyword+"' } ",e.opts.messages!==!1&&(n+=` , message: 'should pass "`+p.keyword+`" keyword validation' `),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+m+" "),n+=" } "):n+=" {} ";var xe=n;n=oe.pop(),!e.compositeRule&&d?e.async?n+=" throw new ValidationError(["+xe+"]); ":n+=" validate.errors = ["+xe+"]; return false; ":n+=" var err = "+xe+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";var C=n;n=oe.pop(),T?y.errors?y.errors!="full"&&(n+=" for (var "+Z+"="+h+"; "+Z+"<errors; "+Z+"++) { var "+M+" = vErrors["+Z+"]; if ("+M+".dataPath === undefined) "+M+".dataPath = (dataPath || '') + "+e.errorPath+"; if ("+M+".schemaPath === undefined) { "+M+'.schemaPath = "'+u+'"; } ',e.opts.verbose&&(n+=" "+M+".schema = "+f+"; "+M+".data = "+m+"; "),n+=" } "):y.errors===!1?n+=" "+C+" ":(n+=" if ("+h+" == errors) { "+C+" } else { for (var "+Z+"="+h+"; "+Z+"<errors; "+Z+"++) { var "+M+" = vErrors["+Z+"]; if ("+M+".dataPath === undefined) "+M+".dataPath = (dataPath || '') + "+e.errorPath+"; if ("+M+".schemaPath === undefined) { "+M+'.schemaPath = "'+u+'"; } ',e.opts.verbose&&(n+=" "+M+".schema = "+f+"; "+M+".data = "+m+"; "),n+=" } } "):I?(n+=" var err = ",e.createErrors!==!1?(n+=" { keyword: '"+(v||"custom")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { keyword: '"+p.keyword+"' } ",e.opts.messages!==!1&&(n+=` , message: 'should pass "`+p.keyword+`" keyword validation' `),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+m+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&d&&(e.async?n+=" throw new ValidationError(vErrors); ":n+=" validate.errors = vErrors; return false; ")):y.errors===!1?n+=" "+C+" ":(n+=" if (Array.isArray("+U+")) { if (vErrors === null) vErrors = "+U+"; else vErrors = vErrors.concat("+U+"); errors = vErrors.length; for (var "+Z+"="+h+"; "+Z+"<errors; "+Z+"++) { var "+M+" = vErrors["+Z+"]; if ("+M+".dataPath === undefined) "+M+".dataPath = (dataPath || '') + "+e.errorPath+"; "+M+'.schemaPath = "'+u+'"; ',e.opts.verbose&&(n+=" "+M+".schema = "+f+"; "+M+".data = "+m+"; "),n+=" } } else { "+C+" } "),n+=" } ",d&&(n+=" else { ")}return n};const Bf={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0};var Hf=Bf,BT={$id:"https://github.com/ajv-validator/ajv/blob/master/lib/definition_schema.js",definitions:{simpleTypes:Hf.definitions.simpleTypes},type:"object",dependencies:{schema:["validate"],$data:["validate"],statements:["inline"],valid:{not:{required:["macro"]}}},properties:{type:Hf.properties.type,schema:{type:"boolean"},statements:{type:"boolean"},dependencies:{type:"array",items:{type:"string"}},metaSchema:{type:"object"},modifying:{type:"boolean"},valid:{type:"boolean"},$data:{type:"boolean"},async:{type:"boolean"},errors:{anyOf:[{type:"boolean"},{const:"full"}]}}},HT=/^[a-z_$][a-z0-9_$-]*$/i,JT=VT,WT=BT,GT={add:KT,get:QT,remove:YT,validate:yl};function KT(t,e){var r=this.RULES;if(r.keywords[t])throw new Error("Keyword "+t+" is already defined");if(!HT.test(t))throw new Error("Keyword "+t+" is not a valid identifier");if(e){this.validateKeyword(e,!0);var a=e.type;if(Array.isArray(a))for(var n=0;n<a.length;n++)o(t,a[n],e);else o(t,a,e);var s=e.metaSchema;s&&(e.$data&&this._opts.$data&&(s={anyOf:[s,{$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"}]}),e.validateSchema=this.compile(s,!0))}r.keywords[t]=r.all[t]=!0;function o(i,l,u){for(var d,v=0;v<r.length;v++){var m=r[v];if(m.type==l){d=m;break}}d||(d={type:l,rules:[]},r.push(d));var c={keyword:i,definition:u,custom:!0,code:JT,implements:u.implements};d.rules.push(c),r.custom[i]=c}return this}function QT(t){var e=this.RULES.custom[t];return e?e.definition:this.RULES.keywords[t]||!1}function YT(t){var e=this.RULES;delete e.keywords[t],delete e.all[t],delete e.custom[t];for(var r=0;r<e.length;r++)for(var a=e[r].rules,n=0;n<a.length;n++)if(a[n].keyword==t){a.splice(n,1);break}return this}function yl(t,e){yl.errors=null;var r=this._validateKeyword=this._validateKeyword||this.compile(WT,!0);if(r(t))return!0;if(yl.errors=r.errors,e)throw new Error("custom keyword definition is invalid: "+this.errorsText(r.errors));return!1}const XT={$schema:"http://json-schema.org/draft-07/schema#",$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON Schema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1};var Jf=Xk,mn=ul,eP=oT,Wf=vf,tP=xf,rP=hT,nP=UT,Gf=FT,Kf=Nn,aP=tt;tt.prototype.validate=oP,tt.prototype.compile=iP,tt.prototype.addSchema=lP,tt.prototype.addMetaSchema=uP,tt.prototype.validateSchema=cP,tt.prototype.getSchema=pP,tt.prototype.removeSchema=fP,tt.prototype.addFormat=xP,tt.prototype.errorsText=bP,tt.prototype._addSchema=mP,tt.prototype._compile=vP,tt.prototype.compileAsync=ZT;var Ws=GT;tt.prototype.addKeyword=Ws.add,tt.prototype.getKeyword=Ws.get,tt.prototype.removeKeyword=Ws.remove,tt.prototype.validateKeyword=Ws.validate;var Qf=fl;tt.ValidationError=Qf.Validation,tt.MissingRefError=Qf.MissingRef,tt.$dataMetaSchema=Gf;var Gs="http://json-schema.org/draft-07/schema",Yf=["removeAdditional","useDefaults","coerceTypes","strictDefaults"],sP=["/properties"];function tt(t){if(!(this instanceof tt))return new tt(t);t=this._opts=Kf.copy(t)||{},PP(this),this._schemas={},this._refs={},this._fragments={},this._formats=rP(t.format),this._cache=t.cache||new eP,this._loadingSchemas={},this._compilations=[],this.RULES=nP(),this._getId=gP(t),t.loopRequired=t.loopRequired||1/0,t.errorDataPath=="property"&&(t._errorDataPathProperty=!0),t.serialize===void 0&&(t.serialize=tP),this._metaOpts=TP(this),t.formats&&IP(this),t.keywords&&kP(this),EP(this),typeof t.meta=="object"&&this.addMetaSchema(t.meta),t.nullable&&this.addKeyword("nullable",{metaSchema:{type:"boolean"}}),SP(this)}function oP(t,e){var r;if(typeof t=="string"){if(r=this.getSchema(t),!r)throw new Error('no schema with key or ref "'+t+'"')}else{var a=this._addSchema(t);r=a.validate||this._compile(a)}var n=r(e);return r.$async!==!0&&(this.errors=r.errors),n}function iP(t,e){var r=this._addSchema(t,void 0,e);return r.validate||this._compile(r)}function lP(t,e,r,a){if(Array.isArray(t)){for(var n=0;n<t.length;n++)this.addSchema(t[n],void 0,r,a);return this}var s=this._getId(t);if(s!==void 0&&typeof s!="string")throw new Error("schema id must be string");return e=mn.normalizeId(e||s),em(this,e),this._schemas[e]=this._addSchema(t,r,a,!0),this}function uP(t,e,r){return this.addSchema(t,e,r,!0),this}function cP(t,e){var r=t.$schema;if(r!==void 0&&typeof r!="string")throw new Error("$schema must be a string");if(r=r||this._opts.defaultMeta||dP(this),!r)return this.logger.warn("meta-schema not available"),this.errors=null,!0;var a=this.validate(r,t);if(!a&&e){var n="schema is invalid: "+this.errorsText();if(this._opts.validateSchema=="log")this.logger.error(n);else throw new Error(n)}return a}function dP(t){var e=t._opts.meta;return t._opts.defaultMeta=typeof e=="object"?t._getId(e)||e:t.getSchema(Gs)?Gs:void 0,t._opts.defaultMeta}function pP(t){var e=Xf(this,t);switch(typeof e){case"object":return e.validate||this._compile(e);case"string":return this.getSchema(e);case"undefined":return hP(this,t)}}function hP(t,e){var r=mn.schema.call(t,{schema:{}},e);if(r){var a=r.schema,n=r.root,s=r.baseId,o=Jf.call(t,a,n,void 0,s);return t._fragments[e]=new Wf({ref:e,fragment:!0,schema:a,root:n,baseId:s,validate:o}),o}}function Xf(t,e){return e=mn.normalizeId(e),t._schemas[e]||t._refs[e]||t._fragments[e]}function fP(t){if(t instanceof RegExp)return Ks(this,this._schemas,t),Ks(this,this._refs,t),this;switch(typeof t){case"undefined":return Ks(this,this._schemas),Ks(this,this._refs),this._cache.clear(),this;case"string":var e=Xf(this,t);return e&&this._cache.del(e.cacheKey),delete this._schemas[t],delete this._refs[t],this;case"object":var r=this._opts.serialize,a=r?r(t):t;this._cache.del(a);var n=this._getId(t);n&&(n=mn.normalizeId(n),delete this._schemas[n],delete this._refs[n])}return this}function Ks(t,e,r){for(var a in e){var n=e[a];!n.meta&&(!r||r.test(a))&&(t._cache.del(n.cacheKey),delete e[a])}}function mP(t,e,r,a){if(typeof t!="object"&&typeof t!="boolean")throw new Error("schema should be object or boolean");var n=this._opts.serialize,s=n?n(t):t,o=this._cache.get(s);if(o)return o;a=a||this._opts.addUsedSchema!==!1;var i=mn.normalizeId(this._getId(t));i&&a&&em(this,i);var l=this._opts.validateSchema!==!1&&!e,u;l&&!(u=i&&i==mn.normalizeId(t.$schema))&&this.validateSchema(t,!0);var d=mn.ids.call(this,t),v=new Wf({id:i,schema:t,localRefs:d,cacheKey:s,meta:r});return i[0]!="#"&&a&&(this._refs[i]=v),this._cache.put(s,v),l&&u&&this.validateSchema(t,!0),v}function vP(t,e){if(t.compiling)return t.validate=n,n.schema=t.schema,n.errors=null,n.root=e||n,t.schema.$async===!0&&(n.$async=!0),n;t.compiling=!0;var r;t.meta&&(r=this._opts,this._opts=this._metaOpts);var a;try{a=Jf.call(this,t.schema,e,t.localRefs)}catch(s){throw delete t.validate,s}finally{t.compiling=!1,t.meta&&(this._opts=r)}return t.validate=a,t.refs=a.refs,t.refVal=a.refVal,t.root=a.root,a;function n(){var s=t.validate,o=s.apply(this,arguments);return n.errors=s.errors,o}}function gP(t){switch(t.schemaId){case"auto":return wP;case"id":return yP;default:return _P}}function yP(t){return t.$id&&this.logger.warn("schema $id ignored",t.$id),t.id}function _P(t){return t.id&&this.logger.warn("schema id ignored",t.id),t.$id}function wP(t){if(t.$id&&t.id&&t.$id!=t.id)throw new Error("schema $id is different from id");return t.$id||t.id}function bP(t,e){if(t=t||this.errors,!t)return"No errors";e=e||{};for(var r=e.separator===void 0?", ":e.separator,a=e.dataVar===void 0?"data":e.dataVar,n="",s=0;s<t.length;s++){var o=t[s];o&&(n+=a+o.dataPath+" "+o.message+r)}return n.slice(0,-r.length)}function xP(t,e){return typeof e=="string"&&(e=new RegExp(e)),this._formats[t]=e,this}function EP(t){var e;if(t._opts.$data&&(e=XT,t.addMetaSchema(e,e.$id,!0)),t._opts.meta!==!1){var r=Bf;t._opts.$data&&(r=Gf(r,sP)),t.addMetaSchema(r,Gs,!0),t._refs["http://json-schema.org/schema"]=Gs}}function SP(t){var e=t._opts.schemas;if(e)if(Array.isArray(e))t.addSchema(e);else for(var r in e)t.addSchema(e[r],r)}function IP(t){for(var e in t._opts.formats){var r=t._opts.formats[e];t.addFormat(e,r)}}function kP(t){for(var e in t._opts.keywords){var r=t._opts.keywords[e];t.addKeyword(e,r)}}function em(t,e){if(t._schemas[e]||t._refs[e])throw new Error('schema with key or id "'+e+'" already exists')}function TP(t){for(var e=Kf.copy(t._opts),r=0;r<Yf.length;r++)delete e[Yf[r]];return e}function PP(t){var e=t._opts.logger;if(e===!1)t.logger={log:_l,warn:_l,error:_l};else{if(e===void 0&&(e=console),!(typeof e=="object"&&e.log&&e.warn&&e.error))throw new Error("logger must implement log, warn and error methods");t.logger=e}}function _l(){}const CP=Jw(aP);class Qs extends gk{constructor(e,r){var a;super(r),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._capabilities=(a=r==null?void 0:r.capabilities)!==null&&a!==void 0?a:{},this._ajv=new CP}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=yk(this._capabilities,e)}assertCapability(e,r){var a;if(!(!((a=this._serverCapabilities)===null||a===void 0)&&a[e]))throw new Error(`Server does not support ${e} (required for ${r})`)}async connect(e,r){if(await super.connect(e),e.sessionId===void 0)try{const a=await this.request({method:"initialize",params:{protocolVersion:Is,capabilities:this._capabilities,clientInfo:this._clientInfo}},ph,r);if(a===void 0)throw new Error(`Server sent invalid initialize result: ${a}`);if(!IE.includes(a.protocolVersion))throw new Error(`Server's protocol version is not supported: ${a.protocolVersion}`);this._serverCapabilities=a.capabilities,this._serverVersion=a.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(a.protocolVersion),this._instructions=a.instructions,await this.notification({method:"notifications/initialized"})}catch(a){throw this.close(),a}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){var r,a,n,s,o;switch(e){case"logging/setLevel":if(!(!((r=this._serverCapabilities)===null||r===void 0)&&r.logging))throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!(!((a=this._serverCapabilities)===null||a===void 0)&&a.prompts))throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!(!((n=this._serverCapabilities)===null||n===void 0)&&n.resources))throw new Error(`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!(!((s=this._serverCapabilities)===null||s===void 0)&&s.tools))throw new Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!(!((o=this._serverCapabilities)===null||o===void 0)&&o.completions))throw new Error(`Server does not support completions (required for ${e})`);break}}assertNotificationCapability(e){var r;switch(e){case"notifications/roots/list_changed":if(!(!((r=this._capabilities.roots)===null||r===void 0)&&r.listChanged))throw new Error(`Client does not support roots list changed notifications (required for ${e})`);break}}assertRequestHandlerCapability(e){switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${e})`);break}}async ping(e){return this.request({method:"ping"},fn,e)}async complete(e,r){return this.request({method:"completion/complete",params:e},Mh,r)}async setLoggingLevel(e,r){return this.request({method:"logging/setLevel",params:{level:e}},fn,r)}async getPrompt(e,r){return this.request({method:"prompts/get",params:e},Ih,r)}async listPrompts(e,r){return this.request({method:"prompts/list",params:e},Eh,r)}async listResources(e,r){return this.request({method:"resources/list",params:e},yh,r)}async listResourceTemplates(e,r){return this.request({method:"resources/templates/list",params:e},_h,r)}async readResource(e,r){return this.request({method:"resources/read",params:e},wh,r)}async subscribeResource(e,r){return this.request({method:"resources/subscribe",params:e},fn,r)}async unsubscribeResource(e,r){return this.request({method:"resources/unsubscribe",params:e},fn,r)}async callTool(e,r=Rs,a){const n=await this.request({method:"tools/call",params:e},r,a),s=this.getToolOutputValidator(e.name);if(s){if(!n.structuredContent&&!n.isError)throw new Lr(vr.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(n.structuredContent)try{if(!s(n.structuredContent))throw new Lr(vr.InvalidParams,`Structured content does not match the tool's output schema: ${this._ajv.errorsText(s.errors)}`)}catch(o){throw o instanceof Lr?o:new Lr(vr.InvalidParams,`Failed to validate structured content: ${o instanceof Error?o.message:String(o)}`)}}return n}cacheToolOutputSchemas(e){this._cachedToolOutputValidators.clear();for(const r of e)if(r.outputSchema)try{const a=this._ajv.compile(r.outputSchema);this._cachedToolOutputValidators.set(r.name,a)}catch{}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,r){const a=await this.request({method:"tools/list",params:e},Th,r);return this.cacheToolOutputSchemas(a.tools),a}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}class tm extends Event{constructor(e,r){var a,n;super(e),this.code=(a=r==null?void 0:r.code)!=null?a:void 0,this.message=(n=r==null?void 0:r.message)!=null?n:void 0}[Symbol.for("nodejs.util.inspect.custom")](e,r,a){return a(rm(this),r)}[Symbol.for("Deno.customInspect")](e,r){return e(rm(this),r)}}function RP(t){const e=globalThis.DOMException;return typeof e=="function"?new e(t,"SyntaxError"):new SyntaxError(t)}function wl(t){return t instanceof Error?"errors"in t&&Array.isArray(t.errors)?t.errors.map(wl).join(", "):"cause"in t&&t.cause instanceof Error?`${t}: ${wl(t.cause)}`:t.message:`${t}`}function rm(t){return{type:t.type,message:t.message,code:t.code,defaultPrevented:t.defaultPrevented,cancelable:t.cancelable,timeStamp:t.timeStamp}}var nm=t=>{throw TypeError(t)},bl=(t,e,r)=>e.has(t)||nm("Cannot "+r),Te=(t,e,r)=>(bl(t,e,"read from private field"),r?r.call(t):e.get(t)),pt=(t,e,r)=>e.has(t)?nm("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),We=(t,e,r,a)=>(bl(t,e,"write to private field"),e.set(t,r),r),Or=(t,e,r)=>(bl(t,e,"access private method"),r),Nt,vn,Mn,Ys,Xs,ka,Dn,Ta,Zr,jn,zn,Ln,Pa,sr,xl,El,Sl,am,Il,kl,Ca,Tl,Pl;class eo extends EventTarget{constructor(e,r){var a,n;super(),pt(this,sr),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,pt(this,Nt),pt(this,vn),pt(this,Mn),pt(this,Ys),pt(this,Xs),pt(this,ka),pt(this,Dn),pt(this,Ta,null),pt(this,Zr),pt(this,jn),pt(this,zn,null),pt(this,Ln,null),pt(this,Pa,null),pt(this,El,async s=>{var o;Te(this,jn).reset();const{body:i,redirected:l,status:u,headers:d}=s;if(u===204){Or(this,sr,Ca).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(l?We(this,Mn,new URL(s.url)):We(this,Mn,void 0),u!==200){Or(this,sr,Ca).call(this,`Non-200 status code (${u})`,u);return}if(!(d.get("content-type")||"").startsWith("text/event-stream")){Or(this,sr,Ca).call(this,'Invalid content type, expected "text/event-stream"',u);return}if(Te(this,Nt)===this.CLOSED)return;We(this,Nt,this.OPEN);const v=new Event("open");if((o=Te(this,Pa))==null||o.call(this,v),this.dispatchEvent(v),typeof i!="object"||!i||!("getReader"in i)){Or(this,sr,Ca).call(this,"Invalid response body, expected a web ReadableStream",u),this.close();return}const m=new TextDecoder,c=i.getReader();let h=!0;do{const{done:g,value:f}=await c.read();f&&Te(this,jn).feed(m.decode(f,{stream:!g})),g&&(h=!1,Te(this,jn).reset(),Or(this,sr,Tl).call(this))}while(h)}),pt(this,Sl,s=>{We(this,Zr,void 0),!(s.name==="AbortError"||s.type==="aborted")&&Or(this,sr,Tl).call(this,wl(s))}),pt(this,Il,s=>{typeof s.id=="string"&&We(this,Ta,s.id);const o=new MessageEvent(s.event||"message",{data:s.data,origin:Te(this,Mn)?Te(this,Mn).origin:Te(this,vn).origin,lastEventId:s.id||""});Te(this,Ln)&&(!s.event||s.event==="message")&&Te(this,Ln).call(this,o),this.dispatchEvent(o)}),pt(this,kl,s=>{We(this,ka,s)}),pt(this,Pl,()=>{We(this,Dn,void 0),Te(this,Nt)===this.CONNECTING&&Or(this,sr,xl).call(this)});try{if(e instanceof URL)We(this,vn,e);else if(typeof e=="string")We(this,vn,new URL(e,OP()));else throw new Error("Invalid URL")}catch{throw RP("An invalid or illegal string was specified")}We(this,jn,$u({onEvent:Te(this,Il),onRetry:Te(this,kl)})),We(this,Nt,this.CONNECTING),We(this,ka,3e3),We(this,Xs,(a=r==null?void 0:r.fetch)!=null?a:globalThis.fetch),We(this,Ys,(n=r==null?void 0:r.withCredentials)!=null?n:!1),Or(this,sr,xl).call(this)}get readyState(){return Te(this,Nt)}get url(){return Te(this,vn).href}get withCredentials(){return Te(this,Ys)}get onerror(){return Te(this,zn)}set onerror(e){We(this,zn,e)}get onmessage(){return Te(this,Ln)}set onmessage(e){We(this,Ln,e)}get onopen(){return Te(this,Pa)}set onopen(e){We(this,Pa,e)}addEventListener(e,r,a){const n=r;super.addEventListener(e,n,a)}removeEventListener(e,r,a){const n=r;super.removeEventListener(e,n,a)}close(){Te(this,Dn)&&clearTimeout(Te(this,Dn)),Te(this,Nt)!==this.CLOSED&&(Te(this,Zr)&&Te(this,Zr).abort(),We(this,Nt,this.CLOSED),We(this,Zr,void 0))}}Nt=new WeakMap,vn=new WeakMap,Mn=new WeakMap,Ys=new WeakMap,Xs=new WeakMap,ka=new WeakMap,Dn=new WeakMap,Ta=new WeakMap,Zr=new WeakMap,jn=new WeakMap,zn=new WeakMap,Ln=new WeakMap,Pa=new WeakMap,sr=new WeakSet,xl=function(){We(this,Nt,this.CONNECTING),We(this,Zr,new AbortController),Te(this,Xs)(Te(this,vn),Or(this,sr,am).call(this)).then(Te(this,El)).catch(Te(this,Sl))},El=new WeakMap,Sl=new WeakMap,am=function(){var t;const e={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...Te(this,Ta)?{"Last-Event-ID":Te(this,Ta)}:void 0},cache:"no-store",signal:(t=Te(this,Zr))==null?void 0:t.signal};return"window"in globalThis&&(e.credentials=this.withCredentials?"include":"same-origin"),e},Il=new WeakMap,kl=new WeakMap,Ca=function(t,e){var r;Te(this,Nt)!==this.CLOSED&&We(this,Nt,this.CLOSED);const a=new tm("error",{code:e,message:t});(r=Te(this,zn))==null||r.call(this,a),this.dispatchEvent(a)},Tl=function(t,e){var r;if(Te(this,Nt)===this.CLOSED)return;We(this,Nt,this.CONNECTING);const a=new tm("error",{code:e,message:t});(r=Te(this,zn))==null||r.call(this,a),this.dispatchEvent(a),We(this,Dn,setTimeout(Te(this,Pl),Te(this,ka)))},Pl=new WeakMap,eo.CONNECTING=0,eo.OPEN=1,eo.CLOSED=2;function OP(){const t="document"in globalThis?globalThis.document:void 0;return t&&typeof t=="object"&&"baseURI"in t&&typeof t.baseURI=="string"?t.baseURI:void 0}class $P extends Error{constructor(e,r,a){super(`SSE error: ${r}`),this.code=e,this.event=a}}class Cl{constructor(e,r){this._url=e,this._resourceMetadataUrl=void 0,this._eventSourceInit=r==null?void 0:r.eventSourceInit,this._requestInit=r==null?void 0:r.requestInit,this._authProvider=r==null?void 0:r.authProvider,this._fetch=r==null?void 0:r.fetch}async _authThenStart(){var e;if(!this._authProvider)throw new ar("No auth provider");let r;try{r=await An(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(a){throw(e=this.onerror)===null||e===void 0||e.call(this,a),a}if(r!=="AUTHORIZED")throw new ar;return await this._startOrAuth()}async _commonHeaders(){var e;const r={};if(this._authProvider){const a=await this._authProvider.tokens();a&&(r.Authorization=`Bearer ${a.access_token}`)}return this._protocolVersion&&(r["mcp-protocol-version"]=this._protocolVersion),new Headers({...r,...(e=this._requestInit)===null||e===void 0?void 0:e.headers})}_startOrAuth(){var e,r,a;const n=(a=(r=(e=this===null||this===void 0?void 0:this._eventSourceInit)===null||e===void 0?void 0:e.fetch)!==null&&r!==void 0?r:this._fetch)!==null&&a!==void 0?a:fetch;return new Promise((s,o)=>{this._eventSource=new eo(this._url.href,{...this._eventSourceInit,fetch:async(i,l)=>{const u=await this._commonHeaders();u.set("Accept","text/event-stream");const d=await n(i,{...l,headers:u});return d.status===401&&d.headers.has("www-authenticate")&&(this._resourceMetadataUrl=Ki(d)),d}}),this._abortController=new AbortController,this._eventSource.onerror=i=>{var l;if(i.code===401&&this._authProvider){this._authThenStart().then(s,o);return}const u=new $P(i.code,i.message,i);o(u),(l=this.onerror)===null||l===void 0||l.call(this,u)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",i=>{var l;const u=i;try{if(this._endpoint=new URL(u.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(d){o(d),(l=this.onerror)===null||l===void 0||l.call(this,d),this.close();return}s()}),this._eventSource.onmessage=i=>{var l,u;const d=i;let v;try{v=hn.parse(JSON.parse(d.data))}catch(m){(l=this.onerror)===null||l===void 0||l.call(this,m);return}(u=this.onmessage)===null||u===void 0||u.call(this,v)}})}async start(){if(this._eventSource)throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(e){if(!this._authProvider)throw new ar("No auth provider");if(await An(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new ar("Failed to authorize")}async close(){var e,r,a;(e=this._abortController)===null||e===void 0||e.abort(),(r=this._eventSource)===null||r===void 0||r.close(),(a=this.onclose)===null||a===void 0||a.call(this)}async send(e){var r,a,n;if(!this._endpoint)throw new Error("Not connected");try{const s=await this._commonHeaders();s.set("content-type","application/json");const o={...this._requestInit,method:"POST",headers:s,body:JSON.stringify(e),signal:(r=this._abortController)===null||r===void 0?void 0:r.signal},i=await((a=this._fetch)!==null&&a!==void 0?a:fetch)(this._endpoint,o);if(!i.ok){if(i.status===401&&this._authProvider){if(this._resourceMetadataUrl=Ki(i),await An(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new ar;return this.send(e)}const l=await i.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${i.status}): ${l}`)}}catch(s){throw(n=this.onerror)===null||n===void 0||n.call(this,s),s}}setProtocolVersion(e){this._protocolVersion=e}}const AP="mcp";class sm{constructor(e){this._url=e}start(){if(this._socket)throw new Error("WebSocketClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,r)=>{this._socket=new WebSocket(this._url,AP),this._socket.onerror=a=>{var n;const s="error"in a?a.error:new Error(`WebSocket error: ${JSON.stringify(a)}`);r(s),(n=this.onerror)===null||n===void 0||n.call(this,s)},this._socket.onopen=()=>{e()},this._socket.onclose=()=>{var a;(a=this.onclose)===null||a===void 0||a.call(this)},this._socket.onmessage=a=>{var n,s;let o;try{o=hn.parse(JSON.parse(a.data))}catch(i){(n=this.onerror)===null||n===void 0||n.call(this,i);return}(s=this.onmessage)===null||s===void 0||s.call(this,o)}})}async close(){var e;(e=this._socket)===null||e===void 0||e.close()}send(e){return new Promise((r,a)=>{var n;if(!this._socket){a(new Error("Not connected"));return}(n=this._socket)===null||n===void 0||n.send(JSON.stringify(e)),r()})}}function to(){const t=["224340fQYLJj","function","onmessage","port2","341XVdnBD","313767JEBgqL","950bpstaX","1354759gUhUbE","wRKyh","onclose","2044SvCTUj","endpoint","24msSkHx","164VuWYGY","mOWMr","EkZCC","addEventListener","postMessage","120705iyGzUz","8878392ivIdKn","close","_listen","3619482FaLQHc","start","_endpoint","kgkem","bzNYT","MessageChannel transport error: ","stringify","onmessageerror","HvyCv","undefined","Jwyua","message","_globalObject","parse","authInfo","thraG","220pGvxgp","_port","EGhzU","onerror","data","MhriV"];return to=function(){return t},to()}(function(t,e){const r=xt,a=xt,n=t();for(;;)try{if(parseInt(r(417))/1*(parseInt(r(421))/2)+parseInt(r(433))/3+parseInt(r(424))/4*(-parseInt(a(429))/5)+parseInt(a(423))/6*(-parseInt(a(418))/7)+-parseInt(a(430))/8+-parseInt(r(416))/9*(-parseInt(r(405))/10)+-parseInt(r(415))/11*(-parseInt(r(411))/12)===e)break;n.push(n.shift())}catch{n.push(n.shift())}})(to,650197);const NP=()=>{const t=xt,e={EGhzU:function(r,a){return r!==a},kIrDB:"undefined",llYQe:function(r,a){return r!==a},PZfJg:function(r,a){return r(a)},Jwyua:"return this"};return typeof globalThis<"u"?globalThis:e[t(407)](typeof window,e.kIrDB)?window:e.llYQe(typeof global,e.kIrDB)?global:typeof self!==t(398)?self:e.PZfJg(Function,e[t(399)])()},MP=(t,e,r)=>{const a=xt,n=xt,s={};s[a(410)]=n(398),s.dBkaX=function(i,l){return i===l},s[n(393)]="function";const o=s;typeof window!==o[n(410)]?t.postMessage(e,"*",r):n(428)in t&&o.dBkaX(typeof t.postMessage,o[a(393)])&&t.postMessage(e,r)};class om{constructor(e){const r=xt;this[r(406)]=e}async start(){const e=xt,r=xt;this[e(406)]&&(this[e(406)][e(413)]=a=>{var n,s;const o=e,i=r;try{const l=hn[o(402)](a.data[o(400)]);(n=this[o(413)])==null||n.call(this,l,a[i(409)].extra)}catch(l){const u=new Error("MessageChannel failed to parse message: "+l);(s=this[i(408)])==null||s.call(this,u)}},this._port[e(396)]=a=>{var n;const s=r,o=r,i=new Error(s(394)+JSON[o(395)](a));(n=this.onerror)==null||n.call(this,i)},this[e(406)][e(434)]())}async send(e,r){const a={lEyuq:function(n){return n()},YihNw:function(n,s){return n(s)}};return new Promise((n,s)=>{var o;const i=xt,l=xt;try{const u={};u[i(403)]=r==null?void 0:r[i(403)];const d={};d[l(400)]=e,d.extra=u,this[l(406)]&&this[i(406)].postMessage(d),a.lEyuq(n)}catch(u){const d=u instanceof Error?u:new Error(a.YihNw(String,u));(o=this[l(408)])==null||o.call(this,d),s(d)}})}async close(){var e,r;const a=xt,n=xt;(e=this._port)==null||e[a(431)](),this._port=void 0,(r=this[n(420)])==null||r.call(this)}}class DP extends om{constructor(e,r=NP()){const a=xt,n=xt,s={EkZCC:function(i,l,u,d){return i(l,u,d)}};super(),this[a(391)]=e,this[n(401)]=r;const o=new MessageChannel;this[n(406)]=o.port1,s[n(426)](MP,this[a(401)],{endpoint:this[n(391)]},[o[n(414)]])}}function xt(t,e){const r=to();return xt=function(a,n){return a=a-(17*-491+-669+9407),r[a]},xt(t,e)}(function(t,e){const r=qe,a=qe,n=t();for(;;)try{if(parseInt(r(355))/1+-parseInt(r(356))/2*(-parseInt(r(373))/3)+-parseInt(r(337))/4+parseInt(a(357))/5+-parseInt(a(389))/6*(-parseInt(r(396))/7)+parseInt(a(325))/8*(parseInt(r(382))/9)+-parseInt(r(366))/10===e)break;n.push(n.shift())}catch{n.push(n.shift())}})(ro,-763475+-52067*10+1724410);const jP=async(t,e,r)=>{var a;const n=qe,s=qe,o={};o[n(345)]="tools/list",o.rqstG="tools/call",o.WqUnk="resources/list",o[n(329)]=s(358),o[n(365)]=n(335),o.ookoz="resources/unsubscribe",o[n(385)]=n(340),o.VTIWq="prompts/list",o.SkoRK=n(376),o.QUtUV=n(388),o.XtowM=s(332);const i=o,{id:l,method:u,params:d}=r;let v={};switch(u){case i[s(345)]:v=await e.listTools(d);break;case i.rqstG:v=await e.callTool(d);break;case i[n(334)]:v=await e[n(350)](d);break;case i[s(329)]:v=await e.listResourceTemplates(d);break;case n(372):v=await e[n(383)](d);break;case i.HgYgW:v=await e.subscribeResource(d);break;case i.ookoz:v=await e.unsubscribeResource(d);break;case i[n(385)]:v=await e.getPrompt(d);break;case i.VTIWq:v=await e.listPrompts(d);break;case i[n(344)]:v=await e[n(376)]();break;case i.QUtUV:v=await e.complete(d);break;case n(390):v=await e[n(336)](d==null?void 0:d.level);break}const m={};m[n(361)]=v,m[n(394)]=i[n(364)],m.id=l,await((a=t==null?void 0:t.transport)==null?void 0:a[n(392)](m))},zP=async(t,e,r)=>{var a;const n=qe,s=qe,o={};o.jQBBS="sampling/createMessage",o.EZqgC="elicitation/create",o[n(370)]=s(376),o.aVeaL=s(332);const i=o,{id:l,method:u,params:d}=r;let v={};switch(u){case n(368):const c={};c.method=u,c[s(367)]=d,v=await e.request(c,jh);break;case i[s(391)]:const h={};h.method=u,h[s(367)]=d,v=await e[s(381)](h,$h);break;case i.EZqgC:const g={};g.method=u,g.params=d,v=await e.request(g,Nh);break;case i[s(370)]:const f={};f.method=u,v=await e[s(381)](f,fn);break}const m={};return m[s(361)]=v,m.jsonrpc=i[s(387)],m.id=l,await((a=t==null?void 0:t[n(371)])==null?void 0:a.send(m)),v},LP=(t,e)=>{const r=qe,a={gXsjT:function(s,o){return s===o},oegpC:r(351),lZOUC:function(s,o,i,l){return s(o,i,l)},ifIKG:"2.0"},n=t._onrequest;t._onrequest=async(s,o)=>{var i,l,u,d,v;const m=r,c=r,{id:h,method:g}=s;try{a[m(333)](g,a.oegpC)?await n[m(386)](t,s,o):await a.lZOUC(jP,t,e,s)}catch(f){const{code:p,message:b,data:y}=f;try{if(p){const _={};_.code=p,_.message=b,_.data=y;const S={};S.error=_,S[m(394)]=a[c(331)],S.id=h,await((i=t==null?void 0:t.transport)==null?void 0:i.send(S))}else(u=(l=t==null?void 0:t[c(371)])==null?void 0:l.onerror)==null||u.call(l,f)}catch(_){(v=(d=t==null?void 0:t[m(371)])==null?void 0:d.onerror)==null||v.call(d,_)}}}},UP=(t,e)=>{const r=qe,a=qe,n={};n[r(363)]=function(o,i){return o!==i},n[r(398)]=r(353),n.hzhyg="notifications/cancelled";const s=n;t._onnotification=async o=>{var i,l;const u=r,d=a,{method:v,params:m}=o;if(s[u(363)](v,s[d(398)])&&(s[u(363)](v,s.hzhyg)||m!=null&&m.forward))try{await e.notification(o)}catch(c){(l=(i=t==null?void 0:t.transport)==null?void 0:i.onerror)==null||l.call(i,c)}}},FP=(t,e)=>async r=>{var a,n,s,o,i;const l=qe,u=qe,d={};d.SEmWX=l(332);const v=d;try{return await zP(t,e,r)}catch(m){const{code:c,message:h,data:g}=m;try{if(c){const f={};f[u(377)]=c,f.message=h,f.data=g;const p={};p[u(348)]=f,p.jsonrpc=v[l(338)],p.id=r.id,await((a=t==null?void 0:t.transport)==null?void 0:a[u(392)](p))}else(s=(n=t==null?void 0:t.transport)==null?void 0:n[u(339)])==null||s.call(n,m)}catch(f){(i=(o=t==null?void 0:t[l(371)])==null?void 0:o[u(339)])==null||i.call(o,f)}}},qP=(t,e)=>async r=>{var a,n,s;const o=qe,i=qe,l={};l.dtUgZ=function(m,c){return m!==c},l.jgCIb=o(353),l.uUjKY="2.0";const u=l,{method:d,params:v}=r;if(u.dtUgZ(d,u.jgCIb)&&(d!==o(400)||v!=null&&v.forward))try{const m={...r};m[o(394)]=u[i(352)],await((a=e==null?void 0:e[o(371)])==null?void 0:a[o(392)](m))}catch(m){(s=(n=t==null?void 0:t[o(371)])==null?void 0:n[i(339)])==null||s.call(n,m)}};function qe(t,e){const r=ro();return qe=function(a,n){return a=a-(9*-113+-1439*-1+-97),r[a]},qe(t,e)}const ZP=(t,e)=>async r=>{var a,n,s,o,i,l;const u=qe,d=qe,v={};v[u(401)]=d(332);const m=v;try{await((a=e==null?void 0:e.transport)==null?void 0:a.send(r))}catch(c){const{code:h,message:g,data:f}=c;try{if(h){const p={};p.code=h,p[u(399)]=g,p.data=f;const b={};b[u(348)]=p,b[u(394)]=m.OhJjz,b.id=r.id,await((n=t==null?void 0:t[u(371)])==null?void 0:n.send(b))}else(o=(s=t==null?void 0:t.transport)==null?void 0:s[d(339)])==null||o.call(s,c)}catch(p){(l=(i=t==null?void 0:t.transport)==null?void 0:i.onerror)==null||l.call(i,p)}}},Rl=()=>{const t=qe,e=qe,r={vnkqu:function(u,d){return u!==d},wxDWr:function(u,d){return u(d)},GdkkV:function(u,d){return u===d}},a=[],n=(u,d)=>{const v=qe,m=qe;if(d){const c=[];for(const h of a)try{c.push(h(u,d))}catch{}for(const h of c)if(r[v(379)](h,null))return h}else for(const c of a)try{r[m(343)](c,u)}catch{}},s=u=>{const d=qe;r[d(384)](typeof u,d(369))&&!a.includes(u)&&a.push(u)},o=u=>{const d=a.indexOf(u);d!==-1&&a.splice(d,1*-6854+8*-33+7119)},i=()=>{const u=qe;a[u(374)]=7102*1+5522+-526*24},l={};return l[t(346)]=n,l[e(330)]=s,l.removeListener=o,l[t(359)]=i,l},VP=t=>{const e=qe,r=qe,a={xwPeb:function(n){return n()},Mfvzm:function(n){return n()}};{const{handleListener:n,addListener:s,removeListener:o,clearListener:i}=a[e(326)](Rl);t._onresponse=n,t[e(395)]=s,t.removeResponseListener=o,t.clearResponseListener=i}{const{handleListener:n,addListener:s,removeListener:o,clearListener:i}=a[r(326)](Rl);t[r(328)]=n,t.addRequestListener=s,t[r(354)]=o,t[r(341)]=i}{const{handleListener:n,addListener:s,removeListener:o,clearListener:i}=a[e(375)](Rl);t[e(342)]=n,t[e(327)]=s,t.removeNotificationListener=o,t.clearNotificationListener=i}};function ro(){const t=["uUjKY","notifications/initialized","removeRequestListener","96194JysfjF","36346SGEWAV","1357830AJaOeY","resources/templates/list","clearListener","iQqcJ","result","tqDZP","sSeCz","XtowM","HgYgW","3913230mjiatC","params","roots/list","function","bfmJT","transport","resources/read","27FNuDmk","length","Mfvzm","ping","code","_onresponse","vnkqu","cjSoZ","request","9gIMIPC","readResource","GdkkV","ptMjy","call","aVeaL","completion/complete","5035122lFbpzR","logging/setLevel","jQBBS","send","_requestHandlers","jsonrpc","addResponseListener","7SpcenI","ElOQH","MDIkN","message","notifications/cancelled","OhJjz","clear","672216JzFEyR","xwPeb","addNotificationListener","fallbackRequestHandler","sYzPD","addListener","ifIKG","2.0","gXsjT","WqUnk","resources/subscribe","setLoggingLevel","2491772kFUWFh","SEmWX","onerror","prompts/get","clearRequestListener","fallbackNotificationHandler","wxDWr","SkoRK","uTeHc","handleListener","Zybtx","error","originalOnResponse","listResources","initialize"];return ro=function(){return t},ro()}const BP=(t,{beforeInit:e,afterInit:r}={})=>{const a=qe,n=qe,s={tqDZP:function(i,l){return i===l},cjSoZ:"function",iQqcJ:a(378),Zybtx:function(i,l){return i(l)},ElOQH:function(i){return i()}},o=new Map(t._notificationHandlers);t[a(393)][a(402)](),t._notificationHandlers[a(402)](),s.tqDZP(typeof e,s[a(380)])&&e(),s[a(362)](t._onresponse.name,s[a(360)])&&(t[n(349)]=t._onresponse),s[a(347)](VP,t),t.addResponseListener(i=>{const l=n;t.originalOnResponse[l(386)](t,i)}),s.tqDZP(typeof r,s[n(380)])&&s[a(397)](r),t[n(327)](i=>{const{method:l}=i,u=o.get(l);s.tqDZP(typeof u,s.cjSoZ)&&u(i)})},HP=yr,JP=yr;(function(t,e){const r=yr,a=yr,n=t();for(;;)try{if(-parseInt(r(393))/1+parseInt(r(397))/2*(-parseInt(r(400))/3)+-parseInt(a(398))/4+parseInt(r(390))/5*(parseInt(a(388))/6)+-parseInt(r(389))/7+-parseInt(r(402))/8*(-parseInt(a(395))/9)+parseInt(a(399))/10*(parseInt(a(385))/11)===e)break;n.push(n.shift())}catch{n.push(n.shift())}})(no,-1*-881393+2*180895+1*-644809);function yr(t,e){const r=no();return yr=function(a,n){return a=a-(-1861+-499*4+4241),r[a]},yr(t,e)}function no(){const t=["toString","getRandomValues","2101mUsYMI","EQHzo","padStart","30UvDAkd","1609706yzlqYx","974735GrhZVO","randomUUID","REzPF","562771BvAnoG","dHTfU","2047455boiYXf","randomBytes","14664qHAdbF","3772144jLpQch","52310AkWksx","318MkjaVb","from","40WRwnSc"];return no=function(){return t},no()}const WP=()=>{const t=yr,e=yr,r={};r.REzPF=function(n,s){return n&s},r.suJHI=function(n,s){return n===s},r[t(386)]=function(n,s){return n&s},r[e(394)]="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";const a=r;return a.suJHI(typeof crypto,"object")&&crypto.randomUUID?crypto[e(391)]():a.dHTfU.replace(/[xy]/g,n=>{const s=t,o=t,i=a[s(392)](crypto[s(384)](new Uint8Array(-25*-62+7113+2*-4331))[741*2+-1385*-2+4252*-1],8648+-107*62+-1999);return(a.suJHI(n,"x")?i:a[o(386)](i,-4377+4*1095)|5079+461*-11).toString(9449+4*-461+-7589)})},GP=t=>{const e=yr,r=yr,a=new Uint8Array(t);return crypto.getRandomValues(a),Array[e(401)](a,n=>n[r(403)](-3*1739+-6509+2*5871)[e(387)](2,"0")).join("")},Vr={};Vr[HP(391)]=WP,Vr[JP(396)]=GP;const Lt=_r;(function(t,e){const r=_r,a=_r,n=t();for(;;)try{if(parseInt(r(521))/1*(parseInt(a(499))/2)+parseInt(a(543))/3*(parseInt(a(514))/4)+parseInt(r(502))/5*(parseInt(a(539))/6)+parseInt(r(553))/7+parseInt(r(516))/8*(-parseInt(r(518))/9)+-parseInt(r(531))/10+-parseInt(r(545))/11*(parseInt(r(541))/12)===e)break;n.push(n.shift())}catch{n.push(n.shift())}})(ao,1472653*1+-2*-897917+-2275789);const KP=(t,e)=>{const r=_r,a=_r,n={FyYHt:function(l,u,d){return l(u,d)},Fxtoq:function(l,u,d){return l(u,d)}};LP(t,e),UP(t,e);const s=FP(e,t),o=n[r(510)](ZP,e,t),i=n[a(549)](qP,e,t);e[a(537)](s),e[r(519)](o),e.addNotificationListener(i),t[a(556)]=()=>{const l=a;e.removeRequestListener(s),e[l(530)](o),e[l(529)](i)}},Ol=(t,e,r)=>{const a=_r,n={pMiva:function(i,l){return i instanceof l},TeTEy:a(546),fyZbd:function(i,l,u){return i(l,u)}},s=()=>{var i;const l=a;n.pMiva(r,Cl)&&((i=r._eventSource)==null||i.addEventListener(n[l(547)],()=>{var u;const d=l;(u=r[d(509)])==null||u[d(546)]()})),KP(t,e)},o={};o.afterInit=s,n.fyZbd(BP,e,o)},im=(t,e=Vr.randomUUID())=>{const r=_r,a=_r,n={OfssH:function(d,v,m){return d(v,m)}},s={};s[r(528)]=e;const o=s,i={};i[r(528)]=e;const l={};l[a(558)]=i,l[r(534)]=r(524);const u={requestInit:l,eventSourceInit:{async fetch(d,v){const m=r,c=a,h=new Headers((v==null?void 0:v[m(558)])||{});Object.entries(o)[c(498)](([f,p])=>{h[c(527)](f,p)});const g={...v};return g[c(558)]=h,n.OfssH(fetch,d,g)},withCredentials:!0}};return t&&(u.requestInit[r(558)].Authorization=r(533)+t,o.Authorization="Bearer "+t),u},lm=(t,e=Vr[Lt(517)]())=>{const r=Lt,a=Lt,n={};n.nwQhY="include";const s=n,o={};o["stream-session-id"]=e;const i={};i.headers=o,i.credentials=s[r(520)];const l={};l[r(544)]=i;const u=l;return t&&(u.requestInit.headers[a(552)]=a(533)+t),u},$l=async(t,e,r)=>{const a=Lt,n=Lt,s={CFfFC:function(i){return i()},egwVO:function(i,l,u,d){return i(l,u,d)}},o=s.CFfFC(r);try{return await t[a(538)](o),o}catch(i){if(i instanceof ar){const l=await e();return await o[n(505)](l),await s[a(525)]($l,t,e,r)}else throw i}};function _r(t,e){const r=ao();return _r=function(a,n){return a=a-(74*-67+-8341+-73*-189),r[a]},_r(t,e)}const um=(t,e)=>{const r=Lt,a=Lt,n={};n.RsKXs=function(o,i){return o in i},n.PBhps="waitForOAuthCode",n[r(535)]="function",n[r(507)]="waitForOAuthCode need to be provided when authProvider is provided";const s=n;if(s.RsKXs(s[a(551)],t))return t[a(523)];if(typeof e===s.yTKoP)return e;throw new Error(s.RZhOv)},QP=async t=>{const e=Lt,r=Lt,a={TFSRn:function(R,L,U){return R(L,U)},HwvVa:"mcp-sse-proxy-client",ufTHS:function(R){return R()},WIVYl:function(R,L,U,Z){return R(L,U,Z)},jniGY:"sessionId"},{client:n,url:s,token:o,sessionId:i,authProvider:l,requestInit:u,eventSourceInit:d,waitForOAuthCode:v}=t,m={};m.authProvider=l,m.requestInit=u,m.eventSourceInit=d;const c=m,h=i||Vr.randomUUID(),g=a[e(506)](im,o,h);if(u){const R={...g.requestInit,...u};R.headers={...g[e(544)].headers,...u.headers},c.requestInit=R}else c[r(544)]=g.requestInit;if(d){const R={...g[e(559)],...d};c.eventSourceInit=R}else c.eventSourceInit=g.eventSourceInit;const f={};f.listChanged=!0;const p={};p.roots=f,p.sampling={},p[e(511)]={};const b=p,y={};y[r(536)]=a.HwvVa,y.version=e(526);const _={};_.capabilities=b;const S=new Qs(y,_),T=()=>new Cl(new URL(s),c);let I=a[r(504)](T);if(l){const R=a[e(506)](um,l,v);I=await a[r(513)]($l,S,R,T)}else await S[e(538)](I);a[r(513)](Ol,S,n,I),I[r(557)]=I[r(542)].searchParams[r(532)](a.jniGY);const O={};return O.transport=I,O.sessionId=I[e(557)],O};function ao(){const t=["ufTHS","finishAuth","TFSRn","RZhOv","Vajmx","_eventSource","FyYHt","elicitation","transport","WIVYl","13320uyrBtN","sampling","8WTwLJD","randomUUID","6438654bkJHij","addResponseListener","nwQhY","11721GVgRMJ","?sessionId=","waitForOAuthCode","include","egwVO","1.0.0","set","sse-session-id","removeNotificationListener","removeResponseListener","11838520fNkjrV","get","Bearer ","credentials","yTKoP","name","addRequestListener","connect","18VhCgQv","mcp-socket-proxy-client","2819364JNqkQZ","_endpoint","699JyrxCR","requestInit","44ofbsvb","close","TeTEy","QgzDy","Fxtoq","roots","PBhps","Authorization","11309130xGCFwl","&token=","version","onclose","sessionId","headers","eventSourceInit","forEach","62FcOkCa","mcp-stream-proxy-client","zXcpO","1794855cQEXDT","biJOc"];return ao=function(){return t},ao()}const YP=async t=>{const e=Lt,r=Lt,a={Vajmx:e(500),biJOc:function(R){return R()},zXcpO:function(R,L,U){return R(L,U)},zDnjZ:function(R,L,U,Z){return R(L,U,Z)},FQMAh:function(R,L,U,Z){return R(L,U,Z)}},{client:n,url:s,token:o,sessionId:i,authProvider:l,requestInit:u,reconnectionOptions:d,waitForOAuthCode:v}=t,m={};m.authProvider=l,m.requestInit=u,m.reconnectionOptions=d;const c=m,h=i||Vr.randomUUID(),g=lm(o,h);if(u){const R={...g.requestInit,...u};R.headers={...g.requestInit.headers,...u.headers},c[e(544)]=R}else c.requestInit=g.requestInit;const f={};f.listChanged=!0;const p={};p[r(550)]=f,p.sampling={},p.elicitation={};const b=p,y={};y[e(536)]=a[r(508)],y[e(555)]="1.0.0";const _={};_.capabilities=b;const S=new Qs(y,_),T=()=>new Ms(new URL(s),c);let I=a[e(503)](T);if(l){const R=a[e(501)](um,l,v);I=await a.zDnjZ($l,S,R,T)}else await S.connect(I);a.FQMAh(Ol,S,n,I);const O={};return O.transport=I,O[r(557)]=I.sessionId,O},XP=async t=>{const e=Lt,r=Lt,a={QgzDy:e(540),jkaVB:function(p,b,y,_){return p(b,y,_)}},{client:n,url:s,token:o,sessionId:i}=t,l={};l.listChanged=!0;const u={};u[e(550)]=l,u[e(515)]={},u[r(511)]={};const d=u,v={};v.name=a[r(548)],v[r(555)]=r(526);const m={};m.capabilities=d;const c=new Qs(v,m),h=i||Vr[r(517)](),g=new sm(new URL(s+e(522)+h+r(554)+o));await c.connect(g),a.jkaVB(Ol,c,n,g);const f={};return f[e(512)]=g,f[r(557)]=h,f},Ra=Mt,so=Mt;function Mt(t,e){const r=oo();return Mt=function(a,n){return a=a-(-16761+51*337),r[a]},Mt(t,e)}(function(t,e){const r=Mt,a=Mt,n=t();for(;;)try{if(-parseInt(r(440))/1+-parseInt(r(458))/2*(parseInt(r(448))/3)+-parseInt(r(451))/4*(parseInt(a(449))/5)+-parseInt(a(455))/6+-parseInt(r(427))/7+-parseInt(a(438))/8*(parseInt(a(459))/9)+parseInt(r(430))/10*(parseInt(a(436))/11)===e)break;n.push(n.shift())}catch{n.push(n.shift())}})(oo,-220880+1*-333337+-2*-384996);function oo(){const t=["650XPHLhD","redirectToAuthorization","10856jPvMVb","GET","qcFPW","_redirectUrl","2187414WnlGuZ","resolve","tokens","3976YyOqUl","27ejNHsa","Content-Type","waitForOAuthCode","2903796yvWZFa","_clientMetadata","application/x-www-form-urlencoded","10beEWJk","json","code","_callBackPromise","reject","saveClientInformation","20776349mLNCcF","_codeVerifier","629912aTknXq","_tokens","52074GwcpRo","state","_state","_redirectCallback","_clientInformation","redirect_uris","Failed to redirect: ","clientInformation","381aduWsB"];return oo=function(){return t},oo()}const eC=()=>Vr.randomBytes(3485*1+-261+-3184);class d2{constructor(e){const r=Mt,a=Mt;this._callBackPromise={};const{clientMetadata:n,state:s,redirectCallback:o,getAuthCodeByState:i,waitForOAuthCode:l}=e;this[r(428)]=n,this[r(454)]=n[r(445)][0],this._state=s||eC(),this._redirectCallback=o||this.redirectCallbackFunction,this._getAuthCodeByState=i||this.getAuthCodeByStateFunction,this[a(426)]=l||this.waitForOAuthCodeFunction()}async redirectCallbackFunction(e){var r,a,n,s,o,i;const l=Mt,u=Mt,d={qITTp:function(h,g,f){return h(g,f)},qcFPW:l(452)},v=await d.qITTp(fetch,e,{method:d[l(453)]});!v.ok&&((a=(r=this._callBackPromise).reject)==null||a.call(r,u(446)+v.statusText));const m=await this._getAuthCodeByState(this[u(454)],this[l(442)]);if(!m.ok){(s=(n=this[l(433)]).reject)==null||s.call(n,"Failed to fetch auth code: "+m.statusText);return}const c=await m[l(431)]();(i=(o=this[u(433)])[l(456)])==null||i.call(o,c[l(432)])}async getAuthCodeByStateFunction(e,r){const a=Mt,n=Mt,s={};s.tuSmb=a(429);const o=s,i={};i[a(460)]=o.tuSmb;const l={};return l[n(441)]=r,fetch(e,{method:"POST",headers:i,body:new URLSearchParams(l)})}waitForOAuthCodeFunction(){const e=Mt,r=this[e(433)];return()=>new Promise((a,n)=>{const s=e;r.resolve=a,r[s(434)]=n})}get redirectUrl(){return this[Mt(454)]}get clientMetadata(){return this._clientMetadata}state(){return this._state}[Ra(447)](){return this[Ra(444)]}[so(435)](e){const r=Ra;this[r(444)]=e}[so(457)](){return this[so(439)]}saveTokens(e){this._tokens=e}[so(450)](e){this[Ra(443)](e)}saveCodeVerifier(e){this._codeVerifier=e}codeVerifier(){if(!this[Ra(437)])throw new Error("No code verifier saved");return this._codeVerifier}}(function(t,e){for(var r=lo,a=lo,n=t();;)try{var s=parseInt(r(361))/1*(parseInt(a(363))/2)+-parseInt(r(358))/3+parseInt(r(359))/4*(parseInt(r(357))/5)+parseInt(a(354))/6*(parseInt(r(360))/7)+parseInt(a(362))/8+parseInt(a(364))/9+-parseInt(a(356))/10*(parseInt(r(355))/11);if(s===e)break;n.push(n.shift())}catch{n.push(n.shift())}})(io,-73523*-3+1*-407717+530518);function io(){var t=["40ecBYYe","1095owKKYD","486870YOVwZy","5752xWiyTO","561484biNVMw","1fWJmxQ","1866064SPnyhb","1109522vMiuMX","1602351pPEGwH","12sVyMLL","2573296LTwOhv"];return io=function(){return t},io()}function lo(t,e){var r=io();return lo=function(a,n){a=a-(-1*-642+503*-5+2227);var s=r[a];return s},lo(t,e)}class tC{constructor(e,r){const a={name:"web-mcp-client",version:"1.0.0"},n={roots:{listChanged:!0},sampling:{},elicitation:{}};this.client=new Qs(e||a,r||{capabilities:n}),this.client.onclose=()=>{var s;(s=this.onclose)==null||s.call(this)},this.client.onerror=s=>{var o;(o=this.onerror)==null||o.call(this,s)}}async connect(e){if(typeof e.start=="function")return this.transport=e,this.transport.onclose=void 0,this.transport.onerror=void 0,this.transport.onmessage=void 0,await this.client.connect(this.transport),{transport:this.transport,sessionId:this.transport.sessionId};const{url:r,token:a,sessionId:n,type:s,agent:o,onError:i}=e;if(o===!0){const d={client:this.client,url:r,token:a,sessionId:n};let v;return await(async()=>{const{transport:c,sessionId:h}=s==="sse"?await QP(d):s==="socket"?await XP(d):await YP(d);c.onerror=async g=>{i==null||i(g)},v={transport:c,sessionId:h}})(),v}const l=new URL(r);let u;if(s==="channel"&&(u=new DP(r),await this.client.connect(u)),s==="sse"){const d=im(a,n);u=new Cl(l,d),await this.client.connect(u)}if(s==="socket"&&(u=new sm(new URL(`${r}?sessionId=${n}&token=${a}`)),u.sessionId=n,await this.client.connect(u)),typeof u>"u"){const d=lm(a,n);u=new Ms(l,d),await this.client.connect(u)}return this.transport=u,{transport:this.transport,sessionId:this.transport.sessionId}}async close(){await this.client.close()}getServerCapabilities(){return this.client.getServerCapabilities()}getServerVersion(){return this.client.getServerVersion()}getInstructions(){return this.client.getInstructions()}async ping(e){return await this.client.ping(e)}async complete(e,r){return await this.client.complete(e,r)}async setLoggingLevel(e,r){return await this.client.setLoggingLevel(e,r)}async getPrompt(e,r){return await this.client.getPrompt(e,r)}async listPrompts(e,r){return await this.client.listPrompts(e,r)}async listResources(e,r){return await this.client.listResources(e,r)}async listResourceTemplates(e,r){return await this.client.listResourceTemplates(e,r)}async readResource(e,r){return await this.client.readResource(e,r)}async subscribeResource(e,r){return await this.client.subscribeResource(e,r)}async unsubscribeResource(e,r){return await this.client.unsubscribeResource(e,r)}async callTool(e,r){return await this.client.callTool(e,Rs,r)}async listTools(e,r){return await this.client.listTools(e,r)}async sendRootsListChanged(){return await this.client.sendRootsListChanged()}request(e,r,a){return this.client.request(e,r,a)}async notification(e,r){return await this.client.notification(e,r)}setRequestHandler(e,r){this.client.setRequestHandler(e,r)}removeRequestHandler(e){this.client.removeRequestHandler(e)}setNotificationHandler(e,r){this.client.setNotificationHandler(e,r)}removeNotificationHandler(e){this.client.removeNotificationHandler(e)}onElicit(e){this.client.setRequestHandler(Ah,e)}onCreateMessage(e){this.client.setRequestHandler(Oh,e)}onListRoots(e){this.client.setRequestHandler(Dh,e)}onToolListChanged(e){this.client.setNotificationHandler(Ph,e)}onPromptListChanged(e){this.client.setNotificationHandler(kh,e)}onResourceListChanged(e){this.client.setNotificationHandler(bh,e)}onResourceUpdated(e){this.client.setNotificationHandler(xh,e)}onLoggingMessage(e){this.client.setNotificationHandler(Rh,e)}async onPagehide(e){e.persisted||(rC(this.transport)?await this.transport.terminateSession():this.transport&&typeof this.transport.close=="function"&&await this.transport.close())}}const rC=t=>t instanceof Ms,Al=async t=>{const e={};try{const r=await t.listTools();for(const{name:a,description:n,inputSchema:s}of r.tools){const o=async(i,l)=>t.callTool({name:a,arguments:i},{signal:l==null?void 0:l.abortSignal});e[a]=K0({description:n,inputSchema:ps({...s,properties:s.properties??{},additionalProperties:!1}),execute:o})}return e}catch(r){throw r}},nC={openai:of,deepseek:hf};class aC{constructor({llmConfig:e,mcpServers:r}){if(this.mcpServers={},this.mcpClients={},this.mcpTools={},this.ignoreToolnames=[],this.messages=[],!e)throw new Error("llmConfig is required to initialize AgentModelProvider");if(this.mcpServers=r||{},this.mcpClients={},this.mcpTools={},e.llm)this.llm=e.llm;else if(e.providerType){const a=e.providerType;let n;typeof a=="string"?n=nC[a]:n=a,this.llm=n({apiKey:e.apiKey,baseURL:e.baseURL})}else throw new Error("Either llmConfig.llm or llmConfig.providerType must be provided")}async _createOneClient(e){try{let r;"type"in e&&e.type.toLocaleLowerCase()==="streamablehttp"?r=new Ms(new URL(e.url)):"type"in e&&e.type==="extension"?r=new mk(e.sessionId):r=e;const a=new tC({name:"mcp-web-client",version:"1.0.0"},{capabilities:{roots:{listChanged:!0},sampling:{},elicitation:{}}});return await a.connect(r),a.__transport__=r,a}catch(r){return this.onError&&this.onError((r==null?void 0:r.message)||"Failed to create MCP client",r),console.error("Failed to create MCP client",e,r),null}}async _closeOneClient(e){var r,a,n;try{const s=e.__transport__;if(s&&s instanceof Ds||s&&s instanceof om)return;await((r=s==null?void 0:s.terminateSession)==null?void 0:r.call(s)),await((a=s==null?void 0:s.close)==null?void 0:a.call(s)),await((n=e==null?void 0:e.close)==null?void 0:n.call(e))}catch{}}async _createMpcClients(){const e=Object.entries(this.mcpServers),r=await Promise.all(e.map(async([a,n])=>{const s=await this._createOneClient(n);return{serverName:a,client:s}}));this.mcpClients={},r.forEach(({serverName:a,client:n})=>{this.mcpClients[a]=n})}async _createMpcTools(){const e=Object.entries(this.mcpClients),r=await Promise.all(e.map(async([a,n])=>{try{const s=n?await Al(n):null;return{serverName:a,tools:s}}catch(s){return this.onError&&this.onError((s==null?void 0:s.message)||"Failed to query tools",s),console.error("Failed to query tools",s),{serverName:a,tools:null}}}));this.mcpTools={},r.forEach(({serverName:a,tools:n})=>{const s=n&&typeof n=="object"?n:{};this.mcpTools[a]=s})}async closeAll(){await Promise.all(Object.values(this.mcpClients).map(async e=>{try{await this._closeOneClient(e)}catch(r){this.onError&&this.onError((r==null?void 0:r.message)||"Failed to close client",r),console.error("Failed to close client",r)}}))}async initClientsAndTools(){var e;await this._createMpcClients(),await this._createMpcTools(),(e=this.onUpdatedTools)==null||e.call(this)}async updateMcpServers(e){await this.closeAll(),this.mcpServers=e||this.mcpServers,await this.initClientsAndTools()}async insertMcpServer(e,r){var s,o;if(this.mcpServers[e])return!1;const a=await this._createOneClient(r);if(!a)return(s=this.onError)==null||s.call(this,`Failed to create MCP client: ${e}`),null;this.mcpClients[e]=a;const n=await Al(a);return this.mcpTools[e]=n&&typeof n=="object"?n:{},this.mcpServers[e]=r,(o=this.onUpdatedTools)==null||o.call(this),a}async removeMcpServer(e){var n;if(!this.mcpServers[e])return;delete this.mcpServers[e];const r=this.mcpClients[e];delete this.mcpClients[e];try{await this._closeOneClient(r)}catch{}const a=this.mcpTools[e];delete this.mcpTools[e],a&&Object.keys(a).forEach(s=>{this.ignoreToolnames=this.ignoreToolnames.filter(o=>o!==s)}),(n=this.onUpdatedTools)==null||n.call(this)}_tempMergeTools(e={}){const r=Object.values(this.mcpTools).reduce((a,n)=>({...a,...n}),{});return Object.assign(r,e),this.ignoreToolnames.forEach(a=>{delete r[a]}),r}async _chat(e,{model:r,maxSteps:a=5,...n}){var i;if(!this.llm)throw new Error("LLM is not initialized");await this.initClientsAndTools();const s={model:this.llm(r),stopWhen:wi(a),...n,tools:this._tempMergeTools(n.tools)};n.message&&!n.messages&&(this.messages.push({role:"user",content:n.message}),s.messages=[...this.messages]);const o=e(s);return(i=o==null?void 0:o.response)==null||i.then(l=>{this.messages.push(...l.messages)}),o}async chat(e){return this._chat(Ux,e)}async chatStream(e){return this._chat(sE,e)}}var Un={},sC=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then},cm={},Ut={};let Nl;const oC=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];Ut.getSymbolSize=function(e){if(!e)throw new Error('"version" cannot be null or undefined');if(e<1||e>40)throw new Error('"version" should be in range from 1 to 40');return e*4+17},Ut.getSymbolTotalCodewords=function(e){return oC[e]},Ut.getBCHDigit=function(t){let e=0;for(;t!==0;)e++,t>>>=1;return e},Ut.setToSJISFunction=function(e){if(typeof e!="function")throw new Error('"toSJISFunc" is not a valid function.');Nl=e},Ut.isKanjiModeEnabled=function(){return typeof Nl<"u"},Ut.toSJIS=function(e){return Nl(e)};var uo={};(function(t){t.L={bit:1},t.M={bit:0},t.Q={bit:3},t.H={bit:2};function e(r){if(typeof r!="string")throw new Error("Param is not a string");switch(r.toLowerCase()){case"l":case"low":return t.L;case"m":case"medium":return t.M;case"q":case"quartile":return t.Q;case"h":case"high":return t.H;default:throw new Error("Unknown EC Level: "+r)}}t.isValid=function(a){return a&&typeof a.bit<"u"&&a.bit>=0&&a.bit<4},t.from=function(a,n){if(t.isValid(a))return a;try{return e(a)}catch{return n}}})(uo);function dm(){this.buffer=[],this.length=0}dm.prototype={get:function(t){const e=Math.floor(t/8);return(this.buffer[e]>>>7-t%8&1)===1},put:function(t,e){for(let r=0;r<e;r++)this.putBit((t>>>e-r-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(t){const e=Math.floor(this.length/8);this.buffer.length<=e&&this.buffer.push(0),t&&(this.buffer[e]|=128>>>this.length%8),this.length++}};var iC=dm;function Oa(t){if(!t||t<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=t,this.data=new Uint8Array(t*t),this.reservedBit=new Uint8Array(t*t)}Oa.prototype.set=function(t,e,r,a){const n=t*this.size+e;this.data[n]=r,a&&(this.reservedBit[n]=!0)},Oa.prototype.get=function(t,e){return this.data[t*this.size+e]},Oa.prototype.xor=function(t,e,r){this.data[t*this.size+e]^=r},Oa.prototype.isReserved=function(t,e){return this.reservedBit[t*this.size+e]};var lC=Oa,pm={};(function(t){const e=Ut.getSymbolSize;t.getRowColCoords=function(a){if(a===1)return[];const n=Math.floor(a/7)+2,s=e(a),o=s===145?26:Math.ceil((s-13)/(2*n-2))*2,i=[s-7];for(let l=1;l<n-1;l++)i[l]=i[l-1]-o;return i.push(6),i.reverse()},t.getPositions=function(a){const n=[],s=t.getRowColCoords(a),o=s.length;for(let i=0;i<o;i++)for(let l=0;l<o;l++)i===0&&l===0||i===0&&l===o-1||i===o-1&&l===0||n.push([s[i],s[l]]);return n}})(pm);var hm={};const uC=Ut.getSymbolSize,fm=7;hm.getPositions=function(e){const r=uC(e);return[[0,0],[r-fm,0],[0,r-fm]]};var mm={};(function(t){t.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};const e={N1:3,N2:3,N3:40,N4:10};t.isValid=function(n){return n!=null&&n!==""&&!isNaN(n)&&n>=0&&n<=7},t.from=function(n){return t.isValid(n)?parseInt(n,10):void 0},t.getPenaltyN1=function(n){const s=n.size;let o=0,i=0,l=0,u=null,d=null;for(let v=0;v<s;v++){i=l=0,u=d=null;for(let m=0;m<s;m++){let c=n.get(v,m);c===u?i++:(i>=5&&(o+=e.N1+(i-5)),u=c,i=1),c=n.get(m,v),c===d?l++:(l>=5&&(o+=e.N1+(l-5)),d=c,l=1)}i>=5&&(o+=e.N1+(i-5)),l>=5&&(o+=e.N1+(l-5))}return o},t.getPenaltyN2=function(n){const s=n.size;let o=0;for(let i=0;i<s-1;i++)for(let l=0;l<s-1;l++){const u=n.get(i,l)+n.get(i,l+1)+n.get(i+1,l)+n.get(i+1,l+1);(u===4||u===0)&&o++}return o*e.N2},t.getPenaltyN3=function(n){const s=n.size;let o=0,i=0,l=0;for(let u=0;u<s;u++){i=l=0;for(let d=0;d<s;d++)i=i<<1&2047|n.get(u,d),d>=10&&(i===1488||i===93)&&o++,l=l<<1&2047|n.get(d,u),d>=10&&(l===1488||l===93)&&o++}return o*e.N3},t.getPenaltyN4=function(n){let s=0;const o=n.data.length;for(let l=0;l<o;l++)s+=n.data[l];return Math.abs(Math.ceil(s*100/o/5)-10)*e.N4};function r(a,n,s){switch(a){case t.Patterns.PATTERN000:return(n+s)%2===0;case t.Patterns.PATTERN001:return n%2===0;case t.Patterns.PATTERN010:return s%3===0;case t.Patterns.PATTERN011:return(n+s)%3===0;case t.Patterns.PATTERN100:return(Math.floor(n/2)+Math.floor(s/3))%2===0;case t.Patterns.PATTERN101:return n*s%2+n*s%3===0;case t.Patterns.PATTERN110:return(n*s%2+n*s%3)%2===0;case t.Patterns.PATTERN111:return(n*s%3+(n+s)%2)%2===0;default:throw new Error("bad maskPattern:"+a)}}t.applyMask=function(n,s){const o=s.size;for(let i=0;i<o;i++)for(let l=0;l<o;l++)s.isReserved(l,i)||s.xor(l,i,r(n,l,i))},t.getBestMask=function(n,s){const o=Object.keys(t.Patterns).length;let i=0,l=1/0;for(let u=0;u<o;u++){s(u),t.applyMask(u,n);const d=t.getPenaltyN1(n)+t.getPenaltyN2(n)+t.getPenaltyN3(n)+t.getPenaltyN4(n);t.applyMask(u,n),d<l&&(l=d,i=u)}return i}})(mm);var co={};const Br=uo,po=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],ho=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];co.getBlocksCount=function(e,r){switch(r){case Br.L:return po[(e-1)*4+0];case Br.M:return po[(e-1)*4+1];case Br.Q:return po[(e-1)*4+2];case Br.H:return po[(e-1)*4+3];default:return}},co.getTotalCodewordsCount=function(e,r){switch(r){case Br.L:return ho[(e-1)*4+0];case Br.M:return ho[(e-1)*4+1];case Br.Q:return ho[(e-1)*4+2];case Br.H:return ho[(e-1)*4+3];default:return}};var vm={},fo={};const $a=new Uint8Array(512),mo=new Uint8Array(256);(function(){let e=1;for(let r=0;r<255;r++)$a[r]=e,mo[e]=r,e<<=1,e&256&&(e^=285);for(let r=255;r<512;r++)$a[r]=$a[r-255]})(),fo.log=function(e){if(e<1)throw new Error("log("+e+")");return mo[e]},fo.exp=function(e){return $a[e]},fo.mul=function(e,r){return e===0||r===0?0:$a[mo[e]+mo[r]]},function(t){const e=fo;t.mul=function(a,n){const s=new Uint8Array(a.length+n.length-1);for(let o=0;o<a.length;o++)for(let i=0;i<n.length;i++)s[o+i]^=e.mul(a[o],n[i]);return s},t.mod=function(a,n){let s=new Uint8Array(a);for(;s.length-n.length>=0;){const o=s[0];for(let l=0;l<n.length;l++)s[l]^=e.mul(n[l],o);let i=0;for(;i<s.length&&s[i]===0;)i++;s=s.slice(i)}return s},t.generateECPolynomial=function(a){let n=new Uint8Array([1]);for(let s=0;s<a;s++)n=t.mul(n,new Uint8Array([1,e.exp(s)]));return n}}(vm);const gm=vm;function Ml(t){this.genPoly=void 0,this.degree=t,this.degree&&this.initialize(this.degree)}Ml.prototype.initialize=function(e){this.degree=e,this.genPoly=gm.generateECPolynomial(this.degree)},Ml.prototype.encode=function(e){if(!this.genPoly)throw new Error("Encoder not initialized");const r=new Uint8Array(e.length+this.degree);r.set(e);const a=gm.mod(r,this.genPoly),n=this.degree-a.length;if(n>0){const s=new Uint8Array(this.degree);return s.set(a,n),s}return a};var cC=Ml,ym={},Hr={},Dl={};Dl.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40};var wr={};const _m="[0-9]+",dC="[A-Z $%*+\\-./:]+";let Aa="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";Aa=Aa.replace(/u/g,"\\u");const pC="(?:(?![A-Z0-9 $%*+\\-./:]|"+Aa+`)(?:.|[\r
68
- ]))+`;wr.KANJI=new RegExp(Aa,"g"),wr.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),wr.BYTE=new RegExp(pC,"g"),wr.NUMERIC=new RegExp(_m,"g"),wr.ALPHANUMERIC=new RegExp(dC,"g");const hC=new RegExp("^"+Aa+"$"),fC=new RegExp("^"+_m+"$"),mC=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");wr.testKanji=function(e){return hC.test(e)},wr.testNumeric=function(e){return fC.test(e)},wr.testAlphanumeric=function(e){return mC.test(e)},function(t){const e=Dl,r=wr;t.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]},t.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]},t.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]},t.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]},t.MIXED={bit:-1},t.getCharCountIndicator=function(s,o){if(!s.ccBits)throw new Error("Invalid mode: "+s);if(!e.isValid(o))throw new Error("Invalid version: "+o);return o>=1&&o<10?s.ccBits[0]:o<27?s.ccBits[1]:s.ccBits[2]},t.getBestModeForData=function(s){return r.testNumeric(s)?t.NUMERIC:r.testAlphanumeric(s)?t.ALPHANUMERIC:r.testKanji(s)?t.KANJI:t.BYTE},t.toString=function(s){if(s&&s.id)return s.id;throw new Error("Invalid mode")},t.isValid=function(s){return s&&s.bit&&s.ccBits};function a(n){if(typeof n!="string")throw new Error("Param is not a string");switch(n.toLowerCase()){case"numeric":return t.NUMERIC;case"alphanumeric":return t.ALPHANUMERIC;case"kanji":return t.KANJI;case"byte":return t.BYTE;default:throw new Error("Unknown mode: "+n)}}t.from=function(s,o){if(t.isValid(s))return s;try{return a(s)}catch{return o}}}(Hr),function(t){const e=Ut,r=co,a=uo,n=Hr,s=Dl,o=7973,i=e.getBCHDigit(o);function l(m,c,h){for(let g=1;g<=40;g++)if(c<=t.getCapacity(g,h,m))return g}function u(m,c){return n.getCharCountIndicator(m,c)+4}function d(m,c){let h=0;return m.forEach(function(g){const f=u(g.mode,c);h+=f+g.getBitsLength()}),h}function v(m,c){for(let h=1;h<=40;h++)if(d(m,h)<=t.getCapacity(h,c,n.MIXED))return h}t.from=function(c,h){return s.isValid(c)?parseInt(c,10):h},t.getCapacity=function(c,h,g){if(!s.isValid(c))throw new Error("Invalid QR Code version");typeof g>"u"&&(g=n.BYTE);const f=e.getSymbolTotalCodewords(c),p=r.getTotalCodewordsCount(c,h),b=(f-p)*8;if(g===n.MIXED)return b;const y=b-u(g,c);switch(g){case n.NUMERIC:return Math.floor(y/10*3);case n.ALPHANUMERIC:return Math.floor(y/11*2);case n.KANJI:return Math.floor(y/13);case n.BYTE:default:return Math.floor(y/8)}},t.getBestVersionForData=function(c,h){let g;const f=a.from(h,a.M);if(Array.isArray(c)){if(c.length>1)return v(c,f);if(c.length===0)return 1;g=c[0]}else g=c;return l(g.mode,g.getLength(),f)},t.getEncodedBits=function(c){if(!s.isValid(c)||c<7)throw new Error("Invalid QR Code version");let h=c<<12;for(;e.getBCHDigit(h)-i>=0;)h^=o<<e.getBCHDigit(h)-i;return c<<12|h}}(ym);var wm={};const jl=Ut,bm=1335,vC=21522,xm=jl.getBCHDigit(bm);wm.getEncodedBits=function(e,r){const a=e.bit<<3|r;let n=a<<10;for(;jl.getBCHDigit(n)-xm>=0;)n^=bm<<jl.getBCHDigit(n)-xm;return(a<<10|n)^vC};var Em={};const gC=Hr;function Fn(t){this.mode=gC.NUMERIC,this.data=t.toString()}Fn.getBitsLength=function(e){return 10*Math.floor(e/3)+(e%3?e%3*3+1:0)},Fn.prototype.getLength=function(){return this.data.length},Fn.prototype.getBitsLength=function(){return Fn.getBitsLength(this.data.length)},Fn.prototype.write=function(e){let r,a,n;for(r=0;r+3<=this.data.length;r+=3)a=this.data.substr(r,3),n=parseInt(a,10),e.put(n,10);const s=this.data.length-r;s>0&&(a=this.data.substr(r),n=parseInt(a,10),e.put(n,s*3+1))};var yC=Fn;const _C=Hr,zl=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function qn(t){this.mode=_C.ALPHANUMERIC,this.data=t}qn.getBitsLength=function(e){return 11*Math.floor(e/2)+6*(e%2)},qn.prototype.getLength=function(){return this.data.length},qn.prototype.getBitsLength=function(){return qn.getBitsLength(this.data.length)},qn.prototype.write=function(e){let r;for(r=0;r+2<=this.data.length;r+=2){let a=zl.indexOf(this.data[r])*45;a+=zl.indexOf(this.data[r+1]),e.put(a,11)}this.data.length%2&&e.put(zl.indexOf(this.data[r]),6)};var wC=qn;const bC=Hr;function Zn(t){this.mode=bC.BYTE,typeof t=="string"?this.data=new TextEncoder().encode(t):this.data=new Uint8Array(t)}Zn.getBitsLength=function(e){return e*8},Zn.prototype.getLength=function(){return this.data.length},Zn.prototype.getBitsLength=function(){return Zn.getBitsLength(this.data.length)},Zn.prototype.write=function(t){for(let e=0,r=this.data.length;e<r;e++)t.put(this.data[e],8)};var xC=Zn;const EC=Hr,SC=Ut;function Vn(t){this.mode=EC.KANJI,this.data=t}Vn.getBitsLength=function(e){return e*13},Vn.prototype.getLength=function(){return this.data.length},Vn.prototype.getBitsLength=function(){return Vn.getBitsLength(this.data.length)},Vn.prototype.write=function(t){let e;for(e=0;e<this.data.length;e++){let r=SC.toSJIS(this.data[e]);if(r>=33088&&r<=40956)r-=33088;else if(r>=57408&&r<=60351)r-=49472;else throw new Error("Invalid SJIS character: "+this.data[e]+`
69
- Make sure your charset is UTF-8`);r=(r>>>8&255)*192+(r&255),t.put(r,13)}};var IC=Vn,Sm={exports:{}};(function(t){var e={single_source_shortest_paths:function(r,a,n){var s={},o={};o[a]=0;var i=e.PriorityQueue.make();i.push(a,0);for(var l,u,d,v,m,c,h,g,f;!i.empty();){l=i.pop(),u=l.value,v=l.cost,m=r[u]||{};for(d in m)m.hasOwnProperty(d)&&(c=m[d],h=v+c,g=o[d],f=typeof o[d]>"u",(f||g>h)&&(o[d]=h,i.push(d,h),s[d]=u))}if(typeof n<"u"&&typeof o[n]>"u"){var p=["Could not find a path from ",a," to ",n,"."].join("");throw new Error(p)}return s},extract_shortest_path_from_predecessor_list:function(r,a){for(var n=[],s=a;s;)n.push(s),r[s],s=r[s];return n.reverse(),n},find_path:function(r,a,n){var s=e.single_source_shortest_paths(r,a,n);return e.extract_shortest_path_from_predecessor_list(s,n)},PriorityQueue:{make:function(r){var a=e.PriorityQueue,n={},s;r=r||{};for(s in a)a.hasOwnProperty(s)&&(n[s]=a[s]);return n.queue=[],n.sorter=r.sorter||a.default_sorter,n},default_sorter:function(r,a){return r.cost-a.cost},push:function(r,a){var n={value:r,cost:a};this.queue.push(n),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};t.exports=e})(Sm);var kC=Sm.exports;(function(t){const e=Hr,r=yC,a=wC,n=xC,s=IC,o=wr,i=Ut,l=kC;function u(p){return unescape(encodeURIComponent(p)).length}function d(p,b,y){const _=[];let S;for(;(S=p.exec(y))!==null;)_.push({data:S[0],index:S.index,mode:b,length:S[0].length});return _}function v(p){const b=d(o.NUMERIC,e.NUMERIC,p),y=d(o.ALPHANUMERIC,e.ALPHANUMERIC,p);let _,S;return i.isKanjiModeEnabled()?(_=d(o.BYTE,e.BYTE,p),S=d(o.KANJI,e.KANJI,p)):(_=d(o.BYTE_KANJI,e.BYTE,p),S=[]),b.concat(y,_,S).sort(function(I,O){return I.index-O.index}).map(function(I){return{data:I.data,mode:I.mode,length:I.length}})}function m(p,b){switch(b){case e.NUMERIC:return r.getBitsLength(p);case e.ALPHANUMERIC:return a.getBitsLength(p);case e.KANJI:return s.getBitsLength(p);case e.BYTE:return n.getBitsLength(p)}}function c(p){return p.reduce(function(b,y){const _=b.length-1>=0?b[b.length-1]:null;return _&&_.mode===y.mode?(b[b.length-1].data+=y.data,b):(b.push(y),b)},[])}function h(p){const b=[];for(let y=0;y<p.length;y++){const _=p[y];switch(_.mode){case e.NUMERIC:b.push([_,{data:_.data,mode:e.ALPHANUMERIC,length:_.length},{data:_.data,mode:e.BYTE,length:_.length}]);break;case e.ALPHANUMERIC:b.push([_,{data:_.data,mode:e.BYTE,length:_.length}]);break;case e.KANJI:b.push([_,{data:_.data,mode:e.BYTE,length:u(_.data)}]);break;case e.BYTE:b.push([{data:_.data,mode:e.BYTE,length:u(_.data)}])}}return b}function g(p,b){const y={},_={start:{}};let S=["start"];for(let T=0;T<p.length;T++){const I=p[T],O=[];for(let R=0;R<I.length;R++){const L=I[R],U=""+T+R;O.push(U),y[U]={node:L,lastCount:0},_[U]={};for(let Z=0;Z<S.length;Z++){const M=S[Z];y[M]&&y[M].node.mode===L.mode?(_[M][U]=m(y[M].lastCount+L.length,L.mode)-m(y[M].lastCount,L.mode),y[M].lastCount+=L.length):(y[M]&&(y[M].lastCount=L.length),_[M][U]=m(L.length,L.mode)+4+e.getCharCountIndicator(L.mode,b))}}S=O}for(let T=0;T<S.length;T++)_[S[T]].end=0;return{map:_,table:y}}function f(p,b){let y;const _=e.getBestModeForData(p);if(y=e.from(b,_),y!==e.BYTE&&y.bit<_.bit)throw new Error('"'+p+'" cannot be encoded with mode '+e.toString(y)+`.
70
- Suggested mode is: `+e.toString(_));switch(y===e.KANJI&&!i.isKanjiModeEnabled()&&(y=e.BYTE),y){case e.NUMERIC:return new r(p);case e.ALPHANUMERIC:return new a(p);case e.KANJI:return new s(p);case e.BYTE:return new n(p)}}t.fromArray=function(b){return b.reduce(function(y,_){return typeof _=="string"?y.push(f(_,null)):_.data&&y.push(f(_.data,_.mode)),y},[])},t.fromString=function(b,y){const _=v(b,i.isKanjiModeEnabled()),S=h(_),T=g(S,y),I=l.find_path(T.map,"start","end"),O=[];for(let R=1;R<I.length-1;R++)O.push(T.table[I[R]].node);return t.fromArray(c(O))},t.rawSplit=function(b){return t.fromArray(v(b,i.isKanjiModeEnabled()))}})(Em);const vo=Ut,Ll=uo,TC=iC,PC=lC,CC=pm,RC=hm,Ul=mm,Fl=co,OC=cC,go=ym,$C=wm,AC=Hr,ql=Em;function NC(t,e){const r=t.size,a=RC.getPositions(e);for(let n=0;n<a.length;n++){const s=a[n][0],o=a[n][1];for(let i=-1;i<=7;i++)if(!(s+i<=-1||r<=s+i))for(let l=-1;l<=7;l++)o+l<=-1||r<=o+l||(i>=0&&i<=6&&(l===0||l===6)||l>=0&&l<=6&&(i===0||i===6)||i>=2&&i<=4&&l>=2&&l<=4?t.set(s+i,o+l,!0,!0):t.set(s+i,o+l,!1,!0))}}function MC(t){const e=t.size;for(let r=8;r<e-8;r++){const a=r%2===0;t.set(r,6,a,!0),t.set(6,r,a,!0)}}function DC(t,e){const r=CC.getPositions(e);for(let a=0;a<r.length;a++){const n=r[a][0],s=r[a][1];for(let o=-2;o<=2;o++)for(let i=-2;i<=2;i++)o===-2||o===2||i===-2||i===2||o===0&&i===0?t.set(n+o,s+i,!0,!0):t.set(n+o,s+i,!1,!0)}}function jC(t,e){const r=t.size,a=go.getEncodedBits(e);let n,s,o;for(let i=0;i<18;i++)n=Math.floor(i/3),s=i%3+r-8-3,o=(a>>i&1)===1,t.set(n,s,o,!0),t.set(s,n,o,!0)}function Zl(t,e,r){const a=t.size,n=$C.getEncodedBits(e,r);let s,o;for(s=0;s<15;s++)o=(n>>s&1)===1,s<6?t.set(s,8,o,!0):s<8?t.set(s+1,8,o,!0):t.set(a-15+s,8,o,!0),s<8?t.set(8,a-s-1,o,!0):s<9?t.set(8,15-s-1+1,o,!0):t.set(8,15-s-1,o,!0);t.set(a-8,8,1,!0)}function zC(t,e){const r=t.size;let a=-1,n=r-1,s=7,o=0;for(let i=r-1;i>0;i-=2)for(i===6&&i--;;){for(let l=0;l<2;l++)if(!t.isReserved(n,i-l)){let u=!1;o<e.length&&(u=(e[o]>>>s&1)===1),t.set(n,i-l,u),s--,s===-1&&(o++,s=7)}if(n+=a,n<0||r<=n){n-=a,a=-a;break}}}function LC(t,e,r){const a=new TC;r.forEach(function(l){a.put(l.mode.bit,4),a.put(l.getLength(),AC.getCharCountIndicator(l.mode,t)),l.write(a)});const n=vo.getSymbolTotalCodewords(t),s=Fl.getTotalCodewordsCount(t,e),o=(n-s)*8;for(a.getLengthInBits()+4<=o&&a.put(0,4);a.getLengthInBits()%8!==0;)a.putBit(0);const i=(o-a.getLengthInBits())/8;for(let l=0;l<i;l++)a.put(l%2?17:236,8);return UC(a,t,e)}function UC(t,e,r){const a=vo.getSymbolTotalCodewords(e),n=Fl.getTotalCodewordsCount(e,r),s=a-n,o=Fl.getBlocksCount(e,r),i=a%o,l=o-i,u=Math.floor(a/o),d=Math.floor(s/o),v=d+1,m=u-d,c=new OC(m);let h=0;const g=new Array(o),f=new Array(o);let p=0;const b=new Uint8Array(t.buffer);for(let I=0;I<o;I++){const O=I<l?d:v;g[I]=b.slice(h,h+O),f[I]=c.encode(g[I]),h+=O,p=Math.max(p,O)}const y=new Uint8Array(a);let _=0,S,T;for(S=0;S<p;S++)for(T=0;T<o;T++)S<g[T].length&&(y[_++]=g[T][S]);for(S=0;S<m;S++)for(T=0;T<o;T++)y[_++]=f[T][S];return y}function FC(t,e,r,a){let n;if(Array.isArray(t))n=ql.fromArray(t);else if(typeof t=="string"){let u=e;if(!u){const d=ql.rawSplit(t);u=go.getBestVersionForData(d,r)}n=ql.fromString(t,u||40)}else throw new Error("Invalid data");const s=go.getBestVersionForData(n,r);if(!s)throw new Error("The amount of data is too big to be stored in a QR Code");if(!e)e=s;else if(e<s)throw new Error(`
53
+ Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`,new ym({message:i,statusCode:o,cause:s})}},Ud="GatewayInvalidRequestError",mw=`vercel.ai.gateway.error.${Ud}`,qd=Symbol.for(mw),Zd,Fd,gw=class extends(Fd=bt,Zd=qd,Fd){constructor({message:e="Invalid request",statusCode:t=400,cause:n}={}){super({message:e,statusCode:t,cause:n}),this[Zd]=!0,this.name=Ud,this.type="invalid_request_error"}static isInstance(e){return bt.hasMarker(e)&&qd in e}},Vd="GatewayRateLimitError",vw=`vercel.ai.gateway.error.${Vd}`,Bd=Symbol.for(vw),Hd,Jd,_w=class extends(Jd=bt,Hd=Bd,Jd){constructor({message:e="Rate limit exceeded",statusCode:t=429,cause:n}={}){super({message:e,statusCode:t,cause:n}),this[Hd]=!0,this.name=Vd,this.type="rate_limit_exceeded"}static isInstance(e){return bt.hasMarker(e)&&Bd in e}},Gd="GatewayModelNotFoundError",yw=`vercel.ai.gateway.error.${Gd}`,Wd=Symbol.for(yw),ww=ir(()=>qn(S({modelId:p()}))),Kd,Yd,Qd=class extends(Yd=bt,Kd=Wd,Yd){constructor({message:e="Model not found",statusCode:t=404,modelId:n,cause:r}={}){super({message:e,statusCode:t,cause:r}),this[Kd]=!0,this.name=Gd,this.type="model_not_found",this.modelId=n}static isInstance(e){return bt.hasMarker(e)&&Wd in e}},Xd="GatewayInternalServerError",bw=`vercel.ai.gateway.error.${Xd}`,e0=Symbol.for(bw),t0,n0,r0=class extends(n0=bt,t0=e0,n0){constructor({message:e="Internal server error",statusCode:t=500,cause:n}={}){super({message:e,statusCode:t,cause:n}),this[t0]=!0,this.name=Xd,this.type="internal_server_error"}static isInstance(e){return bt.hasMarker(e)&&e0 in e}},o0="GatewayResponseError",$w=`vercel.ai.gateway.error.${o0}`,s0=Symbol.for($w),i0,a0,Sw=class extends(a0=bt,i0=s0,a0){constructor({message:e="Invalid response from Gateway",statusCode:t=502,response:n,validationError:r,cause:o}={}){super({message:e,statusCode:t,cause:o}),this[i0]=!0,this.name=o0,this.type="response_error",this.response=n,this.validationError=r}static isInstance(e){return bt.hasMarker(e)&&s0 in e}};async function l0({response:e,statusCode:t,defaultMessage:n="Gateway request failed",cause:r,authMethod:o}){const s=await $n({value:e,schema:Cw});if(!s.success)return new Sw({message:`Invalid error response format: ${n}`,statusCode:t,response:e,validationError:s.error,cause:r});const i=s.value,a=i.error.type,l=i.error.message;switch(a){case"authentication_error":return Ji.createContextualError({apiKeyProvided:o==="api-key",oidcTokenProvided:o==="oidc",statusCode:t,cause:r});case"invalid_request_error":return new gw({message:l,statusCode:t,cause:r});case"rate_limit_exceeded":return new _w({message:l,statusCode:t,cause:r});case"model_not_found":{const c=await $n({value:i.error.param,schema:ww});return new Qd({message:l,statusCode:t,modelId:c.success?c.value.modelId:void 0,cause:r})}case"internal_server_error":return new r0({message:l,statusCode:t,cause:r});default:return new r0({message:l,statusCode:t,cause:r})}}var Cw=ir(()=>qn(S({error:S({message:p(),type:p().nullish(),param:ke().nullish(),code:Q([p(),R()]).nullish()})})));function Zn(e,t){var n;return bt.isInstance(e)?e:Ie.isInstance(e)?l0({response:Ew(e),statusCode:(n=e.statusCode)!=null?n:500,defaultMessage:"Gateway request failed",cause:e,authMethod:t}):l0({response:{},statusCode:500,defaultMessage:e instanceof Error?`Gateway request failed: ${e.message}`:"Unknown Gateway error",cause:e,authMethod:t})}function Ew(e){if(e.data!==void 0)return e.data;if(e.responseBody!=null)try{return JSON.parse(e.responseBody)}catch{return e.responseBody}return{}}var c0="ai-gateway-auth-method";async function Gr(e){const t=await $n({value:e[c0],schema:kw});return t.success?t.value:void 0}var kw=ir(()=>qn(Q([O("api-key"),O("oidc")]))),u0=class{constructor(e){this.config=e}async getAvailableModels(){try{const{value:e}=await wd({url:`${this.config.baseURL}/config`,headers:await Sn(this.config.headers()),successfulResponseHandler:Jo(Iw),failedResponseHandler:Hr({errorSchema:yt(),errorToMessage:t=>t}),fetch:this.config.fetch});return e}catch(e){throw await Zn(e)}}async getCredits(){try{const e=new URL(this.config.baseURL),{value:t}=await wd({url:`${e.origin}/v1/credits`,headers:await Sn(this.config.headers()),successfulResponseHandler:Jo(Tw),failedResponseHandler:Hr({errorSchema:yt(),errorToMessage:n=>n}),fetch:this.config.fetch});return t}catch(e){throw await Zn(e)}}},Iw=ir(()=>qn(S({models:N(S({id:p(),name:p(),description:p().nullish(),pricing:S({input:p(),output:p(),input_cache_read:p().nullish(),input_cache_write:p().nullish()}).transform(({input:e,output:t,input_cache_read:n,input_cache_write:r})=>({input:e,output:t,...n?{cachedInputTokens:n}:{},...r?{cacheCreationInputTokens:r}:{}})).nullish(),specification:S({specificationVersion:O("v2"),provider:p(),modelId:p()}),modelType:me(["language","embedding","image"]).nullish()}))}))),Tw=ir(()=>qn(S({balance:p(),total_used:p()}).transform(({balance:e,total_used:t})=>({balance:e,totalUsed:t})))),xw=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2",this.supportedUrls={"*/*":[/.*/]}}get provider(){return this.config.provider}async getArgs(e){const{abortSignal:t,...n}=e;return{args:this.maybeEncodeFileParts(n),warnings:[]}}async doGenerate(e){const{args:t,warnings:n}=await this.getArgs(e),{abortSignal:r}=e,o=await Sn(this.config.headers());try{const{responseHeaders:s,value:i,rawValue:a}=await ji({url:this.getUrl(),headers:Mi(o,e.headers,this.getModelConfigHeaders(this.modelId,!1),await Sn(this.config.o11yHeaders)),body:t,successfulResponseHandler:Jo(yt()),failedResponseHandler:Hr({errorSchema:yt(),errorToMessage:l=>l}),...r&&{abortSignal:r},fetch:this.config.fetch});return{...i,request:{body:t},response:{headers:s,body:a},warnings:n}}catch(s){throw await Zn(s,await Gr(o))}}async doStream(e){const{args:t,warnings:n}=await this.getArgs(e),{abortSignal:r}=e,o=await Sn(this.config.headers());try{const{value:s,responseHeaders:i}=await ji({url:this.getUrl(),headers:Mi(o,e.headers,this.getModelConfigHeaders(this.modelId,!0),await Sn(this.config.o11yHeaders)),body:t,successfulResponseHandler:X_(yt()),failedResponseHandler:Hr({errorSchema:yt(),errorToMessage:a=>a}),...r&&{abortSignal:r},fetch:this.config.fetch});return{stream:s.pipeThrough(new TransformStream({start(a){n.length>0&&a.enqueue({type:"stream-start",warnings:n})},transform(a,l){if(a.success){const c=a.value;if(c.type==="raw"&&!e.includeRawChunks)return;c.type==="response-metadata"&&c.timestamp&&typeof c.timestamp=="string"&&(c.timestamp=new Date(c.timestamp)),l.enqueue(c)}else l.error(a.error)}})),request:{body:t},response:{headers:i}}}catch(s){throw await Zn(s,await Gr(o))}}isFilePart(e){return e&&typeof e=="object"&&"type"in e&&e.type==="file"}maybeEncodeFileParts(e){for(const t of e.prompt)for(const n of t.content)if(this.isFilePart(n)){const r=n;if(r.data instanceof Uint8Array){const o=Uint8Array.from(r.data),s=Buffer.from(o).toString("base64");r.data=new URL(`data:${r.mediaType||"application/octet-stream"};base64,${s}`)}}return e}getUrl(){return`${this.config.baseURL}/language-model`}getModelConfigHeaders(e,t){return{"ai-language-model-specification-version":"2","ai-language-model-id":e,"ai-language-model-streaming":String(t)}}},Pw=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:n,providerOptions:r}){var o;const s=await Sn(this.config.headers());try{const{responseHeaders:i,value:a,rawValue:l}=await ji({url:this.getUrl(),headers:Mi(s,t??{},this.getModelConfigHeaders(),await Sn(this.config.o11yHeaders)),body:{input:e.length===1?e[0]:e,...r?{providerOptions:r}:{}},successfulResponseHandler:Jo(Rw),failedResponseHandler:Hr({errorSchema:yt(),errorToMessage:c=>c}),...n&&{abortSignal:n},fetch:this.config.fetch});return{embeddings:a.embeddings,usage:(o=a.usage)!=null?o:void 0,providerMetadata:a.providerMetadata,response:{headers:i,body:l}}}catch(i){throw await Zn(i,await Gr(s))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":"2","ai-model-id":this.modelId}}},Rw=ir(()=>qn(S({embeddings:N(N(R())),usage:S({tokens:R()}).nullish(),providerMetadata:ie(p(),ie(p(),ke())).optional()})));async function Ow(){var e;return(e=Nd.getContext().headers)==null?void 0:e["x-vercel-id"]}var Nw="2.0.0",Mw="0.0.1";function Aw(e={}){var t,n;let r=null,o=null;const s=(t=e.metadataCacheRefreshMillis)!=null?t:1e3*60*5;let i=0;const a=(n=Jy(e.baseURL))!=null?n:"https://ai-gateway.vercel.sh/v1/ai",l=async()=>{const g=await jw(e);if(g)return Dn({Authorization:`Bearer ${g.token}`,"ai-gateway-protocol-version":Mw,[c0]:g.authMethod,...e.headers},`ai-sdk/gateway/${Nw}`);throw Ji.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401})},c=()=>{const g=Bo({settingValue:void 0,environmentVariableName:"VERCEL_DEPLOYMENT_ID"}),v=Bo({settingValue:void 0,environmentVariableName:"VERCEL_ENV"}),m=Bo({settingValue:void 0,environmentVariableName:"VERCEL_REGION"});return async()=>{const d=await Ow();return{...g&&{"ai-o11y-deployment-id":g},...v&&{"ai-o11y-environment":v},...m&&{"ai-o11y-region":m},...d&&{"ai-o11y-request-id":d}}}},u=g=>new xw(g,{provider:"gateway",baseURL:a,headers:l,fetch:e.fetch,o11yHeaders:c()}),h=async()=>{var g,v,m;const d=(m=(v=(g=e._internal)==null?void 0:g.currentDate)==null?void 0:v.call(g).getTime())!=null?m:Date.now();return(!r||d-i>s)&&(i=d,r=new u0({baseURL:a,headers:l,fetch:e.fetch}).getAvailableModels().then(w=>(o=w,w)).catch(async w=>{throw await Zn(w,await Gr(await l()))})),o?Promise.resolve(o):r},_=async()=>new u0({baseURL:a,headers:l,fetch:e.fetch}).getCredits().catch(async g=>{throw await Zn(g,await Gr(await l()))}),f=function(g){if(new.target)throw new Error("The Gateway Provider model function cannot be called with the new keyword.");return u(g)};return f.getAvailableModels=h,f.getCredits=_,f.imageModel=g=>{throw new _i({modelId:g,modelType:"imageModel"})},f.languageModel=u,f.textEmbeddingModel=g=>new Pw(g,{provider:"gateway",baseURL:a,headers:l,fetch:e.fetch,o11yHeaders:c()}),f}var Lw=Aw();async function jw(e){const t=Bo({settingValue:e.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});if(t)return{token:t,authMethod:"api-key"};try{return{token:await Nd.getVercelOidcToken(),authMethod:"oidc"}}catch{return null}}var zw=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{},Fn="1.9.0",d0=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function Dw(e){var t=new Set([e]),n=new Set,r=e.match(d0);if(!r)return function(){return!1};var o={major:+r[1],minor:+r[2],patch:+r[3],prerelease:r[4]};if(o.prerelease!=null)return function(l){return l===e};function s(a){return n.add(a),!1}function i(a){return t.add(a),!0}return function(l){if(t.has(l))return!0;if(n.has(l))return!1;var c=l.match(d0);if(!c)return s(l);var u={major:+c[1],minor:+c[2],patch:+c[3],prerelease:c[4]};return u.prerelease!=null||o.major!==u.major?s(l):o.major===0?o.minor===u.minor&&o.patch<=u.patch?i(l):s(l):o.minor<=u.minor?i(l):s(l)}}var Uw=Dw(Fn),qw=Fn.split(".")[0],Wr=Symbol.for("opentelemetry.js.api."+qw),Kr=zw;function Yr(e,t,n,r){var o;r===void 0&&(r=!1);var s=Kr[Wr]=(o=Kr[Wr])!==null&&o!==void 0?o:{version:Fn};if(!r&&s[e]){var i=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+e);return n.error(i.stack||i.message),!1}if(s.version!==Fn){var i=new Error("@opentelemetry/api: Registration of version v"+s.version+" for "+e+" does not match previously registered API v"+Fn);return n.error(i.stack||i.message),!1}return s[e]=t,n.debug("@opentelemetry/api: Registered a global for "+e+" v"+Fn+"."),!0}function Vn(e){var t,n,r=(t=Kr[Wr])===null||t===void 0?void 0:t.version;if(!(!r||!Uw(r)))return(n=Kr[Wr])===null||n===void 0?void 0:n[e]}function Qr(e,t){t.debug("@opentelemetry/api: Unregistering a global for "+e+" v"+Fn+".");var n=Kr[Wr];n&&delete n[e]}var Zw=function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),o,s=[],i;try{for(;(t===void 0||t-- >0)&&!(o=r.next()).done;)s.push(o.value)}catch(a){i={error:a}}finally{try{o&&!o.done&&(n=r.return)&&n.call(r)}finally{if(i)throw i.error}}return s},Fw=function(e,t,n){if(n||arguments.length===2)for(var r=0,o=t.length,s;r<o;r++)(s||!(r in t))&&(s||(s=Array.prototype.slice.call(t,0,r)),s[r]=t[r]);return e.concat(s||Array.prototype.slice.call(t))},Vw=function(){function e(t){this._namespace=t.namespace||"DiagComponentLogger"}return e.prototype.debug=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return Xr("debug",this._namespace,t)},e.prototype.error=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return Xr("error",this._namespace,t)},e.prototype.info=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return Xr("info",this._namespace,t)},e.prototype.warn=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return Xr("warn",this._namespace,t)},e.prototype.verbose=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return Xr("verbose",this._namespace,t)},e}();function Xr(e,t,n){var r=Vn("diag");if(r)return n.unshift(t),r[e].apply(r,Fw([],Zw(n),!1))}var $t;(function(e){e[e.NONE=0]="NONE",e[e.ERROR=30]="ERROR",e[e.WARN=50]="WARN",e[e.INFO=60]="INFO",e[e.DEBUG=70]="DEBUG",e[e.VERBOSE=80]="VERBOSE",e[e.ALL=9999]="ALL"})($t||($t={}));function Bw(e,t){e<$t.NONE?e=$t.NONE:e>$t.ALL&&(e=$t.ALL),t=t||{};function n(r,o){var s=t[r];return typeof s=="function"&&e>=o?s.bind(t):function(){}}return{error:n("error",$t.ERROR),warn:n("warn",$t.WARN),info:n("info",$t.INFO),debug:n("debug",$t.DEBUG),verbose:n("verbose",$t.VERBOSE)}}var Hw=function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),o,s=[],i;try{for(;(t===void 0||t-- >0)&&!(o=r.next()).done;)s.push(o.value)}catch(a){i={error:a}}finally{try{o&&!o.done&&(n=r.return)&&n.call(r)}finally{if(i)throw i.error}}return s},Jw=function(e,t,n){if(n||arguments.length===2)for(var r=0,o=t.length,s;r<o;r++)(s||!(r in t))&&(s||(s=Array.prototype.slice.call(t,0,r)),s[r]=t[r]);return e.concat(s||Array.prototype.slice.call(t))},Gw="diag",Wt=function(){function e(){function t(o){return function(){for(var s=[],i=0;i<arguments.length;i++)s[i]=arguments[i];var a=Vn("diag");if(a)return a[o].apply(a,Jw([],Hw(s),!1))}}var n=this,r=function(o,s){var i,a,l;if(s===void 0&&(s={logLevel:$t.INFO}),o===n){var c=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return n.error((i=c.stack)!==null&&i!==void 0?i:c.message),!1}typeof s=="number"&&(s={logLevel:s});var u=Vn("diag"),h=Bw((a=s.logLevel)!==null&&a!==void 0?a:$t.INFO,o);if(u&&!s.suppressOverrideMessage){var _=(l=new Error().stack)!==null&&l!==void 0?l:"<failed to generate stacktrace>";u.warn("Current logger will be overwritten from "+_),h.warn("Current logger will overwrite one already registered from "+_)}return Yr("diag",h,n,!0)};n.setLogger=r,n.disable=function(){Qr(Gw,n)},n.createComponentLogger=function(o){return new Vw(o)},n.verbose=t("verbose"),n.debug=t("debug"),n.info=t("info"),n.warn=t("warn"),n.error=t("error")}return e.instance=function(){return this._instance||(this._instance=new e),this._instance},e}(),Ww=function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),o,s=[],i;try{for(;(t===void 0||t-- >0)&&!(o=r.next()).done;)s.push(o.value)}catch(a){i={error:a}}finally{try{o&&!o.done&&(n=r.return)&&n.call(r)}finally{if(i)throw i.error}}return s},Kw=function(e){var t=typeof Symbol=="function"&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},Yw=function(){function e(t){this._entries=t?new Map(t):new Map}return e.prototype.getEntry=function(t){var n=this._entries.get(t);if(n)return Object.assign({},n)},e.prototype.getAllEntries=function(){return Array.from(this._entries.entries()).map(function(t){var n=Ww(t,2),r=n[0],o=n[1];return[r,o]})},e.prototype.setEntry=function(t,n){var r=new e(this._entries);return r._entries.set(t,n),r},e.prototype.removeEntry=function(t){var n=new e(this._entries);return n._entries.delete(t),n},e.prototype.removeEntries=function(){for(var t,n,r=[],o=0;o<arguments.length;o++)r[o]=arguments[o];var s=new e(this._entries);try{for(var i=Kw(r),a=i.next();!a.done;a=i.next()){var l=a.value;s._entries.delete(l)}}catch(c){t={error:c}}finally{try{a&&!a.done&&(n=i.return)&&n.call(i)}finally{if(t)throw t.error}}return s},e.prototype.clear=function(){return new e},e}();Wt.instance();function Qw(e){return e===void 0&&(e={}),new Yw(new Map(Object.entries(e)))}function p0(e){return Symbol.for(e)}var Xw=function(){function e(t){var n=this;n._currentContext=t?new Map(t):new Map,n.getValue=function(r){return n._currentContext.get(r)},n.setValue=function(r,o){var s=new e(n._currentContext);return s._currentContext.set(r,o),s},n.deleteValue=function(r){var o=new e(n._currentContext);return o._currentContext.delete(r),o}}return e}(),e3=new Xw,Bn=function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,o){r.__proto__=o}||function(r,o){for(var s in o)Object.prototype.hasOwnProperty.call(o,s)&&(r[s]=o[s])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}}(),t3=function(){function e(){}return e.prototype.createGauge=function(t,n){return d3},e.prototype.createHistogram=function(t,n){return p3},e.prototype.createCounter=function(t,n){return u3},e.prototype.createUpDownCounter=function(t,n){return f3},e.prototype.createObservableGauge=function(t,n){return m3},e.prototype.createObservableCounter=function(t,n){return h3},e.prototype.createObservableUpDownCounter=function(t,n){return g3},e.prototype.addBatchObservableCallback=function(t,n){},e.prototype.removeBatchObservableCallback=function(t){},e}(),Wo=function(){function e(){}return e}(),n3=function(e){Bn(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.add=function(n,r){},t}(Wo),r3=function(e){Bn(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.add=function(n,r){},t}(Wo),o3=function(e){Bn(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.record=function(n,r){},t}(Wo),s3=function(e){Bn(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.record=function(n,r){},t}(Wo),Gi=function(){function e(){}return e.prototype.addCallback=function(t){},e.prototype.removeCallback=function(t){},e}(),i3=function(e){Bn(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t}(Gi),a3=function(e){Bn(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t}(Gi),l3=function(e){Bn(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t}(Gi),c3=new t3,u3=new n3,d3=new o3,p3=new s3,f3=new r3,h3=new i3,m3=new a3,g3=new l3,v3={get:function(e,t){if(e!=null)return e[t]},keys:function(e){return e==null?[]:Object.keys(e)}},_3={set:function(e,t,n){e!=null&&(e[t]=n)}},y3=function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),o,s=[],i;try{for(;(t===void 0||t-- >0)&&!(o=r.next()).done;)s.push(o.value)}catch(a){i={error:a}}finally{try{o&&!o.done&&(n=r.return)&&n.call(r)}finally{if(i)throw i.error}}return s},w3=function(e,t,n){if(n||arguments.length===2)for(var r=0,o=t.length,s;r<o;r++)(s||!(r in t))&&(s||(s=Array.prototype.slice.call(t,0,r)),s[r]=t[r]);return e.concat(s||Array.prototype.slice.call(t))},b3=function(){function e(){}return e.prototype.active=function(){return e3},e.prototype.with=function(t,n,r){for(var o=[],s=3;s<arguments.length;s++)o[s-3]=arguments[s];return n.call.apply(n,w3([r],y3(o),!1))},e.prototype.bind=function(t,n){return n},e.prototype.enable=function(){return this},e.prototype.disable=function(){return this},e}(),$3=function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),o,s=[],i;try{for(;(t===void 0||t-- >0)&&!(o=r.next()).done;)s.push(o.value)}catch(a){i={error:a}}finally{try{o&&!o.done&&(n=r.return)&&n.call(r)}finally{if(i)throw i.error}}return s},S3=function(e,t,n){if(n||arguments.length===2)for(var r=0,o=t.length,s;r<o;r++)(s||!(r in t))&&(s||(s=Array.prototype.slice.call(t,0,r)),s[r]=t[r]);return e.concat(s||Array.prototype.slice.call(t))},Wi="context",C3=new b3,Ko=function(){function e(){}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalContextManager=function(t){return Yr(Wi,t,Wt.instance())},e.prototype.active=function(){return this._getContextManager().active()},e.prototype.with=function(t,n,r){for(var o,s=[],i=3;i<arguments.length;i++)s[i-3]=arguments[i];return(o=this._getContextManager()).with.apply(o,S3([t,n,r],$3(s),!1))},e.prototype.bind=function(t,n){return this._getContextManager().bind(t,n)},e.prototype._getContextManager=function(){return Vn(Wi)||C3},e.prototype.disable=function(){this._getContextManager().disable(),Qr(Wi,Wt.instance())},e}(),Ki;(function(e){e[e.NONE=0]="NONE",e[e.SAMPLED=1]="SAMPLED"})(Ki||(Ki={}));var f0="0000000000000000",h0="00000000000000000000000000000000",E3={traceId:h0,spanId:f0,traceFlags:Ki.NONE},eo=function(){function e(t){t===void 0&&(t=E3),this._spanContext=t}return e.prototype.spanContext=function(){return this._spanContext},e.prototype.setAttribute=function(t,n){return this},e.prototype.setAttributes=function(t){return this},e.prototype.addEvent=function(t,n){return this},e.prototype.addLink=function(t){return this},e.prototype.addLinks=function(t){return this},e.prototype.setStatus=function(t){return this},e.prototype.updateName=function(t){return this},e.prototype.end=function(t){},e.prototype.isRecording=function(){return!1},e.prototype.recordException=function(t,n){},e}(),Yi=p0("OpenTelemetry Context Key SPAN");function Qi(e){return e.getValue(Yi)||void 0}function k3(){return Qi(Ko.getInstance().active())}function Xi(e,t){return e.setValue(Yi,t)}function I3(e){return e.deleteValue(Yi)}function T3(e,t){return Xi(e,new eo(t))}function m0(e){var t;return(t=Qi(e))===null||t===void 0?void 0:t.spanContext()}var x3=/^([0-9a-f]{32})$/i,P3=/^[0-9a-f]{16}$/i;function R3(e){return x3.test(e)&&e!==h0}function O3(e){return P3.test(e)&&e!==f0}function g0(e){return R3(e.traceId)&&O3(e.spanId)}function N3(e){return new eo(e)}var ea=Ko.getInstance(),v0=function(){function e(){}return e.prototype.startSpan=function(t,n,r){r===void 0&&(r=ea.active());var o=!!(n!=null&&n.root);if(o)return new eo;var s=r&&m0(r);return M3(s)&&g0(s)?new eo(s):new eo},e.prototype.startActiveSpan=function(t,n,r,o){var s,i,a;if(!(arguments.length<2)){arguments.length===2?a=n:arguments.length===3?(s=n,a=r):(s=n,i=r,a=o);var l=i??ea.active(),c=this.startSpan(t,s,l),u=Xi(l,c);return ea.with(u,a,void 0,c)}},e}();function M3(e){return typeof e=="object"&&typeof e.spanId=="string"&&typeof e.traceId=="string"&&typeof e.traceFlags=="number"}var A3=new v0,L3=function(){function e(t,n,r,o){this._provider=t,this.name=n,this.version=r,this.options=o}return e.prototype.startSpan=function(t,n,r){return this._getTracer().startSpan(t,n,r)},e.prototype.startActiveSpan=function(t,n,r,o){var s=this._getTracer();return Reflect.apply(s.startActiveSpan,s,arguments)},e.prototype._getTracer=function(){if(this._delegate)return this._delegate;var t=this._provider.getDelegateTracer(this.name,this.version,this.options);return t?(this._delegate=t,this._delegate):A3},e}(),j3=function(){function e(){}return e.prototype.getTracer=function(t,n,r){return new v0},e}(),z3=new j3,_0=function(){function e(){}return e.prototype.getTracer=function(t,n,r){var o;return(o=this.getDelegateTracer(t,n,r))!==null&&o!==void 0?o:new L3(this,t,n,r)},e.prototype.getDelegate=function(){var t;return(t=this._delegate)!==null&&t!==void 0?t:z3},e.prototype.setDelegate=function(t){this._delegate=t},e.prototype.getDelegateTracer=function(t,n,r){var o;return(o=this._delegate)===null||o===void 0?void 0:o.getTracer(t,n,r)},e}(),Yo;(function(e){e[e.UNSET=0]="UNSET",e[e.OK=1]="OK",e[e.ERROR=2]="ERROR"})(Yo||(Yo={})),Ko.getInstance(),Wt.instance();var D3=function(){function e(){}return e.prototype.getMeter=function(t,n,r){return c3},e}(),U3=new D3,ta="metrics",q3=function(){function e(){}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalMeterProvider=function(t){return Yr(ta,t,Wt.instance())},e.prototype.getMeterProvider=function(){return Vn(ta)||U3},e.prototype.getMeter=function(t,n,r){return this.getMeterProvider().getMeter(t,n,r)},e.prototype.disable=function(){Qr(ta,Wt.instance())},e}();q3.getInstance();var Z3=function(){function e(){}return e.prototype.inject=function(t,n){},e.prototype.extract=function(t,n){return t},e.prototype.fields=function(){return[]},e}(),na=p0("OpenTelemetry Baggage Key");function y0(e){return e.getValue(na)||void 0}function F3(){return y0(Ko.getInstance().active())}function V3(e,t){return e.setValue(na,t)}function B3(e){return e.deleteValue(na)}var ra="propagation",H3=new Z3,J3=function(){function e(){this.createBaggage=Qw,this.getBaggage=y0,this.getActiveBaggage=F3,this.setBaggage=V3,this.deleteBaggage=B3}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalPropagator=function(t){return Yr(ra,t,Wt.instance())},e.prototype.inject=function(t,n,r){return r===void 0&&(r=_3),this._getGlobalPropagator().inject(t,n,r)},e.prototype.extract=function(t,n,r){return r===void 0&&(r=v3),this._getGlobalPropagator().extract(t,n,r)},e.prototype.fields=function(){return this._getGlobalPropagator().fields()},e.prototype.disable=function(){Qr(ra,Wt.instance())},e.prototype._getGlobalPropagator=function(){return Vn(ra)||H3},e}();J3.getInstance();var oa="trace",G3=function(){function e(){this._proxyTracerProvider=new _0,this.wrapSpanContext=N3,this.isSpanContextValid=g0,this.deleteSpan=I3,this.getSpan=Qi,this.getActiveSpan=k3,this.getSpanContext=m0,this.setSpan=Xi,this.setSpanContext=T3}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalTracerProvider=function(t){var n=Yr(oa,this._proxyTracerProvider,Wt.instance());return n&&this._proxyTracerProvider.setDelegate(t),n},e.prototype.getTracerProvider=function(){return Vn(oa)||this._proxyTracerProvider},e.prototype.getTracer=function(t,n){return this.getTracerProvider().getTracer(t,n)},e.prototype.disable=function(){Qr(oa,Wt.instance()),this._proxyTracerProvider=new _0},e}(),W3=G3.getInstance(),K3=Object.defineProperty,Y3=(e,t)=>{for(var n in t)K3(e,n,{get:t[n],enumerable:!0})},w0="AI_NoOutputSpecifiedError",b0=`vercel.ai.error.${w0}`,Q3=Symbol.for(b0),$0,S0=class extends ee{constructor({message:e="No output specified."}={}){super({name:w0,message:e}),this[$0]=!0}static isInstance(e){return ee.hasMarker(e,b0)}};$0=Q3;function X3(e){const t="AI SDK Warning:";switch(e.type){case"unsupported-setting":{let n=`${t} The "${e.setting}" setting is not supported by this model`;return e.details&&(n+=` - ${e.details}`),n}case"unsupported-tool":{const n="name"in e.tool?e.tool.name:"unknown tool";let r=`${t} The tool "${n}" is not supported by this model`;return e.details&&(r+=` - ${e.details}`),r}case"other":return`${t} ${e.message}`;default:return`${t} ${JSON.stringify(e,null,2)}`}}var eb="AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.",C0=!1,E0=e=>{if(e.length===0)return;const t=globalThis.AI_SDK_LOG_WARNINGS;if(t!==!1){if(typeof t=="function"){t(e);return}C0||(C0=!0,console.info(eb));for(const n of e)console.warn(X3(n))}},k0="AI_InvalidArgumentError",I0=`vercel.ai.error.${k0}`,tb=Symbol.for(I0),T0,Kt=class extends ee{constructor({parameter:e,value:t,message:n}){super({name:k0,message:`Invalid argument for parameter ${e}: ${n}`}),this[T0]=!0,this.parameter=e,this.value=t}static isInstance(e){return ee.hasMarker(e,I0)}};T0=tb;var x0="AI_InvalidToolInputError",P0=`vercel.ai.error.${x0}`,nb=Symbol.for(P0),R0,O0=class extends ee{constructor({toolInput:e,toolName:t,cause:n,message:r=`Invalid input for tool ${t}: ${sr(n)}`}){super({name:x0,message:r,cause:n}),this[R0]=!0,this.toolInput=e,this.toolName=t}static isInstance(e){return ee.hasMarker(e,P0)}};R0=nb;var rb="AI_MCPClientError",N0=`vercel.ai.error.${rb}`,ob=Symbol.for(N0),M0,Ve=class extends ee{constructor({name:e="MCPClientError",message:t,cause:n,data:r,code:o}){super({name:e,message:t,cause:n}),this[M0]=!0,this.data=r,this.code=o}static isInstance(e){return ee.hasMarker(e,N0)}};M0=ob;var A0="AI_NoObjectGeneratedError",L0=`vercel.ai.error.${A0}`,sb=Symbol.for(L0),j0,z0=class extends ee{constructor({message:e="No object generated.",cause:t,text:n,response:r,usage:o,finishReason:s}){super({name:A0,message:e,cause:t}),this[j0]=!0,this.text=n,this.response=r,this.usage=o,this.finishReason=s}static isInstance(e){return ee.hasMarker(e,L0)}};j0=sb;var D0="AI_NoOutputGeneratedError",U0=`vercel.ai.error.${D0}`,ib=Symbol.for(U0),q0,ab=class extends ee{constructor({message:e="No output generated.",cause:t}={}){super({name:D0,message:e,cause:t}),this[q0]=!0}static isInstance(e){return ee.hasMarker(e,U0)}};q0=ib;var Z0="AI_NoSuchToolError",F0=`vercel.ai.error.${Z0}`,lb=Symbol.for(F0),V0,sa=class extends ee{constructor({toolName:e,availableTools:t=void 0,message:n=`Model tried to call unavailable tool '${e}'. ${t===void 0?"No tools are available.":`Available tools: ${t.join(", ")}.`}`}){super({name:Z0,message:n}),this[V0]=!0,this.toolName=e,this.availableTools=t}static isInstance(e){return ee.hasMarker(e,F0)}};V0=lb;var B0="AI_ToolCallRepairError",H0=`vercel.ai.error.${B0}`,cb=Symbol.for(H0),J0,ub=class extends ee{constructor({cause:e,originalError:t,message:n=`Error repairing tool call: ${sr(e)}`}){super({name:B0,message:n,cause:e}),this[J0]=!0,this.originalError=t}static isInstance(e){return ee.hasMarker(e,H0)}};J0=cb;var db=class extends ee{constructor(e){super({name:"AI_UnsupportedModelVersionError",message:`Unsupported model version ${e.version} for provider "${e.provider}" and model "${e.modelId}". AI SDK 5 only supports models that implement specification version "v2".`}),this.version=e.version,this.provider=e.provider,this.modelId=e.modelId}},G0="AI_InvalidMessageRoleError",W0=`vercel.ai.error.${G0}`,pb=Symbol.for(W0),K0,fb=class extends ee{constructor({role:e,message:t=`Invalid message role: '${e}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:G0,message:t}),this[K0]=!0,this.role=e}static isInstance(e){return ee.hasMarker(e,W0)}};K0=pb;var Y0="AI_DownloadError",Q0=`vercel.ai.error.${Y0}`,hb=Symbol.for(Q0),X0,ia=class extends ee{constructor({url:e,statusCode:t,statusText:n,cause:r,message:o=r==null?`Failed to download ${e}: ${t} ${n}`:`Failed to download ${e}: ${r}`}){super({name:Y0,message:o,cause:r}),this[X0]=!0,this.url=e,this.statusCode=t,this.statusText=n}static isInstance(e){return ee.hasMarker(e,Q0)}};X0=hb;var ep="AI_RetryError",tp=`vercel.ai.error.${ep}`,mb=Symbol.for(tp),np,rp=class extends ee{constructor({message:e,reason:t,errors:n}){super({name:ep,message:e}),this[np]=!0,this.reason=t,this.errors=n,this.lastError=n[n.length-1]}static isInstance(e){return ee.hasMarker(e,tp)}};np=mb;function Qo(e){if(typeof e!="string"){if(e.specificationVersion!=="v2")throw new db({version:e.specificationVersion,provider:e.provider,modelId:e.modelId});return e}return gb().languageModel(e)}function gb(){var e;return(e=globalThis.AI_SDK_DEFAULT_PROVIDER)!=null?e:Lw}var vb=[{mediaType:"image/gif",bytesPrefix:[71,73,70]},{mediaType:"image/png",bytesPrefix:[137,80,78,71]},{mediaType:"image/jpeg",bytesPrefix:[255,216]},{mediaType:"image/webp",bytesPrefix:[82,73,70,70,null,null,null,null,87,69,66,80]},{mediaType:"image/bmp",bytesPrefix:[66,77]},{mediaType:"image/tiff",bytesPrefix:[73,73,42,0]},{mediaType:"image/tiff",bytesPrefix:[77,77,0,42]},{mediaType:"image/avif",bytesPrefix:[0,0,0,32,102,116,121,112,97,118,105,102]},{mediaType:"image/heic",bytesPrefix:[0,0,0,32,102,116,121,112,104,101,105,99]}],_b=e=>{const t=typeof e=="string"?Zi(e):e,n=(t[6]&127)<<21|(t[7]&127)<<14|(t[8]&127)<<7|t[9]&127;return t.slice(n+10)};function yb(e){return typeof e=="string"&&e.startsWith("SUQz")||typeof e!="string"&&e.length>10&&e[0]===73&&e[1]===68&&e[2]===51?_b(e):e}function wb({data:e,signatures:t}){const n=yb(e),r=typeof n=="string"?Zi(n.substring(0,Math.min(n.length,24))):n;for(const o of t)if(r.length>=o.bytesPrefix.length&&o.bytesPrefix.every((s,i)=>s===null||r[i]===s))return o.mediaType}var Xo="5.0.76",bb=async({url:e})=>{var t;const n=e.toString();try{const r=await fetch(n,{headers:Dn({},`ai-sdk/${Xo}`,Br())});if(!r.ok)throw new ia({url:n,statusCode:r.status,statusText:r.statusText});return{data:new Uint8Array(await r.arrayBuffer()),mediaType:(t=r.headers.get("content-type"))!=null?t:void 0}}catch(r){throw ia.isInstance(r)?r:new ia({url:n,cause:r})}},$b=(e=bb)=>t=>Promise.all(t.map(async n=>n.isUrlSupportedByModel?null:e(n)));function Sb(e){try{const[t,n]=e.split(",");return{mediaType:t.split(";")[0].split(":")[1],base64Content:n}}catch{return{mediaType:void 0,base64Content:void 0}}}var op=Q([p(),Vo(Uint8Array),Vo(ArrayBuffer),gd(e=>{var t,n;return(n=(t=globalThis.Buffer)==null?void 0:t.isBuffer(e))!=null?n:!1},{message:"Must be a Buffer"})]);function sp(e){if(e instanceof Uint8Array)return{data:e,mediaType:void 0};if(e instanceof ArrayBuffer)return{data:new Uint8Array(e),mediaType:void 0};if(typeof e=="string")try{e=new URL(e)}catch{}if(e instanceof URL&&e.protocol==="data:"){const{mediaType:t,base64Content:n}=Sb(e.toString());if(t==null||n==null)throw new ee({name:"InvalidDataContentError",message:`Invalid data URL format in content ${e.toString()}`});return{data:n,mediaType:t}}return{data:e,mediaType:void 0}}function Cb(e){return typeof e=="string"?e:e instanceof ArrayBuffer?Fi(new Uint8Array(e)):Fi(e)}async function ip({prompt:e,supportedUrls:t,download:n=$b()}){const r=await kb(e.messages,n,t);return[...e.system!=null?[{role:"system",content:e.system}]:[],...e.messages.map(o=>Eb({message:o,downloadedAssets:r}))]}function Eb({message:e,downloadedAssets:t}){const n=e.role;switch(n){case"system":return{role:"system",content:e.content,providerOptions:e.providerOptions};case"user":return typeof e.content=="string"?{role:"user",content:[{type:"text",text:e.content}],providerOptions:e.providerOptions}:{role:"user",content:e.content.map(r=>Ib(r,t)).filter(r=>r.type!=="text"||r.text!==""),providerOptions:e.providerOptions};case"assistant":return typeof e.content=="string"?{role:"assistant",content:[{type:"text",text:e.content}],providerOptions:e.providerOptions}:{role:"assistant",content:e.content.filter(r=>r.type!=="text"||r.text!==""||r.providerOptions!=null).map(r=>{const o=r.providerOptions;switch(r.type){case"file":{const{data:s,mediaType:i}=sp(r.data);return{type:"file",data:s,filename:r.filename,mediaType:i??r.mediaType,providerOptions:o}}case"reasoning":return{type:"reasoning",text:r.text,providerOptions:o};case"text":return{type:"text",text:r.text,providerOptions:o};case"tool-call":return{type:"tool-call",toolCallId:r.toolCallId,toolName:r.toolName,input:r.input,providerExecuted:r.providerExecuted,providerOptions:o};case"tool-result":return{type:"tool-result",toolCallId:r.toolCallId,toolName:r.toolName,output:r.output,providerOptions:o}}}),providerOptions:e.providerOptions};case"tool":return{role:"tool",content:e.content.map(r=>({type:"tool-result",toolCallId:r.toolCallId,toolName:r.toolName,output:r.output,providerOptions:r.providerOptions})),providerOptions:e.providerOptions};default:{const r=n;throw new fb({role:r})}}}async function kb(e,t,n){const r=e.filter(s=>s.role==="user").map(s=>s.content).filter(s=>Array.isArray(s)).flat().filter(s=>s.type==="image"||s.type==="file").map(s=>{var i;const a=(i=s.mediaType)!=null?i:s.type==="image"?"image/*":void 0;let l=s.type==="image"?s.image:s.data;if(typeof l=="string")try{l=new URL(l)}catch{}return{mediaType:a,data:l}}).filter(s=>s.data instanceof URL).map(s=>({url:s.data,isUrlSupportedByModel:s.mediaType!=null&&U_({url:s.data.toString(),mediaType:s.mediaType,supportedUrls:n})})),o=await t(r);return Object.fromEntries(o.map((s,i)=>s==null?null:[r[i].url.toString(),{data:s.data,mediaType:s.mediaType}]).filter(s=>s!=null))}function Ib(e,t){var n;if(e.type==="text")return{type:"text",text:e.text,providerOptions:e.providerOptions};let r;const o=e.type;switch(o){case"image":r=e.image;break;case"file":r=e.data;break;default:throw new Error(`Unsupported part type: ${o}`)}const{data:s,mediaType:i}=sp(r);let a=i??e.mediaType,l=s;if(l instanceof URL){const c=t[l.toString()];c&&(l=c.data,a??(a=c.mediaType))}switch(o){case"image":return(l instanceof Uint8Array||typeof l=="string")&&(a=(n=wb({data:l,signatures:vb}))!=null?n:a),{type:"file",mediaType:a??"image/*",filename:void 0,data:l,providerOptions:e.providerOptions};case"file":{if(a==null)throw new Error("Media type is missing for file part");return{type:"file",mediaType:a,filename:e.filename,data:l,providerOptions:e.providerOptions}}}}function aa({maxOutputTokens:e,temperature:t,topP:n,topK:r,presencePenalty:o,frequencyPenalty:s,seed:i,stopSequences:a}){if(e!=null){if(!Number.isInteger(e))throw new Kt({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be an integer"});if(e<1)throw new Kt({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be >= 1"})}if(t!=null&&typeof t!="number")throw new Kt({parameter:"temperature",value:t,message:"temperature must be a number"});if(n!=null&&typeof n!="number")throw new Kt({parameter:"topP",value:n,message:"topP must be a number"});if(r!=null&&typeof r!="number")throw new Kt({parameter:"topK",value:r,message:"topK must be a number"});if(o!=null&&typeof o!="number")throw new Kt({parameter:"presencePenalty",value:o,message:"presencePenalty must be a number"});if(s!=null&&typeof s!="number")throw new Kt({parameter:"frequencyPenalty",value:s,message:"frequencyPenalty must be a number"});if(i!=null&&!Number.isInteger(i))throw new Kt({parameter:"seed",value:i,message:"seed must be an integer"});return{maxOutputTokens:e,temperature:t,topP:n,topK:r,presencePenalty:o,frequencyPenalty:s,stopSequences:a,seed:i}}function Tb(e){return e!=null&&Object.keys(e).length>0}function ap({tools:e,toolChoice:t,activeTools:n}){return Tb(e)?{tools:(n!=null?Object.entries(e).filter(([o])=>n.includes(o)):Object.entries(e)).map(([o,s])=>{const i=s.type;switch(i){case void 0:case"dynamic":case"function":return{type:"function",name:o,description:s.description,inputSchema:Go(s.inputSchema).jsonSchema,providerOptions:s.providerOptions};case"provider-defined":return{type:"provider-defined",name:o,id:s.id,args:s.args};default:{const a=i;throw new Error(`Unsupported tool type: ${a}`)}}}),toolChoice:t==null?{type:"auto"}:typeof t=="string"?{type:t}:{type:"tool",toolName:t.toolName}}:{tools:void 0,toolChoice:void 0}}var to=md(()=>Q([i_(),p(),R(),ne(),ie(p(),to),N(to)])),Yt=ie(p(),ie(p(),to)),lp=S({type:O("text"),text:p(),providerOptions:Yt.optional()}),xb=S({type:O("image"),image:Q([op,Vo(URL)]),mediaType:p().optional(),providerOptions:Yt.optional()}),cp=S({type:O("file"),data:Q([op,Vo(URL)]),filename:p().optional(),mediaType:p(),providerOptions:Yt.optional()}),Pb=S({type:O("reasoning"),text:p(),providerOptions:Yt.optional()}),Rb=S({type:O("tool-call"),toolCallId:p(),toolName:p(),input:ke(),providerOptions:Yt.optional(),providerExecuted:ne().optional()}),Ob=Fe("type",[S({type:O("text"),value:p()}),S({type:O("json"),value:to}),S({type:O("error-text"),value:p()}),S({type:O("error-json"),value:to}),S({type:O("content"),value:N(Q([S({type:O("text"),text:p()}),S({type:O("media"),data:p(),mediaType:p()})]))})]),up=S({type:O("tool-result"),toolCallId:p(),toolName:p(),output:Ob,providerOptions:Yt.optional()}),Nb=S({role:O("system"),content:p(),providerOptions:Yt.optional()}),Mb=S({role:O("user"),content:Q([p(),N(Q([lp,xb,cp]))]),providerOptions:Yt.optional()}),Ab=S({role:O("assistant"),content:Q([p(),N(Q([lp,cp,Pb,Rb,up]))]),providerOptions:Yt.optional()}),Lb=S({role:O("tool"),content:N(up),providerOptions:Yt.optional()}),jb=Q([Nb,Mb,Ab,Lb]);async function dp(e){if(e.prompt==null&&e.messages==null)throw new An({prompt:e,message:"prompt or messages must be defined"});if(e.prompt!=null&&e.messages!=null)throw new An({prompt:e,message:"prompt and messages cannot be defined at the same time"});if(e.system!=null&&typeof e.system!="string")throw new An({prompt:e,message:"system must be a string"});let t;if(e.prompt!=null&&typeof e.prompt=="string")t=[{role:"user",content:e.prompt}];else if(e.prompt!=null&&Array.isArray(e.prompt))t=e.prompt;else if(e.messages!=null)t=e.messages;else throw new An({prompt:e,message:"prompt or messages must be defined"});if(t.length===0)throw new An({prompt:e,message:"messages must not be empty"});const n=await $n({value:t,schema:N(jb)});if(!n.success)throw new An({prompt:e,message:"The messages must be a ModelMessage[]. If you have passed a UIMessage[], you can use convertToModelMessages to convert them.",cause:n.error});return{messages:t,system:e.system}}function pp(e){return Ji.isInstance(e)||Qd.isInstance(e)?new ee({name:"GatewayError",message:"Vercel AI Gateway access failed. If you want to use AI SDK providers directly, use the providers, e.g. @ai-sdk/openai, or register a different global default provider.",cause:e}):e}function ar({operationId:e,telemetry:t}){return{"operation.name":`${e}${(t==null?void 0:t.functionId)!=null?` ${t.functionId}`:""}`,"resource.name":t==null?void 0:t.functionId,"ai.operationId":e,"ai.telemetry.functionId":t==null?void 0:t.functionId}}function fp({model:e,settings:t,telemetry:n,headers:r}){var o;return{"ai.model.provider":e.provider,"ai.model.id":e.modelId,...Object.entries(t).reduce((s,[i,a])=>(s[`ai.settings.${i}`]=a,s),{}),...Object.entries((o=n==null?void 0:n.metadata)!=null?o:{}).reduce((s,[i,a])=>(s[`ai.telemetry.metadata.${i}`]=a,s),{}),...Object.entries(r??{}).reduce((s,[i,a])=>(a!==void 0&&(s[`ai.request.headers.${i}`]=a),s),{})}}var zb={startSpan(){return es},startActiveSpan(e,t,n,r){if(typeof t=="function")return t(es);if(typeof n=="function")return n(es);if(typeof r=="function")return r(es)}},es={spanContext(){return Db},setAttribute(){return this},setAttributes(){return this},addEvent(){return this},addLink(){return this},addLinks(){return this},setStatus(){return this},updateName(){return this},end(){return this},isRecording(){return!1},recordException(){return this}},Db={traceId:"",spanId:"",traceFlags:0};function hp({isEnabled:e=!1,tracer:t}={}){return e?t||W3.getTracer("ai"):zb}function lr({name:e,tracer:t,attributes:n,fn:r,endWhenDone:o=!0}){return t.startActiveSpan(e,{attributes:n},async s=>{try{const i=await r(s);return o&&s.end(),i}catch(i){try{la(s,i)}finally{s.end()}throw i}})}function la(e,t){t instanceof Error?(e.recordException({name:t.name,message:t.message,stack:t.stack}),e.setStatus({code:Yo.ERROR,message:t.message})):e.setStatus({code:Yo.ERROR})}function kt({telemetry:e,attributes:t}){return(e==null?void 0:e.isEnabled)!==!0?{}:Object.entries(t).reduce((n,[r,o])=>{if(o==null)return n;if(typeof o=="object"&&"input"in o&&typeof o.input=="function"){if((e==null?void 0:e.recordInputs)===!1)return n;const s=o.input();return s==null?n:{...n,[r]:s}}if(typeof o=="object"&&"output"in o&&typeof o.output=="function"){if((e==null?void 0:e.recordOutputs)===!1)return n;const s=o.output();return s==null?n:{...n,[r]:s}}return{...n,[r]:o}},{})}function mp(e){return JSON.stringify(e.map(t=>({...t,content:typeof t.content=="string"?t.content:t.content.map(n=>n.type==="file"?{...n,data:n.data instanceof Uint8Array?Cb(n.data):n.data}:n)})))}function gp(e,t){return{inputTokens:no(e.inputTokens,t.inputTokens),outputTokens:no(e.outputTokens,t.outputTokens),totalTokens:no(e.totalTokens,t.totalTokens),reasoningTokens:no(e.reasoningTokens,t.reasoningTokens),cachedInputTokens:no(e.cachedInputTokens,t.cachedInputTokens)}}function no(e,t){return e==null&&t==null?void 0:(e??0)+(t??0)}function ca(e){return e===void 0?[]:Array.isArray(e)?e:[e]}function Ub({error:e,exponentialBackoffDelay:t}){const n=e.responseHeaders;if(!n)return t;let r;const o=n["retry-after-ms"];if(o){const i=parseFloat(o);Number.isNaN(i)||(r=i)}const s=n["retry-after"];if(s&&r===void 0){const i=parseFloat(s);Number.isNaN(i)?r=Date.parse(s)-Date.now():r=i*1e3}return r!=null&&!Number.isNaN(r)&&0<=r&&(r<60*1e3||r<t)?r:t}var qb=({maxRetries:e=2,initialDelayInMs:t=2e3,backoffFactor:n=2,abortSignal:r}={})=>async o=>vp(o,{maxRetries:e,delayInMs:t,backoffFactor:n,abortSignal:r});async function vp(e,{maxRetries:t,delayInMs:n,backoffFactor:r,abortSignal:o},s=[]){try{return await e()}catch(i){if(zn(i)||t===0)throw i;const a=Ai(i),l=[...s,i],c=l.length;if(c>t)throw new rp({message:`Failed after ${c} attempts. Last error: ${a}`,reason:"maxRetriesExceeded",errors:l});if(i instanceof Error&&Ie.isInstance(i)&&i.isRetryable===!0&&c<=t)return await A_(Ub({error:i,exponentialBackoffDelay:n}),{abortSignal:o}),vp(e,{maxRetries:t,delayInMs:r*n,backoffFactor:r,abortSignal:o},l);throw c===1?i:new rp({message:`Failed after ${c} attempts with non-retryable error: '${a}'`,reason:"errorNotRetryable",errors:l})}}function _p({maxRetries:e,abortSignal:t}){if(e!=null){if(!Number.isInteger(e))throw new Kt({parameter:"maxRetries",value:e,message:"maxRetries must be an integer"});if(e<0)throw new Kt({parameter:"maxRetries",value:e,message:"maxRetries must be >= 0"})}const n=e??2;return{maxRetries:n,retry:qb({maxRetries:n,abortSignal:t})}}function yp(e){const t=e.filter(n=>n.type==="text");if(t.length!==0)return t.map(n=>n.text).join("")}var wp=class{constructor({data:e,mediaType:t}){const n=e instanceof Uint8Array;this.base64Data=n?void 0:e,this.uint8ArrayData=n?e:void 0,this.mediaType=t}get base64(){return this.base64Data==null&&(this.base64Data=Fi(this.uint8ArrayData)),this.base64Data}get uint8Array(){return this.uint8ArrayData==null&&(this.uint8ArrayData=Zi(this.base64Data)),this.uint8ArrayData}},Zb=class extends wp{constructor(e){super(e),this.type="file"}};async function bp({toolCall:e,tools:t,repairToolCall:n,system:r,messages:o}){try{if(t==null)throw new sa({toolName:e.toolName});try{return await $p({toolCall:e,tools:t})}catch(s){if(n==null||!(sa.isInstance(s)||O0.isInstance(s)))throw s;let i=null;try{i=await n({toolCall:e,tools:t,inputSchema:({toolName:a})=>{const{inputSchema:l}=t[a];return Go(l).jsonSchema},system:r,messages:o,error:s})}catch(a){throw new ub({cause:a,originalError:s})}if(i==null)throw s;return await $p({toolCall:i,tools:t})}}catch(s){const i=await Un({text:e.input}),a=i.success?i.value:e.input;return{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:a,dynamic:!0,invalid:!0,error:s}}}async function $p({toolCall:e,tools:t}){const n=e.toolName,r=t[n];if(r==null)throw new sa({toolName:e.toolName,availableTools:Object.keys(t)});const o=Go(r.inputSchema),s=e.input.trim()===""?await $n({value:{},schema:o}):await Un({text:e.input,schema:o});if(s.success===!1)throw new O0({toolName:n,toolInput:e.input,cause:s.error});return r.type==="dynamic"?{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:s.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,dynamic:!0}:{type:"tool-call",toolCallId:e.toolCallId,toolName:n,input:s.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata}}var Sp=class{constructor({content:e,finishReason:t,usage:n,warnings:r,request:o,response:s,providerMetadata:i}){this.content=e,this.finishReason=t,this.usage=n,this.warnings=r,this.request=o,this.response=s,this.providerMetadata=i}get text(){return this.content.filter(e=>e.type==="text").map(e=>e.text).join("")}get reasoning(){return this.content.filter(e=>e.type==="reasoning")}get reasoningText(){return this.reasoning.length===0?void 0:this.reasoning.map(e=>e.text).join("")}get files(){return this.content.filter(e=>e.type==="file").map(e=>e.file)}get sources(){return this.content.filter(e=>e.type==="source")}get toolCalls(){return this.content.filter(e=>e.type==="tool-call")}get staticToolCalls(){return this.toolCalls.filter(e=>e.dynamic!==!0)}get dynamicToolCalls(){return this.toolCalls.filter(e=>e.dynamic===!0)}get toolResults(){return this.content.filter(e=>e.type==="tool-result")}get staticToolResults(){return this.toolResults.filter(e=>e.dynamic!==!0)}get dynamicToolResults(){return this.toolResults.filter(e=>e.dynamic===!0)}};function ua(e){return({steps:t})=>t.length===e}async function Cp({stopConditions:e,steps:t}){return(await Promise.all(e.map(n=>n({steps:t})))).some(n=>n)}function da({output:e,tool:t,errorMode:n}){return n==="text"?{type:"error-text",value:sr(e)}:n==="json"?{type:"error-json",value:Ep(e)}:t!=null&&t.toModelOutput?t.toModelOutput(e):typeof e=="string"?{type:"text",value:e}:{type:"json",value:Ep(e)}}function Ep(e){return e===void 0?null:e}function pa({content:e,tools:t}){const n=[],r=e.filter(s=>s.type!=="source").filter(s=>(s.type!=="tool-result"||s.providerExecuted)&&(s.type!=="tool-error"||s.providerExecuted)).filter(s=>s.type!=="text"||s.text.length>0).map(s=>{switch(s.type){case"text":return{type:"text",text:s.text,providerOptions:s.providerMetadata};case"reasoning":return{type:"reasoning",text:s.text,providerOptions:s.providerMetadata};case"file":return{type:"file",data:s.file.base64,mediaType:s.file.mediaType,providerOptions:s.providerMetadata};case"tool-call":return{type:"tool-call",toolCallId:s.toolCallId,toolName:s.toolName,input:s.input,providerExecuted:s.providerExecuted,providerOptions:s.providerMetadata};case"tool-result":return{type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:da({tool:t==null?void 0:t[s.toolName],output:s.output,errorMode:"none"}),providerExecuted:!0,providerOptions:s.providerMetadata};case"tool-error":return{type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:da({tool:t==null?void 0:t[s.toolName],output:s.error,errorMode:"json"}),providerOptions:s.providerMetadata}}});r.length>0&&n.push({role:"assistant",content:r});const o=e.filter(s=>s.type==="tool-result"||s.type==="tool-error").filter(s=>!s.providerExecuted).map(s=>({type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:da({tool:t==null?void 0:t[s.toolName],output:s.type==="tool-result"?s.output:s.error,errorMode:s.type==="tool-error"?"text":"none"})}));return o.length>0&&n.push({role:"tool",content:o}),n}var Fb=Vr({prefix:"aitxt",size:24});async function Vb({model:e,tools:t,toolChoice:n,system:r,prompt:o,messages:s,maxRetries:i,abortSignal:a,headers:l,stopWhen:c=ua(1),experimental_output:u,experimental_telemetry:h,providerOptions:_,experimental_activeTools:f,activeTools:g=f,experimental_prepareStep:v,prepareStep:m=v,experimental_repairToolCall:d,experimental_download:w,experimental_context:y,_internal:{generateId:b=Fb,currentDate:k=()=>new Date}={},onStepFinish:x,...T}){const D=Qo(e),U=ca(c),{maxRetries:H,retry:q}=_p({maxRetries:i,abortSignal:a}),F=aa(T),B=Dn(l??{},`ai/${Xo}`),V=fp({model:D,telemetry:h,headers:B,settings:{...F,maxRetries:H}}),se=await dp({system:r,prompt:o,messages:s}),ge=hp(h);try{return await lr({name:"ai.generateText",attributes:kt({telemetry:h,attributes:{...ar({operationId:"ai.generateText",telemetry:h}),...V,"ai.model.provider":D.provider,"ai.model.id":D.modelId,"ai.prompt":{input:()=>JSON.stringify({system:r,prompt:o,messages:s})}}}),tracer:ge,fn:async te=>{var ue,le,L,I,M,P,C;const E=aa(T);let $,j=[],z=[];const de=[],oe=[];do{const Ne=[...se.messages,...de],ve=await(m==null?void 0:m({model:D,steps:oe,stepNumber:oe.length,messages:Ne})),ye=Qo((ue=ve==null?void 0:ve.model)!=null?ue:D),Le=await ip({prompt:{system:(le=ve==null?void 0:ve.system)!=null?le:se.system,messages:(L=ve==null?void 0:ve.messages)!=null?L:Ne},supportedUrls:await ye.supportedUrls,download:w}),{toolChoice:fe,tools:Ze}=ap({tools:t,toolChoice:(I=ve==null?void 0:ve.toolChoice)!=null?I:n,activeTools:(M=ve==null?void 0:ve.activeTools)!=null?M:g});$=await q(()=>{var Se;return lr({name:"ai.generateText.doGenerate",attributes:kt({telemetry:h,attributes:{...ar({operationId:"ai.generateText.doGenerate",telemetry:h}),...V,"ai.model.provider":ye.provider,"ai.model.id":ye.modelId,"ai.prompt.messages":{input:()=>mp(Le)},"ai.prompt.tools":{input:()=>Ze==null?void 0:Ze.map(vt=>JSON.stringify(vt))},"ai.prompt.toolChoice":{input:()=>fe!=null?JSON.stringify(fe):void 0},"gen_ai.system":ye.provider,"gen_ai.request.model":ye.modelId,"gen_ai.request.frequency_penalty":T.frequencyPenalty,"gen_ai.request.max_tokens":T.maxOutputTokens,"gen_ai.request.presence_penalty":T.presencePenalty,"gen_ai.request.stop_sequences":T.stopSequences,"gen_ai.request.temperature":(Se=T.temperature)!=null?Se:void 0,"gen_ai.request.top_k":T.topK,"gen_ai.request.top_p":T.topP}}),tracer:ge,fn:async vt=>{var mn,_t,Ye,Nt,Nn,Mn,Nr,hi;const Be=await ye.doGenerate({...E,tools:Ze,toolChoice:fe,responseFormat:u==null?void 0:u.responseFormat,prompt:Le,providerOptions:_,abortSignal:a,headers:B}),gn={id:(_t=(mn=Be.response)==null?void 0:mn.id)!=null?_t:b(),timestamp:(Nt=(Ye=Be.response)==null?void 0:Ye.timestamp)!=null?Nt:k(),modelId:(Mn=(Nn=Be.response)==null?void 0:Nn.modelId)!=null?Mn:ye.modelId,headers:(Nr=Be.response)==null?void 0:Nr.headers,body:(hi=Be.response)==null?void 0:hi.body};return vt.setAttributes(kt({telemetry:h,attributes:{"ai.response.finishReason":Be.finishReason,"ai.response.text":{output:()=>yp(Be.content)},"ai.response.toolCalls":{output:()=>{const vn=kp(Be.content);return vn==null?void 0:JSON.stringify(vn)}},"ai.response.id":gn.id,"ai.response.model":gn.modelId,"ai.response.timestamp":gn.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(Be.providerMetadata),"ai.usage.promptTokens":Be.usage.inputTokens,"ai.usage.completionTokens":Be.usage.outputTokens,"gen_ai.response.finish_reasons":[Be.finishReason],"gen_ai.response.id":gn.id,"gen_ai.response.model":gn.modelId,"gen_ai.usage.input_tokens":Be.usage.inputTokens,"gen_ai.usage.output_tokens":Be.usage.outputTokens}})),{...Be,response:gn}}})});const gt=await Promise.all($.content.filter(Se=>Se.type==="tool-call").map(Se=>bp({toolCall:Se,tools:t,repairToolCall:d,system:r,messages:Ne})));for(const Se of gt){if(Se.invalid)continue;const vt=t[Se.toolName];(vt==null?void 0:vt.onInputAvailable)!=null&&await vt.onInputAvailable({input:Se.input,toolCallId:Se.toolCallId,messages:Ne,abortSignal:a,experimental_context:y})}const J=gt.filter(Se=>Se.invalid&&Se.dynamic);z=[];for(const Se of J)z.push({type:"tool-error",toolCallId:Se.toolCallId,toolName:Se.toolName,input:Se.input,error:Ai(Se.error),dynamic:!0});j=gt.filter(Se=>!Se.providerExecuted),t!=null&&z.push(...await Bb({toolCalls:j.filter(Se=>!Se.invalid),tools:t,tracer:ge,telemetry:h,messages:Ne,abortSignal:a,experimental_context:y}));const $e=Jb({content:$.content,toolCalls:gt,toolOutputs:z});de.push(...pa({content:$e,tools:t}));const Ot=new Sp({content:$e,finishReason:$.finishReason,usage:$.usage,warnings:$.warnings,providerMetadata:$.providerMetadata,request:(P=$.request)!=null?P:{},response:{...$.response,messages:structuredClone(de)}});E0((C=$.warnings)!=null?C:[]),oe.push(Ot),await(x==null?void 0:x(Ot))}while(j.length>0&&z.length===j.length&&!await Cp({stopConditions:U,steps:oe}));te.setAttributes(kt({telemetry:h,attributes:{"ai.response.finishReason":$.finishReason,"ai.response.text":{output:()=>yp($.content)},"ai.response.toolCalls":{output:()=>{const Ne=kp($.content);return Ne==null?void 0:JSON.stringify(Ne)}},"ai.response.providerMetadata":JSON.stringify($.providerMetadata),"ai.usage.promptTokens":$.usage.inputTokens,"ai.usage.completionTokens":$.usage.outputTokens}}));const _e=oe[oe.length-1];let Rt;return _e.finishReason==="stop"&&(Rt=await(u==null?void 0:u.parseOutput({text:_e.text},{response:_e.response,usage:_e.usage,finishReason:_e.finishReason}))),new Hb({steps:oe,resolvedOutput:Rt})}})}catch(te){throw pp(te)}}async function Bb({toolCalls:e,tools:t,tracer:n,telemetry:r,messages:o,abortSignal:s,experimental_context:i}){return(await Promise.all(e.map(async({toolCallId:l,toolName:c,input:u})=>{const h=t[c];if((h==null?void 0:h.execute)!=null)return lr({name:"ai.toolCall",attributes:kt({telemetry:r,attributes:{...ar({operationId:"ai.toolCall",telemetry:r}),"ai.toolCall.name":c,"ai.toolCall.id":l,"ai.toolCall.args":{output:()=>JSON.stringify(u)}}}),tracer:n,fn:async _=>{try{const f=xd({execute:h.execute.bind(h),input:u,options:{toolCallId:l,messages:o,abortSignal:s,experimental_context:i}});let g;for await(const v of f)v.type==="final"&&(g=v.output);try{_.setAttributes(kt({telemetry:r,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(g)}}}))}catch{}return{type:"tool-result",toolCallId:l,toolName:c,input:u,output:g,dynamic:h.type==="dynamic"}}catch(f){return la(_,f),{type:"tool-error",toolCallId:l,toolName:c,input:u,error:f,dynamic:h.type==="dynamic"}}}})}))).filter(l=>l!=null)}var Hb=class{constructor(e){this.steps=e.steps,this.resolvedOutput=e.resolvedOutput}get finalStep(){return this.steps[this.steps.length-1]}get content(){return this.finalStep.content}get text(){return this.finalStep.text}get files(){return this.finalStep.files}get reasoningText(){return this.finalStep.reasoningText}get reasoning(){return this.finalStep.reasoning}get toolCalls(){return this.finalStep.toolCalls}get staticToolCalls(){return this.finalStep.staticToolCalls}get dynamicToolCalls(){return this.finalStep.dynamicToolCalls}get toolResults(){return this.finalStep.toolResults}get staticToolResults(){return this.finalStep.staticToolResults}get dynamicToolResults(){return this.finalStep.dynamicToolResults}get sources(){return this.finalStep.sources}get finishReason(){return this.finalStep.finishReason}get warnings(){return this.finalStep.warnings}get providerMetadata(){return this.finalStep.providerMetadata}get response(){return this.finalStep.response}get request(){return this.finalStep.request}get usage(){return this.finalStep.usage}get totalUsage(){return this.steps.reduce((e,t)=>gp(e,t.usage),{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0,reasoningTokens:void 0,cachedInputTokens:void 0})}get experimental_output(){if(this.resolvedOutput==null)throw new S0;return this.resolvedOutput}};function kp(e){const t=e.filter(n=>n.type==="tool-call");if(t.length!==0)return t.map(n=>({toolCallId:n.toolCallId,toolName:n.toolName,input:n.input}))}function Jb({content:e,toolCalls:t,toolOutputs:n}){return[...e.map(r=>{switch(r.type){case"text":case"reasoning":case"source":return r;case"file":return{type:"file",file:new wp(r)};case"tool-call":return t.find(o=>o.toolCallId===r.toolCallId);case"tool-result":{const o=t.find(s=>s.toolCallId===r.toolCallId);if(o==null)throw new Error(`Tool call ${r.toolCallId} not found.`);return r.isError?{type:"tool-error",toolCallId:r.toolCallId,toolName:r.toolName,input:o.input,error:r.result,providerExecuted:!0,dynamic:o.dynamic}:{type:"tool-result",toolCallId:r.toolCallId,toolName:r.toolName,input:o.input,output:r.result,providerExecuted:!0,dynamic:o.dynamic}}}}),...n]}function ts(e,t){const n=new Headers(e??{});for(const[r,o]of Object.entries(t))n.has(r)||n.set(r,o);return n}function Gb({status:e,statusText:t,headers:n,textStream:r}){return new Response(r.pipeThrough(new TextEncoderStream),{status:e??200,statusText:t,headers:ts(n,{"content-type":"text/plain; charset=utf-8"})})}function Ip({response:e,status:t,statusText:n,headers:r,stream:o}){e.writeHead(t??200,n,r);const s=o.getReader();(async()=>{try{for(;;){const{done:a,value:l}=await s.read();if(a)break;e.write(l)||await new Promise(u=>{e.once("drain",u)})}}catch(a){throw a}finally{e.end()}})()}function Wb({response:e,status:t,statusText:n,headers:r,textStream:o}){Ip({response:e,status:t,statusText:n,headers:Object.fromEntries(ts(r,{"content-type":"text/plain; charset=utf-8"}).entries()),stream:o.pipeThrough(new TextEncoderStream)})}var Tp=class extends TransformStream{constructor(){super({transform(e,t){t.enqueue(`data: ${JSON.stringify(e)}
54
+
55
+ `)},flush(e){e.enqueue(`data: [DONE]
56
+
57
+ `)}})}},xp={"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive","x-vercel-ai-ui-message-stream":"v1","x-accel-buffering":"no"};function Kb({status:e,statusText:t,headers:n,stream:r,consumeSseStream:o}){let s=r.pipeThrough(new Tp);if(o){const[i,a]=s.tee();s=i,o({stream:a})}return new Response(s.pipeThrough(new TextEncoderStream),{status:e,statusText:t,headers:ts(n,xp)})}function Yb({originalMessages:e,responseMessageId:t}){if(e==null)return;const n=e[e.length-1];return(n==null?void 0:n.role)==="assistant"?n.id:typeof t=="function"?t():t}function Qb(e){return e.type.startsWith("data-")}function Pp(e,t){if(e===void 0&&t===void 0)return;if(e===void 0)return t;if(t===void 0)return e;const n={...e};for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)){const o=t[r];if(o===void 0)continue;const s=r in e?e[r]:void 0,i=o!==null&&typeof o=="object"&&!Array.isArray(o)&&!(o instanceof Date)&&!(o instanceof RegExp),a=s!=null&&typeof s=="object"&&!Array.isArray(s)&&!(s instanceof Date)&&!(s instanceof RegExp);i&&a?n[r]=Pp(s,o):n[r]=o}return n}function Xb(e){const t=["ROOT"];let n=-1,r=null;function o(l,c,u){switch(l){case'"':{n=c,t.pop(),t.push(u),t.push("INSIDE_STRING");break}case"f":case"t":case"n":{n=c,r=c,t.pop(),t.push(u),t.push("INSIDE_LITERAL");break}case"-":{t.pop(),t.push(u),t.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=c,t.pop(),t.push(u),t.push("INSIDE_NUMBER");break}case"{":{n=c,t.pop(),t.push(u),t.push("INSIDE_OBJECT_START");break}case"[":{n=c,t.pop(),t.push(u),t.push("INSIDE_ARRAY_START");break}}}function s(l,c){switch(l){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{n=c,t.pop();break}}}function i(l,c){switch(l){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=c,t.pop();break}}}for(let l=0;l<e.length;l++){const c=e[l];switch(t[t.length-1]){case"ROOT":o(c,l,"FINISH");break;case"INSIDE_OBJECT_START":{switch(c){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}case"}":{n=l,t.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(c){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(c){case'"':{t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(c){case":":{t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{o(c,l,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{s(c,l);break}case"INSIDE_STRING":{switch(c){case'"':{t.pop(),n=l;break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:n=l}break}case"INSIDE_ARRAY_START":{switch(c){case"]":{n=l,t.pop();break}default:{n=l,o(c,l,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(c){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=l,t.pop();break}default:{n=l;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{o(c,l,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),n=l;break}case"INSIDE_NUMBER":{switch(c){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=l;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(c,l),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&s(c,l);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&s(c,l);break}case"]":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(c,l);break}default:{t.pop();break}}break}case"INSIDE_LITERAL":{const h=e.substring(r,l+1);!"false".startsWith(h)&&!"true".startsWith(h)&&!"null".startsWith(h)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?s(c,l):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(c,l)):n=l;break}}}let a=e.slice(0,n+1);for(let l=t.length-1;l>=0;l--)switch(t[l]){case"INSIDE_STRING":{a+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{a+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{a+="]";break}case"INSIDE_LITERAL":{const u=e.substring(r,e.length);"true".startsWith(u)?a+="true".slice(u.length):"false".startsWith(u)?a+="false".slice(u.length):"null".startsWith(u)&&(a+="null".slice(u.length))}}return a}async function Rp(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await Un({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await Un({text:Xb(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function fa(e){return e.type.startsWith("tool-")}function Op(e){return e.type.split("-").slice(1).join("-")}function e9({lastMessage:e,messageId:t}){return{message:(e==null?void 0:e.role)==="assistant"?e:{id:t,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function t9({stream:e,messageMetadataSchema:t,dataPartSchemas:n,runUpdateMessageJob:r,onError:o,onToolCall:s,onData:i}){return e.pipeThrough(new TransformStream({async transform(a,l){await r(async({state:c,write:u})=>{var h,_,f,g;function v(b){const x=c.message.parts.filter(fa).find(T=>T.toolCallId===b);if(x==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return x}function m(b){const x=c.message.parts.filter(T=>T.type==="dynamic-tool").find(T=>T.toolCallId===b);if(x==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return x}function d(b){var k;const x=c.message.parts.find(U=>fa(U)&&U.toolCallId===b.toolCallId),T=b,D=x;x!=null?(x.state=b.state,D.input=T.input,D.output=T.output,D.errorText=T.errorText,D.rawInput=T.rawInput,D.preliminary=T.preliminary,D.providerExecuted=(k=T.providerExecuted)!=null?k:x.providerExecuted,T.providerMetadata!=null&&x.state==="input-available"&&(x.callProviderMetadata=T.providerMetadata)):c.message.parts.push({type:`tool-${b.toolName}`,toolCallId:b.toolCallId,state:b.state,input:T.input,output:T.output,rawInput:T.rawInput,errorText:T.errorText,providerExecuted:T.providerExecuted,preliminary:T.preliminary,...T.providerMetadata!=null?{callProviderMetadata:T.providerMetadata}:{}})}function w(b){var k;const x=c.message.parts.find(U=>U.type==="dynamic-tool"&&U.toolCallId===b.toolCallId),T=b,D=x;x!=null?(x.state=b.state,D.toolName=b.toolName,D.input=T.input,D.output=T.output,D.errorText=T.errorText,D.rawInput=(k=T.rawInput)!=null?k:D.rawInput,D.preliminary=T.preliminary,T.providerMetadata!=null&&x.state==="input-available"&&(x.callProviderMetadata=T.providerMetadata)):c.message.parts.push({type:"dynamic-tool",toolName:b.toolName,toolCallId:b.toolCallId,state:b.state,input:T.input,output:T.output,errorText:T.errorText,preliminary:T.preliminary,...T.providerMetadata!=null?{callProviderMetadata:T.providerMetadata}:{}})}async function y(b){if(b!=null){const k=c.message.metadata!=null?Pp(c.message.metadata,b):b;t!=null&&await Li({value:k,schema:t}),c.message.metadata=k}}switch(a.type){case"text-start":{const b={type:"text",text:"",providerMetadata:a.providerMetadata,state:"streaming"};c.activeTextParts[a.id]=b,c.message.parts.push(b),u();break}case"text-delta":{const b=c.activeTextParts[a.id];b.text+=a.delta,b.providerMetadata=(h=a.providerMetadata)!=null?h:b.providerMetadata,u();break}case"text-end":{const b=c.activeTextParts[a.id];b.state="done",b.providerMetadata=(_=a.providerMetadata)!=null?_:b.providerMetadata,delete c.activeTextParts[a.id],u();break}case"reasoning-start":{const b={type:"reasoning",text:"",providerMetadata:a.providerMetadata,state:"streaming"};c.activeReasoningParts[a.id]=b,c.message.parts.push(b),u();break}case"reasoning-delta":{const b=c.activeReasoningParts[a.id];b.text+=a.delta,b.providerMetadata=(f=a.providerMetadata)!=null?f:b.providerMetadata,u();break}case"reasoning-end":{const b=c.activeReasoningParts[a.id];b.providerMetadata=(g=a.providerMetadata)!=null?g:b.providerMetadata,b.state="done",delete c.activeReasoningParts[a.id],u();break}case"file":{c.message.parts.push({type:"file",mediaType:a.mediaType,url:a.url}),u();break}case"source-url":{c.message.parts.push({type:"source-url",sourceId:a.sourceId,url:a.url,title:a.title,providerMetadata:a.providerMetadata}),u();break}case"source-document":{c.message.parts.push({type:"source-document",sourceId:a.sourceId,mediaType:a.mediaType,title:a.title,filename:a.filename,providerMetadata:a.providerMetadata}),u();break}case"tool-input-start":{const b=c.message.parts.filter(fa);c.partialToolCalls[a.toolCallId]={text:"",toolName:a.toolName,index:b.length,dynamic:a.dynamic},a.dynamic?w({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0}):d({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0,providerExecuted:a.providerExecuted}),u();break}case"tool-input-delta":{const b=c.partialToolCalls[a.toolCallId];b.text+=a.inputTextDelta;const{value:k}=await Rp(b.text);b.dynamic?w({toolCallId:a.toolCallId,toolName:b.toolName,state:"input-streaming",input:k}):d({toolCallId:a.toolCallId,toolName:b.toolName,state:"input-streaming",input:k}),u();break}case"tool-input-available":{a.dynamic?w({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-available",input:a.input,providerMetadata:a.providerMetadata}):d({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-available",input:a.input,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}),u(),s&&!a.providerExecuted&&await s({toolCall:a});break}case"tool-input-error":{a.dynamic?w({toolCallId:a.toolCallId,toolName:a.toolName,state:"output-error",input:a.input,errorText:a.errorText,providerMetadata:a.providerMetadata}):d({toolCallId:a.toolCallId,toolName:a.toolName,state:"output-error",input:void 0,rawInput:a.input,errorText:a.errorText,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}),u();break}case"tool-output-available":{if(a.dynamic){const b=m(a.toolCallId);w({toolCallId:a.toolCallId,toolName:b.toolName,state:"output-available",input:b.input,output:a.output,preliminary:a.preliminary})}else{const b=v(a.toolCallId);d({toolCallId:a.toolCallId,toolName:Op(b),state:"output-available",input:b.input,output:a.output,providerExecuted:a.providerExecuted,preliminary:a.preliminary})}u();break}case"tool-output-error":{if(a.dynamic){const b=m(a.toolCallId);w({toolCallId:a.toolCallId,toolName:b.toolName,state:"output-error",input:b.input,errorText:a.errorText})}else{const b=v(a.toolCallId);d({toolCallId:a.toolCallId,toolName:Op(b),state:"output-error",input:b.input,rawInput:b.rawInput,errorText:a.errorText})}u();break}case"start-step":{c.message.parts.push({type:"step-start"});break}case"finish-step":{c.activeTextParts={},c.activeReasoningParts={};break}case"start":{a.messageId!=null&&(c.message.id=a.messageId),await y(a.messageMetadata),(a.messageId!=null||a.messageMetadata!=null)&&u();break}case"finish":{await y(a.messageMetadata),a.messageMetadata!=null&&u();break}case"message-metadata":{await y(a.messageMetadata),a.messageMetadata!=null&&u();break}case"error":{o==null||o(new Error(a.errorText));break}default:if(Qb(a)){(n==null?void 0:n[a.type])!=null&&await Li({value:a.data,schema:n[a.type]});const b=a;if(b.transient){i==null||i(b);break}const k=b.id!=null?c.message.parts.find(x=>b.type===x.type&&b.id===x.id):void 0;k!=null?k.data=b.data:c.message.parts.push(b),i==null||i(b),u()}}l.enqueue(a)})}}))}function n9({messageId:e,originalMessages:t=[],onFinish:n,onError:r,stream:o}){let s=t==null?void 0:t[t.length-1];(s==null?void 0:s.role)!=="assistant"?s=void 0:e=s.id;let i=!1;const a=o.pipeThrough(new TransformStream({transform(_,f){if(_.type==="start"){const g=_;g.messageId==null&&e!=null&&(g.messageId=e)}_.type==="abort"&&(i=!0),f.enqueue(_)}}));if(n==null)return a;const l=e9({lastMessage:s?structuredClone(s):void 0,messageId:e??""}),c=async _=>{await _({state:l,write:()=>{}})};let u=!1;const h=async()=>{if(u||!n)return;u=!0;const _=l.message.id===(s==null?void 0:s.id);await n({isAborted:i,isContinuation:_,responseMessage:l.message,messages:[..._?t.slice(0,-1):t,l.message]})};return t9({stream:a,runUpdateMessageJob:c,onError:r}).pipeThrough(new TransformStream({transform(_,f){f.enqueue(_)},async cancel(){await h()},async flush(){await h()}}))}function r9({response:e,status:t,statusText:n,headers:r,stream:o,consumeSseStream:s}){let i=o.pipeThrough(new Tp);if(s){const[a,l]=i.tee();i=a,s({stream:l})}Ip({response:e,status:t,statusText:n,headers:Object.fromEntries(ts(r,xp).entries()),stream:i.pipeThrough(new TextEncoderStream)})}function ns(e){const t=e.pipeThrough(new TransformStream);return t[Symbol.asyncIterator]=function(){const n=this.getReader();let r=!1;async function o(s){var i;r=!0;try{s&&await((i=n.cancel)==null?void 0:i.call(n))}finally{try{n.releaseLock()}catch{}}}return{async next(){if(r)return{done:!0,value:void 0};const{done:s,value:i}=await n.read();return s?(await o(!0),{done:!0,value:void 0}):{done:!1,value:i}},async return(){return await o(!0),{done:!0,value:void 0}},async throw(s){throw await o(!0),s}}},t}async function o9({stream:e,onError:t}){const n=e.getReader();try{for(;;){const{done:r}=await n.read();if(r)break}}catch(r){t==null||t(r)}finally{n.releaseLock()}}function Np(){let e,t;return{promise:new Promise((r,o)=>{e=r,t=o}),resolve:e,reject:t}}function s9(){let e=[],t=null,n=!1,r=Np();const o=()=>{n=!0,r.resolve(),e.forEach(i=>i.cancel()),e=[],t==null||t.close()},s=async()=>{if(n&&e.length===0){t==null||t.close();return}if(e.length===0)return r=Np(),await r.promise,s();try{const{value:i,done:a}=await e[0].read();a?(e.shift(),e.length>0?await s():n&&(t==null||t.close())):t==null||t.enqueue(i)}catch(i){t==null||t.error(i),e.shift(),o()}};return{stream:new ReadableStream({start(i){t=i},pull:s,async cancel(){for(const i of e)await i.cancel();e=[],n=!0}}),addStream:i=>{if(n)throw new Error("Cannot add inner stream: outer stream is closed");e.push(i.getReader()),r.resolve()},close:()=>{n=!0,r.resolve(),e.length===0&&(t==null||t.close())},terminate:o}}var rs=class{constructor(){this.status={type:"pending"},this._resolve=void 0,this._reject=void 0}get promise(){return this._promise?this._promise:(this._promise=new Promise((e,t)=>{this.status.type==="resolved"?e(this.status.value):this.status.type==="rejected"&&t(this.status.error),this._resolve=e,this._reject=t}),this._promise)}resolve(e){var t;this.status={type:"resolved",value:e},this._promise&&((t=this._resolve)==null||t.call(this,e))}reject(e){var t;this.status={type:"rejected",error:e},this._promise&&((t=this._reject)==null||t.call(this,e))}};function i9(){var e,t;return(t=(e=globalThis==null?void 0:globalThis.performance)==null?void 0:e.now())!=null?t:Date.now()}function a9({tools:e,generatorStream:t,tracer:n,telemetry:r,system:o,messages:s,abortSignal:i,repairToolCall:a,experimental_context:l}){let c=null;const u=new ReadableStream({start(d){c=d}}),h=new Set,_=new Map;let f=!1,g;function v(){f&&h.size===0&&(g!=null&&c.enqueue(g),c.close())}const m=new TransformStream({async transform(d,w){const y=d.type;switch(y){case"stream-start":case"text-start":case"text-delta":case"text-end":case"reasoning-start":case"reasoning-delta":case"reasoning-end":case"tool-input-start":case"tool-input-delta":case"tool-input-end":case"source":case"response-metadata":case"error":case"raw":{w.enqueue(d);break}case"file":{w.enqueue({type:"file",file:new Zb({data:d.data,mediaType:d.mediaType})});break}case"finish":{g={type:"finish",finishReason:d.finishReason,usage:d.usage,providerMetadata:d.providerMetadata};break}case"tool-call":{try{const b=await bp({toolCall:d,tools:e,repairToolCall:a,system:o,messages:s});if(w.enqueue(b),b.invalid){c.enqueue({type:"tool-error",toolCallId:b.toolCallId,toolName:b.toolName,input:b.input,error:Ai(b.error),dynamic:!0});break}const k=e[b.toolName];if(_.set(b.toolCallId,b.input),k.onInputAvailable!=null&&await k.onInputAvailable({input:b.input,toolCallId:b.toolCallId,messages:s,abortSignal:i,experimental_context:l}),k.execute!=null&&b.providerExecuted!==!0){const x=L_();h.add(x),lr({name:"ai.toolCall",attributes:kt({telemetry:r,attributes:{...ar({operationId:"ai.toolCall",telemetry:r}),"ai.toolCall.name":b.toolName,"ai.toolCall.id":b.toolCallId,"ai.toolCall.args":{output:()=>JSON.stringify(b.input)}}}),tracer:n,fn:async T=>{let D;try{const U=xd({execute:k.execute.bind(k),input:b.input,options:{toolCallId:b.toolCallId,messages:s,abortSignal:i,experimental_context:l}});for await(const H of U)c.enqueue({...b,type:"tool-result",output:H.output,...H.type==="preliminary"&&{preliminary:!0}}),H.type==="final"&&(D=H.output)}catch(U){la(T,U),c.enqueue({...b,type:"tool-error",error:U}),h.delete(x),v();return}h.delete(x),v();try{T.setAttributes(kt({telemetry:r,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(D)}}}))}catch{}}})}}catch(b){c.enqueue({type:"error",error:b})}break}case"tool-result":{const b=d.toolName;d.isError?c.enqueue({type:"tool-error",toolCallId:d.toolCallId,toolName:b,input:_.get(d.toolCallId),providerExecuted:d.providerExecuted,error:d.result}):w.enqueue({type:"tool-result",toolCallId:d.toolCallId,toolName:b,input:_.get(d.toolCallId),output:d.result,providerExecuted:d.providerExecuted});break}default:{const b=y;throw new Error(`Unhandled chunk type: ${b}`)}}},flush(){f=!0,v()}});return new ReadableStream({async start(d){return Promise.all([t.pipeThrough(m).pipeTo(new WritableStream({write(w){d.enqueue(w)},close(){}})),u.pipeTo(new WritableStream({write(w){d.enqueue(w)},close(){d.close()}}))])}})}var l9=Vr({prefix:"aitxt",size:24});function c9({model:e,tools:t,toolChoice:n,system:r,prompt:o,messages:s,maxRetries:i,abortSignal:a,headers:l,stopWhen:c=ua(1),experimental_output:u,experimental_telemetry:h,prepareStep:_,providerOptions:f,experimental_activeTools:g,activeTools:v=g,experimental_repairToolCall:m,experimental_transform:d,experimental_download:w,includeRawChunks:y=!1,onChunk:b,onError:k=({error:V})=>{console.error(V)},onFinish:x,onAbort:T,onStepFinish:D,experimental_context:U,_internal:{now:H=i9,generateId:q=l9,currentDate:F=()=>new Date}={},...B}){return new d9({model:Qo(e),telemetry:h,headers:l,settings:B,maxRetries:i,abortSignal:a,system:r,prompt:o,messages:s,tools:t,toolChoice:n,transforms:ca(d),activeTools:v,repairToolCall:m,stopConditions:ca(c),output:u,providerOptions:f,prepareStep:_,includeRawChunks:y,onChunk:b,onError:k,onFinish:x,onAbort:T,onStepFinish:D,now:H,currentDate:F,generateId:q,experimental_context:U,download:w})}function u9(e){if(!e)return new TransformStream({transform(i,a){a.enqueue({part:i,partialOutput:void 0})}});let t,n="",r="",o="";function s({controller:i,partialOutput:a=void 0}){i.enqueue({part:{type:"text-delta",id:t,text:r},partialOutput:a}),r=""}return new TransformStream({async transform(i,a){if(i.type==="finish-step"&&r.length>0&&s({controller:a}),i.type!=="text-delta"&&i.type!=="text-start"&&i.type!=="text-end"){a.enqueue({part:i,partialOutput:void 0});return}if(t==null)t=i.id;else if(i.id!==t){a.enqueue({part:i,partialOutput:void 0});return}if(i.type==="text-start"){a.enqueue({part:i,partialOutput:void 0});return}if(i.type==="text-end"){r.length>0&&s({controller:a}),a.enqueue({part:i,partialOutput:void 0});return}n+=i.text,r+=i.text;const l=await e.parsePartial({text:n});if(l!=null){const c=JSON.stringify(l.partial);c!==o&&(s({controller:a,partialOutput:l.partial}),o=c)}}})}var d9=class{constructor({model:e,telemetry:t,headers:n,settings:r,maxRetries:o,abortSignal:s,system:i,prompt:a,messages:l,tools:c,toolChoice:u,transforms:h,activeTools:_,repairToolCall:f,stopConditions:g,output:v,providerOptions:m,prepareStep:d,includeRawChunks:w,now:y,currentDate:b,generateId:k,onChunk:x,onError:T,onFinish:D,onAbort:U,onStepFinish:H,experimental_context:q,download:F}){this._totalUsage=new rs,this._finishReason=new rs,this._steps=new rs,this.output=v,this.includeRawChunks=w,this.tools=c;let B,V=[];const se=[];let ge,te,ue={},le=[];const L=[];let I,M={},P={};const C=new TransformStream({async transform(ve,ye){var Le,fe,Ze,gt;ye.enqueue(ve);const{part:J}=ve;if((J.type==="text-delta"||J.type==="reasoning-delta"||J.type==="source"||J.type==="tool-call"||J.type==="tool-result"||J.type==="tool-input-start"||J.type==="tool-input-delta"||J.type==="raw")&&await(x==null?void 0:x({chunk:J})),J.type==="error"&&await T({error:pp(J.error)}),J.type==="text-start"&&(M[J.id]={type:"text",text:"",providerMetadata:J.providerMetadata},V.push(M[J.id])),J.type==="text-delta"){const $e=M[J.id];if($e==null){ye.enqueue({part:{type:"error",error:`text part ${J.id} not found`},partialOutput:void 0});return}$e.text+=J.text,$e.providerMetadata=(Le=J.providerMetadata)!=null?Le:$e.providerMetadata}if(J.type==="text-end"){const $e=M[J.id];if($e==null){ye.enqueue({part:{type:"error",error:`text part ${J.id} not found`},partialOutput:void 0});return}$e.providerMetadata=(fe=J.providerMetadata)!=null?fe:$e.providerMetadata,delete M[J.id]}if(J.type==="reasoning-start"&&(P[J.id]={type:"reasoning",text:"",providerMetadata:J.providerMetadata},V.push(P[J.id])),J.type==="reasoning-delta"){const $e=P[J.id];if($e==null){ye.enqueue({part:{type:"error",error:`reasoning part ${J.id} not found`},partialOutput:void 0});return}$e.text+=J.text,$e.providerMetadata=(Ze=J.providerMetadata)!=null?Ze:$e.providerMetadata}if(J.type==="reasoning-end"){const $e=P[J.id];if($e==null){ye.enqueue({part:{type:"error",error:`reasoning part ${J.id} not found`},partialOutput:void 0});return}$e.providerMetadata=(gt=J.providerMetadata)!=null?gt:$e.providerMetadata,delete P[J.id]}if(J.type==="file"&&V.push({type:"file",file:J.file}),J.type==="source"&&V.push(J),J.type==="tool-call"&&V.push(J),J.type==="tool-result"&&!J.preliminary&&V.push(J),J.type==="tool-error"&&V.push(J),J.type==="start-step"&&(ue=J.request,le=J.warnings),J.type==="finish-step"){const $e=pa({content:V,tools:c}),Ot=new Sp({content:V,finishReason:J.finishReason,usage:J.usage,warnings:le,request:ue,response:{...J.response,messages:[...se,...$e]},providerMetadata:J.providerMetadata});await(H==null?void 0:H(Ot)),E0(le),L.push(Ot),V=[],P={},M={},se.push(...$e),B.resolve()}J.type==="finish"&&(te=J.totalUsage,ge=J.finishReason)},async flush(ve){try{if(L.length===0){const Ze=new ab({message:"No output generated. Check the stream for errors."});Ne._finishReason.reject(Ze),Ne._totalUsage.reject(Ze),Ne._steps.reject(Ze);return}const ye=ge??"unknown",Le=te??{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};Ne._finishReason.resolve(ye),Ne._totalUsage.resolve(Le),Ne._steps.resolve(L);const fe=L[L.length-1];await(D==null?void 0:D({finishReason:ye,totalUsage:Le,usage:fe.usage,content:fe.content,text:fe.text,reasoningText:fe.reasoningText,reasoning:fe.reasoning,files:fe.files,sources:fe.sources,toolCalls:fe.toolCalls,staticToolCalls:fe.staticToolCalls,dynamicToolCalls:fe.dynamicToolCalls,toolResults:fe.toolResults,staticToolResults:fe.staticToolResults,dynamicToolResults:fe.dynamicToolResults,request:fe.request,response:fe.response,warnings:fe.warnings,providerMetadata:fe.providerMetadata,steps:L})),I.setAttributes(kt({telemetry:t,attributes:{"ai.response.finishReason":ye,"ai.response.text":{output:()=>fe.text},"ai.response.toolCalls":{output:()=>{var Ze;return(Ze=fe.toolCalls)!=null&&Ze.length?JSON.stringify(fe.toolCalls):void 0}},"ai.response.providerMetadata":JSON.stringify(fe.providerMetadata),"ai.usage.inputTokens":Le.inputTokens,"ai.usage.outputTokens":Le.outputTokens,"ai.usage.totalTokens":Le.totalTokens,"ai.usage.reasoningTokens":Le.reasoningTokens,"ai.usage.cachedInputTokens":Le.cachedInputTokens}}))}catch(ye){ve.error(ye)}finally{I.end()}}}),E=s9();this.addStream=E.addStream,this.closeStream=E.close;const $=E.stream.getReader();let j=new ReadableStream({async start(ve){ve.enqueue({type:"start"})},async pull(ve){function ye(){U==null||U({steps:L}),ve.enqueue({type:"abort"}),ve.close()}try{const{done:Le,value:fe}=await $.read();if(Le){ve.close();return}if(s!=null&&s.aborted){ye();return}ve.enqueue(fe)}catch(Le){zn(Le)&&(s!=null&&s.aborted)?ye():ve.error(Le)}},cancel(ve){return E.stream.cancel(ve)}});for(const ve of h)j=j.pipeThrough(ve({tools:c,stopStream(){E.terminate()}}));this.baseStream=j.pipeThrough(u9(v)).pipeThrough(C);const{maxRetries:z,retry:de}=_p({maxRetries:o,abortSignal:s}),oe=hp(t),_e=aa(r),Rt=fp({model:e,telemetry:t,headers:n,settings:{..._e,maxRetries:z}}),Ne=this;lr({name:"ai.streamText",attributes:kt({telemetry:t,attributes:{...ar({operationId:"ai.streamText",telemetry:t}),...Rt,"ai.prompt":{input:()=>JSON.stringify({system:i,prompt:a,messages:l})}}}),tracer:oe,endWhenDone:!1,fn:async ve=>{I=ve;async function ye({currentStep:Le,responseMessages:fe,usage:Ze}){var gt,J,$e,Ot,Se;const vt=Ne.includeRawChunks;B=new rs;const mn=await dp({system:i,prompt:a,messages:l}),_t=[...mn.messages,...fe],Ye=await(d==null?void 0:d({model:e,steps:L,stepNumber:L.length,messages:_t})),Nt=Qo((gt=Ye==null?void 0:Ye.model)!=null?gt:e),Nn=await ip({prompt:{system:(J=Ye==null?void 0:Ye.system)!=null?J:mn.system,messages:($e=Ye==null?void 0:Ye.messages)!=null?$e:_t},supportedUrls:await Nt.supportedUrls,download:F}),{toolChoice:Mn,tools:Nr}=ap({tools:c,toolChoice:(Ot=Ye==null?void 0:Ye.toolChoice)!=null?Ot:u,activeTools:(Se=Ye==null?void 0:Ye.activeTools)!=null?Se:_}),{result:{stream:hi,response:Be,request:gn},doStreamSpan:vn,startTimestampMs:fm}=await de(()=>lr({name:"ai.streamText.doStream",attributes:kt({telemetry:t,attributes:{...ar({operationId:"ai.streamText.doStream",telemetry:t}),...Rt,"ai.model.provider":Nt.provider,"ai.model.id":Nt.modelId,"ai.prompt.messages":{input:()=>mp(Nn)},"ai.prompt.tools":{input:()=>Nr==null?void 0:Nr.map(X=>JSON.stringify(X))},"ai.prompt.toolChoice":{input:()=>Mn!=null?JSON.stringify(Mn):void 0},"gen_ai.system":Nt.provider,"gen_ai.request.model":Nt.modelId,"gen_ai.request.frequency_penalty":_e.frequencyPenalty,"gen_ai.request.max_tokens":_e.maxOutputTokens,"gen_ai.request.presence_penalty":_e.presencePenalty,"gen_ai.request.stop_sequences":_e.stopSequences,"gen_ai.request.temperature":_e.temperature,"gen_ai.request.top_k":_e.topK,"gen_ai.request.top_p":_e.topP}}),tracer:oe,endWhenDone:!1,fn:async X=>({startTimestampMs:y(),doStreamSpan:X,result:await Nt.doStream({..._e,tools:Nr,toolChoice:Mn,responseFormat:v==null?void 0:v.responseFormat,prompt:Nn,providerOptions:m,abortSignal:s,headers:n,includeRawChunks:vt})})})),hI=a9({tools:c,generatorStream:hi,tracer:oe,telemetry:t,system:i,messages:_t,repairToolCall:f,abortSignal:s,experimental_context:q}),mI=gn??{},mi=[],xc=[];let Pc;const Rc={};let Mr="unknown",Jt={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},Oc,hm=!0,cn={id:k(),timestamp:b(),modelId:e.modelId},mm="";Ne.addStream(hI.pipeThrough(new TransformStream({async transform(X,Qe){var Ro,Oo,gi,_n;if(X.type==="stream-start"){Pc=X.warnings;return}if(hm){const ct=y()-fm;hm=!1,vn.addEvent("ai.stream.firstChunk",{"ai.response.msToFirstChunk":ct}),vn.setAttributes({"ai.response.msToFirstChunk":ct}),Qe.enqueue({type:"start-step",request:mI,warnings:Pc??[]})}const gm=X.type;switch(gm){case"text-start":case"text-end":{Qe.enqueue(X);break}case"text-delta":{X.delta.length>0&&(Qe.enqueue({type:"text-delta",id:X.id,text:X.delta,providerMetadata:X.providerMetadata}),mm+=X.delta);break}case"reasoning-start":case"reasoning-end":{Qe.enqueue(X);break}case"reasoning-delta":{Qe.enqueue({type:"reasoning-delta",id:X.id,text:X.delta,providerMetadata:X.providerMetadata});break}case"tool-call":{Qe.enqueue(X),mi.push(X);break}case"tool-result":{Qe.enqueue(X),X.preliminary||xc.push(X);break}case"tool-error":{Qe.enqueue(X),xc.push(X);break}case"response-metadata":{cn={id:(Ro=X.id)!=null?Ro:cn.id,timestamp:(Oo=X.timestamp)!=null?Oo:cn.timestamp,modelId:(gi=X.modelId)!=null?gi:cn.modelId};break}case"finish":{Jt=X.usage,Mr=X.finishReason,Oc=X.providerMetadata;const ct=y()-fm;vn.addEvent("ai.stream.finish"),vn.setAttributes({"ai.response.msToFinish":ct,"ai.response.avgOutputTokensPerSecond":1e3*((_n=Jt.outputTokens)!=null?_n:0)/ct});break}case"file":{Qe.enqueue(X);break}case"source":{Qe.enqueue(X);break}case"tool-input-start":{Rc[X.id]=X.toolName;const ct=c==null?void 0:c[X.toolName];(ct==null?void 0:ct.onInputStart)!=null&&await ct.onInputStart({toolCallId:X.id,messages:_t,abortSignal:s,experimental_context:q}),Qe.enqueue({...X,dynamic:(ct==null?void 0:ct.type)==="dynamic"});break}case"tool-input-end":{delete Rc[X.id],Qe.enqueue(X);break}case"tool-input-delta":{const ct=Rc[X.id],Nc=c==null?void 0:c[ct];(Nc==null?void 0:Nc.onInputDelta)!=null&&await Nc.onInputDelta({inputTextDelta:X.delta,toolCallId:X.id,messages:_t,abortSignal:s,experimental_context:q}),Qe.enqueue(X);break}case"error":{Qe.enqueue(X),Mr="error";break}case"raw":{vt&&Qe.enqueue(X);break}default:{const ct=gm;throw new Error(`Unknown chunk type: ${ct}`)}}},async flush(X){const Qe=mi.length>0?JSON.stringify(mi):void 0;try{vn.setAttributes(kt({telemetry:t,attributes:{"ai.response.finishReason":Mr,"ai.response.text":{output:()=>mm},"ai.response.toolCalls":{output:()=>Qe},"ai.response.id":cn.id,"ai.response.model":cn.modelId,"ai.response.timestamp":cn.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(Oc),"ai.usage.inputTokens":Jt.inputTokens,"ai.usage.outputTokens":Jt.outputTokens,"ai.usage.totalTokens":Jt.totalTokens,"ai.usage.reasoningTokens":Jt.reasoningTokens,"ai.usage.cachedInputTokens":Jt.cachedInputTokens,"gen_ai.response.finish_reasons":[Mr],"gen_ai.response.id":cn.id,"gen_ai.response.model":cn.modelId,"gen_ai.usage.input_tokens":Jt.inputTokens,"gen_ai.usage.output_tokens":Jt.outputTokens}}))}catch{}finally{vn.end()}X.enqueue({type:"finish-step",finishReason:Mr,usage:Jt,providerMetadata:Oc,response:{...cn,headers:Be==null?void 0:Be.headers}});const Ro=gp(Ze,Jt);await B.promise;const Oo=mi.filter(_n=>_n.providerExecuted!==!0),gi=xc.filter(_n=>_n.providerExecuted!==!0);if(Oo.length>0&&gi.length===Oo.length&&!await Cp({stopConditions:g,steps:L})){fe.push(...pa({content:L[L.length-1].content,tools:c}));try{await ye({currentStep:Le+1,responseMessages:fe,usage:Ro})}catch(_n){X.enqueue({type:"error",error:_n}),Ne.closeStream()}}else X.enqueue({type:"finish",finishReason:Mr,totalUsage:Ro}),Ne.closeStream()}})))}await ye({currentStep:0,responseMessages:[],usage:{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0}})}}).catch(ve=>{Ne.addStream(new ReadableStream({start(ye){ye.enqueue({type:"error",error:ve}),ye.close()}})),Ne.closeStream()})}get steps(){return this.consumeStream(),this._steps.promise}get finalStep(){return this.steps.then(e=>e[e.length-1])}get content(){return this.finalStep.then(e=>e.content)}get warnings(){return this.finalStep.then(e=>e.warnings)}get providerMetadata(){return this.finalStep.then(e=>e.providerMetadata)}get text(){return this.finalStep.then(e=>e.text)}get reasoningText(){return this.finalStep.then(e=>e.reasoningText)}get reasoning(){return this.finalStep.then(e=>e.reasoning)}get sources(){return this.finalStep.then(e=>e.sources)}get files(){return this.finalStep.then(e=>e.files)}get toolCalls(){return this.finalStep.then(e=>e.toolCalls)}get staticToolCalls(){return this.finalStep.then(e=>e.staticToolCalls)}get dynamicToolCalls(){return this.finalStep.then(e=>e.dynamicToolCalls)}get toolResults(){return this.finalStep.then(e=>e.toolResults)}get staticToolResults(){return this.finalStep.then(e=>e.staticToolResults)}get dynamicToolResults(){return this.finalStep.then(e=>e.dynamicToolResults)}get usage(){return this.finalStep.then(e=>e.usage)}get request(){return this.finalStep.then(e=>e.request)}get response(){return this.finalStep.then(e=>e.response)}get totalUsage(){return this.consumeStream(),this._totalUsage.promise}get finishReason(){return this.consumeStream(),this._finishReason.promise}teeStream(){const[e,t]=this.baseStream.tee();return this.baseStream=t,e}get textStream(){return ns(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){e.type==="text-delta"&&t.enqueue(e.text)}})))}get fullStream(){return ns(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){t.enqueue(e)}})))}async consumeStream(e){var t;try{await o9({stream:this.fullStream,onError:e==null?void 0:e.onError})}catch(n){(t=e==null?void 0:e.onError)==null||t.call(e,n)}}get experimental_partialOutputStream(){if(this.output==null)throw new S0;return ns(this.teeStream().pipeThrough(new TransformStream({transform({partialOutput:e},t){e!=null&&t.enqueue(e)}})))}toUIMessageStream({originalMessages:e,generateMessageId:t,onFinish:n,messageMetadata:r,sendReasoning:o=!0,sendSources:s=!1,sendStart:i=!0,sendFinish:a=!0,onError:l=sr}={}){const c=t!=null?Yb({originalMessages:e,responseMessageId:t}):void 0,u={},h=f=>{var g,v;const m=u[f];return((v=(g=this.tools)==null?void 0:g[m])==null?void 0:v.type)==="dynamic"?!0:void 0},_=this.fullStream.pipeThrough(new TransformStream({transform:async(f,g)=>{const v=r==null?void 0:r({part:f}),m=f.type;switch(m){case"text-start":{g.enqueue({type:"text-start",id:f.id,...f.providerMetadata!=null?{providerMetadata:f.providerMetadata}:{}});break}case"text-delta":{g.enqueue({type:"text-delta",id:f.id,delta:f.text,...f.providerMetadata!=null?{providerMetadata:f.providerMetadata}:{}});break}case"text-end":{g.enqueue({type:"text-end",id:f.id,...f.providerMetadata!=null?{providerMetadata:f.providerMetadata}:{}});break}case"reasoning-start":{g.enqueue({type:"reasoning-start",id:f.id,...f.providerMetadata!=null?{providerMetadata:f.providerMetadata}:{}});break}case"reasoning-delta":{o&&g.enqueue({type:"reasoning-delta",id:f.id,delta:f.text,...f.providerMetadata!=null?{providerMetadata:f.providerMetadata}:{}});break}case"reasoning-end":{g.enqueue({type:"reasoning-end",id:f.id,...f.providerMetadata!=null?{providerMetadata:f.providerMetadata}:{}});break}case"file":{g.enqueue({type:"file",mediaType:f.file.mediaType,url:`data:${f.file.mediaType};base64,${f.file.base64}`});break}case"source":{s&&f.sourceType==="url"&&g.enqueue({type:"source-url",sourceId:f.id,url:f.url,title:f.title,...f.providerMetadata!=null?{providerMetadata:f.providerMetadata}:{}}),s&&f.sourceType==="document"&&g.enqueue({type:"source-document",sourceId:f.id,mediaType:f.mediaType,title:f.title,filename:f.filename,...f.providerMetadata!=null?{providerMetadata:f.providerMetadata}:{}});break}case"tool-input-start":{u[f.id]=f.toolName;const d=h(f.id);g.enqueue({type:"tool-input-start",toolCallId:f.id,toolName:f.toolName,...f.providerExecuted!=null?{providerExecuted:f.providerExecuted}:{},...d!=null?{dynamic:d}:{}});break}case"tool-input-delta":{g.enqueue({type:"tool-input-delta",toolCallId:f.id,inputTextDelta:f.delta});break}case"tool-call":{u[f.toolCallId]=f.toolName;const d=h(f.toolCallId);f.invalid?g.enqueue({type:"tool-input-error",toolCallId:f.toolCallId,toolName:f.toolName,input:f.input,...f.providerExecuted!=null?{providerExecuted:f.providerExecuted}:{},...f.providerMetadata!=null?{providerMetadata:f.providerMetadata}:{},...d!=null?{dynamic:d}:{},errorText:l(f.error)}):g.enqueue({type:"tool-input-available",toolCallId:f.toolCallId,toolName:f.toolName,input:f.input,...f.providerExecuted!=null?{providerExecuted:f.providerExecuted}:{},...f.providerMetadata!=null?{providerMetadata:f.providerMetadata}:{},...d!=null?{dynamic:d}:{}});break}case"tool-result":{const d=h(f.toolCallId);g.enqueue({type:"tool-output-available",toolCallId:f.toolCallId,output:f.output,...f.providerExecuted!=null?{providerExecuted:f.providerExecuted}:{},...f.preliminary!=null?{preliminary:f.preliminary}:{},...d!=null?{dynamic:d}:{}});break}case"tool-error":{const d=h(f.toolCallId);g.enqueue({type:"tool-output-error",toolCallId:f.toolCallId,errorText:l(f.error),...f.providerExecuted!=null?{providerExecuted:f.providerExecuted}:{},...d!=null?{dynamic:d}:{}});break}case"error":{g.enqueue({type:"error",errorText:l(f.error)});break}case"start-step":{g.enqueue({type:"start-step"});break}case"finish-step":{g.enqueue({type:"finish-step"});break}case"start":{i&&g.enqueue({type:"start",...v!=null?{messageMetadata:v}:{},...c!=null?{messageId:c}:{}});break}case"finish":{a&&g.enqueue({type:"finish",...v!=null?{messageMetadata:v}:{}});break}case"abort":{g.enqueue(f);break}case"tool-input-end":break;case"raw":break;default:{const d=m;throw new Error(`Unknown chunk type: ${d}`)}}v!=null&&m!=="start"&&m!=="finish"&&g.enqueue({type:"message-metadata",messageMetadata:v})}}));return ns(n9({stream:_,messageId:c??(t==null?void 0:t()),originalMessages:e,onFinish:n,onError:l}))}pipeUIMessageStreamToResponse(e,{originalMessages:t,generateMessageId:n,onFinish:r,messageMetadata:o,sendReasoning:s,sendSources:i,sendFinish:a,sendStart:l,onError:c,...u}={}){r9({response:e,stream:this.toUIMessageStream({originalMessages:t,generateMessageId:n,onFinish:r,messageMetadata:o,sendReasoning:s,sendSources:i,sendFinish:a,sendStart:l,onError:c}),...u})}pipeTextStreamToResponse(e,t){Wb({response:e,textStream:this.textStream,...t})}toUIMessageStreamResponse({originalMessages:e,generateMessageId:t,onFinish:n,messageMetadata:r,sendReasoning:o,sendSources:s,sendFinish:i,sendStart:a,onError:l,...c}={}){return Kb({stream:this.toUIMessageStream({originalMessages:e,generateMessageId:t,onFinish:n,messageMetadata:r,sendReasoning:o,sendSources:s,sendFinish:i,sendStart:a,onError:l}),...c})}toTextStreamResponse(e){return Gb({textStream:this.textStream,...e})}};Vr({prefix:"aiobj",size:24}),Vr({prefix:"aiobj",size:24});var p9={};Y3(p9,{object:()=>h9,text:()=>f9});var f9=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:e}){return{partial:e}},async parseOutput({text:e}){return e}}),h9=({schema:e})=>{const t=Go(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:n}){const r=await Rp(n);switch(r.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:r.value};default:{const o=r.state;throw new Error(`Unsupported parse state: ${o}`)}}},async parseOutput({text:n},r){const o=await Un({text:n});if(!o.success)throw new z0({message:"No object generated: could not parse the response.",cause:o.error,text:n,response:r.response,usage:r.usage,finishReason:r.finishReason});const s=await $n({value:o.value,schema:t});if(!s.success)throw new z0({message:"No object generated: response did not match schema.",cause:s.error,text:n,response:r.response,usage:r.usage,finishReason:r.finishReason});return s.value}}},Mp="2025-06-18",m9=[Mp,"2025-03-26","2024-11-05"],g9=He({name:p(),version:p()}),ha=He({_meta:Y(S({}).loose())}),ro=ha,v9=S({method:p(),params:Y(ha)}),_9=He({experimental:Y(S({}).loose()),logging:Y(S({}).loose()),prompts:Y(He({listChanged:Y(ne())})),resources:Y(He({subscribe:Y(ne()),listChanged:Y(ne())})),tools:Y(He({listChanged:Y(ne())}))}),y9=ro.extend({protocolVersion:p(),capabilities:_9,serverInfo:g9,instructions:Y(p())}),w9=ro.extend({nextCursor:Y(p())}),b9=S({name:p(),description:Y(p()),inputSchema:S({type:O("object"),properties:Y(S({}).loose())}).loose()}).loose(),$9=w9.extend({tools:N(b9)}),S9=S({type:O("text"),text:p()}).loose(),C9=S({type:O("image"),data:ad(),mimeType:p()}).loose(),Ap=S({uri:p(),mimeType:Y(p())}).loose(),E9=Ap.extend({text:p()}),k9=Ap.extend({blob:ad()}),I9=S({type:O("resource"),resource:Q([E9,k9])}).loose(),T9=ro.extend({content:N(Q([S9,C9,I9])),isError:ne().default(!1).optional()}).or(ro.extend({toolResult:ke()})),os="2.0",x9=S({jsonrpc:O(os),id:Q([p(),R().int()])}).merge(v9).strict(),P9=S({jsonrpc:O(os),id:Q([p(),R().int()]),result:ro}).strict(),R9=S({jsonrpc:O(os),id:Q([p(),R().int()]),error:S({code:R().int(),message:p(),data:Y(ke())})}).strict(),O9=S({jsonrpc:O(os)}).merge(S({method:p(),params:Y(ha)})).strict(),N9=Q([x9,O9,P9,R9]),M9=class{constructor({url:e,headers:t}){this.connected=!1,this.url=new URL(e),this.headers=t}async start(){return new Promise((e,t)=>{if(this.connected)return e();this.abortController=new AbortController,(async()=>{var r,o,s;try{const i=Dn({...this.headers,Accept:"text/event-stream"},`ai-sdk/${Xo}`,Br()),a=await fetch(this.url.href,{headers:i,signal:(r=this.abortController)==null?void 0:r.signal});if(!a.ok||!a.body){const h=new Ve({message:`MCP SSE Transport Error: ${a.status} ${a.statusText}`});return(o=this.onerror)==null||o.call(this,h),t(h)}const c=a.body.pipeThrough(new TextDecoderStream).pipeThrough(new Mo).getReader(),u=async()=>{var h,_,f;try{for(;;){const{done:g,value:v}=await c.read();if(g){if(this.connected)throw this.connected=!1,new Ve({message:"MCP SSE Transport Error: Connection closed unexpectedly"});return}const{event:m,data:d}=v;if(m==="endpoint"){if(this.endpoint=new URL(d,this.url),this.endpoint.origin!==this.url.origin)throw new Ve({message:`MCP SSE Transport Error: Endpoint origin does not match connection origin: ${this.endpoint.origin}`});this.connected=!0,e()}else if(m==="message")try{const w=N9.parse(JSON.parse(d));(h=this.onmessage)==null||h.call(this,w)}catch(w){const y=new Ve({message:"MCP SSE Transport Error: Failed to parse message",cause:w});(_=this.onerror)==null||_.call(this,y)}}}catch(g){if(g instanceof Error&&g.name==="AbortError")return;(f=this.onerror)==null||f.call(this,g),t(g)}};this.sseConnection={close:()=>c.cancel()},u()}catch(i){if(i instanceof Error&&i.name==="AbortError")return;(s=this.onerror)==null||s.call(this,i),t(i)}})()})}async close(){var e,t,n;this.connected=!1,(e=this.sseConnection)==null||e.close(),(t=this.abortController)==null||t.abort(),(n=this.onclose)==null||n.call(this)}async send(e){var t,n,r;if(!this.endpoint||!this.connected)throw new Ve({message:"MCP SSE Transport Error: Not connected"});try{const s={method:"POST",headers:Dn({...this.headers,"Content-Type":"application/json"},`ai-sdk/${Xo}`,Br()),body:JSON.stringify(e),signal:(t=this.abortController)==null?void 0:t.signal},i=await fetch(this.endpoint,s);if(!i.ok){const a=await i.text().catch(()=>null),l=new Ve({message:`MCP SSE Transport Error: POSTing to endpoint (HTTP ${i.status}): ${a}`});(n=this.onerror)==null||n.call(this,l);return}}catch(o){(r=this.onerror)==null||r.call(this,o);return}}};function A9(e){if(e.type!=="sse")throw new Ve({message:"Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface."});return new M9(e)}function L9(e){return"start"in e&&typeof e.start=="function"&&"send"in e&&typeof e.send=="function"&&"close"in e&&typeof e.close=="function"}var j9="1.0.0";async function z9(e){const t=new D9(e);return await t.init(),t}var D9=class{constructor({transport:e,name:t="ai-sdk-mcp-client",onUncaughtError:n}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this.isClosed=!0,this.onUncaughtError=n,L9(e)?this.transport=e:this.transport=A9(e),this.transport.onclose=()=>this.onClose(),this.transport.onerror=r=>this.onError(r),this.transport.onmessage=r=>{if("method"in r){this.onError(new Ve({message:"Unsupported message type"}));return}this.onResponse(r)},this.clientInfo={name:t,version:j9}}async init(){try{await this.transport.start(),this.isClosed=!1;const e=await this.request({request:{method:"initialize",params:{protocolVersion:Mp,capabilities:{},clientInfo:this.clientInfo}},resultSchema:y9});if(e===void 0)throw new Ve({message:"Server sent invalid initialize result"});if(!m9.includes(e.protocolVersion))throw new Ve({message:`Server's protocol version is not supported: ${e.protocolVersion}`});return this.serverCapabilities=e.capabilities,await this.notification({method:"notifications/initialized"}),this}catch(e){throw await this.close(),e}}async close(){var e;this.isClosed||(await((e=this.transport)==null?void 0:e.close()),this.onClose())}assertCapability(e){switch(e){case"initialize":break;case"tools/list":case"tools/call":if(!this.serverCapabilities.tools)throw new Ve({message:"Server does not support tools"});break;default:throw new Ve({message:`Unsupported method: ${e}`})}}async request({request:e,resultSchema:t,options:n}){return new Promise((r,o)=>{if(this.isClosed)return o(new Ve({message:"Attempted to send a request from a closed client"}));this.assertCapability(e.method);const s=n==null?void 0:n.signal;s==null||s.throwIfAborted();const i=this.requestMessageId++,a={...e,jsonrpc:"2.0",id:i},l=()=>{this.responseHandlers.delete(i)};this.responseHandlers.set(i,c=>{if(s!=null&&s.aborted)return o(new Ve({message:"Request was aborted",cause:s.reason}));if(c instanceof Error)return o(c);try{const u=t.parse(c.result);r(u)}catch(u){const h=new Ve({message:"Failed to parse server response",cause:u});o(h)}}),this.transport.send(a).catch(c=>{l(),o(c)})})}async listTools({params:e,options:t}={}){try{return this.request({request:{method:"tools/list",params:e},resultSchema:$9,options:t})}catch(n){throw n}}async callTool({name:e,args:t,options:n}){try{return this.request({request:{method:"tools/call",params:{name:e,arguments:t}},resultSchema:T9,options:{signal:n==null?void 0:n.abortSignal}})}catch(r){throw r}}async notification(e){const t={...e,jsonrpc:"2.0"};await this.transport.send(t)}async tools({schemas:e="automatic"}={}){var t;const n={};try{const r=await this.listTools();for(const{name:o,description:s,inputSchema:i}of r.tools){if(e!=="automatic"&&!(o in e))continue;const a=this,l=async(u,h)=>{var _;return(_=h==null?void 0:h.abortSignal)==null||_.throwIfAborted(),a.callTool({name:o,args:u,options:h})},c=e==="automatic"?$d({description:s,inputSchema:Jr({...i,properties:(t=i.properties)!=null?t:{},additionalProperties:!1}),execute:l}):{description:s,inputSchema:e[o].inputSchema,execute:l};n[o]=c}return n}catch(r){throw r}}onClose(){if(this.isClosed)return;this.isClosed=!0;const e=new Ve({message:"Connection closed"});for(const t of this.responseHandlers.values())t(e);this.responseHandlers.clear()}onError(e){this.onUncaughtError&&this.onUncaughtError(e)}onResponse(e){const t=Number(e.id),n=this.responseHandlers.get(t);if(n===void 0)throw new Ve({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(e)}`});this.responseHandlers.delete(t),n("result"in e?e:new Ve({message:e.error.message,code:e.error.code,data:e.error.data,cause:e.error}))}};function ma(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function Lp(e=fetch,t){return t?async(n,r)=>{const o={...t,...r,headers:r!=null&&r.headers?{...ma(t.headers),...ma(r.headers)}:t.headers};return e(n,o)}:e}const ss="2025-06-18",U9=[ss,"2025-03-26","2024-11-05","2024-10-07"],is="2.0",Qt=gd(e=>e!==null&&(typeof e=="object"||typeof e=="function")),jp=Q([p(),R().int()]),zp=p(),q9=He({progressToken:jp.optional()}),jt=He({_meta:q9.optional()}),dt=S({method:p(),params:jt.optional()}),cr=He({_meta:ie(p(),ke()).optional()}),zt=S({method:p(),params:cr.optional()}),It=He({_meta:ie(p(),ke()).optional()}),as=Q([p(),R().int()]),Dp=S({jsonrpc:O(is),id:as,...dt.shape}).strict(),Up=e=>Dp.safeParse(e).success,qp=S({jsonrpc:O(is),...zt.shape}).strict(),Z9=e=>qp.safeParse(e).success,Zp=S({jsonrpc:O(is),id:as,result:It}).strict(),ga=e=>Zp.safeParse(e).success;var Xe;(function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(Xe||(Xe={}));const Fp=S({jsonrpc:O(is),id:as,error:S({code:R().int(),message:p(),data:Y(ke())})}).strict(),F9=e=>Fp.safeParse(e).success,Hn=Q([Dp,qp,Zp,Fp]),Jn=It.strict(),V9=cr.extend({requestId:as,reason:p().optional()}),va=zt.extend({method:O("notifications/cancelled"),params:V9}),B9=S({src:p(),mimeType:p().optional(),sizes:N(p()).optional()}),oo=S({icons:N(B9).optional()}),ur=S({name:p(),title:p().optional()}),Vp=ur.extend({...ur.shape,...oo.shape,version:p(),websiteUrl:p().optional()}),H9=Pi(S({applyDefaults:ne().optional()}),ie(p(),ke())),J9=O_(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,Pi(S({form:H9.optional(),url:Qt.optional()}),ie(p(),ke()).optional())),G9=S({experimental:ie(p(),Qt).optional(),sampling:S({context:Qt.optional(),tools:Qt.optional()}).optional(),elicitation:J9.optional(),roots:S({listChanged:ne().optional()}).optional()}),W9=jt.extend({protocolVersion:p(),capabilities:G9,clientInfo:Vp}),K9=dt.extend({method:O("initialize"),params:W9}),Y9=S({experimental:ie(p(),Qt).optional(),logging:Qt.optional(),completions:Qt.optional(),prompts:Y(S({listChanged:Y(ne())})),resources:S({subscribe:ne().optional(),listChanged:ne().optional()}).optional(),tools:S({listChanged:ne().optional()}).optional()}),Bp=It.extend({protocolVersion:p(),capabilities:Y9,serverInfo:Vp,instructions:p().optional()}),Hp=zt.extend({method:O("notifications/initialized")}),Q9=e=>Hp.safeParse(e).success,_a=dt.extend({method:O("ping")}),X9=S({progress:R(),total:Y(R()),message:Y(p())}),e4=S({...cr.shape,...X9.shape,progressToken:jp}),ya=zt.extend({method:O("notifications/progress"),params:e4}),t4=jt.extend({cursor:zp.optional()}),ls=dt.extend({params:t4.optional()}),cs=It.extend({nextCursor:Y(zp)}),Jp=S({uri:p(),mimeType:Y(p()),_meta:ie(p(),ke()).optional()}),Gp=Jp.extend({text:p()}),wa=p().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),Wp=Jp.extend({blob:wa}),Kp=S({...ur.shape,...oo.shape,uri:p(),description:Y(p()),mimeType:Y(p()),_meta:Y(He({}))}),n4=S({...ur.shape,...oo.shape,uriTemplate:p(),description:Y(p()),mimeType:Y(p()),_meta:Y(He({}))}),r4=ls.extend({method:O("resources/list")}),Yp=cs.extend({resources:N(Kp)}),o4=ls.extend({method:O("resources/templates/list")}),Qp=cs.extend({resourceTemplates:N(n4)}),ba=jt.extend({uri:p()}),s4=ba,i4=dt.extend({method:O("resources/read"),params:s4}),Xp=It.extend({contents:N(Q([Gp,Wp]))}),ef=zt.extend({method:O("notifications/resources/list_changed")}),a4=ba,l4=dt.extend({method:O("resources/subscribe"),params:a4}),c4=ba,u4=dt.extend({method:O("resources/unsubscribe"),params:c4}),d4=cr.extend({uri:p()}),tf=zt.extend({method:O("notifications/resources/updated"),params:d4}),p4=S({name:p(),description:Y(p()),required:Y(ne())}),f4=S({...ur.shape,...oo.shape,description:Y(p()),arguments:Y(N(p4)),_meta:Y(He({}))}),h4=ls.extend({method:O("prompts/list")}),nf=cs.extend({prompts:N(f4)}),m4=jt.extend({name:p(),arguments:ie(p(),p()).optional()}),g4=dt.extend({method:O("prompts/get"),params:m4}),rf=S({type:O("text"),text:p(),_meta:ie(p(),ke()).optional()}),of=S({type:O("image"),data:wa,mimeType:p(),_meta:ie(p(),ke()).optional()}),sf=S({type:O("audio"),data:wa,mimeType:p(),_meta:ie(p(),ke()).optional()}),v4=S({type:O("tool_use"),name:p(),id:p(),input:S({}).passthrough(),_meta:Y(S({}).passthrough())}).passthrough(),_4=S({type:O("resource"),resource:Q([Gp,Wp]),_meta:ie(p(),ke()).optional()}),y4=Kp.extend({type:O("resource_link")}),$a=Q([rf,of,sf,y4,_4]),w4=S({role:me(["user","assistant"]),content:$a}),af=It.extend({description:Y(p()),messages:N(w4)}),lf=zt.extend({method:O("notifications/prompts/list_changed")}),b4=S({title:p().optional(),readOnlyHint:ne().optional(),destructiveHint:ne().optional(),idempotentHint:ne().optional(),openWorldHint:ne().optional()}),cf=S({...ur.shape,...oo.shape,description:p().optional(),inputSchema:S({type:O("object"),properties:ie(p(),Qt).optional(),required:N(p()).optional()}).catchall(ke()),outputSchema:S({type:O("object"),properties:ie(p(),Qt).optional(),required:N(p()).optional()}).catchall(ke()).optional(),annotations:Y(b4),_meta:ie(p(),ke()).optional()}),$4=ls.extend({method:O("tools/list")}),uf=cs.extend({tools:N(cf)}),us=It.extend({content:N($a).default([]),structuredContent:ie(p(),ke()).optional(),isError:Y(ne())});us.or(It.extend({toolResult:ke()}));const S4=jt.extend({name:p(),arguments:Y(ie(p(),ke()))}),C4=dt.extend({method:O("tools/call"),params:S4}),df=zt.extend({method:O("notifications/tools/list_changed")}),pf=me(["debug","info","notice","warning","error","critical","alert","emergency"]),E4=jt.extend({level:pf}),k4=dt.extend({method:O("logging/setLevel"),params:E4}),I4=cr.extend({level:pf,logger:p().optional(),data:ke()}),ff=zt.extend({method:O("notifications/message"),params:I4}),T4=S({name:p().optional()}),x4=S({hints:Y(N(T4)),costPriority:Y(R().min(0).max(1)),speedPriority:Y(R().min(0).max(1)),intelligencePriority:Y(R().min(0).max(1))}),P4=S({mode:Y(me(["auto","required","none"]))}),R4=S({type:O("tool_result"),toolUseId:p().describe("The unique identifier for the corresponding tool call."),content:N($a).default([]),structuredContent:S({}).passthrough().optional(),isError:Y(ne()),_meta:Y(S({}).passthrough())}).passthrough(),ds=Fe("type",[rf,of,sf,v4,R4]),O4=S({role:me(["user","assistant"]),content:Q([ds,N(ds)]),_meta:Y(S({}).passthrough())}).passthrough(),N4=jt.extend({messages:N(O4),modelPreferences:x4.optional(),systemPrompt:p().optional(),includeContext:me(["none","thisServer","allServers"]).optional(),temperature:R().optional(),maxTokens:R().int(),stopSequences:N(p()).optional(),metadata:Qt.optional(),tools:Y(N(cf)),toolChoice:Y(P4)}),hf=dt.extend({method:O("sampling/createMessage"),params:N4}),mf=It.extend({model:p(),stopReason:Y(me(["endTurn","stopSequence","maxTokens","toolUse"]).or(p())),role:me(["user","assistant"]),content:Q([ds,N(ds)])}),M4=S({type:O("boolean"),title:p().optional(),description:p().optional(),default:ne().optional()}),A4=S({type:O("string"),title:p().optional(),description:p().optional(),minLength:R().optional(),maxLength:R().optional(),format:me(["email","uri","date","date-time"]).optional(),default:p().optional()}),L4=S({type:me(["number","integer"]),title:p().optional(),description:p().optional(),minimum:R().optional(),maximum:R().optional(),default:R().optional()}),j4=S({type:O("string"),title:p().optional(),description:p().optional(),enum:N(p()),default:p().optional()}),z4=S({type:O("string"),title:p().optional(),description:p().optional(),oneOf:N(S({const:p(),title:p()})),default:p().optional()}),D4=S({type:O("string"),title:p().optional(),description:p().optional(),enum:N(p()),enumNames:N(p()).optional(),default:p().optional()}),U4=Q([j4,z4]),q4=S({type:O("array"),title:p().optional(),description:p().optional(),minItems:R().optional(),maxItems:R().optional(),items:S({type:O("string"),enum:N(p())}),default:N(p()).optional()}),Z4=S({type:O("array"),title:p().optional(),description:p().optional(),minItems:R().optional(),maxItems:R().optional(),items:S({anyOf:N(S({const:p(),title:p()}))}),default:N(p()).optional()}),F4=Q([q4,Z4]),V4=Q([D4,U4,F4]),B4=Q([V4,M4,A4,L4]),H4=jt.extend({mode:O("form").optional(),message:p(),requestedSchema:S({type:O("object"),properties:ie(p(),B4),required:N(p()).optional()})}),J4=jt.extend({mode:O("url"),message:p(),elicitationId:p(),url:p().url()}),G4=Q([H4,J4]),Sa=dt.extend({method:O("elicitation/create"),params:G4}),W4=cr.extend({elicitationId:p()}),K4=zt.extend({method:O("notifications/elicitation/complete"),params:W4}),Ca=It.extend({action:me(["accept","decline","cancel"]),content:ie(p(),Q([p(),R(),ne(),N(p())])).optional()}),Y4=S({type:O("ref/resource"),uri:p()}),Q4=S({type:O("ref/prompt"),name:p()}),X4=jt.extend({ref:Q([Q4,Y4]),argument:S({name:p(),value:p()}),context:S({arguments:ie(p(),p()).optional()}).optional()}),e6=dt.extend({method:O("completion/complete"),params:X4}),gf=It.extend({completion:He({values:N(p()).max(100),total:Y(R().int()),hasMore:Y(ne())})}),t6=S({uri:p().startsWith("file://"),name:p().optional(),_meta:ie(p(),ke()).optional()}),vf=dt.extend({method:O("roots/list")}),_f=It.extend({roots:N(t6)}),n6=zt.extend({method:O("notifications/roots/list_changed")});Q([_a,K9,e6,k4,g4,h4,r4,o4,i4,l4,u4,C4,$4]),Q([va,ya,Hp,n6]),Q([Jn,mf,Ca,_f]),Q([_a,hf,Sa,vf]),Q([va,ya,ff,tf,ef,df,lf,K4]),Q([Jn,Bp,gf,af,nf,Yp,Qp,Xp,us,uf]);class ot extends Error{constructor(t,n,r){super(`MCP error ${t}: ${n}`),this.code=t,this.data=r,this.name="McpError"}static fromError(t,n,r){if(t===Xe.UrlElicitationRequired&&r){const o=r;if(o.elicitations)return new r6(o.elicitations,n)}return new ot(t,n,r)}}class r6 extends ot{constructor(t,n=`URL elicitation${t.length>1?"s":""} required`){super(Xe.UrlElicitationRequired,n,{elicitations:t})}get elicitations(){var t,n;return(n=(t=this.data)===null||t===void 0?void 0:t.elicitations)!==null&&n!==void 0?n:[]}}let Ea;Ea=globalThis.crypto;async function o6(e){return(await Ea).getRandomValues(new Uint8Array(e))}async function s6(e){const t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",n=Math.pow(2,8)-Math.pow(2,8)%t.length;let r="";for(;r.length<e;){const o=await o6(e-r.length);for(const s of o)s<n&&(r+=t[s%t.length])}return r}async function i6(e){return await s6(e)}async function a6(e){const t=await(await Ea).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function l6(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;const t=await i6(e),n=await a6(t);return{code_verifier:t,code_challenge:n}}const Je=Zv().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:N_.custom,message:"URL must be parseable",fatal:!0}),Lm}).refine(e=>{const t=new URL(e);return t.protocol!=="javascript:"&&t.protocol!=="data:"&&t.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),c6=He({resource:p().url(),authorization_servers:N(Je).optional(),jwks_uri:p().url().optional(),scopes_supported:N(p()).optional(),bearer_methods_supported:N(p()).optional(),resource_signing_alg_values_supported:N(p()).optional(),resource_name:p().optional(),resource_documentation:p().optional(),resource_policy_uri:p().url().optional(),resource_tos_uri:p().url().optional(),tls_client_certificate_bound_access_tokens:ne().optional(),authorization_details_types_supported:N(p()).optional(),dpop_signing_alg_values_supported:N(p()).optional(),dpop_bound_access_tokens_required:ne().optional()}),yf=He({issuer:p(),authorization_endpoint:Je,token_endpoint:Je,registration_endpoint:Je.optional(),scopes_supported:N(p()).optional(),response_types_supported:N(p()),response_modes_supported:N(p()).optional(),grant_types_supported:N(p()).optional(),token_endpoint_auth_methods_supported:N(p()).optional(),token_endpoint_auth_signing_alg_values_supported:N(p()).optional(),service_documentation:Je.optional(),revocation_endpoint:Je.optional(),revocation_endpoint_auth_methods_supported:N(p()).optional(),revocation_endpoint_auth_signing_alg_values_supported:N(p()).optional(),introspection_endpoint:p().optional(),introspection_endpoint_auth_methods_supported:N(p()).optional(),introspection_endpoint_auth_signing_alg_values_supported:N(p()).optional(),code_challenge_methods_supported:N(p()).optional(),client_id_metadata_document_supported:ne().optional()}),u6=He({issuer:p(),authorization_endpoint:Je,token_endpoint:Je,userinfo_endpoint:Je.optional(),jwks_uri:Je,registration_endpoint:Je.optional(),scopes_supported:N(p()).optional(),response_types_supported:N(p()),response_modes_supported:N(p()).optional(),grant_types_supported:N(p()).optional(),acr_values_supported:N(p()).optional(),subject_types_supported:N(p()),id_token_signing_alg_values_supported:N(p()),id_token_encryption_alg_values_supported:N(p()).optional(),id_token_encryption_enc_values_supported:N(p()).optional(),userinfo_signing_alg_values_supported:N(p()).optional(),userinfo_encryption_alg_values_supported:N(p()).optional(),userinfo_encryption_enc_values_supported:N(p()).optional(),request_object_signing_alg_values_supported:N(p()).optional(),request_object_encryption_alg_values_supported:N(p()).optional(),request_object_encryption_enc_values_supported:N(p()).optional(),token_endpoint_auth_methods_supported:N(p()).optional(),token_endpoint_auth_signing_alg_values_supported:N(p()).optional(),display_values_supported:N(p()).optional(),claim_types_supported:N(p()).optional(),claims_supported:N(p()).optional(),service_documentation:p().optional(),claims_locales_supported:N(p()).optional(),ui_locales_supported:N(p()).optional(),claims_parameter_supported:ne().optional(),request_parameter_supported:ne().optional(),request_uri_parameter_supported:ne().optional(),require_request_uri_registration:ne().optional(),op_policy_uri:Je.optional(),op_tos_uri:Je.optional(),client_id_metadata_document_supported:ne().optional()}),d6=S({...u6.shape,...yf.pick({code_challenge_methods_supported:!0}).shape}),wf=S({access_token:p(),id_token:p().optional(),token_type:p(),expires_in:R().optional(),scope:p().optional(),refresh_token:p().optional()}).strip(),p6=S({error:p(),error_description:p().optional(),error_uri:p().optional()}),bf=Je.optional().or(O("").transform(()=>{})),f6=S({redirect_uris:N(Je),token_endpoint_auth_method:p().optional(),grant_types:N(p()).optional(),response_types:N(p()).optional(),client_name:p().optional(),client_uri:Je.optional(),logo_uri:bf,scope:p().optional(),contacts:N(p()).optional(),tos_uri:bf,policy_uri:p().optional(),jwks_uri:Je.optional(),jwks:yt().optional(),software_id:p().optional(),software_version:p().optional(),software_statement:p().optional()}).strip(),h6=S({client_id:p(),client_secret:p().optional(),client_id_issued_at:R().optional(),client_secret_expires_at:R().optional()}).strip(),m6=f6.merge(h6);S({error:p(),error_description:p().optional()}).strip(),S({token:p(),token_type_hint:p().optional()}).strip();function g6(e){const t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function v6({requestedResource:e,configuredResource:t}){const n=typeof e=="string"?new URL(e):new URL(e.href),r=typeof t=="string"?new URL(t):new URL(t.href);if(n.origin!==r.origin||n.pathname.length<r.pathname.length)return!1;const o=n.pathname.endsWith("/")?n.pathname:n.pathname+"/",s=r.pathname.endsWith("/")?r.pathname:r.pathname+"/";return o.startsWith(s)}class Ge extends Error{constructor(t,n){super(t),this.errorUri=n,this.name=this.constructor.name}toResponseObject(){const t={error:this.errorCode,error_description:this.message};return this.errorUri&&(t.error_uri=this.errorUri),t}get errorCode(){return this.constructor.errorCode}}class ka extends Ge{}ka.errorCode="invalid_request";class ps extends Ge{}ps.errorCode="invalid_client";class fs extends Ge{}fs.errorCode="invalid_grant";class hs extends Ge{}hs.errorCode="unauthorized_client";class Ia extends Ge{}Ia.errorCode="unsupported_grant_type";class Ta extends Ge{}Ta.errorCode="invalid_scope";class xa extends Ge{}xa.errorCode="access_denied";class dr extends Ge{}dr.errorCode="server_error";class Pa extends Ge{}Pa.errorCode="temporarily_unavailable";class Ra extends Ge{}Ra.errorCode="unsupported_response_type";class Oa extends Ge{}Oa.errorCode="unsupported_token_type";class Na extends Ge{}Na.errorCode="invalid_token";class Ma extends Ge{}Ma.errorCode="method_not_allowed";class Aa extends Ge{}Aa.errorCode="too_many_requests";class ms extends Ge{}ms.errorCode="invalid_client_metadata";class La extends Ge{}La.errorCode="insufficient_scope";const _6={[ka.errorCode]:ka,[ps.errorCode]:ps,[fs.errorCode]:fs,[hs.errorCode]:hs,[Ia.errorCode]:Ia,[Ta.errorCode]:Ta,[xa.errorCode]:xa,[dr.errorCode]:dr,[Pa.errorCode]:Pa,[Ra.errorCode]:Ra,[Oa.errorCode]:Oa,[Na.errorCode]:Na,[Ma.errorCode]:Ma,[Aa.errorCode]:Aa,[ms.errorCode]:ms,[La.errorCode]:La};class Tt extends Error{constructor(t){super(t??"Unauthorized")}}function y6(e){return["client_secret_basic","client_secret_post","none"].includes(e)}const ja="code",za="S256";function $f(e,t){const n=e.client_secret!==void 0;return t.length===0?n?"client_secret_post":"none":"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&y6(e.token_endpoint_auth_method)&&t.includes(e.token_endpoint_auth_method)?e.token_endpoint_auth_method:n&&t.includes("client_secret_basic")?"client_secret_basic":n&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":n?"client_secret_post":"none"}function Sf(e,t,n,r){const{client_id:o,client_secret:s}=t;switch(e){case"client_secret_basic":w6(o,s,n);return;case"client_secret_post":b6(o,s,r);return;case"none":$6(o,r);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function w6(e,t,n){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");const r=btoa(`${e}:${t}`);n.set("Authorization",`Basic ${r}`)}function b6(e,t,n){n.set("client_id",e),t&&n.set("client_secret",t)}function $6(e,t){t.set("client_id",e)}async function Da(e){const t=e instanceof Response?e.status:void 0,n=e instanceof Response?await e.text():e;try{const r=p6.parse(JSON.parse(n)),{error:o,error_description:s,error_uri:i}=r,a=_6[o]||dr;return new a(s||"",i)}catch(r){const o=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${r}. Raw body: ${n}`;return new dr(o)}}async function Gn(e,t){var n,r;try{return await Ua(e,t)}catch(o){if(o instanceof ps||o instanceof hs)return await((n=e.invalidateCredentials)===null||n===void 0?void 0:n.call(e,"all")),await Ua(e,t);if(o instanceof fs)return await((r=e.invalidateCredentials)===null||r===void 0?void 0:r.call(e,"tokens")),await Ua(e,t);throw o}}async function Ua(e,{serverUrl:t,authorizationCode:n,scope:r,resourceMetadataUrl:o,fetchFn:s}){var i,a;let l,c;try{l=await E6(t,{resourceMetadataUrl:o},s),l.authorization_servers&&l.authorization_servers.length>0&&(c=l.authorization_servers[0])}catch{}c||(c=new URL("/",t));const u=await C6(t,e,l),h=await P6(c,{fetchFn:s});let _=await Promise.resolve(e.clientInformation());if(!_){if(n!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");const d=(h==null?void 0:h.client_id_metadata_document_supported)===!0,w=e.clientMetadataUrl;if(w&&!S6(w))throw new ms(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${w}`);if(d&&w)_={client_id:w},await((i=e.saveClientInformation)===null||i===void 0?void 0:i.call(e,_));else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");const b=await M6(c,{metadata:h,clientMetadata:e.clientMetadata,fetchFn:s});await e.saveClientInformation(b),_=b}}if(n!==void 0){const d=await e.codeVerifier(),w=await O6(c,{metadata:h,clientInformation:_,authorizationCode:n,codeVerifier:d,redirectUri:e.redirectUrl,resource:u,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(w),"AUTHORIZED"}const f=await e.tokens();if(f!=null&&f.refresh_token)try{const d=await N6(c,{metadata:h,clientInformation:_,refreshToken:f.refresh_token,resource:u,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(d),"AUTHORIZED"}catch(d){if(!(!(d instanceof Ge)||d instanceof dr))throw d}const g=e.state?await e.state():void 0,{authorizationUrl:v,codeVerifier:m}=await R6(c,{metadata:h,clientInformation:_,state:g,redirectUrl:e.redirectUrl,scope:r||((a=l==null?void 0:l.scopes_supported)===null||a===void 0?void 0:a.join(" "))||e.clientMetadata.scope,resource:u});return await e.saveCodeVerifier(m),await e.redirectToAuthorization(v),"REDIRECT"}function S6(e){if(!e)return!1;try{const t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}async function C6(e,t,n){const r=g6(e);if(t.validateResourceURL)return await t.validateResourceURL(r,n==null?void 0:n.resource);if(n){if(!v6({requestedResource:r,configuredResource:n.resource}))throw new Error(`Protected resource ${n.resource} does not match expected ${r} (or origin)`);return new URL(n.resource)}}function gs(e){const t=e.headers.get("WWW-Authenticate");if(!t)return{};const[n,r]=t.split(" ");if(n.toLowerCase()!=="bearer"||!r)return{};const o=qa(e,"resource_metadata")||void 0;let s;if(o)try{s=new URL(o)}catch{}const i=qa(e,"scope")||void 0,a=qa(e,"error")||void 0;return{resourceMetadataUrl:s,scope:i,error:a}}function qa(e,t){const n=e.headers.get("WWW-Authenticate");if(!n)return null;const r=new RegExp(`${t}=(?:"([^"]+)"|([^\\s,]+))`),o=n.match(r);return o?o[1]||o[2]:null}async function E6(e,t,n=fetch){const r=await T6(e,"oauth-protected-resource",n,{protocolVersion:t==null?void 0:t.protocolVersion,metadataUrl:t==null?void 0:t.resourceMetadataUrl});if(!r||r.status===404)throw new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!r.ok)throw new Error(`HTTP ${r.status} trying to load well-known OAuth protected resource metadata.`);return c6.parse(await r.json())}async function Za(e,t,n=fetch){try{return await n(e,{headers:t})}catch(r){if(r instanceof TypeError)return t?Za(e,void 0,n):void 0;throw r}}function k6(e,t="",n={}){return t.endsWith("/")&&(t=t.slice(0,-1)),n.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function Cf(e,t,n=fetch){return await Za(e,{"MCP-Protocol-Version":t},n)}function I6(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}async function T6(e,t,n,r){var o,s;const i=new URL(e),a=(o=r==null?void 0:r.protocolVersion)!==null&&o!==void 0?o:ss;let l;if(r!=null&&r.metadataUrl)l=new URL(r.metadataUrl);else{const u=k6(t,i.pathname);l=new URL(u,(s=r==null?void 0:r.metadataServerUrl)!==null&&s!==void 0?s:i),l.search=i.search}let c=await Cf(l,a,n);if(!(r!=null&&r.metadataUrl)&&I6(c,i.pathname)){const u=new URL(`/.well-known/${t}`,i);c=await Cf(u,a,n)}return c}function x6(e){const t=typeof e=="string"?new URL(e):e,n=t.pathname!=="/",r=[];if(!n)return r.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),r.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),r;let o=t.pathname;return o.endsWith("/")&&(o=o.slice(0,-1)),r.push({url:new URL(`/.well-known/oauth-authorization-server${o}`,t.origin),type:"oauth"}),r.push({url:new URL(`/.well-known/openid-configuration${o}`,t.origin),type:"oidc"}),r.push({url:new URL(`${o}/.well-known/openid-configuration`,t.origin),type:"oidc"}),r}async function P6(e,{fetchFn:t=fetch,protocolVersion:n=ss}={}){const r={"MCP-Protocol-Version":n,Accept:"application/json"},o=x6(e);for(const{url:s,type:i}of o){const a=await Za(s,r,t);if(a){if(!a.ok){if(a.status>=400&&a.status<500)continue;throw new Error(`HTTP ${a.status} trying to load ${i==="oauth"?"OAuth":"OpenID provider"} metadata from ${s}`)}return i==="oauth"?yf.parse(await a.json()):d6.parse(await a.json())}}}async function R6(e,{metadata:t,clientInformation:n,redirectUrl:r,scope:o,state:s,resource:i}){let a;if(t){if(a=new URL(t.authorization_endpoint),!t.response_types_supported.includes(ja))throw new Error(`Incompatible auth server: does not support response type ${ja}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(za))throw new Error(`Incompatible auth server: does not support code challenge method ${za}`)}else a=new URL("/authorize",e);const l=await l6(),c=l.code_verifier,u=l.code_challenge;return a.searchParams.set("response_type",ja),a.searchParams.set("client_id",n.client_id),a.searchParams.set("code_challenge",u),a.searchParams.set("code_challenge_method",za),a.searchParams.set("redirect_uri",String(r)),s&&a.searchParams.set("state",s),o&&a.searchParams.set("scope",o),o!=null&&o.includes("offline_access")&&a.searchParams.append("prompt","consent"),i&&a.searchParams.set("resource",i.href),{authorizationUrl:a,codeVerifier:c}}async function O6(e,{metadata:t,clientInformation:n,authorizationCode:r,codeVerifier:o,redirectUri:s,resource:i,addClientAuthentication:a,fetchFn:l}){var c;const u="authorization_code",h=t!=null&&t.token_endpoint?new URL(t.token_endpoint):new URL("/token",e);if(t!=null&&t.grant_types_supported&&!t.grant_types_supported.includes(u))throw new Error(`Incompatible auth server: does not support grant type ${u}`);const _=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),f=new URLSearchParams({grant_type:u,code:r,code_verifier:o,redirect_uri:String(s)});if(a)a(_,f,e,t);else{const v=(c=t==null?void 0:t.token_endpoint_auth_methods_supported)!==null&&c!==void 0?c:[],m=$f(n,v);Sf(m,n,_,f)}i&&f.set("resource",i.href);const g=await(l??fetch)(h,{method:"POST",headers:_,body:f});if(!g.ok)throw await Da(g);return wf.parse(await g.json())}async function N6(e,{metadata:t,clientInformation:n,refreshToken:r,resource:o,addClientAuthentication:s,fetchFn:i}){var a;const l="refresh_token";let c;if(t){if(c=new URL(t.token_endpoint),t.grant_types_supported&&!t.grant_types_supported.includes(l))throw new Error(`Incompatible auth server: does not support grant type ${l}`)}else c=new URL("/token",e);const u=new Headers({"Content-Type":"application/x-www-form-urlencoded"}),h=new URLSearchParams({grant_type:l,refresh_token:r});if(s)s(u,h,e,t);else{const f=(a=t==null?void 0:t.token_endpoint_auth_methods_supported)!==null&&a!==void 0?a:[],g=$f(n,f);Sf(g,n,u,h)}o&&h.set("resource",o.href);const _=await(i??fetch)(c,{method:"POST",headers:u,body:h});if(!_.ok)throw await Da(_);return wf.parse({refresh_token:r,...await _.json()})}async function M6(e,{metadata:t,clientMetadata:n,fetchFn:r}){let o;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");o=new URL(t.registration_endpoint)}else o=new URL("/register",e);const s=await(r??fetch)(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!s.ok)throw await Da(s);return m6.parse(await s.json())}const A6={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class so extends Error{constructor(t,n){super(`Streamable HTTP error: ${n}`),this.code=t}}class vs{constructor(t,n){var r;this._hasCompletedAuthFlow=!1,this._url=t,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=n==null?void 0:n.requestInit,this._authProvider=n==null?void 0:n.authProvider,this._fetch=n==null?void 0:n.fetch,this._fetchWithInit=Lp(n==null?void 0:n.fetch,n==null?void 0:n.requestInit),this._sessionId=n==null?void 0:n.sessionId,this._reconnectionOptions=(r=n==null?void 0:n.reconnectionOptions)!==null&&r!==void 0?r:A6}async _authThenStart(){var t;if(!this._authProvider)throw new Tt("No auth provider");let n;try{n=await Gn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw(t=this.onerror)===null||t===void 0||t.call(this,r),r}if(n!=="AUTHORIZED")throw new Tt;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var t;const n={};if(this._authProvider){const o=await this._authProvider.tokens();o&&(n.Authorization=`Bearer ${o.access_token}`)}this._sessionId&&(n["mcp-session-id"]=this._sessionId),this._protocolVersion&&(n["mcp-protocol-version"]=this._protocolVersion);const r=ma((t=this._requestInit)===null||t===void 0?void 0:t.headers);return new Headers({...n,...r})}async _startOrAuthSse(t){var n,r,o;const{resumptionToken:s}=t;try{const i=await this._commonHeaders();i.set("Accept","text/event-stream"),s&&i.set("last-event-id",s);const a=await((n=this._fetch)!==null&&n!==void 0?n:fetch)(this._url,{method:"GET",headers:i,signal:(r=this._abortController)===null||r===void 0?void 0:r.signal});if(!a.ok){if(a.status===401&&this._authProvider)return await this._authThenStart();if(a.status===405)return;throw new so(a.status,`Failed to open SSE stream: ${a.statusText}`)}this._handleSseStream(a.body,t,!0)}catch(i){throw(o=this.onerror)===null||o===void 0||o.call(this,i),i}}_getNextReconnectionDelay(t){if(this._serverRetryMs!==void 0)return this._serverRetryMs;const n=this._reconnectionOptions.initialReconnectionDelay,r=this._reconnectionOptions.reconnectionDelayGrowFactor,o=this._reconnectionOptions.maxReconnectionDelay;return Math.min(n*Math.pow(r,t),o)}_scheduleReconnection(t,n=0){var r;const o=this._reconnectionOptions.maxRetries;if(o>0&&n>=o){(r=this.onerror)===null||r===void 0||r.call(this,new Error(`Maximum reconnection attempts (${o}) exceeded.`));return}const s=this._getNextReconnectionDelay(n);setTimeout(()=>{this._startOrAuthSse(t).catch(i=>{var a;(a=this.onerror)===null||a===void 0||a.call(this,new Error(`Failed to reconnect SSE stream: ${i instanceof Error?i.message:String(i)}`)),this._scheduleReconnection(t,n+1)})},s)}_handleSseStream(t,n,r){if(!t)return;const{onresumptiontoken:o,replayMessageId:s}=n;let i,a=!1;(async()=>{var c,u,h,_;try{const f=t.pipeThrough(new TextDecoderStream).pipeThrough(new Mo({onRetry:v=>{this._serverRetryMs=v}})).getReader();for(;;){const{value:v,done:m}=await f.read();if(m)break;if(v.id&&(i=v.id,a=!0,o==null||o(v.id)),!v.event||v.event==="message")try{const d=Hn.parse(JSON.parse(v.data));s!==void 0&&ga(d)&&(d.id=s),(c=this.onmessage)===null||c===void 0||c.call(this,d)}catch(d){(u=this.onerror)===null||u===void 0||u.call(this,d)}}(r||a)&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:i,onresumptiontoken:o,replayMessageId:s},0)}catch(f){if((h=this.onerror)===null||h===void 0||h.call(this,new Error(`SSE stream disconnected: ${f}`)),(r||a)&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:i,onresumptiontoken:o,replayMessageId:s},0)}catch(v){(_=this.onerror)===null||_===void 0||_.call(this,new Error(`Failed to reconnect: ${v instanceof Error?v.message:String(v)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(t){if(!this._authProvider)throw new Tt("No auth provider");if(await Gn(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Tt("Failed to authorize")}async close(){var t,n;(t=this._abortController)===null||t===void 0||t.abort(),(n=this.onclose)===null||n===void 0||n.call(this)}async send(t,n){var r,o,s,i;try{const{resumptionToken:a,onresumptiontoken:l}=n||{};if(a){this._startOrAuthSse({resumptionToken:a,replayMessageId:Up(t)?t.id:void 0}).catch(m=>{var d;return(d=this.onerror)===null||d===void 0?void 0:d.call(this,m)});return}const c=await this._commonHeaders();c.set("content-type","application/json"),c.set("accept","application/json, text/event-stream");const u={...this._requestInit,method:"POST",headers:c,body:JSON.stringify(t),signal:(r=this._abortController)===null||r===void 0?void 0:r.signal},h=await((o=this._fetch)!==null&&o!==void 0?o:fetch)(this._url,u),_=h.headers.get("mcp-session-id");if(_&&(this._sessionId=_),!h.ok){if(h.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new so(401,"Server returned 401 after successful authentication");const{resourceMetadataUrl:d,scope:w}=gs(h);if(this._resourceMetadataUrl=d,this._scope=w,await Gn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Tt;return this._hasCompletedAuthFlow=!0,this.send(t)}if(h.status===403&&this._authProvider){const{resourceMetadataUrl:d,scope:w,error:y}=gs(h);if(y==="insufficient_scope"){const b=h.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===b)throw new so(403,"Server returned 403 after trying upscoping");if(w&&(this._scope=w),d&&(this._resourceMetadataUrl=d),this._lastUpscopingHeader=b??void 0,await Gn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new Tt;return this.send(t)}}const m=await h.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${h.status}): ${m}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,h.status===202){Q9(t)&&this._startOrAuthSse({resumptionToken:void 0}).catch(m=>{var d;return(d=this.onerror)===null||d===void 0?void 0:d.call(this,m)});return}const g=(Array.isArray(t)?t:[t]).filter(m=>"method"in m&&"id"in m&&m.id!==void 0).length>0,v=h.headers.get("content-type");if(g)if(v!=null&&v.includes("text/event-stream"))this._handleSseStream(h.body,{onresumptiontoken:l},!1);else if(v!=null&&v.includes("application/json")){const m=await h.json(),d=Array.isArray(m)?m.map(w=>Hn.parse(w)):[Hn.parse(m)];for(const w of d)(s=this.onmessage)===null||s===void 0||s.call(this,w)}else throw new so(-1,`Unexpected content type: ${v}`)}catch(a){throw(i=this.onerror)===null||i===void 0||i.call(this,a),a}}get sessionId(){return this._sessionId}async terminateSession(){var t,n,r;if(this._sessionId)try{const o=await this._commonHeaders(),s={...this._requestInit,method:"DELETE",headers:o,signal:(t=this._abortController)===null||t===void 0?void 0:t.signal},i=await((n=this._fetch)!==null&&n!==void 0?n:fetch)(this._url,s);if(!i.ok&&i.status!==405)throw new so(i.status,`Failed to terminate session: ${i.statusText}`);this._sessionId=void 0}catch(o){throw(r=this.onerror)===null||r===void 0||r.call(this,o),o}}setProtocolVersion(t){this._protocolVersion=t}get protocolVersion(){return this._protocolVersion}async resumeStream(t,n){await this._startOrAuthSse({resumptionToken:t,onresumptiontoken:n==null?void 0:n.onresumptiontoken})}}class _s{constructor(){this._messageQueue=[]}static createLinkedPair(){const t=new _s,n=new _s;return t._otherTransport=n,n._otherTransport=t,[t,n]}async start(){for(var t;this._messageQueue.length>0;){const n=this._messageQueue.shift();(t=this.onmessage)===null||t===void 0||t.call(this,n.message,n.extra)}}async close(){var t;const n=this._otherTransport;this._otherTransport=void 0,await(n==null?void 0:n.close()),(t=this.onclose)===null||t===void 0||t.call(this)}async send(t,n){if(!this._otherTransport)throw new Error("Not connected");this._otherTransport.onmessage?this._otherTransport.onmessage(t,{authInfo:n==null?void 0:n.authInfo}):this._otherTransport._messageQueue.push({message:t,extra:{authInfo:n==null?void 0:n.authInfo}})}}function xt(...e){return e.reduce((t,n)=>({...t,...n??{}}),{})}function io(e){return Object.fromEntries([...e.headers])}var L6=({prefix:e,size:t=16,alphabet:n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:r="-"}={})=>{const o=()=>{const s=n.length,i=new Array(t);for(let a=0;a<t;a++)i[a]=n[Math.random()*s|0];return i.join("")};if(e==null)return o;if(n.includes(r))throw new vi({argument:"separator",message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${o()}`},st=L6();function Fa(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}var j6=["fetch failed","failed to fetch"];function z6({error:e,url:t,requestBodyValues:n}){if(Fa(e))return e;if(e instanceof TypeError&&j6.includes(e.message.toLowerCase())){const r=e.cause;if(r!=null)return new Ie({message:`Cannot connect to API: ${r.message}`,cause:r,url:t,requestBodyValues:n,isRetryable:!0})}return e}function D6(e=globalThis){var t,n,r;return e.window?"runtime/browser":(t=e.navigator)!=null&&t.userAgent?`runtime/${e.navigator.userAgent.toLowerCase()}`:(r=(n=e.process)==null?void 0:n.versions)!=null&&r.node?`runtime/node.js/${e.process.version.substring(0)}`:e.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function U6(e){if(e==null)return{};const t={};if(e instanceof Headers)e.forEach((n,r)=>{t[r.toLowerCase()]=n});else{Array.isArray(e)||(e=Object.entries(e));for(const[n,r]of e)r!=null&&(t[n.toLowerCase()]=r)}return t}function Va(e,...t){const n=new Headers(U6(e)),r=n.get("user-agent")||"";return n.set("user-agent",[r,...t].filter(Boolean).join(" ")),Object.fromEntries(n.entries())}var q6="3.0.18";function Ef({apiKey:e,environmentVariableName:t,apiKeyParameterName:n="apiKey",description:r}){if(typeof e=="string")return e;if(e!=null)throw new No({message:`${r} API key must be a string.`});if(typeof process>"u")throw new No({message:`${r} API key is missing. Pass it using the '${n}' parameter. Environment variables is not supported in this environment.`});if(e=process.env[t],e==null)throw new No({message:`${r} API key is missing. Pass it using the '${n}' parameter or the ${t} environment variable.`});if(typeof e!="string")throw new No({message:`${r} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}function Z6({settingValue:e,environmentVariableName:t}){if(typeof e=="string")return e;if(!(e!=null||typeof process>"u")&&(e=process.env[t],!(e==null||typeof e!="string")))return e}function F6(e){var t;const[n,r=""]=e.toLowerCase().split("/");return(t={mpeg:"mp3","x-wav":"wav",opus:"ogg",mp4:"m4a","x-m4a":"m4a"}[r])!=null?t:r}var V6=/"__proto__"\s*:/,B6=/"constructor"\s*:/;function kf(e){const t=JSON.parse(e);return t===null||typeof t!="object"||V6.test(e)===!1&&B6.test(e)===!1?t:H6(t)}function H6(e){let t=[e];for(;t.length;){const n=t;t=[];for(const r of n){if(Object.prototype.hasOwnProperty.call(r,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(r,"constructor")&&Object.prototype.hasOwnProperty.call(r.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const o in r){const s=r[o];s&&typeof s=="object"&&t.push(s)}}}return e}function Ba(e){const{stackTraceLimit:t}=Error;try{Error.stackTraceLimit=0}catch{return kf(e)}try{return kf(e)}finally{Error.stackTraceLimit=t}}var ys=Symbol.for("vercel.ai.validator");function J6(e){return{[ys]:!0,validate:e}}function G6(e){return typeof e=="object"&&e!==null&&ys in e&&e[ys]===!0&&"validate"in e}function it(e){let t;return()=>(t==null&&(t=e()),t)}function W6(e){return G6(e)?e:typeof e=="function"?e():K6(e)}function K6(e){return J6(async t=>{const n=await e["~standard"].validate(t);return n.issues==null?{success:!0,value:n.value}:{success:!1,error:new Gt({value:t,cause:n.issues})}})}async function Cn({value:e,schema:t}){const n=await ao({value:e,schema:t});if(!n.success)throw Gt.wrap({value:e,cause:n.error});return n.value}async function ao({value:e,schema:t}){const n=W6(t);try{if(n.validate==null)return{success:!0,value:e,rawValue:e};const r=await n.validate(e);return r.success?{success:!0,value:r.value,rawValue:e}:{success:!1,error:Gt.wrap({value:e,cause:r.error}),rawValue:e}}catch(r){return{success:!1,error:Gt.wrap({value:e,cause:r}),rawValue:e}}}async function Y6({text:e,schema:t}){try{const n=Ba(e);return t==null?n:Cn({value:n,schema:t})}catch(n){throw yn.isInstance(n)||Gt.isInstance(n)?n:new yn({text:e,cause:n})}}async function If({text:e,schema:t}){try{const n=Ba(e);return t==null?{success:!0,value:n,rawValue:n}:await ao({value:n,schema:t})}catch(n){return{success:!1,error:yn.isInstance(n)?n:new yn({text:e,cause:n}),rawValue:void 0}}}function ws(e){try{return Ba(e),!0}catch{return!1}}function Q6({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new Mo).pipeThrough(new TransformStream({async transform({data:n},r){n!=="[DONE]"&&r.enqueue(await If({text:n,schema:t}))}}))}async function Xt({provider:e,providerOptions:t,schema:n}){if((t==null?void 0:t[e])==null)return;const r=await ao({value:t[e],schema:n});if(!r.success)throw new vi({argument:"providerOptions",message:`invalid ${e} provider options`,cause:r.error});return r.value}var X6=()=>globalThis.fetch,Dt=async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:o,abortSignal:s,fetch:i})=>Tf({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:o,abortSignal:s,fetch:i}),e5=async({url:e,headers:t,formData:n,failedResponseHandler:r,successfulResponseHandler:o,abortSignal:s,fetch:i})=>Tf({url:e,headers:t,body:{content:n,values:Object.fromEntries(n.entries())},failedResponseHandler:r,successfulResponseHandler:o,abortSignal:s,fetch:i}),Tf=async({url:e,headers:t={},body:n,successfulResponseHandler:r,failedResponseHandler:o,abortSignal:s,fetch:i=X6()})=>{try{const a=await i(e,{method:"POST",headers:Va(t,`ai-sdk/provider-utils/${q6}`,D6()),body:n.content,signal:s}),l=io(a);if(!a.ok){let c;try{c=await o({response:a,url:e,requestBodyValues:n.values})}catch(u){throw Fa(u)||Ie.isInstance(u)?u:new Ie({message:"Failed to process error response",cause:u,statusCode:a.status,url:e,responseHeaders:l,requestBodyValues:n.values})}throw c.value}try{return await r({response:a,url:e,requestBodyValues:n.values})}catch(c){throw c instanceof Error&&(Fa(c)||Ie.isInstance(c))?c:new Ie({message:"Failed to process successful response",cause:c,statusCode:a.status,url:e,responseHeaders:l,requestBodyValues:n.values})}}catch(a){throw z6({error:a,url:e,requestBodyValues:n.values})}};function _I(e){return e}function pr({id:e,name:t,inputSchema:n,outputSchema:r}){return({execute:o,toModelOutput:s,onInputStart:i,onInputDelta:a,onInputAvailable:l,...c})=>({type:"provider-defined",id:e,name:t,args:c,inputSchema:n,outputSchema:r,execute:o,toModelOutput:s,onInputStart:i,onInputDelta:a,onInputAvailable:l})}var xf=({errorSchema:e,errorToMessage:t,isRetryable:n})=>async({response:r,url:o,requestBodyValues:s})=>{const i=await r.text(),a=io(r);if(i.trim()==="")return{responseHeaders:a,value:new Ie({message:r.statusText,url:o,requestBodyValues:s,statusCode:r.status,responseHeaders:a,responseBody:i,isRetryable:n==null?void 0:n(r)})};try{const l=await Y6({text:i,schema:e});return{responseHeaders:a,value:new Ie({message:t(l),url:o,requestBodyValues:s,statusCode:r.status,responseHeaders:a,responseBody:i,data:l,isRetryable:n==null?void 0:n(r,l)})}}catch{return{responseHeaders:a,value:new Ie({message:r.statusText,url:o,requestBodyValues:s,statusCode:r.status,responseHeaders:a,responseBody:i,isRetryable:n==null?void 0:n(r)})}}},bs=e=>async({response:t})=>{const n=io(t);if(t.body==null)throw new Zc({});return{responseHeaders:n,value:Q6({stream:t.body,schema:e})}},Wn=e=>async({response:t,url:n,requestBodyValues:r})=>{const o=await t.text(),s=await If({text:o,schema:e}),i=io(t);if(!s.success)throw new Ie({message:"Invalid JSON response",cause:s.error,statusCode:t.status,responseHeaders:i,responseBody:o,url:n,requestBodyValues:r});return{responseHeaders:i,value:s.value,rawValue:s.rawValue}},t5=()=>async({response:e,url:t,requestBodyValues:n})=>{const r=io(e);if(!e.body)throw new Ie({message:"Response body is empty",url:t,requestBodyValues:n,statusCode:e.status,responseHeaders:r,responseBody:void 0});try{const o=await e.arrayBuffer();return{responseHeaders:r,value:new Uint8Array(o)}}catch(o){throw new Ie({message:"Failed to read response as array buffer",url:t,requestBodyValues:n,statusCode:e.status,responseHeaders:r,responseBody:void 0,cause:o})}},n5=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join("/")},r5=Symbol("Let zodToJsonSchema decide on which parser to use"),Pf={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",strictUnions:!1,definitions:{},errorMessages:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},o5=e=>typeof e=="string"?{...Pf,name:e}:{...Pf,...e};function St(){return{}}function s5(e,t){var n,r,o;const s={type:"array"};return(n=e.type)!=null&&n._def&&((o=(r=e.type)==null?void 0:r._def)==null?void 0:o.typeName)!==Z.ZodAny&&(s.items=Ee(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&(s.minItems=e.minLength.value),e.maxLength&&(s.maxItems=e.maxLength.value),e.exactLength&&(s.minItems=e.exactLength.value,s.maxItems=e.exactLength.value),s}function i5(e){const t={type:"integer",format:"int64"};if(!e.checks)return t;for(const n of e.checks)switch(n.kind){case"min":n.inclusive?t.minimum=n.value:t.exclusiveMinimum=n.value;break;case"max":n.inclusive?t.maximum=n.value:t.exclusiveMaximum=n.value;break;case"multipleOf":t.multipleOf=n.value;break}return t}function a5(){return{type:"boolean"}}function Rf(e,t){return Ee(e.type._def,t)}var l5=(e,t)=>Ee(e.innerType._def,t);function Of(e,t,n){const r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((o,s)=>Of(e,t,o))};switch(r){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return c5(e)}}var c5=e=>{const t={type:"integer",format:"unix-time"};for(const n of e.checks)switch(n.kind){case"min":t.minimum=n.value;break;case"max":t.maximum=n.value;break}return t};function u5(e,t){return{...Ee(e.innerType._def,t),default:e.defaultValue()}}function d5(e,t){return t.effectStrategy==="input"?Ee(e.schema._def,t):St()}function p5(e){return{type:"string",enum:Array.from(e.values)}}var f5=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function h5(e,t){const n=[Ee(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),Ee(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(o=>!!o),r=[];return n.forEach(o=>{if(f5(o))r.push(...o.allOf);else{let s=o;if("additionalProperties"in o&&o.additionalProperties===!1){const{additionalProperties:i,...a}=o;s=a}r.push(s)}}),r.length?{allOf:r}:void 0}function m5(e){const t=typeof e.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(e.value)?"array":"object"}:{type:t==="bigint"?"integer":t,const:e.value}}var Ha=void 0,Ut={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:()=>(Ha===void 0&&(Ha=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Ha),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 Nf(e,t){const n={type:"string"};if(e.checks)for(const r of e.checks)switch(r.kind){case"min":n.minLength=typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value;break;case"max":n.maxLength=typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value;break;case"email":switch(t.emailStrategy){case"format:email":qt(n,"email",r.message,t);break;case"format:idn-email":qt(n,"idn-email",r.message,t);break;case"pattern:zod":at(n,Ut.email,r.message,t);break}break;case"url":qt(n,"uri",r.message,t);break;case"uuid":qt(n,"uuid",r.message,t);break;case"regex":at(n,r.regex,r.message,t);break;case"cuid":at(n,Ut.cuid,r.message,t);break;case"cuid2":at(n,Ut.cuid2,r.message,t);break;case"startsWith":at(n,RegExp(`^${Ja(r.value,t)}`),r.message,t);break;case"endsWith":at(n,RegExp(`${Ja(r.value,t)}$`),r.message,t);break;case"datetime":qt(n,"date-time",r.message,t);break;case"date":qt(n,"date",r.message,t);break;case"time":qt(n,"time",r.message,t);break;case"duration":qt(n,"duration",r.message,t);break;case"length":n.minLength=typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,n.maxLength=typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value;break;case"includes":{at(n,RegExp(Ja(r.value,t)),r.message,t);break}case"ip":{r.version!=="v6"&&qt(n,"ipv4",r.message,t),r.version!=="v4"&&qt(n,"ipv6",r.message,t);break}case"base64url":at(n,Ut.base64url,r.message,t);break;case"jwt":at(n,Ut.jwt,r.message,t);break;case"cidr":{r.version!=="v6"&&at(n,Ut.ipv4Cidr,r.message,t),r.version!=="v4"&&at(n,Ut.ipv6Cidr,r.message,t);break}case"emoji":at(n,Ut.emoji(),r.message,t);break;case"ulid":{at(n,Ut.ulid,r.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{qt(n,"binary",r.message,t);break}case"contentEncoding:base64":{n.contentEncoding="base64";break}case"pattern:zod":{at(n,Ut.base64,r.message,t);break}}break}case"nanoid":at(n,Ut.nanoid,r.message,t)}return n}function Ja(e,t){return t.patternStrategy==="escape"?v5(e):e}var g5=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function v5(e){let t="";for(let n=0;n<e.length;n++)g5.has(e[n])||(t+="\\"),t+=e[n];return t}function qt(e,t,n,r){var o;e.format||(o=e.anyOf)!=null&&o.some(s=>s.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format}),delete e.format),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):e.format=t}function at(e,t,n,r){var o;e.pattern||(o=e.allOf)!=null&&o.some(s=>s.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern}),delete e.pattern),e.allOf.push({pattern:Mf(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):e.pattern=Mf(t,r)}function Mf(e,t){var n;if(!t.applyRegexFlags||!e.flags)return e.source;const r={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},o=r.i?e.source.toLowerCase():e.source;let s="",i=!1,a=!1,l=!1;for(let c=0;c<o.length;c++){if(i){s+=o[c],i=!1;continue}if(r.i){if(a){if(o[c].match(/[a-z]/)){l?(s+=o[c],s+=`${o[c-2]}-${o[c]}`.toUpperCase(),l=!1):o[c+1]==="-"&&((n=o[c+2])!=null&&n.match(/[a-z]/))?(s+=o[c],l=!0):s+=`${o[c]}${o[c].toUpperCase()}`;continue}}else if(o[c].match(/[a-z]/)){s+=`[${o[c]}${o[c].toUpperCase()}]`;continue}}if(r.m){if(o[c]==="^"){s+=`(^|(?<=[\r
58
+ ]))`;continue}else if(o[c]==="$"){s+=`($|(?=[\r
59
+ ]))`;continue}}if(r.s&&o[c]==="."){s+=a?`${o[c]}\r
60
+ `:`[${o[c]}\r
61
+ ]`;continue}s+=o[c],o[c]==="\\"?i=!0:a&&o[c]==="]"?a=!1:!a&&o[c]==="["&&(a=!0)}try{new RegExp(s)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return s}function Af(e,t){var n,r,o,s,i,a;const l={type:"object",additionalProperties:(n=Ee(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]}))!=null?n:t.allowedAdditionalProperties};if(((r=e.keyType)==null?void 0:r._def.typeName)===Z.ZodString&&((o=e.keyType._def.checks)!=null&&o.length)){const{type:c,...u}=Nf(e.keyType._def,t);return{...l,propertyNames:u}}else{if(((s=e.keyType)==null?void 0:s._def.typeName)===Z.ZodEnum)return{...l,propertyNames:{enum:e.keyType._def.values}};if(((i=e.keyType)==null?void 0:i._def.typeName)===Z.ZodBranded&&e.keyType._def.type._def.typeName===Z.ZodString&&((a=e.keyType._def.type._def.checks)!=null&&a.length)){const{type:c,...u}=Rf(e.keyType._def,t);return{...l,propertyNames:u}}}return l}function _5(e,t){if(t.mapStrategy==="record")return Af(e,t);const n=Ee(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||St(),r=Ee(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||St();return{type:"array",maxItems:125,items:{type:"array",items:[n,r],minItems:2,maxItems:2}}}function y5(e){const t=e.values,r=Object.keys(e.values).filter(s=>typeof t[t[s]]!="number").map(s=>t[s]),o=Array.from(new Set(r.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:r}}function w5(){return{not:St()}}function b5(){return{type:"null"}}var Ga={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function $5(e,t){const n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(r=>r._def.typeName in Ga&&(!r._def.checks||!r._def.checks.length))){const r=n.reduce((o,s)=>{const i=Ga[s._def.typeName];return i&&!o.includes(i)?[...o,i]:o},[]);return{type:r.length>1?r:r[0]}}else if(n.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){const r=n.reduce((o,s)=>{const i=typeof s._def.value;switch(i){case"string":case"number":case"boolean":return[...o,i];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];case"symbol":case"undefined":case"function":default:return o}},[]);if(r.length===n.length){const o=r.filter((s,i,a)=>a.indexOf(s)===i);return{type:o.length>1?o:o[0],enum:n.reduce((s,i)=>s.includes(i._def.value)?s:[...s,i._def.value],[])}}}else if(n.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((r,o)=>[...r,...o._def.values.filter(s=>!r.includes(s))],[])};return S5(e,t)}var S5=(e,t)=>{const n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((r,o)=>Ee(r._def,{...t,currentPath:[...t.currentPath,"anyOf",`${o}`]})).filter(r=>!!r&&(!t.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return n.length?{anyOf:n}:void 0};function C5(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[Ga[e.innerType._def.typeName],"null"]};const n=Ee(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}function E5(e){const t={type:"number"};if(!e.checks)return t;for(const n of e.checks)switch(n.kind){case"int":t.type="integer";break;case"min":n.inclusive?t.minimum=n.value:t.exclusiveMinimum=n.value;break;case"max":n.inclusive?t.maximum=n.value:t.exclusiveMaximum=n.value;break;case"multipleOf":t.multipleOf=n.value;break}return t}function k5(e,t){const n={type:"object",properties:{}},r=[],o=e.shape();for(const i in o){let a=o[i];if(a===void 0||a._def===void 0)continue;const l=T5(a),c=Ee(a._def,{...t,currentPath:[...t.currentPath,"properties",i],propertyPath:[...t.currentPath,"properties",i]});c!==void 0&&(n.properties[i]=c,l||r.push(i))}r.length&&(n.required=r);const s=I5(e,t);return s!==void 0&&(n.additionalProperties=s),n}function I5(e,t){if(e.catchall._def.typeName!=="ZodNever")return Ee(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 T5(e){try{return e.isOptional()}catch{return!0}}var x5=(e,t)=>{var n;if(t.currentPath.toString()===((n=t.propertyPath)==null?void 0:n.toString()))return Ee(e.innerType._def,t);const r=Ee(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:St()},r]}:St()},P5=(e,t)=>{if(t.pipeStrategy==="input")return Ee(e.in._def,t);if(t.pipeStrategy==="output")return Ee(e.out._def,t);const n=Ee(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),r=Ee(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,r].filter(o=>o!==void 0)}};function R5(e,t){return Ee(e.type._def,t)}function O5(e,t){const r={type:"array",uniqueItems:!0,items:Ee(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&(r.minItems=e.minSize.value),e.maxSize&&(r.maxItems=e.maxSize.value),r}function N5(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((n,r)=>Ee(n._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[]),additionalItems:Ee(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((n,r)=>Ee(n._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[])}}function M5(){return{not:St()}}function A5(){return St()}var L5=(e,t)=>Ee(e.innerType._def,t),j5=(e,t,n)=>{switch(t){case Z.ZodString:return Nf(e,n);case Z.ZodNumber:return E5(e);case Z.ZodObject:return k5(e,n);case Z.ZodBigInt:return i5(e);case Z.ZodBoolean:return a5();case Z.ZodDate:return Of(e,n);case Z.ZodUndefined:return M5();case Z.ZodNull:return b5();case Z.ZodArray:return s5(e,n);case Z.ZodUnion:case Z.ZodDiscriminatedUnion:return $5(e,n);case Z.ZodIntersection:return h5(e,n);case Z.ZodTuple:return N5(e,n);case Z.ZodRecord:return Af(e,n);case Z.ZodLiteral:return m5(e);case Z.ZodEnum:return p5(e);case Z.ZodNativeEnum:return y5(e);case Z.ZodNullable:return C5(e,n);case Z.ZodOptional:return x5(e,n);case Z.ZodMap:return _5(e,n);case Z.ZodSet:return O5(e,n);case Z.ZodLazy:return()=>e.getter()._def;case Z.ZodPromise:return R5(e,n);case Z.ZodNaN:case Z.ZodNever:return w5();case Z.ZodEffects:return d5(e,n);case Z.ZodAny:return St();case Z.ZodUnknown:return A5();case Z.ZodDefault:return u5(e,n);case Z.ZodBranded:return Rf(e,n);case Z.ZodReadonly:return L5(e,n);case Z.ZodCatch:return l5(e,n);case Z.ZodPipeline:return P5(e,n);case Z.ZodFunction:case Z.ZodVoid:case Z.ZodSymbol:return;default:return(r=>{})()}};function Ee(e,t,n=!1){var r;const o=t.seen.get(e);if(t.override){const l=(r=t.override)==null?void 0:r.call(t,e,t,o,n);if(l!==r5)return l}if(o&&!n){const l=z5(o,t);if(l!==void 0)return l}const s={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,s);const i=j5(e,e.typeName,t),a=typeof i=="function"?Ee(i(),t):i;if(a&&D5(e,t,a),t.postProcess){const l=t.postProcess(a,e,t);return s.jsonSchema=a,l}return s.jsonSchema=a,a}var z5=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:n5(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((n,r)=>t.currentPath[r]===n)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),St()):t.$refStrategy==="seen"?St():void 0}},D5=(e,t,n)=>(e.description&&(n.description=e.description),n),U5=e=>{const t=o5(e),n=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([r,o])=>[o._def,{def:o._def,path:[...t.basePath,t.definitionPath,r],jsonSchema:void 0}]))}},q5=(e,t)=>{var n;const r=U5(t);let o=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[u,h])=>{var _;return{...c,[u]:(_=Ee(h._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0))!=null?_:St()}},{}):void 0;const s=typeof t=="string"?t:(t==null?void 0:t.nameStrategy)==="title"||t==null?void 0:t.name,i=(n=Ee(e._def,s===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,s]},!1))!=null?n:St(),a=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;a!==void 0&&(i.title=a);const l=s===void 0?o?{...i,[r.definitionPath]:o}:i:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,s].join("/"),[r.definitionPath]:{...o,[s]:i}};return l.$schema="http://json-schema.org/draft-07/schema#",l},Z5=q5;function F5(e,t){var n;const r=(n=void 0)!=null?n:!1;return Lf(()=>Z5(e,{$refStrategy:r?"root":"none"}),{validate:async o=>{const s=await e.safeParseAsync(o);return s.success?{success:!0,value:s.data}:{success:!1,error:s.error}}})}function V5(e,t){var n;const r=(n=void 0)!=null?n:!1;return Lf(()=>nd(e,{target:"draft-7",io:"output",reused:r?"ref":"inline"}),{validate:async o=>{const s=await Ti(e,o);return s.success?{success:!0,value:s.data}:{success:!1,error:s.error}}})}function B5(e){return"_zod"in e}function we(e,t){return B5(e)?V5(e):F5(e)}var H5=Symbol.for("vercel.ai.schema");function et(e){let t;return()=>(t==null&&(t=e()),t)}function Lf(e,{validate:t}={}){return{[H5]:!0,_type:void 0,[ys]:!0,get jsonSchema(){return typeof e=="function"&&(e=e()),e},validate:t}}var{btoa:J5,atob:G5}=globalThis;function W5(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=G5(t);return Uint8Array.from(n,r=>r.codePointAt(0))}function K5(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return J5(t)}function Kn(e){return e instanceof Uint8Array?K5(e):e}function jf(e){return e==null?void 0:e.replace(/\/$/,"")}var Wa=S({error:S({message:p(),type:p().nullish(),param:yt().nullish(),code:Q([p(),R()]).nullish()})}),en=xf({errorSchema:Wa,errorToMessage:e=>e.error.message});function Y5({prompt:e,systemMessageMode:t="system"}){const n=[],r=[];for(const{role:o,content:s}of e)switch(o){case"system":{switch(t){case"system":{n.push({role:"system",content:s});break}case"developer":{n.push({role:"developer",content:s});break}case"remove":{r.push({type:"other",message:"system messages are removed for this model"});break}default:{const i=t;throw new Error(`Unsupported system message mode: ${i}`)}}break}case"user":{if(s.length===1&&s[0].type==="text"){n.push({role:"user",content:s[0].text});break}n.push({role:"user",content:s.map((i,a)=>{var l,c,u;switch(i.type){case"text":return{type:"text",text:i.text};case"file":if(i.mediaType.startsWith("image/")){const h=i.mediaType==="image/*"?"image/jpeg":i.mediaType;return{type:"image_url",image_url:{url:i.data instanceof URL?i.data.toString():`data:${h};base64,${Kn(i.data)}`,detail:(c=(l=i.providerOptions)==null?void 0:l.openai)==null?void 0:c.imageDetail}}}else if(i.mediaType.startsWith("audio/")){if(i.data instanceof URL)throw new Mt({functionality:"audio file parts with URLs"});switch(i.mediaType){case"audio/wav":return{type:"input_audio",input_audio:{data:Kn(i.data),format:"wav"}};case"audio/mp3":case"audio/mpeg":return{type:"input_audio",input_audio:{data:Kn(i.data),format:"mp3"}};default:throw new Mt({functionality:`audio content parts with media type ${i.mediaType}`})}}else if(i.mediaType==="application/pdf"){if(i.data instanceof URL)throw new Mt({functionality:"PDF file parts with URLs"});return{type:"file",file:typeof i.data=="string"&&i.data.startsWith("file-")?{file_id:i.data}:{filename:(u=i.filename)!=null?u:`part-${a}.pdf`,file_data:`data:application/pdf;base64,${Kn(i.data)}`}}}else throw new Mt({functionality:`file part media type ${i.mediaType}`})}})});break}case"assistant":{let i="";const a=[];for(const l of s)switch(l.type){case"text":{i+=l.text;break}case"tool-call":{a.push({id:l.toolCallId,type:"function",function:{name:l.toolName,arguments:JSON.stringify(l.input)}});break}}n.push({role:"assistant",content:i,tool_calls:a.length>0?a:void 0});break}case"tool":{for(const i of s){const a=i.output;let l;switch(a.type){case"text":case"error-text":l=a.value;break;case"content":case"json":case"error-json":l=JSON.stringify(a.value);break}n.push({role:"tool",tool_call_id:i.toolCallId,content:l})}break}default:{const i=o;throw new Error(`Unsupported role: ${i}`)}}return{messages:n,warnings:r}}function Ka({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n?new Date(n*1e3):void 0}}function zf(e){switch(e){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"unknown"}}var Q5=it(()=>we(S({id:p().nullish(),created:R().nullish(),model:p().nullish(),choices:N(S({message:S({role:O("assistant").nullish(),content:p().nullish(),tool_calls:N(S({id:p().nullish(),type:O("function"),function:S({name:p(),arguments:p()})})).nullish(),annotations:N(S({type:O("url_citation"),start_index:R(),end_index:R(),url:p(),title:p()})).nullish()}),index:R(),logprobs:S({content:N(S({token:p(),logprob:R(),top_logprobs:N(S({token:p(),logprob:R()}))})).nullish()}).nullish(),finish_reason:p().nullish()})),usage:S({prompt_tokens:R().nullish(),completion_tokens:R().nullish(),total_tokens:R().nullish(),prompt_tokens_details:S({cached_tokens:R().nullish()}).nullish(),completion_tokens_details:S({reasoning_tokens:R().nullish(),accepted_prediction_tokens:R().nullish(),rejected_prediction_tokens:R().nullish()}).nullish()}).nullish()}))),X5=it(()=>we(Q([S({id:p().nullish(),created:R().nullish(),model:p().nullish(),choices:N(S({delta:S({role:me(["assistant"]).nullish(),content:p().nullish(),tool_calls:N(S({index:R(),id:p().nullish(),type:O("function").nullish(),function:S({name:p().nullish(),arguments:p().nullish()})})).nullish(),annotations:N(S({type:O("url_citation"),start_index:R(),end_index:R(),url:p(),title:p()})).nullish()}).nullish(),logprobs:S({content:N(S({token:p(),logprob:R(),top_logprobs:N(S({token:p(),logprob:R()}))})).nullish()}).nullish(),finish_reason:p().nullish(),index:R()})),usage:S({prompt_tokens:R().nullish(),completion_tokens:R().nullish(),total_tokens:R().nullish(),prompt_tokens_details:S({cached_tokens:R().nullish()}).nullish(),completion_tokens_details:S({reasoning_tokens:R().nullish(),accepted_prediction_tokens:R().nullish(),rejected_prediction_tokens:R().nullish()}).nullish()}).nullish()}),Wa]))),e8=it(()=>we(S({logitBias:ie(M_(),R()).optional(),logprobs:Q([ne(),R()]).optional(),parallelToolCalls:ne().optional(),user:p().optional(),reasoningEffort:me(["none","minimal","low","medium","high"]).optional(),maxCompletionTokens:R().optional(),store:ne().optional(),metadata:ie(p().max(64),p().max(512)).optional(),prediction:ie(p(),yt()).optional(),structuredOutputs:ne().optional(),serviceTier:me(["auto","flex","priority","default"]).optional(),strictJsonSchema:ne().optional(),textVerbosity:me(["low","medium","high"]).optional(),promptCacheKey:p().optional(),promptCacheRetention:me(["in_memory","24h"]).optional(),safetyIdentifier:p().optional()})));function t8({tools:e,toolChoice:t,structuredOutputs:n,strictJsonSchema:r}){e=e!=null&&e.length?e:void 0;const o=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:o};const s=[];for(const a of e)switch(a.type){case"function":s.push({type:"function",function:{name:a.name,description:a.description,parameters:a.inputSchema,strict:n?r:void 0}});break;default:o.push({type:"unsupported-tool",tool:a});break}if(t==null)return{tools:s,toolChoice:void 0,toolWarnings:o};const i=t.type;switch(i){case"auto":case"none":case"required":return{tools:s,toolChoice:i,toolWarnings:o};case"tool":return{tools:s,toolChoice:{type:"function",function:{name:t.toolName}},toolWarnings:o};default:{const a=i;throw new Mt({functionality:`tool choice type: ${a}`})}}}var n8=class{constructor(e,t){this.specificationVersion="v2",this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:o,frequencyPenalty:s,presencePenalty:i,stopSequences:a,responseFormat:l,seed:c,tools:u,toolChoice:h,providerOptions:_}){var f,g,v,m;const d=[],w=(f=await Xt({provider:"openai",providerOptions:_,schema:e8}))!=null?f:{},y=(g=w.structuredOutputs)!=null?g:!0;o!=null&&d.push({type:"unsupported-setting",setting:"topK"}),(l==null?void 0:l.type)==="json"&&l.schema!=null&&!y&&d.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{messages:b,warnings:k}=Y5({prompt:e,systemMessageMode:s8(this.modelId)});d.push(...k);const x=(v=w.strictJsonSchema)!=null?v:!1,T={model:this.modelId,logit_bias:w.logitBias,logprobs:w.logprobs===!0||typeof w.logprobs=="number"?!0:void 0,top_logprobs:typeof w.logprobs=="number"?w.logprobs:typeof w.logprobs=="boolean"&&w.logprobs?0:void 0,user:w.user,parallel_tool_calls:w.parallelToolCalls,max_tokens:t,temperature:n,top_p:r,frequency_penalty:s,presence_penalty:i,response_format:(l==null?void 0:l.type)==="json"?y&&l.schema!=null?{type:"json_schema",json_schema:{schema:l.schema,strict:x,name:(m=l.name)!=null?m:"response",description:l.description}}:{type:"json_object"}:void 0,stop:a,seed:c,verbosity:w.textVerbosity,max_completion_tokens:w.maxCompletionTokens,store:w.store,metadata:w.metadata,prediction:w.prediction,reasoning_effort:w.reasoningEffort,service_tier:w.serviceTier,prompt_cache_key:w.promptCacheKey,prompt_cache_retention:w.promptCacheRetention,safety_identifier:w.safetyIdentifier,messages:b};Df(this.modelId)?(T.temperature!=null&&(T.temperature=void 0,d.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"})),T.top_p!=null&&(T.top_p=void 0,d.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"})),T.frequency_penalty!=null&&(T.frequency_penalty=void 0,d.push({type:"unsupported-setting",setting:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"})),T.presence_penalty!=null&&(T.presence_penalty=void 0,d.push({type:"unsupported-setting",setting:"presencePenalty",details:"presencePenalty is not supported for reasoning models"})),T.logit_bias!=null&&(T.logit_bias=void 0,d.push({type:"other",message:"logitBias is not supported for reasoning models"})),T.logprobs!=null&&(T.logprobs=void 0,d.push({type:"other",message:"logprobs is not supported for reasoning models"})),T.top_logprobs!=null&&(T.top_logprobs=void 0,d.push({type:"other",message:"topLogprobs is not supported for reasoning models"})),T.max_tokens!=null&&(T.max_completion_tokens==null&&(T.max_completion_tokens=T.max_tokens),T.max_tokens=void 0)):(this.modelId.startsWith("gpt-4o-search-preview")||this.modelId.startsWith("gpt-4o-mini-search-preview"))&&T.temperature!=null&&(T.temperature=void 0,d.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for the search preview models and has been removed."})),w.serviceTier==="flex"&&!r8(this.modelId)&&(d.push({type:"unsupported-setting",setting:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),T.service_tier=void 0),w.serviceTier==="priority"&&!o8(this.modelId)&&(d.push({type:"unsupported-setting",setting:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),T.service_tier=void 0);const{tools:D,toolChoice:U,toolWarnings:H}=t8({tools:u,toolChoice:h,structuredOutputs:y,strictJsonSchema:x});return{args:{...T,tools:D,tool_choice:U},warnings:[...d,...H]}}async doGenerate(e){var t,n,r,o,s,i,a,l,c,u,h,_,f,g;const{args:v,warnings:m}=await this.getArgs(e),{responseHeaders:d,value:w,rawValue:y}=await Dt({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:xt(this.config.headers(),e.headers),body:v,failedResponseHandler:en,successfulResponseHandler:Wn(Q5),abortSignal:e.abortSignal,fetch:this.config.fetch}),b=w.choices[0],k=[],x=b.message.content;x!=null&&x.length>0&&k.push({type:"text",text:x});for(const H of(t=b.message.tool_calls)!=null?t:[])k.push({type:"tool-call",toolCallId:(n=H.id)!=null?n:st(),toolName:H.function.name,input:H.function.arguments});for(const H of(r=b.message.annotations)!=null?r:[])k.push({type:"source",sourceType:"url",id:st(),url:H.url,title:H.title});const T=(o=w.usage)==null?void 0:o.completion_tokens_details,D=(s=w.usage)==null?void 0:s.prompt_tokens_details,U={openai:{}};return(T==null?void 0:T.accepted_prediction_tokens)!=null&&(U.openai.acceptedPredictionTokens=T==null?void 0:T.accepted_prediction_tokens),(T==null?void 0:T.rejected_prediction_tokens)!=null&&(U.openai.rejectedPredictionTokens=T==null?void 0:T.rejected_prediction_tokens),((i=b.logprobs)==null?void 0:i.content)!=null&&(U.openai.logprobs=b.logprobs.content),{content:k,finishReason:zf(b.finish_reason),usage:{inputTokens:(l=(a=w.usage)==null?void 0:a.prompt_tokens)!=null?l:void 0,outputTokens:(u=(c=w.usage)==null?void 0:c.completion_tokens)!=null?u:void 0,totalTokens:(_=(h=w.usage)==null?void 0:h.total_tokens)!=null?_:void 0,reasoningTokens:(f=T==null?void 0:T.reasoning_tokens)!=null?f:void 0,cachedInputTokens:(g=D==null?void 0:D.cached_tokens)!=null?g:void 0},request:{body:v},response:{...Ka(w),headers:d,body:y},warnings:m,providerMetadata:U}}async doStream(e){const{args:t,warnings:n}=await this.getArgs(e),r={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:o,value:s}=await Dt({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:xt(this.config.headers(),e.headers),body:r,failedResponseHandler:en,successfulResponseHandler:bs(X5),abortSignal:e.abortSignal,fetch:this.config.fetch}),i=[];let a="unknown";const l={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};let c=!1,u=!1;const h={openai:{}};return{stream:s.pipeThrough(new TransformStream({start(_){_.enqueue({type:"stream-start",warnings:n})},transform(_,f){var g,v,m,d,w,y,b,k,x,T,D,U,H,q,F,B,V,se,ge,te,ue,le,L,I;if(e.includeRawChunks&&f.enqueue({type:"raw",rawValue:_.rawValue}),!_.success){a="error",f.enqueue({type:"error",error:_.error});return}const M=_.value;if("error"in M){a="error",f.enqueue({type:"error",error:M.error});return}if(!c){const E=Ka(M);Object.values(E).some(Boolean)&&(c=!0,f.enqueue({type:"response-metadata",...Ka(M)}))}M.usage!=null&&(l.inputTokens=(g=M.usage.prompt_tokens)!=null?g:void 0,l.outputTokens=(v=M.usage.completion_tokens)!=null?v:void 0,l.totalTokens=(m=M.usage.total_tokens)!=null?m:void 0,l.reasoningTokens=(w=(d=M.usage.completion_tokens_details)==null?void 0:d.reasoning_tokens)!=null?w:void 0,l.cachedInputTokens=(b=(y=M.usage.prompt_tokens_details)==null?void 0:y.cached_tokens)!=null?b:void 0,((k=M.usage.completion_tokens_details)==null?void 0:k.accepted_prediction_tokens)!=null&&(h.openai.acceptedPredictionTokens=(x=M.usage.completion_tokens_details)==null?void 0:x.accepted_prediction_tokens),((T=M.usage.completion_tokens_details)==null?void 0:T.rejected_prediction_tokens)!=null&&(h.openai.rejectedPredictionTokens=(D=M.usage.completion_tokens_details)==null?void 0:D.rejected_prediction_tokens));const P=M.choices[0];if((P==null?void 0:P.finish_reason)!=null&&(a=zf(P.finish_reason)),((U=P==null?void 0:P.logprobs)==null?void 0:U.content)!=null&&(h.openai.logprobs=P.logprobs.content),(P==null?void 0:P.delta)==null)return;const C=P.delta;if(C.content!=null&&(u||(f.enqueue({type:"text-start",id:"0"}),u=!0),f.enqueue({type:"text-delta",id:"0",delta:C.content})),C.tool_calls!=null)for(const E of C.tool_calls){const $=E.index;if(i[$]==null){if(E.type!=="function")throw new Ar({data:E,message:"Expected 'function' type."});if(E.id==null)throw new Ar({data:E,message:"Expected 'id' to be a string."});if(((H=E.function)==null?void 0:H.name)==null)throw new Ar({data:E,message:"Expected 'function.name' to be a string."});f.enqueue({type:"tool-input-start",id:E.id,toolName:E.function.name}),i[$]={id:E.id,type:"function",function:{name:E.function.name,arguments:(q=E.function.arguments)!=null?q:""},hasFinished:!1};const z=i[$];((F=z.function)==null?void 0:F.name)!=null&&((B=z.function)==null?void 0:B.arguments)!=null&&(z.function.arguments.length>0&&f.enqueue({type:"tool-input-delta",id:z.id,delta:z.function.arguments}),ws(z.function.arguments)&&(f.enqueue({type:"tool-input-end",id:z.id}),f.enqueue({type:"tool-call",toolCallId:(V=z.id)!=null?V:st(),toolName:z.function.name,input:z.function.arguments}),z.hasFinished=!0));continue}const j=i[$];j.hasFinished||(((se=E.function)==null?void 0:se.arguments)!=null&&(j.function.arguments+=(te=(ge=E.function)==null?void 0:ge.arguments)!=null?te:""),f.enqueue({type:"tool-input-delta",id:j.id,delta:(ue=E.function.arguments)!=null?ue:""}),((le=j.function)==null?void 0:le.name)!=null&&((L=j.function)==null?void 0:L.arguments)!=null&&ws(j.function.arguments)&&(f.enqueue({type:"tool-input-end",id:j.id}),f.enqueue({type:"tool-call",toolCallId:(I=j.id)!=null?I:st(),toolName:j.function.name,input:j.function.arguments}),j.hasFinished=!0))}if(C.annotations!=null)for(const E of C.annotations)f.enqueue({type:"source",sourceType:"url",id:st(),url:E.url,title:E.title})},flush(_){u&&_.enqueue({type:"text-end",id:"0"}),_.enqueue({type:"finish",finishReason:a,usage:l,...h!=null?{providerMetadata:h}:{}})}})),request:{body:r},response:{headers:o}}}};function Df(e){return(e.startsWith("o")||e.startsWith("gpt-5"))&&!e.startsWith("gpt-5-chat")}function r8(e){return e.startsWith("o3")||e.startsWith("o4-mini")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-chat")}function o8(e){return e.startsWith("gpt-4")||e.startsWith("gpt-5-mini")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-nano")&&!e.startsWith("gpt-5-chat")||e.startsWith("o3")||e.startsWith("o4-mini")}function s8(e){var t,n;return Df(e)?(n=(t=i8[e])==null?void 0:t.systemMessageMode)!=null?n:"developer":"system"}var i8={o3:{systemMessageMode:"developer"},"o3-2025-04-16":{systemMessageMode:"developer"},"o3-mini":{systemMessageMode:"developer"},"o3-mini-2025-01-31":{systemMessageMode:"developer"},"o4-mini":{systemMessageMode:"developer"},"o4-mini-2025-04-16":{systemMessageMode:"developer"}};function a8({prompt:e,user:t="user",assistant:n="assistant"}){let r="";e[0].role==="system"&&(r+=`${e[0].content}
62
+
63
+ `,e=e.slice(1));for(const{role:o,content:s}of e)switch(o){case"system":throw new An({message:"Unexpected system message in prompt: ${content}",prompt:e});case"user":{const i=s.map(a=>{switch(a.type){case"text":return a.text}}).filter(Boolean).join("");r+=`${t}:
64
+ ${i}
65
+
66
+ `;break}case"assistant":{const i=s.map(a=>{switch(a.type){case"text":return a.text;case"tool-call":throw new Mt({functionality:"tool-call messages"})}}).join("");r+=`${n}:
67
+ ${i}
68
+
69
+ `;break}case"tool":throw new Mt({functionality:"tool messages"});default:{const i=o;throw new Error(`Unsupported role: ${i}`)}}return r+=`${n}:
70
+ `,{prompt:r,stopSequences:[`
71
+ ${t}:`]}}function Uf({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n!=null?new Date(n*1e3):void 0}}function qf(e){switch(e){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"unknown"}}var l8=it(()=>we(S({id:p().nullish(),created:R().nullish(),model:p().nullish(),choices:N(S({text:p(),finish_reason:p(),logprobs:S({tokens:N(p()),token_logprobs:N(R()),top_logprobs:N(ie(p(),R())).nullish()}).nullish()})),usage:S({prompt_tokens:R(),completion_tokens:R(),total_tokens:R()}).nullish()}))),c8=it(()=>we(Q([S({id:p().nullish(),created:R().nullish(),model:p().nullish(),choices:N(S({text:p(),finish_reason:p().nullish(),index:R(),logprobs:S({tokens:N(p()),token_logprobs:N(R()),top_logprobs:N(ie(p(),R())).nullish()}).nullish()})),usage:S({prompt_tokens:R(),completion_tokens:R(),total_tokens:R()}).nullish()}),Wa]))),Zf=it(()=>we(S({echo:ne().optional(),logitBias:ie(p(),R()).optional(),suffix:p().optional(),user:p().optional(),logprobs:Q([ne(),R()]).optional()}))),u8=class{constructor(e,t){this.specificationVersion="v2",this.supportedUrls={},this.modelId=e,this.config=t}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:o,frequencyPenalty:s,presencePenalty:i,stopSequences:a,responseFormat:l,tools:c,toolChoice:u,seed:h,providerOptions:_}){const f=[],g={...await Xt({provider:"openai",providerOptions:_,schema:Zf}),...await Xt({provider:this.providerOptionsName,providerOptions:_,schema:Zf})};o!=null&&f.push({type:"unsupported-setting",setting:"topK"}),c!=null&&c.length&&f.push({type:"unsupported-setting",setting:"tools"}),u!=null&&f.push({type:"unsupported-setting",setting:"toolChoice"}),l!=null&&l.type!=="text"&&f.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format is not supported."});const{prompt:v,stopSequences:m}=a8({prompt:e}),d=[...m??[],...a??[]];return{args:{model:this.modelId,echo:g.echo,logit_bias:g.logitBias,logprobs:(g==null?void 0:g.logprobs)===!0?0:(g==null?void 0:g.logprobs)===!1||g==null?void 0:g.logprobs,suffix:g.suffix,user:g.user,max_tokens:t,temperature:n,top_p:r,frequency_penalty:s,presence_penalty:i,seed:h,prompt:v,stop:d.length>0?d:void 0},warnings:f}}async doGenerate(e){var t,n,r;const{args:o,warnings:s}=await this.getArgs(e),{responseHeaders:i,value:a,rawValue:l}=await Dt({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:xt(this.config.headers(),e.headers),body:o,failedResponseHandler:en,successfulResponseHandler:Wn(l8),abortSignal:e.abortSignal,fetch:this.config.fetch}),c=a.choices[0],u={openai:{}};return c.logprobs!=null&&(u.openai.logprobs=c.logprobs),{content:[{type:"text",text:c.text}],usage:{inputTokens:(t=a.usage)==null?void 0:t.prompt_tokens,outputTokens:(n=a.usage)==null?void 0:n.completion_tokens,totalTokens:(r=a.usage)==null?void 0:r.total_tokens},finishReason:qf(c.finish_reason),request:{body:o},response:{...Uf(a),headers:i,body:l},providerMetadata:u,warnings:s}}async doStream(e){const{args:t,warnings:n}=await this.getArgs(e),r={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:o,value:s}=await Dt({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:xt(this.config.headers(),e.headers),body:r,failedResponseHandler:en,successfulResponseHandler:bs(c8),abortSignal:e.abortSignal,fetch:this.config.fetch});let i="unknown";const a={openai:{}},l={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};let c=!0;return{stream:s.pipeThrough(new TransformStream({start(u){u.enqueue({type:"stream-start",warnings:n})},transform(u,h){if(e.includeRawChunks&&h.enqueue({type:"raw",rawValue:u.rawValue}),!u.success){i="error",h.enqueue({type:"error",error:u.error});return}const _=u.value;if("error"in _){i="error",h.enqueue({type:"error",error:_.error});return}c&&(c=!1,h.enqueue({type:"response-metadata",...Uf(_)}),h.enqueue({type:"text-start",id:"0"})),_.usage!=null&&(l.inputTokens=_.usage.prompt_tokens,l.outputTokens=_.usage.completion_tokens,l.totalTokens=_.usage.total_tokens);const f=_.choices[0];(f==null?void 0:f.finish_reason)!=null&&(i=qf(f.finish_reason)),(f==null?void 0:f.logprobs)!=null&&(a.openai.logprobs=f.logprobs),(f==null?void 0:f.text)!=null&&f.text.length>0&&h.enqueue({type:"text-delta",id:"0",delta:f.text})},flush(u){c||u.enqueue({type:"text-end",id:"0"}),u.enqueue({type:"finish",finishReason:i,providerMetadata:a,usage:l})}})),request:{body:r},response:{headers:o}}}},d8=it(()=>we(S({dimensions:R().optional(),user:p().optional()}))),p8=it(()=>we(S({data:N(S({embedding:N(R())})),usage:S({prompt_tokens:R()}).nullish()}))),f8=class{constructor(e,t){this.specificationVersion="v2",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=e,this.config=t}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:n,providerOptions:r}){var o;if(e.length>this.maxEmbeddingsPerCall)throw new Rm({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});const s=(o=await Xt({provider:"openai",providerOptions:r,schema:d8}))!=null?o:{},{responseHeaders:i,value:a,rawValue:l}=await Dt({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:xt(this.config.headers(),t),body:{model:this.modelId,input:e,encoding_format:"float",dimensions:s.dimensions,user:s.user},failedResponseHandler:en,successfulResponseHandler:Wn(p8),abortSignal:n,fetch:this.config.fetch});return{embeddings:a.data.map(c=>c.embedding),usage:a.usage?{tokens:a.usage.prompt_tokens}:void 0,response:{headers:i,body:l}}}},h8=it(()=>we(S({data:N(S({b64_json:p(),revised_prompt:p().nullish()}))}))),m8={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10,"gpt-image-1-mini":10},g8=new Set(["gpt-image-1","gpt-image-1-mini"]),v8=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2"}get maxImagesPerCall(){var e;return(e=m8[this.modelId])!=null?e:1}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,size:n,aspectRatio:r,seed:o,providerOptions:s,headers:i,abortSignal:a}){var l,c,u,h;const _=[];r!=null&&_.push({type:"unsupported-setting",setting:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),o!=null&&_.push({type:"unsupported-setting",setting:"seed"});const f=(u=(c=(l=this.config._internal)==null?void 0:l.currentDate)==null?void 0:c.call(l))!=null?u:new Date,{value:g,responseHeaders:v}=await Dt({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:xt(this.config.headers(),i),body:{model:this.modelId,prompt:e,n:t,size:n,...(h=s.openai)!=null?h:{},...g8.has(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:en,successfulResponseHandler:Wn(h8),abortSignal:a,fetch:this.config.fetch});return{images:g.data.map(m=>m.b64_json),warnings:_,response:{timestamp:f,modelId:this.modelId,headers:v},providerMetadata:{openai:{images:g.data.map(m=>m.revised_prompt?{revisedPrompt:m.revised_prompt}:null)}}}}},_8=et(()=>we(S({code:p().nullish(),containerId:p()}))),y8=et(()=>we(S({outputs:N(Fe("type",[S({type:O("logs"),logs:p()}),S({type:O("image"),url:p()})])).nullish()}))),w8=et(()=>we(S({container:Q([p(),S({fileIds:N(p()).optional()})]).optional()}))),b8=pr({id:"openai.code_interpreter",name:"code_interpreter",inputSchema:_8,outputSchema:y8}),$8=(e={})=>b8(e),Ff=S({key:p(),type:me(["eq","ne","gt","gte","lt","lte"]),value:Q([p(),R(),ne()])}),Vf=S({type:me(["and","or"]),filters:N(Q([Ff,md(()=>Vf)]))}),S8=et(()=>we(S({vectorStoreIds:N(p()),maxNumResults:R().optional(),ranking:S({ranker:p().optional(),scoreThreshold:R().optional()}).optional(),filters:Q([Ff,Vf]).optional()}))),C8=et(()=>we(S({queries:N(p()),results:N(S({attributes:ie(p(),ke()),fileId:p(),filename:p(),score:R(),text:p()})).nullable()}))),E8=pr({id:"openai.file_search",name:"file_search",inputSchema:S({}),outputSchema:C8}),k8=et(()=>we(S({background:me(["auto","opaque","transparent"]).optional(),inputFidelity:me(["low","high"]).optional(),inputImageMask:S({fileId:p().optional(),imageUrl:p().optional()}).optional(),model:p().optional(),moderation:me(["auto"]).optional(),outputCompression:R().int().min(0).max(100).optional(),outputFormat:me(["png","jpeg","webp"]).optional(),partialImages:R().int().min(0).max(3).optional(),quality:me(["auto","low","medium","high"]).optional(),size:me(["1024x1024","1024x1536","1536x1024","auto"]).optional()}).strict())),I8=et(()=>we(S({}))),T8=et(()=>we(S({result:p()}))),x8=pr({id:"openai.image_generation",name:"image_generation",inputSchema:I8,outputSchema:T8}),P8=(e={})=>x8(e),Bf=et(()=>we(S({action:S({type:O("exec"),command:N(p()),timeoutMs:R().optional(),user:p().optional(),workingDirectory:p().optional(),env:ie(p(),p()).optional()})}))),Hf=et(()=>we(S({output:p()}))),R8=pr({id:"openai.local_shell",name:"local_shell",inputSchema:Bf,outputSchema:Hf}),O8=et(()=>we(S({externalWebAccess:ne().optional(),filters:S({allowedDomains:N(p()).optional()}).optional(),searchContextSize:me(["low","medium","high"]).optional(),userLocation:S({type:O("approximate"),country:p().optional(),city:p().optional(),region:p().optional(),timezone:p().optional()}).optional()}))),N8=et(()=>we(S({}))),M8=et(()=>we(S({action:Fe("type",[S({type:O("search"),query:p().optional()}),S({type:O("openPage"),url:p()}),S({type:O("find"),url:p(),pattern:p()})]),sources:N(Fe("type",[S({type:O("url"),url:p()}),S({type:O("api"),name:p()})])).optional()}))),A8=pr({id:"openai.web_search",name:"web_search",inputSchema:N8,outputSchema:M8}),L8=(e={})=>A8(e),j8=et(()=>we(S({searchContextSize:me(["low","medium","high"]).optional(),userLocation:S({type:O("approximate"),country:p().optional(),city:p().optional(),region:p().optional(),timezone:p().optional()}).optional()}))),z8=et(()=>we(S({}))),D8=et(()=>we(S({action:Fe("type",[S({type:O("search"),query:p().optional()}),S({type:O("openPage"),url:p()}),S({type:O("find"),url:p(),pattern:p()})])}))),U8=pr({id:"openai.web_search_preview",name:"web_search_preview",inputSchema:z8,outputSchema:D8}),q8={codeInterpreter:$8,fileSearch:E8,imageGeneration:P8,localShell:R8,webSearchPreview:U8,webSearch:L8};function Jf(e,t){return t?t.some(n=>e.startsWith(n)):!1}async function Z8({prompt:e,systemMessageMode:t,fileIdPrefixes:n,store:r,hasLocalShellTool:o=!1}){var s,i,a,l;const c=[],u=[];for(const{role:h,content:_}of e)switch(h){case"system":{switch(t){case"system":{c.push({role:"system",content:_});break}case"developer":{c.push({role:"developer",content:_});break}case"remove":{u.push({type:"other",message:"system messages are removed for this model"});break}default:{const f=t;throw new Error(`Unsupported system message mode: ${f}`)}}break}case"user":{c.push({role:"user",content:_.map((f,g)=>{var v,m,d;switch(f.type){case"text":return{type:"input_text",text:f.text};case"file":if(f.mediaType.startsWith("image/")){const w=f.mediaType==="image/*"?"image/jpeg":f.mediaType;return{type:"input_image",...f.data instanceof URL?{image_url:f.data.toString()}:typeof f.data=="string"&&Jf(f.data,n)?{file_id:f.data}:{image_url:`data:${w};base64,${Kn(f.data)}`},detail:(m=(v=f.providerOptions)==null?void 0:v.openai)==null?void 0:m.imageDetail}}else{if(f.mediaType==="application/pdf")return f.data instanceof URL?{type:"input_file",file_url:f.data.toString()}:{type:"input_file",...typeof f.data=="string"&&Jf(f.data,n)?{file_id:f.data}:{filename:(d=f.filename)!=null?d:`part-${g}.pdf`,file_data:`data:application/pdf;base64,${Kn(f.data)}`}};throw new Mt({functionality:`file part media type ${f.mediaType}`})}}})});break}case"assistant":{const f={},g={};for(const v of _)switch(v.type){case"text":{const m=(i=(s=v.providerOptions)==null?void 0:s.openai)==null?void 0:i.itemId;if(r&&m!=null){c.push({type:"item_reference",id:m});break}c.push({role:"assistant",content:[{type:"output_text",text:v.text}],id:m});break}case"tool-call":{if(g[v.toolCallId]=v,v.providerExecuted)break;const m=(l=(a=v.providerOptions)==null?void 0:a.openai)==null?void 0:l.itemId;if(r&&m!=null){c.push({type:"item_reference",id:m});break}if(o&&v.toolName==="local_shell"){const d=await Cn({value:v.input,schema:Bf});c.push({type:"local_shell_call",call_id:v.toolCallId,id:m,action:{type:"exec",command:d.action.command,timeout_ms:d.action.timeoutMs,user:d.action.user,working_directory:d.action.workingDirectory,env:d.action.env}});break}c.push({type:"function_call",call_id:v.toolCallId,name:v.toolName,arguments:JSON.stringify(v.input),id:m});break}case"tool-result":{r?c.push({type:"item_reference",id:v.toolCallId}):u.push({type:"other",message:`Results for OpenAI tool ${v.toolName} are not sent to the API when store is false`});break}case"reasoning":{const m=await Xt({provider:"openai",providerOptions:v.providerOptions,schema:F8}),d=m==null?void 0:m.itemId;if(d!=null){const w=f[d];if(r)w===void 0&&(c.push({type:"item_reference",id:d}),f[d]={type:"reasoning",id:d,summary:[]});else{const y=[];v.text.length>0?y.push({type:"summary_text",text:v.text}):w!==void 0&&u.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(v)}.`}),w===void 0?(f[d]={type:"reasoning",id:d,encrypted_content:m==null?void 0:m.reasoningEncryptedContent,summary:y},c.push(f[d])):(w.summary.push(...y),(m==null?void 0:m.reasoningEncryptedContent)!=null&&(w.encrypted_content=m.reasoningEncryptedContent))}}else u.push({type:"other",message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(v)}.`});break}}break}case"tool":{for(const f of _){const g=f.output;if(o&&f.toolName==="local_shell"&&g.type==="json"){const m=await Cn({value:g.value,schema:Hf});c.push({type:"local_shell_call_output",call_id:f.toolCallId,output:m.output});break}let v;switch(g.type){case"text":case"error-text":v=g.value;break;case"json":case"error-json":v=JSON.stringify(g.value);break;case"content":v=g.value.map(m=>{switch(m.type){case"text":return{type:"input_text",text:m.text};case"media":return m.mediaType.startsWith("image/")?{type:"input_image",image_url:`data:${m.mediaType};base64,${m.data}`}:{type:"input_file",filename:"data",file_data:`data:${m.mediaType};base64,${m.data}`}}});break}c.push({type:"function_call_output",call_id:f.toolCallId,output:v})}break}default:{const f=h;throw new Error(`Unsupported role: ${f}`)}}return{input:c,warnings:u}}var F8=S({itemId:p().nullish(),reasoningEncryptedContent:p().nullish()});function Gf({finishReason:e,hasFunctionCall:t}){switch(e){case void 0:case null:return t?"tool-calls":"stop";case"max_output_tokens":return"length";case"content_filter":return"content-filter";default:return t?"tool-calls":"unknown"}}var V8=it(()=>we(Q([S({type:O("response.output_text.delta"),item_id:p(),delta:p(),logprobs:N(S({token:p(),logprob:R(),top_logprobs:N(S({token:p(),logprob:R()}))})).nullish()}),S({type:me(["response.completed","response.incomplete"]),response:S({incomplete_details:S({reason:p()}).nullish(),usage:S({input_tokens:R(),input_tokens_details:S({cached_tokens:R().nullish()}).nullish(),output_tokens:R(),output_tokens_details:S({reasoning_tokens:R().nullish()}).nullish()}),service_tier:p().nullish()})}),S({type:O("response.created"),response:S({id:p(),created_at:R(),model:p(),service_tier:p().nullish()})}),S({type:O("response.output_item.added"),output_index:R(),item:Fe("type",[S({type:O("message"),id:p()}),S({type:O("reasoning"),id:p(),encrypted_content:p().nullish()}),S({type:O("function_call"),id:p(),call_id:p(),name:p(),arguments:p()}),S({type:O("web_search_call"),id:p(),status:p()}),S({type:O("computer_call"),id:p(),status:p()}),S({type:O("file_search_call"),id:p()}),S({type:O("image_generation_call"),id:p()}),S({type:O("code_interpreter_call"),id:p(),container_id:p(),code:p().nullable(),outputs:N(Fe("type",[S({type:O("logs"),logs:p()}),S({type:O("image"),url:p()})])).nullable(),status:p()})])}),S({type:O("response.output_item.done"),output_index:R(),item:Fe("type",[S({type:O("message"),id:p()}),S({type:O("reasoning"),id:p(),encrypted_content:p().nullish()}),S({type:O("function_call"),id:p(),call_id:p(),name:p(),arguments:p(),status:O("completed")}),S({type:O("code_interpreter_call"),id:p(),code:p().nullable(),container_id:p(),outputs:N(Fe("type",[S({type:O("logs"),logs:p()}),S({type:O("image"),url:p()})])).nullable()}),S({type:O("image_generation_call"),id:p(),result:p()}),S({type:O("web_search_call"),id:p(),status:p(),action:Fe("type",[S({type:O("search"),query:p().nullish(),sources:N(Fe("type",[S({type:O("url"),url:p()}),S({type:O("api"),name:p()})])).nullish()}),S({type:O("open_page"),url:p()}),S({type:O("find"),url:p(),pattern:p()})])}),S({type:O("file_search_call"),id:p(),queries:N(p()),results:N(S({attributes:ie(p(),ke()),file_id:p(),filename:p(),score:R(),text:p()})).nullish()}),S({type:O("local_shell_call"),id:p(),call_id:p(),action:S({type:O("exec"),command:N(p()),timeout_ms:R().optional(),user:p().optional(),working_directory:p().optional(),env:ie(p(),p()).optional()})}),S({type:O("computer_call"),id:p(),status:O("completed")})])}),S({type:O("response.function_call_arguments.delta"),item_id:p(),output_index:R(),delta:p()}),S({type:O("response.image_generation_call.partial_image"),item_id:p(),output_index:R(),partial_image_b64:p()}),S({type:O("response.code_interpreter_call_code.delta"),item_id:p(),output_index:R(),delta:p()}),S({type:O("response.code_interpreter_call_code.done"),item_id:p(),output_index:R(),code:p()}),S({type:O("response.output_text.annotation.added"),annotation:Fe("type",[S({type:O("url_citation"),start_index:R(),end_index:R(),url:p(),title:p()}),S({type:O("file_citation"),file_id:p(),filename:p().nullish(),index:R().nullish(),start_index:R().nullish(),end_index:R().nullish(),quote:p().nullish()})])}),S({type:O("response.reasoning_summary_part.added"),item_id:p(),summary_index:R()}),S({type:O("response.reasoning_summary_text.delta"),item_id:p(),summary_index:R(),delta:p()}),S({type:O("response.reasoning_summary_part.done"),item_id:p(),summary_index:R()}),S({type:O("error"),sequence_number:R(),error:S({type:p(),code:p(),message:p(),param:p().nullish()})}),S({type:p()}).loose().transform(e=>({type:"unknown_chunk",message:e.type}))]))),B8=it(()=>we(S({id:p().optional(),created_at:R().optional(),error:S({message:p(),type:p(),param:p().nullish(),code:p()}).nullish(),model:p().optional(),output:N(Fe("type",[S({type:O("message"),role:O("assistant"),id:p(),content:N(S({type:O("output_text"),text:p(),logprobs:N(S({token:p(),logprob:R(),top_logprobs:N(S({token:p(),logprob:R()}))})).nullish(),annotations:N(Fe("type",[S({type:O("url_citation"),start_index:R(),end_index:R(),url:p(),title:p()}),S({type:O("file_citation"),file_id:p(),filename:p().nullish(),index:R().nullish(),start_index:R().nullish(),end_index:R().nullish(),quote:p().nullish()}),S({type:O("container_file_citation"),container_id:p(),file_id:p(),filename:p().nullish(),start_index:R().nullish(),end_index:R().nullish(),index:R().nullish()}),S({type:O("file_path"),file_id:p(),index:R().nullish()})]))}))}),S({type:O("web_search_call"),id:p(),status:p(),action:Fe("type",[S({type:O("search"),query:p().nullish(),sources:N(Fe("type",[S({type:O("url"),url:p()}),S({type:O("api"),name:p()})])).nullish()}),S({type:O("open_page"),url:p()}),S({type:O("find"),url:p(),pattern:p()})])}),S({type:O("file_search_call"),id:p(),queries:N(p()),results:N(S({attributes:ie(p(),Q([p(),R(),ne()])),file_id:p(),filename:p(),score:R(),text:p()})).nullish()}),S({type:O("code_interpreter_call"),id:p(),code:p().nullable(),container_id:p(),outputs:N(Fe("type",[S({type:O("logs"),logs:p()}),S({type:O("image"),url:p()})])).nullable()}),S({type:O("image_generation_call"),id:p(),result:p()}),S({type:O("local_shell_call"),id:p(),call_id:p(),action:S({type:O("exec"),command:N(p()),timeout_ms:R().optional(),user:p().optional(),working_directory:p().optional(),env:ie(p(),p()).optional()})}),S({type:O("function_call"),call_id:p(),name:p(),arguments:p(),id:p()}),S({type:O("computer_call"),id:p(),status:p().optional()}),S({type:O("reasoning"),id:p(),encrypted_content:p().nullish(),summary:N(S({type:O("summary_text"),text:p()}))})])).optional(),service_tier:p().nullish(),incomplete_details:S({reason:p()}).nullish(),usage:S({input_tokens:R(),input_tokens_details:S({cached_tokens:R().nullish()}).nullish(),output_tokens:R(),output_tokens_details:S({reasoning_tokens:R().nullish()}).nullish()}).optional()}))),Wf=20,H8=it(()=>we(S({conversation:p().nullish(),include:N(me(["reasoning.encrypted_content","file_search_call.results","message.output_text.logprobs"])).nullish(),instructions:p().nullish(),logprobs:Q([ne(),R().min(1).max(Wf)]).optional(),maxToolCalls:R().nullish(),metadata:yt().nullish(),parallelToolCalls:ne().nullish(),previousResponseId:p().nullish(),promptCacheKey:p().nullish(),promptCacheRetention:me(["in_memory","24h"]).nullish(),reasoningEffort:p().nullish(),reasoningSummary:p().nullish(),safetyIdentifier:p().nullish(),serviceTier:me(["auto","flex","priority","default"]).nullish(),store:ne().nullish(),strictJsonSchema:ne().nullish(),textVerbosity:me(["low","medium","high"]).nullish(),truncation:me(["auto","disabled"]).nullish(),user:p().nullish()})));async function J8({tools:e,toolChoice:t,strictJsonSchema:n}){e=e!=null&&e.length?e:void 0;const r=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:r};const o=[];for(const i of e)switch(i.type){case"function":o.push({type:"function",name:i.name,description:i.description,parameters:i.inputSchema,strict:n});break;case"provider-defined":{switch(i.id){case"openai.file_search":{const a=await Cn({value:i.args,schema:S8});o.push({type:"file_search",vector_store_ids:a.vectorStoreIds,max_num_results:a.maxNumResults,ranking_options:a.ranking?{ranker:a.ranking.ranker,score_threshold:a.ranking.scoreThreshold}:void 0,filters:a.filters});break}case"openai.local_shell":{o.push({type:"local_shell"});break}case"openai.web_search_preview":{const a=await Cn({value:i.args,schema:j8});o.push({type:"web_search_preview",search_context_size:a.searchContextSize,user_location:a.userLocation});break}case"openai.web_search":{const a=await Cn({value:i.args,schema:O8});o.push({type:"web_search",filters:a.filters!=null?{allowed_domains:a.filters.allowedDomains}:void 0,external_web_access:a.externalWebAccess,search_context_size:a.searchContextSize,user_location:a.userLocation});break}case"openai.code_interpreter":{const a=await Cn({value:i.args,schema:w8});o.push({type:"code_interpreter",container:a.container==null?{type:"auto",file_ids:void 0}:typeof a.container=="string"?a.container:{type:"auto",file_ids:a.container.fileIds}});break}case"openai.image_generation":{const a=await Cn({value:i.args,schema:k8});o.push({type:"image_generation",background:a.background,input_fidelity:a.inputFidelity,input_image_mask:a.inputImageMask?{file_id:a.inputImageMask.fileId,image_url:a.inputImageMask.imageUrl}:void 0,model:a.model,size:a.size,quality:a.quality,moderation:a.moderation,output_format:a.outputFormat,output_compression:a.outputCompression});break}}break}default:r.push({type:"unsupported-tool",tool:i});break}if(t==null)return{tools:o,toolChoice:void 0,toolWarnings:r};const s=t.type;switch(s){case"auto":case"none":case"required":return{tools:o,toolChoice:s,toolWarnings:r};case"tool":return{tools:o,toolChoice:t.toolName==="code_interpreter"||t.toolName==="file_search"||t.toolName==="image_generation"||t.toolName==="web_search_preview"||t.toolName==="web_search"?{type:t.toolName}:{type:"function",name:t.toolName},toolWarnings:r};default:{const i=s;throw new Mt({functionality:`tool choice type: ${i}`})}}}var G8=class{constructor(e,t){this.specificationVersion="v2",this.supportedUrls={"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({maxOutputTokens:e,temperature:t,stopSequences:n,topP:r,topK:o,presencePenalty:s,frequencyPenalty:i,seed:a,prompt:l,providerOptions:c,tools:u,toolChoice:h,responseFormat:_}){var f,g,v,m;const d=[],w=o7(this.modelId);o!=null&&d.push({type:"unsupported-setting",setting:"topK"}),a!=null&&d.push({type:"unsupported-setting",setting:"seed"}),s!=null&&d.push({type:"unsupported-setting",setting:"presencePenalty"}),i!=null&&d.push({type:"unsupported-setting",setting:"frequencyPenalty"}),n!=null&&d.push({type:"unsupported-setting",setting:"stopSequences"});const y=await Xt({provider:"openai",providerOptions:c,schema:H8});y!=null&&y.conversation&&(y!=null&&y.previousResponseId)&&d.push({type:"unsupported-setting",setting:"conversation",details:"conversation and previousResponseId cannot be used together"});const{input:b,warnings:k}=await Z8({prompt:l,systemMessageMode:w.systemMessageMode,fileIdPrefixes:this.config.fileIdPrefixes,store:(f=y==null?void 0:y.store)!=null?f:!0,hasLocalShellTool:U("openai.local_shell")});d.push(...k);const x=(g=y==null?void 0:y.strictJsonSchema)!=null?g:!1;let T=y==null?void 0:y.include;function D(te){T==null?T=[te]:T.includes(te)||(T=[...T,te])}function U(te){return(u==null?void 0:u.find(ue=>ue.type==="provider-defined"&&ue.id===te))!=null}const H=typeof(y==null?void 0:y.logprobs)=="number"?y==null?void 0:y.logprobs:(y==null?void 0:y.logprobs)===!0?Wf:void 0;H&&D("message.output_text.logprobs");const q=(v=u==null?void 0:u.find(te=>te.type==="provider-defined"&&(te.id==="openai.web_search"||te.id==="openai.web_search_preview")))==null?void 0:v.name;q&&D("web_search_call.action.sources"),U("openai.code_interpreter")&&D("code_interpreter_call.outputs");const F=y==null?void 0:y.store;F===!1&&w.isReasoningModel&&D("reasoning.encrypted_content");const B={model:this.modelId,input:b,temperature:t,top_p:r,max_output_tokens:e,...((_==null?void 0:_.type)==="json"||(y==null?void 0:y.textVerbosity))&&{text:{...(_==null?void 0:_.type)==="json"&&{format:_.schema!=null?{type:"json_schema",strict:x,name:(m=_.name)!=null?m:"response",description:_.description,schema:_.schema}:{type:"json_object"}},...(y==null?void 0:y.textVerbosity)&&{verbosity:y.textVerbosity}}},conversation:y==null?void 0:y.conversation,max_tool_calls:y==null?void 0:y.maxToolCalls,metadata:y==null?void 0:y.metadata,parallel_tool_calls:y==null?void 0:y.parallelToolCalls,previous_response_id:y==null?void 0:y.previousResponseId,store:F,user:y==null?void 0:y.user,instructions:y==null?void 0:y.instructions,service_tier:y==null?void 0:y.serviceTier,include:T,prompt_cache_key:y==null?void 0:y.promptCacheKey,prompt_cache_retention:y==null?void 0:y.promptCacheRetention,safety_identifier:y==null?void 0:y.safetyIdentifier,top_logprobs:H,truncation:y==null?void 0:y.truncation,...w.isReasoningModel&&((y==null?void 0:y.reasoningEffort)!=null||(y==null?void 0:y.reasoningSummary)!=null)&&{reasoning:{...(y==null?void 0:y.reasoningEffort)!=null&&{effort:y.reasoningEffort},...(y==null?void 0:y.reasoningSummary)!=null&&{summary:y.reasoningSummary}}}};w.isReasoningModel?(B.temperature!=null&&(B.temperature=void 0,d.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"})),B.top_p!=null&&(B.top_p=void 0,d.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"}))):((y==null?void 0:y.reasoningEffort)!=null&&d.push({type:"unsupported-setting",setting:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"}),(y==null?void 0:y.reasoningSummary)!=null&&d.push({type:"unsupported-setting",setting:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"})),(y==null?void 0:y.serviceTier)==="flex"&&!w.supportsFlexProcessing&&(d.push({type:"unsupported-setting",setting:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete B.service_tier),(y==null?void 0:y.serviceTier)==="priority"&&!w.supportsPriorityProcessing&&(d.push({type:"unsupported-setting",setting:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),delete B.service_tier);const{tools:V,toolChoice:se,toolWarnings:ge}=await J8({tools:u,toolChoice:h,strictJsonSchema:x});return{webSearchToolName:q,args:{...B,tools:V,tool_choice:se},warnings:[...d,...ge],store:F}}async doGenerate(e){var t,n,r,o,s,i,a,l,c,u,h,_,f,g,v,m,d,w,y,b,k,x,T,D,U,H,q,F;const{args:B,warnings:V,webSearchToolName:se}=await this.getArgs(e),ge=this.config.url({path:"/responses",modelId:this.modelId}),te=this.config.provider.replace(".responses",""),{responseHeaders:ue,value:le,rawValue:L}=await Dt({url:ge,headers:xt(this.config.headers(),e.headers),body:B,failedResponseHandler:en,successfulResponseHandler:Wn(B8),abortSignal:e.abortSignal,fetch:this.config.fetch});if(le.error)throw new Ie({message:le.error.message,url:ge,requestBodyValues:B,statusCode:400,responseHeaders:ue,responseBody:L,isRetryable:!1});const I=[],M=[];let P=!1;for(const $ of le.output)switch($.type){case"reasoning":{$.summary.length===0&&$.summary.push({type:"summary_text",text:""});for(const j of $.summary)I.push({type:"reasoning",text:j.text,providerMetadata:{[te]:{itemId:$.id,reasoningEncryptedContent:(t=$.encrypted_content)!=null?t:null}}});break}case"image_generation_call":{I.push({type:"tool-call",toolCallId:$.id,toolName:"image_generation",input:"{}",providerExecuted:!0}),I.push({type:"tool-result",toolCallId:$.id,toolName:"image_generation",result:{result:$.result},providerExecuted:!0});break}case"local_shell_call":{I.push({type:"tool-call",toolCallId:$.call_id,toolName:"local_shell",input:JSON.stringify({action:$.action}),providerMetadata:{[te]:{itemId:$.id}}});break}case"message":{for(const j of $.content){(r=(n=e.providerOptions)==null?void 0:n.openai)!=null&&r.logprobs&&j.logprobs&&M.push(j.logprobs),I.push({type:"text",text:j.text,providerMetadata:{[te]:{itemId:$.id}}});for(const z of j.annotations)z.type==="url_citation"?I.push({type:"source",sourceType:"url",id:(i=(s=(o=this.config).generateId)==null?void 0:s.call(o))!=null?i:st(),url:z.url,title:z.title}):z.type==="file_citation"?I.push({type:"source",sourceType:"document",id:(c=(l=(a=this.config).generateId)==null?void 0:l.call(a))!=null?c:st(),mediaType:"text/plain",title:(h=(u=z.quote)!=null?u:z.filename)!=null?h:"Document",filename:(_=z.filename)!=null?_:z.file_id,...z.file_id?{providerMetadata:{[te]:{fileId:z.file_id}}}:{}}):z.type==="container_file_citation"?I.push({type:"source",sourceType:"document",id:(v=(g=(f=this.config).generateId)==null?void 0:g.call(f))!=null?v:st(),mediaType:"text/plain",title:(d=(m=z.filename)!=null?m:z.file_id)!=null?d:"Document",filename:(w=z.filename)!=null?w:z.file_id,providerMetadata:{[te]:{fileId:z.file_id,containerId:z.container_id,...z.index!=null?{index:z.index}:{}}}}):z.type==="file_path"&&I.push({type:"source",sourceType:"document",id:(k=(b=(y=this.config).generateId)==null?void 0:b.call(y))!=null?k:st(),mediaType:"application/octet-stream",title:z.file_id,filename:z.file_id,providerMetadata:{[te]:{fileId:z.file_id,...z.index!=null?{index:z.index}:{}}}})}break}case"function_call":{P=!0,I.push({type:"tool-call",toolCallId:$.call_id,toolName:$.name,input:$.arguments,providerMetadata:{[te]:{itemId:$.id}}});break}case"web_search_call":{I.push({type:"tool-call",toolCallId:$.id,toolName:se??"web_search",input:JSON.stringify({}),providerExecuted:!0}),I.push({type:"tool-result",toolCallId:$.id,toolName:se??"web_search",result:Yf($.action),providerExecuted:!0});break}case"computer_call":{I.push({type:"tool-call",toolCallId:$.id,toolName:"computer_use",input:"",providerExecuted:!0}),I.push({type:"tool-result",toolCallId:$.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:$.status||"completed"},providerExecuted:!0});break}case"file_search_call":{I.push({type:"tool-call",toolCallId:$.id,toolName:"file_search",input:"{}",providerExecuted:!0}),I.push({type:"tool-result",toolCallId:$.id,toolName:"file_search",result:{queries:$.queries,results:(T=(x=$.results)==null?void 0:x.map(j=>({attributes:j.attributes,fileId:j.file_id,filename:j.filename,score:j.score,text:j.text})))!=null?T:null},providerExecuted:!0});break}case"code_interpreter_call":{I.push({type:"tool-call",toolCallId:$.id,toolName:"code_interpreter",input:JSON.stringify({code:$.code,containerId:$.container_id}),providerExecuted:!0}),I.push({type:"tool-result",toolCallId:$.id,toolName:"code_interpreter",result:{outputs:$.outputs},providerExecuted:!0});break}}const C={[te]:{...le.id!=null?{responseId:le.id}:{}}};M.length>0&&(C[te].logprobs=M),typeof le.service_tier=="string"&&(C[te].serviceTier=le.service_tier);const E=le.usage;return{content:I,finishReason:Gf({finishReason:(D=le.incomplete_details)==null?void 0:D.reason,hasFunctionCall:P}),usage:{inputTokens:E.input_tokens,outputTokens:E.output_tokens,totalTokens:E.input_tokens+E.output_tokens,reasoningTokens:(H=(U=E.output_tokens_details)==null?void 0:U.reasoning_tokens)!=null?H:void 0,cachedInputTokens:(F=(q=E.input_tokens_details)==null?void 0:q.cached_tokens)!=null?F:void 0},request:{body:B},response:{id:le.id,timestamp:new Date(le.created_at*1e3),modelId:le.model,headers:ue,body:L},providerMetadata:C,warnings:V}}async doStream(e){const{args:t,warnings:n,webSearchToolName:r,store:o}=await this.getArgs(e),{responseHeaders:s,value:i}=await Dt({url:this.config.url({path:"/responses",modelId:this.modelId}),headers:xt(this.config.headers(),e.headers),body:{...t,stream:!0},failedResponseHandler:en,successfulResponseHandler:bs(V8),abortSignal:e.abortSignal,fetch:this.config.fetch}),a=this,l=this.config.provider.replace(".responses","");let c="unknown";const u={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},h=[];let _=null;const f={},g=[];let v=!1;const m={};let d;return{stream:i.pipeThrough(new TransformStream({start(w){w.enqueue({type:"stream-start",warnings:n})},transform(w,y){var b,k,x,T,D,U,H,q,F,B,V,se,ge,te,ue,le,L,I,M,P,C,E;if(e.includeRawChunks&&y.enqueue({type:"raw",rawValue:w.rawValue}),!w.success){c="error",y.enqueue({type:"error",error:w.error});return}const $=w.value;if(Kf($))$.item.type==="function_call"?(f[$.output_index]={toolName:$.item.name,toolCallId:$.item.call_id},y.enqueue({type:"tool-input-start",id:$.item.call_id,toolName:$.item.name})):$.item.type==="web_search_call"?(f[$.output_index]={toolName:r??"web_search",toolCallId:$.item.id},y.enqueue({type:"tool-input-start",id:$.item.id,toolName:r??"web_search",providerExecuted:!0}),y.enqueue({type:"tool-input-end",id:$.item.id}),y.enqueue({type:"tool-call",toolCallId:$.item.id,toolName:r??"web_search",input:JSON.stringify({}),providerExecuted:!0})):$.item.type==="computer_call"?(f[$.output_index]={toolName:"computer_use",toolCallId:$.item.id},y.enqueue({type:"tool-input-start",id:$.item.id,toolName:"computer_use",providerExecuted:!0})):$.item.type==="code_interpreter_call"?(f[$.output_index]={toolName:"code_interpreter",toolCallId:$.item.id,codeInterpreter:{containerId:$.item.container_id}},y.enqueue({type:"tool-input-start",id:$.item.id,toolName:"code_interpreter",providerExecuted:!0}),y.enqueue({type:"tool-input-delta",id:$.item.id,delta:`{"containerId":"${$.item.container_id}","code":"`})):$.item.type==="file_search_call"?y.enqueue({type:"tool-call",toolCallId:$.item.id,toolName:"file_search",input:"{}",providerExecuted:!0}):$.item.type==="image_generation_call"?y.enqueue({type:"tool-call",toolCallId:$.item.id,toolName:"image_generation",input:"{}",providerExecuted:!0}):$.item.type==="message"?(g.splice(0,g.length),y.enqueue({type:"text-start",id:$.item.id,providerMetadata:{[l]:{itemId:$.item.id}}})):Kf($)&&$.item.type==="reasoning"&&(m[$.item.id]={encryptedContent:$.item.encrypted_content,summaryParts:{0:"active"}},y.enqueue({type:"reasoning-start",id:`${$.item.id}:0`,providerMetadata:{[l]:{itemId:$.item.id,reasoningEncryptedContent:(b=$.item.encrypted_content)!=null?b:null}}}));else if(K8($)){if($.item.type==="message")y.enqueue({type:"text-end",id:$.item.id,providerMetadata:{[l]:{itemId:$.item.id,...g.length>0&&{annotations:g}}}});else if($.item.type==="function_call")f[$.output_index]=void 0,v=!0,y.enqueue({type:"tool-input-end",id:$.item.call_id}),y.enqueue({type:"tool-call",toolCallId:$.item.call_id,toolName:$.item.name,input:$.item.arguments,providerMetadata:{[l]:{itemId:$.item.id}}});else if($.item.type==="web_search_call")f[$.output_index]=void 0,y.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:r??"web_search",result:Yf($.item.action),providerExecuted:!0});else if($.item.type==="computer_call")f[$.output_index]=void 0,y.enqueue({type:"tool-input-end",id:$.item.id}),y.enqueue({type:"tool-call",toolCallId:$.item.id,toolName:"computer_use",input:"",providerExecuted:!0}),y.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:$.item.status||"completed"},providerExecuted:!0});else if($.item.type==="file_search_call")f[$.output_index]=void 0,y.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:"file_search",result:{queries:$.item.queries,results:(x=(k=$.item.results)==null?void 0:k.map(j=>({attributes:j.attributes,fileId:j.file_id,filename:j.filename,score:j.score,text:j.text})))!=null?x:null},providerExecuted:!0});else if($.item.type==="code_interpreter_call")f[$.output_index]=void 0,y.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:"code_interpreter",result:{outputs:$.item.outputs},providerExecuted:!0});else if($.item.type==="image_generation_call")y.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:"image_generation",result:{result:$.item.result},providerExecuted:!0});else if($.item.type==="local_shell_call")f[$.output_index]=void 0,y.enqueue({type:"tool-call",toolCallId:$.item.call_id,toolName:"local_shell",input:JSON.stringify({action:{type:"exec",command:$.item.action.command,timeoutMs:$.item.action.timeout_ms,user:$.item.action.user,workingDirectory:$.item.action.working_directory,env:$.item.action.env}}),providerMetadata:{[l]:{itemId:$.item.id}}});else if($.item.type==="reasoning"){const j=m[$.item.id],z=Object.entries(j.summaryParts).filter(([de,oe])=>oe==="active"||oe==="can-conclude").map(([de])=>de);for(const de of z)y.enqueue({type:"reasoning-end",id:`${$.item.id}:${de}`,providerMetadata:{[l]:{itemId:$.item.id,reasoningEncryptedContent:(T=$.item.encrypted_content)!=null?T:null}}});delete m[$.item.id]}}else if(X8($)){const j=f[$.output_index];j!=null&&y.enqueue({type:"tool-input-delta",id:j.toolCallId,delta:$.delta})}else if(e7($)){const j=f[$.output_index];j!=null&&y.enqueue({type:"tool-input-delta",id:j.toolCallId,delta:JSON.stringify($.delta).slice(1,-1)})}else if(t7($)){const j=f[$.output_index];j!=null&&(y.enqueue({type:"tool-input-delta",id:j.toolCallId,delta:'"}'}),y.enqueue({type:"tool-input-end",id:j.toolCallId}),y.enqueue({type:"tool-call",toolCallId:j.toolCallId,toolName:"code_interpreter",input:JSON.stringify({code:$.code,containerId:j.codeInterpreter.containerId}),providerExecuted:!0}))}else if(Q8($))_=$.response.id,y.enqueue({type:"response-metadata",id:$.response.id,timestamp:new Date($.response.created_at*1e3),modelId:$.response.model});else if(W8($))y.enqueue({type:"text-delta",id:$.item_id,delta:$.delta}),(U=(D=e.providerOptions)==null?void 0:D.openai)!=null&&U.logprobs&&$.logprobs&&h.push($.logprobs);else if($.type==="response.reasoning_summary_part.added"){if($.summary_index>0){const j=m[$.item_id];j.summaryParts[$.summary_index]="active";for(const z of Object.keys(j.summaryParts))j.summaryParts[z]==="can-conclude"&&(y.enqueue({type:"reasoning-end",id:`${$.item_id}:${z}`,providerMetadata:{[l]:{itemId:$.item_id}}}),j.summaryParts[z]="concluded");y.enqueue({type:"reasoning-start",id:`${$.item_id}:${$.summary_index}`,providerMetadata:{[l]:{itemId:$.item_id,reasoningEncryptedContent:(q=(H=m[$.item_id])==null?void 0:H.encryptedContent)!=null?q:null}}})}}else $.type==="response.reasoning_summary_text.delta"?y.enqueue({type:"reasoning-delta",id:`${$.item_id}:${$.summary_index}`,delta:$.delta,providerMetadata:{[l]:{itemId:$.item_id}}}):$.type==="response.reasoning_summary_part.done"?o?(y.enqueue({type:"reasoning-end",id:`${$.item_id}:${$.summary_index}`,providerMetadata:{[l]:{itemId:$.item_id}}}),m[$.item_id].summaryParts[$.summary_index]="concluded"):m[$.item_id].summaryParts[$.summary_index]="can-conclude":Y8($)?(c=Gf({finishReason:(F=$.response.incomplete_details)==null?void 0:F.reason,hasFunctionCall:v}),u.inputTokens=$.response.usage.input_tokens,u.outputTokens=$.response.usage.output_tokens,u.totalTokens=$.response.usage.input_tokens+$.response.usage.output_tokens,u.reasoningTokens=(V=(B=$.response.usage.output_tokens_details)==null?void 0:B.reasoning_tokens)!=null?V:void 0,u.cachedInputTokens=(ge=(se=$.response.usage.input_tokens_details)==null?void 0:se.cached_tokens)!=null?ge:void 0,typeof $.response.service_tier=="string"&&(d=$.response.service_tier)):n7($)?(g.push($.annotation),$.annotation.type==="url_citation"?y.enqueue({type:"source",sourceType:"url",id:(le=(ue=(te=a.config).generateId)==null?void 0:ue.call(te))!=null?le:st(),url:$.annotation.url,title:$.annotation.title}):$.annotation.type==="file_citation"&&y.enqueue({type:"source",sourceType:"document",id:(M=(I=(L=a.config).generateId)==null?void 0:I.call(L))!=null?M:st(),mediaType:"text/plain",title:(C=(P=$.annotation.quote)!=null?P:$.annotation.filename)!=null?C:"Document",filename:(E=$.annotation.filename)!=null?E:$.annotation.file_id,...$.annotation.file_id?{providerMetadata:{[l]:{fileId:$.annotation.file_id}}}:{}})):r7($)&&y.enqueue({type:"error",error:$})},flush(w){const y={[l]:{responseId:_}};h.length>0&&(y[l].logprobs=h),d!==void 0&&(y[l].serviceTier=d),w.enqueue({type:"finish",finishReason:c,usage:u,providerMetadata:y})}})),request:{body:t},response:{headers:s}}}};function W8(e){return e.type==="response.output_text.delta"}function K8(e){return e.type==="response.output_item.done"}function Y8(e){return e.type==="response.completed"||e.type==="response.incomplete"}function Q8(e){return e.type==="response.created"}function X8(e){return e.type==="response.function_call_arguments.delta"}function e7(e){return e.type==="response.code_interpreter_call_code.delta"}function t7(e){return e.type==="response.code_interpreter_call_code.done"}function Kf(e){return e.type==="response.output_item.added"}function n7(e){return e.type==="response.output_text.annotation.added"}function r7(e){return e.type==="error"}function o7(e){const t=e.startsWith("o3")||e.startsWith("o4-mini")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-chat"),n=e.startsWith("gpt-4")||e.startsWith("gpt-5-mini")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-nano")&&!e.startsWith("gpt-5-chat")||e.startsWith("o3")||e.startsWith("o4-mini"),r={systemMessageMode:"system",supportsFlexProcessing:t,supportsPriorityProcessing:n};return e.startsWith("gpt-5-chat")?{...r,isReasoningModel:!1}:e.startsWith("o")||e.startsWith("gpt-5")||e.startsWith("codex-")||e.startsWith("computer-use")?{...r,isReasoningModel:!0,systemMessageMode:"developer"}:{...r,isReasoningModel:!1}}function Yf(e){var t;switch(e.type){case"search":return{action:{type:"search",query:(t=e.query)!=null?t:void 0},...e.sources!=null&&{sources:e.sources}};case"open_page":return{action:{type:"openPage",url:e.url}};case"find":return{action:{type:"find",url:e.url,pattern:e.pattern}}}}var s7=it(()=>we(S({instructions:p().nullish(),speed:R().min(.25).max(4).default(1).nullish()}))),i7=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2"}get provider(){return this.config.provider}async getArgs({text:e,voice:t="alloy",outputFormat:n="mp3",speed:r,instructions:o,language:s,providerOptions:i}){const a=[],l=await Xt({provider:"openai",providerOptions:i,schema:s7}),c={model:this.modelId,input:e,voice:t,response_format:"mp3",speed:r,instructions:o};if(n&&(["mp3","opus","aac","flac","wav","pcm"].includes(n)?c.response_format=n:a.push({type:"unsupported-setting",setting:"outputFormat",details:`Unsupported output format: ${n}. Using mp3 instead.`})),l){const u={};for(const h in u){const _=u[h];_!==void 0&&(c[h]=_)}}return s&&a.push({type:"unsupported-setting",setting:"language",details:`OpenAI speech models do not support language selection. Language parameter "${s}" was ignored.`}),{requestBody:c,warnings:a}}async doGenerate(e){var t,n,r;const o=(r=(n=(t=this.config._internal)==null?void 0:t.currentDate)==null?void 0:n.call(t))!=null?r:new Date,{requestBody:s,warnings:i}=await this.getArgs(e),{value:a,responseHeaders:l,rawValue:c}=await Dt({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:xt(this.config.headers(),e.headers),body:s,failedResponseHandler:en,successfulResponseHandler:t5(),abortSignal:e.abortSignal,fetch:this.config.fetch});return{audio:a,warnings:i,request:{body:JSON.stringify(s)},response:{timestamp:o,modelId:this.modelId,headers:l,body:c}}}},a7=it(()=>we(S({text:p(),language:p().nullish(),duration:R().nullish(),words:N(S({word:p(),start:R(),end:R()})).nullish(),segments:N(S({id:R(),seek:R(),start:R(),end:R(),text:p(),tokens:N(R()),temperature:R(),avg_logprob:R(),compression_ratio:R(),no_speech_prob:R()})).nullish()}))),l7=it(()=>we(S({include:N(p()).optional(),language:p().optional(),prompt:p().optional(),temperature:R().min(0).max(1).default(0).optional(),timestampGranularities:N(me(["word","segment"])).default(["segment"]).optional()}))),Qf={afrikaans:"af",arabic:"ar",armenian:"hy",azerbaijani:"az",belarusian:"be",bosnian:"bs",bulgarian:"bg",catalan:"ca",chinese:"zh",croatian:"hr",czech:"cs",danish:"da",dutch:"nl",english:"en",estonian:"et",finnish:"fi",french:"fr",galician:"gl",german:"de",greek:"el",hebrew:"he",hindi:"hi",hungarian:"hu",icelandic:"is",indonesian:"id",italian:"it",japanese:"ja",kannada:"kn",kazakh:"kk",korean:"ko",latvian:"lv",lithuanian:"lt",macedonian:"mk",malay:"ms",marathi:"mr",maori:"mi",nepali:"ne",norwegian:"no",persian:"fa",polish:"pl",portuguese:"pt",romanian:"ro",russian:"ru",serbian:"sr",slovak:"sk",slovenian:"sl",spanish:"es",swahili:"sw",swedish:"sv",tagalog:"tl",tamil:"ta",thai:"th",turkish:"tr",ukrainian:"uk",urdu:"ur",vietnamese:"vi",welsh:"cy"},c7=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2"}get provider(){return this.config.provider}async getArgs({audio:e,mediaType:t,providerOptions:n}){const r=[],o=await Xt({provider:"openai",providerOptions:n,schema:l7}),s=new FormData,i=e instanceof Uint8Array?new Blob([e]):new Blob([W5(e)]);s.append("model",this.modelId);const a=F6(t);if(s.append("file",new File([i],"audio",{type:t}),`audio.${a}`),o){const l={include:o.include,language:o.language,prompt:o.prompt,response_format:["gpt-4o-transcribe","gpt-4o-mini-transcribe"].includes(this.modelId)?"json":"verbose_json",temperature:o.temperature,timestamp_granularities:o.timestampGranularities};for(const[c,u]of Object.entries(l))if(u!=null)if(Array.isArray(u))for(const h of u)s.append(`${c}[]`,String(h));else s.append(c,String(u))}return{formData:s,warnings:r}}async doGenerate(e){var t,n,r,o,s,i,a,l;const c=(r=(n=(t=this.config._internal)==null?void 0:t.currentDate)==null?void 0:n.call(t))!=null?r:new Date,{formData:u,warnings:h}=await this.getArgs(e),{value:_,responseHeaders:f,rawValue:g}=await e5({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:xt(this.config.headers(),e.headers),formData:u,failedResponseHandler:en,successfulResponseHandler:Wn(a7),abortSignal:e.abortSignal,fetch:this.config.fetch}),v=_.language!=null&&_.language in Qf?Qf[_.language]:void 0;return{text:_.text,segments:(a=(i=(o=_.segments)==null?void 0:o.map(m=>({text:m.text,startSecond:m.start,endSecond:m.end})))!=null?i:(s=_.words)==null?void 0:s.map(m=>({text:m.word,startSecond:m.start,endSecond:m.end})))!=null?a:[],language:v,durationInSeconds:(l=_.duration)!=null?l:void 0,warnings:h,response:{timestamp:c,modelId:this.modelId,headers:f,body:g}}}},u7="2.0.75";function Xf(e={}){var t,n;const r=(t=jf(Z6({settingValue:e.baseURL,environmentVariableName:"OPENAI_BASE_URL"})))!=null?t:"https://api.openai.com/v1",o=(n=e.name)!=null?n:"openai",s=()=>Va({Authorization:`Bearer ${Ef({apiKey:e.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":e.organization,"OpenAI-Project":e.project,...e.headers},`ai-sdk/openai/${u7}`),i=v=>new n8(v,{provider:`${o}.chat`,url:({path:m})=>`${r}${m}`,headers:s,fetch:e.fetch}),a=v=>new u8(v,{provider:`${o}.completion`,url:({path:m})=>`${r}${m}`,headers:s,fetch:e.fetch}),l=v=>new f8(v,{provider:`${o}.embedding`,url:({path:m})=>`${r}${m}`,headers:s,fetch:e.fetch}),c=v=>new v8(v,{provider:`${o}.image`,url:({path:m})=>`${r}${m}`,headers:s,fetch:e.fetch}),u=v=>new c7(v,{provider:`${o}.transcription`,url:({path:m})=>`${r}${m}`,headers:s,fetch:e.fetch}),h=v=>new i7(v,{provider:`${o}.speech`,url:({path:m})=>`${r}${m}`,headers:s,fetch:e.fetch}),_=v=>{if(new.target)throw new Error("The OpenAI model function cannot be called with the new keyword.");return f(v)},f=v=>new G8(v,{provider:`${o}.responses`,url:({path:m})=>`${r}${m}`,headers:s,fetch:e.fetch,fileIdPrefixes:["file-"]}),g=function(v){return _(v)};return g.languageModel=_,g.chat=i,g.completion=a,g.responses=f,g.embedding=l,g.textEmbedding=l,g.textEmbeddingModel=l,g.image=c,g.imageModel=c,g.transcription=u,g.transcriptionModel=u,g.speech=h,g.speechModel=h,g.tools=q8,g}Xf();function lo(e){var t,n;return(n=(t=e==null?void 0:e.providerOptions)==null?void 0:t.openaiCompatible)!=null?n:{}}function d7(e){const t=[];for(const{role:n,content:r,...o}of e){const s=lo({...o});switch(n){case"system":{t.push({role:"system",content:r,...s});break}case"user":{if(r.length===1&&r[0].type==="text"){t.push({role:"user",content:r[0].text,...lo(r[0])});break}t.push({role:"user",content:r.map(i=>{const a=lo(i);switch(i.type){case"text":return{type:"text",text:i.text,...a};case"file":if(i.mediaType.startsWith("image/")){const l=i.mediaType==="image/*"?"image/jpeg":i.mediaType;return{type:"image_url",image_url:{url:i.data instanceof URL?i.data.toString():`data:${l};base64,${Kn(i.data)}`},...a}}else throw new Mt({functionality:`file part media type ${i.mediaType}`})}}),...s});break}case"assistant":{let i="";const a=[];for(const l of r){const c=lo(l);switch(l.type){case"text":{i+=l.text;break}case"tool-call":{a.push({id:l.toolCallId,type:"function",function:{name:l.toolName,arguments:JSON.stringify(l.input)},...c});break}}}t.push({role:"assistant",content:i,tool_calls:a.length>0?a:void 0,...s});break}case"tool":{for(const i of r){const a=i.output;let l;switch(a.type){case"text":case"error-text":l=a.value;break;case"content":case"json":case"error-json":l=JSON.stringify(a.value);break}const c=lo(i);t.push({role:"tool",tool_call_id:i.toolCallId,content:l,...c})}break}default:{const i=n;throw new Error(`Unsupported role: ${i}`)}}}return t}function eh({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n!=null?new Date(n*1e3):void 0}}function th(e){switch(e){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"unknown"}}var Ya=S({user:p().optional(),reasoningEffort:p().optional(),textVerbosity:p().optional()}),p7=S({error:S({message:p(),type:p().nullish(),param:yt().nullish(),code:Q([p(),R()]).nullish()})}),f7={errorSchema:p7,errorToMessage:e=>e.error.message};function h7({tools:e,toolChoice:t}){e=e!=null&&e.length?e:void 0;const n=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:n};const r=[];for(const s of e)s.type==="provider-defined"?n.push({type:"unsupported-tool",tool:s}):r.push({type:"function",function:{name:s.name,description:s.description,parameters:s.inputSchema}});if(t==null)return{tools:r,toolChoice:void 0,toolWarnings:n};const o=t.type;switch(o){case"auto":case"none":case"required":return{tools:r,toolChoice:o,toolWarnings:n};case"tool":return{tools:r,toolChoice:{type:"function",function:{name:t.toolName}},toolWarnings:n};default:{const s=o;throw new Mt({functionality:`tool choice type: ${s}`})}}}var m7=class{constructor(e,t){this.specificationVersion="v2";var n,r;this.modelId=e,this.config=t;const o=(n=t.errorStructure)!=null?n:f7;this.chunkSchema=v7(o.errorSchema),this.failedResponseHandler=xf(o),this.supportsStructuredOutputs=(r=t.supportsStructuredOutputs)!=null?r:!1}get provider(){return this.config.provider}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get supportedUrls(){var e,t,n;return(n=(t=(e=this.config).supportedUrls)==null?void 0:t.call(e))!=null?n:{}}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:o,frequencyPenalty:s,presencePenalty:i,providerOptions:a,stopSequences:l,responseFormat:c,seed:u,toolChoice:h,tools:_}){var f,g,v,m;const d=[],w=Object.assign((f=await Xt({provider:"openai-compatible",providerOptions:a,schema:Ya}))!=null?f:{},(g=await Xt({provider:this.providerOptionsName,providerOptions:a,schema:Ya}))!=null?g:{});o!=null&&d.push({type:"unsupported-setting",setting:"topK"}),(c==null?void 0:c.type)==="json"&&c.schema!=null&&!this.supportsStructuredOutputs&&d.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{tools:y,toolChoice:b,toolWarnings:k}=h7({tools:_,toolChoice:h});return{args:{model:this.modelId,user:w.user,max_tokens:t,temperature:n,top_p:r,frequency_penalty:s,presence_penalty:i,response_format:(c==null?void 0:c.type)==="json"?this.supportsStructuredOutputs===!0&&c.schema!=null?{type:"json_schema",json_schema:{schema:c.schema,name:(v=c.name)!=null?v:"response",description:c.description}}:{type:"json_object"}:void 0,stop:l,seed:u,...Object.fromEntries(Object.entries((m=a==null?void 0:a[this.providerOptionsName])!=null?m:{}).filter(([x])=>!Object.keys(Ya.shape).includes(x))),reasoning_effort:w.reasoningEffort,verbosity:w.textVerbosity,messages:d7(e),tools:y,tool_choice:b},warnings:[...d,...k]}}async doGenerate(e){var t,n,r,o,s,i,a,l,c,u,h,_,f,g,v,m,d;const{args:w,warnings:y}=await this.getArgs({...e}),b=JSON.stringify(w),{responseHeaders:k,value:x,rawValue:T}=await Dt({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:xt(this.config.headers(),e.headers),body:w,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:Wn(g7),abortSignal:e.abortSignal,fetch:this.config.fetch}),D=x.choices[0],U=[],H=D.message.content;H!=null&&H.length>0&&U.push({type:"text",text:H});const q=(t=D.message.reasoning_content)!=null?t:D.message.reasoning;if(q!=null&&q.length>0&&U.push({type:"reasoning",text:q}),D.message.tool_calls!=null)for(const V of D.message.tool_calls)U.push({type:"tool-call",toolCallId:(n=V.id)!=null?n:st(),toolName:V.function.name,input:V.function.arguments});const F={[this.providerOptionsName]:{},...await((o=(r=this.config.metadataExtractor)==null?void 0:r.extractMetadata)==null?void 0:o.call(r,{parsedBody:T}))},B=(s=x.usage)==null?void 0:s.completion_tokens_details;return(B==null?void 0:B.accepted_prediction_tokens)!=null&&(F[this.providerOptionsName].acceptedPredictionTokens=B==null?void 0:B.accepted_prediction_tokens),(B==null?void 0:B.rejected_prediction_tokens)!=null&&(F[this.providerOptionsName].rejectedPredictionTokens=B==null?void 0:B.rejected_prediction_tokens),{content:U,finishReason:th(D.finish_reason),usage:{inputTokens:(a=(i=x.usage)==null?void 0:i.prompt_tokens)!=null?a:void 0,outputTokens:(c=(l=x.usage)==null?void 0:l.completion_tokens)!=null?c:void 0,totalTokens:(h=(u=x.usage)==null?void 0:u.total_tokens)!=null?h:void 0,reasoningTokens:(g=(f=(_=x.usage)==null?void 0:_.completion_tokens_details)==null?void 0:f.reasoning_tokens)!=null?g:void 0,cachedInputTokens:(d=(m=(v=x.usage)==null?void 0:v.prompt_tokens_details)==null?void 0:m.cached_tokens)!=null?d:void 0},providerMetadata:F,request:{body:b},response:{...eh(x),headers:k,body:T},warnings:y}}async doStream(e){var t;const{args:n,warnings:r}=await this.getArgs({...e}),o={...n,stream:!0,stream_options:this.config.includeUsage?{include_usage:!0}:void 0},s=(t=this.config.metadataExtractor)==null?void 0:t.createStreamExtractor(),{responseHeaders:i,value:a}=await Dt({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:xt(this.config.headers(),e.headers),body:o,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:bs(this.chunkSchema),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=[];let c="unknown";const u={completionTokens:void 0,completionTokensDetails:{reasoningTokens:void 0,acceptedPredictionTokens:void 0,rejectedPredictionTokens:void 0},promptTokens:void 0,promptTokensDetails:{cachedTokens:void 0},totalTokens:void 0};let h=!0;const _=this.providerOptionsName;let f=!1,g=!1;return{stream:a.pipeThrough(new TransformStream({start(v){v.enqueue({type:"stream-start",warnings:r})},transform(v,m){var d,w,y,b,k,x,T,D,U,H,q,F,B;if(e.includeRawChunks&&m.enqueue({type:"raw",rawValue:v.rawValue}),!v.success){c="error",m.enqueue({type:"error",error:v.error});return}const V=v.value;if(s==null||s.processChunk(v.rawValue),"error"in V){c="error",m.enqueue({type:"error",error:V.error.message});return}if(h&&(h=!1,m.enqueue({type:"response-metadata",...eh(V)})),V.usage!=null){const{prompt_tokens:ue,completion_tokens:le,total_tokens:L,prompt_tokens_details:I,completion_tokens_details:M}=V.usage;u.promptTokens=ue??void 0,u.completionTokens=le??void 0,u.totalTokens=L??void 0,(M==null?void 0:M.reasoning_tokens)!=null&&(u.completionTokensDetails.reasoningTokens=M==null?void 0:M.reasoning_tokens),(M==null?void 0:M.accepted_prediction_tokens)!=null&&(u.completionTokensDetails.acceptedPredictionTokens=M==null?void 0:M.accepted_prediction_tokens),(M==null?void 0:M.rejected_prediction_tokens)!=null&&(u.completionTokensDetails.rejectedPredictionTokens=M==null?void 0:M.rejected_prediction_tokens),(I==null?void 0:I.cached_tokens)!=null&&(u.promptTokensDetails.cachedTokens=I==null?void 0:I.cached_tokens)}const se=V.choices[0];if((se==null?void 0:se.finish_reason)!=null&&(c=th(se.finish_reason)),(se==null?void 0:se.delta)==null)return;const ge=se.delta,te=(d=ge.reasoning_content)!=null?d:ge.reasoning;if(te&&(f||(m.enqueue({type:"reasoning-start",id:"reasoning-0"}),f=!0),m.enqueue({type:"reasoning-delta",id:"reasoning-0",delta:te})),ge.content&&(g||(m.enqueue({type:"text-start",id:"txt-0"}),g=!0),m.enqueue({type:"text-delta",id:"txt-0",delta:ge.content})),ge.tool_calls!=null)for(const ue of ge.tool_calls){const le=ue.index;if(l[le]==null){if(ue.id==null)throw new Ar({data:ue,message:"Expected 'id' to be a string."});if(((w=ue.function)==null?void 0:w.name)==null)throw new Ar({data:ue,message:"Expected 'function.name' to be a string."});m.enqueue({type:"tool-input-start",id:ue.id,toolName:ue.function.name}),l[le]={id:ue.id,type:"function",function:{name:ue.function.name,arguments:(y=ue.function.arguments)!=null?y:""},hasFinished:!1};const I=l[le];((b=I.function)==null?void 0:b.name)!=null&&((k=I.function)==null?void 0:k.arguments)!=null&&(I.function.arguments.length>0&&m.enqueue({type:"tool-input-delta",id:I.id,delta:I.function.arguments}),ws(I.function.arguments)&&(m.enqueue({type:"tool-input-end",id:I.id}),m.enqueue({type:"tool-call",toolCallId:(x=I.id)!=null?x:st(),toolName:I.function.name,input:I.function.arguments}),I.hasFinished=!0));continue}const L=l[le];L.hasFinished||(((T=ue.function)==null?void 0:T.arguments)!=null&&(L.function.arguments+=(U=(D=ue.function)==null?void 0:D.arguments)!=null?U:""),m.enqueue({type:"tool-input-delta",id:L.id,delta:(H=ue.function.arguments)!=null?H:""}),((q=L.function)==null?void 0:q.name)!=null&&((F=L.function)==null?void 0:F.arguments)!=null&&ws(L.function.arguments)&&(m.enqueue({type:"tool-input-end",id:L.id}),m.enqueue({type:"tool-call",toolCallId:(B=L.id)!=null?B:st(),toolName:L.function.name,input:L.function.arguments}),L.hasFinished=!0))}},flush(v){var m,d,w,y,b,k;f&&v.enqueue({type:"reasoning-end",id:"reasoning-0"}),g&&v.enqueue({type:"text-end",id:"txt-0"});for(const T of l.filter(D=>!D.hasFinished))v.enqueue({type:"tool-input-end",id:T.id}),v.enqueue({type:"tool-call",toolCallId:(m=T.id)!=null?m:st(),toolName:T.function.name,input:T.function.arguments});const x={[_]:{},...s==null?void 0:s.buildMetadata()};u.completionTokensDetails.acceptedPredictionTokens!=null&&(x[_].acceptedPredictionTokens=u.completionTokensDetails.acceptedPredictionTokens),u.completionTokensDetails.rejectedPredictionTokens!=null&&(x[_].rejectedPredictionTokens=u.completionTokensDetails.rejectedPredictionTokens),v.enqueue({type:"finish",finishReason:c,usage:{inputTokens:(d=u.promptTokens)!=null?d:void 0,outputTokens:(w=u.completionTokens)!=null?w:void 0,totalTokens:(y=u.totalTokens)!=null?y:void 0,reasoningTokens:(b=u.completionTokensDetails.reasoningTokens)!=null?b:void 0,cachedInputTokens:(k=u.promptTokensDetails.cachedTokens)!=null?k:void 0},providerMetadata:x})}})),request:{body:o},response:{headers:i}}}},nh=S({prompt_tokens:R().nullish(),completion_tokens:R().nullish(),total_tokens:R().nullish(),prompt_tokens_details:S({cached_tokens:R().nullish()}).nullish(),completion_tokens_details:S({reasoning_tokens:R().nullish(),accepted_prediction_tokens:R().nullish(),rejected_prediction_tokens:R().nullish()}).nullish()}).nullish(),g7=S({id:p().nullish(),created:R().nullish(),model:p().nullish(),choices:N(S({message:S({role:O("assistant").nullish(),content:p().nullish(),reasoning_content:p().nullish(),reasoning:p().nullish(),tool_calls:N(S({id:p().nullish(),function:S({name:p(),arguments:p()})})).nullish()}),finish_reason:p().nullish()})),usage:nh}),v7=e=>Q([S({id:p().nullish(),created:R().nullish(),model:p().nullish(),choices:N(S({delta:S({role:me(["assistant"]).nullish(),content:p().nullish(),reasoning_content:p().nullish(),reasoning:p().nullish(),tool_calls:N(S({index:R(),id:p().nullish(),function:S({name:p().nullish(),arguments:p().nullish()})})).nullish()}).nullish(),finish_reason:p().nullish()})),usage:nh}),e]);S({echo:ne().optional(),logitBias:ie(p(),R()).optional(),suffix:p().optional(),user:p().optional()});var _7=S({prompt_tokens:R(),completion_tokens:R(),total_tokens:R()});S({id:p().nullish(),created:R().nullish(),model:p().nullish(),choices:N(S({text:p(),finish_reason:p()})),usage:_7.nullish()}),S({dimensions:R().optional(),user:p().optional()}),S({data:N(S({embedding:N(R())})),usage:S({prompt_tokens:R()}).nullish(),providerMetadata:ie(p(),ie(p(),yt())).optional()}),S({data:N(S({b64_json:p()}))});var rh=e=>{var t,n;return e==null?void 0:{deepseek:{promptCacheHitTokens:(t=e.prompt_cache_hit_tokens)!=null?t:NaN,promptCacheMissTokens:(n=e.prompt_cache_miss_tokens)!=null?n:NaN}}},y7={extractMetadata:async({parsedBody:e})=>{const t=await ao({value:e,schema:w7});return!t.success||t.value.usage==null?void 0:rh(t.value.usage)},createStreamExtractor:()=>{let e;return{processChunk:async t=>{var n,r;const o=await ao({value:t,schema:b7});o.success&&((r=(n=o.value.choices)==null?void 0:n[0])==null?void 0:r.finish_reason)==="stop"&&o.value.usage&&(e=o.value.usage)},buildMetadata:()=>rh(e)}}},oh=S({prompt_cache_hit_tokens:R().nullish(),prompt_cache_miss_tokens:R().nullish()}),w7=S({usage:oh.nullish()}),b7=S({choices:N(S({finish_reason:p().nullish()})).nullish(),usage:oh.nullish()}),$7="1.0.30";function sh(e={}){var t;const n=jf((t=e.baseURL)!=null?t:"https://api.deepseek.com/v1"),r=()=>Va({Authorization:`Bearer ${Ef({apiKey:e.apiKey,environmentVariableName:"DEEPSEEK_API_KEY",description:"DeepSeek API key"})}`,...e.headers},`ai-sdk/deepseek/${$7}`);class o extends m7{addJsonInstruction(l){var c;if(((c=l.responseFormat)==null?void 0:c.type)!=="json")return l;const _=[...Array.isArray(l.prompt)?l.prompt:[],{role:"user",content:[{type:"text",text:"Return ONLY a valid JSON object."}]}];return{...l,prompt:_}}async doGenerate(l){return super.doGenerate(this.addJsonInstruction(l))}async doStream(l){return super.doStream(this.addJsonInstruction(l))}}const s=a=>new o(a,{provider:"deepseek.chat",url:({path:l})=>`${n}${l}`,headers:r,fetch:e.fetch,metadataExtractor:y7}),i=a=>s(a);return i.languageModel=s,i.chat=s,i.textEmbeddingModel=a=>{throw new _i({modelId:a,modelType:"textEmbeddingModel"})},i.imageModel=a=>{throw new _i({modelId:a,modelType:"imageModel"})},i}sh();const S7=(e,t,n)=>{if(n.endsWith("content"))chrome.tabs.query({},r=>{r.forEach(o=>{chrome.tabs.sendMessage(o.id,{type:e,data:t,direction:n,tabId:o.id})})});else return chrome.runtime.sendMessage({direction:n,type:e,data:t})},C7=(e,t,n,r)=>{const o=(s,i,a)=>{if(s.type===e&&s.direction===n){const{data:l}=s;t(l,i,a),a(i)}};return chrome.runtime.onMessage.addListener(o),()=>chrome.runtime.onMessage.removeListener(o)};class E7{constructor(t){this._isStarted=!1,this._isClosed=!1,this.targetSessionId=t,this._messageListener=C7("mcp-server-to-client",n=>{var r;try{if(n.sessionId!==this.targetSessionId)return;const o=Hn.parse(n.mcpMessage);(r=this.onmessage)==null||r.call(this,o)}catch(o){console.log("【Client Transport】处理server消息错误:",o)}},"content->side")}_throwError(t,n){if(t()){const r=new Error(n);throw console.log(n,r),this.onerror&&this.onerror(r),r}}async start(){this._throwError(()=>this._isClosed,"【Client Transport】 未启动,无法重新启动"),this._isStarted=!0}async send(t,n){this._throwError(()=>!this._isStarted,"【Client Transport】 未启动,无法发送消息"),this._throwError(()=>this._isClosed,"【Client Transport】 已关闭,无法发送消息");const r=chrome.sessionRegistry.get(this.targetSessionId);this._throwError(()=>!r,`【Client Transport】sessionRegistry中未找到${this.targetSessionId}`);const o=r.tabIds[r.tabIds.length-1];S7("mcp-client-to-server",{sessionId:this.targetSessionId,tabId:o,mcpMessage:t},"side->content")}async close(){if(!this._isClosed)try{this._isClosed=!0,this._isStarted=!1,this._messageListener&&this._messageListener(),this.onclose&&this.onclose()}catch{this._throwError(()=>!0,"【Client Transport】 关闭时发生错误")}}}function $s(e){return!!e._zod}function Ss(e,t){return $s(e)?Eu(e,t):e.safeParse(t)}function ih(e){var t,n;if(!e)return;let r;if($s(e)?r=(n=(t=e._zod)===null||t===void 0?void 0:t.def)===null||n===void 0?void 0:n.shape:r=e.shape,!!r){if(typeof r=="function")try{return r()}catch{return}return r}}function k7(e){var t;if($s(e)){const i=(t=e._zod)===null||t===void 0?void 0:t.def;if(i){if(i.value!==void 0)return i.value;if(Array.isArray(i.values)&&i.values.length>0)return i.values[0]}}const r=e._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}const o=e.value;if(o!==void 0)return o}new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function ah(e){const t=ih(e),n=t==null?void 0:t.method;if(!n)throw new Error("Schema is missing a method literal");const r=k7(n);if(typeof r!="string")throw new Error("Schema method literal must be a string");return r}function lh(e,t){const n=Ss(e,t);if(!n.success)throw n.error;return n.data}const I7=6e4;class T7{constructor(t){this._options=t,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this.setNotificationHandler(va,n=>{const r=this._requestHandlerAbortControllers.get(n.params.requestId);r==null||r.abort(n.params.reason)}),this.setNotificationHandler(ya,n=>{this._onprogress(n)}),this.setRequestHandler(_a,n=>({}))}_setupTimeout(t,n,r,o,s=!1){this._timeoutInfo.set(t,{timeoutId:setTimeout(o,n),startTime:Date.now(),timeout:n,maxTotalTimeout:r,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(t){const n=this._timeoutInfo.get(t);if(!n)return!1;const r=Date.now()-n.startTime;if(n.maxTotalTimeout&&r>=n.maxTotalTimeout)throw this._timeoutInfo.delete(t),ot.fromError(Xe.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:n.maxTotalTimeout,totalElapsed:r});return clearTimeout(n.timeoutId),n.timeoutId=setTimeout(n.onTimeout,n.timeout),!0}_cleanupTimeout(t){const n=this._timeoutInfo.get(t);n&&(clearTimeout(n.timeoutId),this._timeoutInfo.delete(t))}async connect(t){var n,r,o;this._transport=t;const s=(n=this.transport)===null||n===void 0?void 0:n.onclose;this._transport.onclose=()=>{s==null||s(),this._onclose()};const i=(r=this.transport)===null||r===void 0?void 0:r.onerror;this._transport.onerror=l=>{i==null||i(l),this._onerror(l)};const a=(o=this._transport)===null||o===void 0?void 0:o.onmessage;this._transport.onmessage=(l,c)=>{a==null||a(l,c),ga(l)||F9(l)?this._onresponse(l):Up(l)?this._onrequest(l,c):Z9(l)?this._onnotification(l):this._onerror(new Error(`Unknown message type: ${JSON.stringify(l)}`))},await this._transport.start()}_onclose(){var t;const n=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear(),this._transport=void 0,(t=this.onclose)===null||t===void 0||t.call(this);const r=ot.fromError(Xe.ConnectionClosed,"Connection closed");for(const o of n.values())o(r)}_onerror(t){var n;(n=this.onerror)===null||n===void 0||n.call(this,t)}_onnotification(t){var n;const r=(n=this._notificationHandlers.get(t.method))!==null&&n!==void 0?n:this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(t)).catch(o=>this._onerror(new Error(`Uncaught error in notification handler: ${o}`)))}_onrequest(t,n){var r,o;const s=(r=this._requestHandlers.get(t.method))!==null&&r!==void 0?r:this.fallbackRequestHandler,i=this._transport;if(s===void 0){i==null||i.send({jsonrpc:"2.0",id:t.id,error:{code:Xe.MethodNotFound,message:"Method not found"}}).catch(c=>this._onerror(new Error(`Failed to send an error response: ${c}`)));return}const a=new AbortController;this._requestHandlerAbortControllers.set(t.id,a);const l={signal:a.signal,sessionId:i==null?void 0:i.sessionId,_meta:(o=t.params)===null||o===void 0?void 0:o._meta,sendNotification:c=>this.notification(c,{relatedRequestId:t.id}),sendRequest:(c,u,h)=>this.request(c,u,{...h,relatedRequestId:t.id}),authInfo:n==null?void 0:n.authInfo,requestId:t.id,requestInfo:n==null?void 0:n.requestInfo};Promise.resolve().then(()=>s(t,l)).then(c=>{if(!a.signal.aborted)return i==null?void 0:i.send({result:c,jsonrpc:"2.0",id:t.id})},c=>{var u;if(!a.signal.aborted)return i==null?void 0:i.send({jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(c.code)?c.code:Xe.InternalError,message:(u=c.message)!==null&&u!==void 0?u:"Internal error",...c.data!==void 0&&{data:c.data}}})}).catch(c=>this._onerror(new Error(`Failed to send response: ${c}`))).finally(()=>{this._requestHandlerAbortControllers.delete(t.id)})}_onprogress(t){const{progressToken:n,...r}=t.params,o=Number(n),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(t)}`));return}const i=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(l){i(l);return}s(r)}_onresponse(t){const n=Number(t.id),r=this._responseHandlers.get(n);if(r===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(t)}`));return}if(this._responseHandlers.delete(n),this._progressHandlers.delete(n),this._cleanupTimeout(n),ga(t))r(t);else{const o=ot.fromError(t.error.code,t.error.message,t.error.data);r(o)}}get transport(){return this._transport}async close(){var t;await((t=this._transport)===null||t===void 0?void 0:t.close())}request(t,n,r){const{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}=r??{};return new Promise((a,l)=>{var c,u,h,_,f,g;if(!this._transport){l(new Error("Not connected"));return}((c=this._options)===null||c===void 0?void 0:c.enforceStrictCapabilities)===!0&&this.assertCapabilityForMethod(t.method),(u=r==null?void 0:r.signal)===null||u===void 0||u.throwIfAborted();const v=this._requestMessageId++,m={...t,jsonrpc:"2.0",id:v};r!=null&&r.onprogress&&(this._progressHandlers.set(v,r.onprogress),m.params={...t.params,_meta:{...((h=t.params)===null||h===void 0?void 0:h._meta)||{},progressToken:v}});const d=b=>{var k;this._responseHandlers.delete(v),this._progressHandlers.delete(v),this._cleanupTimeout(v),(k=this._transport)===null||k===void 0||k.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:v,reason:String(b)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(x=>this._onerror(new Error(`Failed to send cancellation: ${x}`))),l(b)};this._responseHandlers.set(v,b=>{var k;if(!(!((k=r==null?void 0:r.signal)===null||k===void 0)&&k.aborted)){if(b instanceof Error)return l(b);try{const x=Ss(n,b.result);x.success?a(x.data):l(x.error)}catch(x){l(x)}}}),(_=r==null?void 0:r.signal)===null||_===void 0||_.addEventListener("abort",()=>{var b;d((b=r==null?void 0:r.signal)===null||b===void 0?void 0:b.reason)});const w=(f=r==null?void 0:r.timeout)!==null&&f!==void 0?f:I7,y=()=>d(ot.fromError(Xe.RequestTimeout,"Request timed out",{timeout:w}));this._setupTimeout(v,w,r==null?void 0:r.maxTotalTimeout,y,(g=r==null?void 0:r.resetTimeoutOnProgress)!==null&&g!==void 0?g:!1),this._transport.send(m,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(b=>{this._cleanupTimeout(v),l(b)})})}async notification(t,n){var r,o;if(!this._transport)throw new Error("Not connected");if(this.assertNotificationCapability(t.method),((o=(r=this._options)===null||r===void 0?void 0:r.debouncedNotificationMethods)!==null&&o!==void 0?o:[]).includes(t.method)&&!t.params&&!(n!=null&&n.relatedRequestId)){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{var l;if(this._pendingDebouncedNotifications.delete(t.method),!this._transport)return;const c={...t,jsonrpc:"2.0"};(l=this._transport)===null||l===void 0||l.send(c,n).catch(u=>this._onerror(u))});return}const a={...t,jsonrpc:"2.0"};await this._transport.send(a,n)}setRequestHandler(t,n){const r=ah(t);this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(o,s)=>{const i=lh(t,o);return Promise.resolve(n(i,s))})}removeRequestHandler(t){this._requestHandlers.delete(t)}assertCanSetRequestHandler(t){if(this._requestHandlers.has(t))throw new Error(`A request handler for ${t} already exists, which would be overridden`)}setNotificationHandler(t,n){const r=ah(t);this._notificationHandlers.set(r,o=>{const s=lh(t,o);return Promise.resolve(n(s))})}removeNotificationHandler(t){this._notificationHandlers.delete(t)}}function ch(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function x7(e,t){const n={...e};for(const r in t){const o=r,s=t[o];if(s===void 0)continue;const i=n[o];ch(i)&&ch(s)?n[o]={...i,...s}:n[o]=s}return n}var Qa={exports:{}},uh={},Zt={},fr={},co={},ce={},uo={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;class t{}e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class n extends t{constructor(w){if(super(),!e.IDENTIFIER.test(w))throw new Error("CodeGen: name must be a valid identifier");this.str=w}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}e.Name=n;class r extends t{constructor(w){super(),this._items=typeof w=="string"?[w]:w}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const w=this._items[0];return w===""||w==='""'}get str(){var w;return(w=this._str)!==null&&w!==void 0?w:this._str=this._items.reduce((y,b)=>`${y}${b}`,"")}get names(){var w;return(w=this._names)!==null&&w!==void 0?w:this._names=this._items.reduce((y,b)=>(b instanceof n&&(y[b.str]=(y[b.str]||0)+1),y),{})}}e._Code=r,e.nil=new r("");function o(d,...w){const y=[d[0]];let b=0;for(;b<w.length;)a(y,w[b]),y.push(d[++b]);return new r(y)}e._=o;const s=new r("+");function i(d,...w){const y=[f(d[0])];let b=0;for(;b<w.length;)y.push(s),a(y,w[b]),y.push(s,f(d[++b]));return l(y),new r(y)}e.str=i;function a(d,w){w instanceof r?d.push(...w._items):w instanceof n?d.push(w):d.push(h(w))}e.addCodeArg=a;function l(d){let w=1;for(;w<d.length-1;){if(d[w]===s){const y=c(d[w-1],d[w+1]);if(y!==void 0){d.splice(w-1,3,y);continue}d[w++]="+"}w++}}function c(d,w){if(w==='""')return d;if(d==='""')return w;if(typeof d=="string")return w instanceof n||d[d.length-1]!=='"'?void 0:typeof w!="string"?`${d.slice(0,-1)}${w}"`:w[0]==='"'?d.slice(0,-1)+w.slice(1):void 0;if(typeof w=="string"&&w[0]==='"'&&!(d instanceof n))return`"${d}${w.slice(1)}`}function u(d,w){return w.emptyStr()?d:d.emptyStr()?w:i`${d}${w}`}e.strConcat=u;function h(d){return typeof d=="number"||typeof d=="boolean"||d===null?d:f(Array.isArray(d)?d.join(","):d)}function _(d){return new r(f(d))}e.stringify=_;function f(d){return JSON.stringify(d).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}e.safeStringify=f;function g(d){return typeof d=="string"&&e.IDENTIFIER.test(d)?new r(`.${d}`):o`[${d}]`}e.getProperty=g;function v(d){if(typeof d=="string"&&e.IDENTIFIER.test(d))return new r(`${d}`);throw new Error(`CodeGen: invalid export name: ${d}, use explicit $id name mapping`)}e.getEsmExportName=v;function m(d){return new r(d.toString())}e.regexpCode=m})(uo);var Xa={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;const t=uo;class n extends Error{constructor(c){super(`CodeGen: "code" for ${c} not defined`),this.value=c.value}}var r;(function(l){l[l.Started=0]="Started",l[l.Completed=1]="Completed"})(r||(e.UsedValueState=r={})),e.varKinds={const:new t.Name("const"),let:new t.Name("let"),var:new t.Name("var")};class o{constructor({prefixes:c,parent:u}={}){this._names={},this._prefixes=c,this._parent=u}toName(c){return c instanceof t.Name?c:this.name(c)}name(c){return new t.Name(this._newName(c))}_newName(c){const u=this._names[c]||this._nameGroup(c);return`${c}${u.index++}`}_nameGroup(c){var u,h;if(!((h=(u=this._parent)===null||u===void 0?void 0:u._prefixes)===null||h===void 0)&&h.has(c)||this._prefixes&&!this._prefixes.has(c))throw new Error(`CodeGen: prefix "${c}" is not allowed in this scope`);return this._names[c]={prefix:c,index:0}}}e.Scope=o;class s extends t.Name{constructor(c,u){super(u),this.prefix=c}setValue(c,{property:u,itemIndex:h}){this.value=c,this.scopePath=(0,t._)`.${new t.Name(u)}[${h}]`}}e.ValueScopeName=s;const i=(0,t._)`\n`;class a extends o{constructor(c){super(c),this._values={},this._scope=c.scope,this.opts={...c,_n:c.lines?i:t.nil}}get(){return this._scope}name(c){return new s(c,this._newName(c))}value(c,u){var h;if(u.ref===void 0)throw new Error("CodeGen: ref must be passed in value");const _=this.toName(c),{prefix:f}=_,g=(h=u.key)!==null&&h!==void 0?h:u.ref;let v=this._values[f];if(v){const w=v.get(g);if(w)return w}else v=this._values[f]=new Map;v.set(g,_);const m=this._scope[f]||(this._scope[f]=[]),d=m.length;return m[d]=u.ref,_.setValue(u,{property:f,itemIndex:d}),_}getValue(c,u){const h=this._values[c];if(h)return h.get(u)}scopeRefs(c,u=this._values){return this._reduceValues(u,h=>{if(h.scopePath===void 0)throw new Error(`CodeGen: name "${h}" has no value`);return(0,t._)`${c}${h.scopePath}`})}scopeCode(c=this._values,u,h){return this._reduceValues(c,_=>{if(_.value===void 0)throw new Error(`CodeGen: name "${_}" has no value`);return _.value.code},u,h)}_reduceValues(c,u,h={},_){let f=t.nil;for(const g in c){const v=c[g];if(!v)continue;const m=h[g]=h[g]||new Map;v.forEach(d=>{if(m.has(d))return;m.set(d,r.Started);let w=u(d);if(w){const y=this.opts.es5?e.varKinds.var:e.varKinds.const;f=(0,t._)`${f}${y} ${d} = ${w};${this.opts._n}`}else if(w=_==null?void 0:_(d))f=(0,t._)`${f}${w}${this.opts._n}`;else throw new n(d);m.set(d,r.Completed)})}return f}}e.ValueScope=a})(Xa),function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;const t=uo,n=Xa;var r=uo;Object.defineProperty(e,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(e,"strConcat",{enumerable:!0,get:function(){return r.strConcat}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(e,"getProperty",{enumerable:!0,get:function(){return r.getProperty}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(e,"regexpCode",{enumerable:!0,get:function(){return r.regexpCode}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return r.Name}});var o=Xa;Object.defineProperty(e,"Scope",{enumerable:!0,get:function(){return o.Scope}}),Object.defineProperty(e,"ValueScope",{enumerable:!0,get:function(){return o.ValueScope}}),Object.defineProperty(e,"ValueScopeName",{enumerable:!0,get:function(){return o.ValueScopeName}}),Object.defineProperty(e,"varKinds",{enumerable:!0,get:function(){return o.varKinds}}),e.operators={GT:new t._Code(">"),GTE:new t._Code(">="),LT:new t._Code("<"),LTE:new t._Code("<="),EQ:new t._Code("==="),NEQ:new t._Code("!=="),NOT:new t._Code("!"),OR:new t._Code("||"),AND:new t._Code("&&"),ADD:new t._Code("+")};class s{optimizeNodes(){return this}optimizeNames(C,E){return this}}class i extends s{constructor(C,E,$){super(),this.varKind=C,this.name=E,this.rhs=$}render({es5:C,_n:E}){const $=C?n.varKinds.var:this.varKind,j=this.rhs===void 0?"":` = ${this.rhs}`;return`${$} ${this.name}${j};`+E}optimizeNames(C,E){if(C[this.name.str])return this.rhs&&(this.rhs=V(this.rhs,C,E)),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}}class a extends s{constructor(C,E,$){super(),this.lhs=C,this.rhs=E,this.sideEffects=$}render({_n:C}){return`${this.lhs} = ${this.rhs};`+C}optimizeNames(C,E){if(!(this.lhs instanceof t.Name&&!C[this.lhs.str]&&!this.sideEffects))return this.rhs=V(this.rhs,C,E),this}get names(){const C=this.lhs instanceof t.Name?{}:{...this.lhs.names};return B(C,this.rhs)}}class l extends a{constructor(C,E,$,j){super(C,$,j),this.op=E}render({_n:C}){return`${this.lhs} ${this.op}= ${this.rhs};`+C}}class c extends s{constructor(C){super(),this.label=C,this.names={}}render({_n:C}){return`${this.label}:`+C}}class u extends s{constructor(C){super(),this.label=C,this.names={}}render({_n:C}){return`break${this.label?` ${this.label}`:""};`+C}}class h extends s{constructor(C){super(),this.error=C}render({_n:C}){return`throw ${this.error};`+C}get names(){return this.error.names}}class _ extends s{constructor(C){super(),this.code=C}render({_n:C}){return`${this.code};`+C}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(C,E){return this.code=V(this.code,C,E),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}}class f extends s{constructor(C=[]){super(),this.nodes=C}render(C){return this.nodes.reduce((E,$)=>E+$.render(C),"")}optimizeNodes(){const{nodes:C}=this;let E=C.length;for(;E--;){const $=C[E].optimizeNodes();Array.isArray($)?C.splice(E,1,...$):$?C[E]=$:C.splice(E,1)}return C.length>0?this:void 0}optimizeNames(C,E){const{nodes:$}=this;let j=$.length;for(;j--;){const z=$[j];z.optimizeNames(C,E)||(se(C,z.names),$.splice(j,1))}return $.length>0?this:void 0}get names(){return this.nodes.reduce((C,E)=>F(C,E.names),{})}}class g extends f{render(C){return"{"+C._n+super.render(C)+"}"+C._n}}class v extends f{}class m extends g{}m.kind="else";class d extends g{constructor(C,E){super(E),this.condition=C}render(C){let E=`if(${this.condition})`+super.render(C);return this.else&&(E+="else "+this.else.render(C)),E}optimizeNodes(){super.optimizeNodes();const C=this.condition;if(C===!0)return this.nodes;let E=this.else;if(E){const $=E.optimizeNodes();E=this.else=Array.isArray($)?new m($):$}if(E)return C===!1?E instanceof d?E:E.nodes:this.nodes.length?this:new d(ge(C),E instanceof d?[E]:E.nodes);if(!(C===!1||!this.nodes.length))return this}optimizeNames(C,E){var $;if(this.else=($=this.else)===null||$===void 0?void 0:$.optimizeNames(C,E),!!(super.optimizeNames(C,E)||this.else))return this.condition=V(this.condition,C,E),this}get names(){const C=super.names;return B(C,this.condition),this.else&&F(C,this.else.names),C}}d.kind="if";class w extends g{}w.kind="for";class y extends w{constructor(C){super(),this.iteration=C}render(C){return`for(${this.iteration})`+super.render(C)}optimizeNames(C,E){if(super.optimizeNames(C,E))return this.iteration=V(this.iteration,C,E),this}get names(){return F(super.names,this.iteration.names)}}class b extends w{constructor(C,E,$,j){super(),this.varKind=C,this.name=E,this.from=$,this.to=j}render(C){const E=C.es5?n.varKinds.var:this.varKind,{name:$,from:j,to:z}=this;return`for(${E} ${$}=${j}; ${$}<${z}; ${$}++)`+super.render(C)}get names(){const C=B(super.names,this.from);return B(C,this.to)}}class k extends w{constructor(C,E,$,j){super(),this.loop=C,this.varKind=E,this.name=$,this.iterable=j}render(C){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(C)}optimizeNames(C,E){if(super.optimizeNames(C,E))return this.iterable=V(this.iterable,C,E),this}get names(){return F(super.names,this.iterable.names)}}class x extends g{constructor(C,E,$){super(),this.name=C,this.args=E,this.async=$}render(C){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(C)}}x.kind="func";class T extends f{render(C){return"return "+super.render(C)}}T.kind="return";class D extends g{render(C){let E="try"+super.render(C);return this.catch&&(E+=this.catch.render(C)),this.finally&&(E+=this.finally.render(C)),E}optimizeNodes(){var C,E;return super.optimizeNodes(),(C=this.catch)===null||C===void 0||C.optimizeNodes(),(E=this.finally)===null||E===void 0||E.optimizeNodes(),this}optimizeNames(C,E){var $,j;return super.optimizeNames(C,E),($=this.catch)===null||$===void 0||$.optimizeNames(C,E),(j=this.finally)===null||j===void 0||j.optimizeNames(C,E),this}get names(){const C=super.names;return this.catch&&F(C,this.catch.names),this.finally&&F(C,this.finally.names),C}}class U extends g{constructor(C){super(),this.error=C}render(C){return`catch(${this.error})`+super.render(C)}}U.kind="catch";class H extends g{render(C){return"finally"+super.render(C)}}H.kind="finally";class q{constructor(C,E={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...E,_n:E.lines?`
72
+ `:""},this._extScope=C,this._scope=new n.Scope({parent:C}),this._nodes=[new v]}toString(){return this._root.render(this.opts)}name(C){return this._scope.name(C)}scopeName(C){return this._extScope.name(C)}scopeValue(C,E){const $=this._extScope.value(C,E);return(this._values[$.prefix]||(this._values[$.prefix]=new Set)).add($),$}getScopeValue(C,E){return this._extScope.getValue(C,E)}scopeRefs(C){return this._extScope.scopeRefs(C,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(C,E,$,j){const z=this._scope.toName(E);return $!==void 0&&j&&(this._constants[z.str]=$),this._leafNode(new i(C,z,$)),z}const(C,E,$){return this._def(n.varKinds.const,C,E,$)}let(C,E,$){return this._def(n.varKinds.let,C,E,$)}var(C,E,$){return this._def(n.varKinds.var,C,E,$)}assign(C,E,$){return this._leafNode(new a(C,E,$))}add(C,E){return this._leafNode(new l(C,e.operators.ADD,E))}code(C){return typeof C=="function"?C():C!==t.nil&&this._leafNode(new _(C)),this}object(...C){const E=["{"];for(const[$,j]of C)E.length>1&&E.push(","),E.push($),($!==j||this.opts.es5)&&(E.push(":"),(0,t.addCodeArg)(E,j));return E.push("}"),new t._Code(E)}if(C,E,$){if(this._blockNode(new d(C)),E&&$)this.code(E).else().code($).endIf();else if(E)this.code(E).endIf();else if($)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(C){return this._elseNode(new d(C))}else(){return this._elseNode(new m)}endIf(){return this._endBlockNode(d,m)}_for(C,E){return this._blockNode(C),E&&this.code(E).endFor(),this}for(C,E){return this._for(new y(C),E)}forRange(C,E,$,j,z=this.opts.es5?n.varKinds.var:n.varKinds.let){const de=this._scope.toName(C);return this._for(new b(z,de,E,$),()=>j(de))}forOf(C,E,$,j=n.varKinds.const){const z=this._scope.toName(C);if(this.opts.es5){const de=E instanceof t.Name?E:this.var("_arr",E);return this.forRange("_i",0,(0,t._)`${de}.length`,oe=>{this.var(z,(0,t._)`${de}[${oe}]`),$(z)})}return this._for(new k("of",j,z,E),()=>$(z))}forIn(C,E,$,j=this.opts.es5?n.varKinds.var:n.varKinds.const){if(this.opts.ownProperties)return this.forOf(C,(0,t._)`Object.keys(${E})`,$);const z=this._scope.toName(C);return this._for(new k("in",j,z,E),()=>$(z))}endFor(){return this._endBlockNode(w)}label(C){return this._leafNode(new c(C))}break(C){return this._leafNode(new u(C))}return(C){const E=new T;if(this._blockNode(E),this.code(C),E.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(T)}try(C,E,$){if(!E&&!$)throw new Error('CodeGen: "try" without "catch" and "finally"');const j=new D;if(this._blockNode(j),this.code(C),E){const z=this.name("e");this._currNode=j.catch=new U(z),E(z)}return $&&(this._currNode=j.finally=new H,this.code($)),this._endBlockNode(U,H)}throw(C){return this._leafNode(new h(C))}block(C,E){return this._blockStarts.push(this._nodes.length),C&&this.code(C).endBlock(E),this}endBlock(C){const E=this._blockStarts.pop();if(E===void 0)throw new Error("CodeGen: not in self-balancing block");const $=this._nodes.length-E;if($<0||C!==void 0&&$!==C)throw new Error(`CodeGen: wrong number of nodes: ${$} vs ${C} expected`);return this._nodes.length=E,this}func(C,E=t.nil,$,j){return this._blockNode(new x(C,E,$)),j&&this.code(j).endFunc(),this}endFunc(){return this._endBlockNode(x)}optimize(C=1){for(;C-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(C){return this._currNode.nodes.push(C),this}_blockNode(C){this._currNode.nodes.push(C),this._nodes.push(C)}_endBlockNode(C,E){const $=this._currNode;if($ instanceof C||E&&$ instanceof E)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${E?`${C.kind}/${E.kind}`:C.kind}"`)}_elseNode(C){const E=this._currNode;if(!(E instanceof d))throw new Error('CodeGen: "else" without "if"');return this._currNode=E.else=C,this}get _root(){return this._nodes[0]}get _currNode(){const C=this._nodes;return C[C.length-1]}set _currNode(C){const E=this._nodes;E[E.length-1]=C}}e.CodeGen=q;function F(P,C){for(const E in C)P[E]=(P[E]||0)+(C[E]||0);return P}function B(P,C){return C instanceof t._CodeOrName?F(P,C.names):P}function V(P,C,E){if(P instanceof t.Name)return $(P);if(!j(P))return P;return new t._Code(P._items.reduce((z,de)=>(de instanceof t.Name&&(de=$(de)),de instanceof t._Code?z.push(...de._items):z.push(de),z),[]));function $(z){const de=E[z.str];return de===void 0||C[z.str]!==1?z:(delete C[z.str],de)}function j(z){return z instanceof t._Code&&z._items.some(de=>de instanceof t.Name&&C[de.str]===1&&E[de.str]!==void 0)}}function se(P,C){for(const E in C)P[E]=(P[E]||0)-(C[E]||0)}function ge(P){return typeof P=="boolean"||typeof P=="number"||P===null?!P:(0,t._)`!${M(P)}`}e.not=ge;const te=I(e.operators.AND);function ue(...P){return P.reduce(te)}e.and=ue;const le=I(e.operators.OR);function L(...P){return P.reduce(le)}e.or=L;function I(P){return(C,E)=>C===t.nil?E:E===t.nil?C:(0,t._)`${M(C)} ${P} ${M(E)}`}function M(P){return P instanceof t.Name?P:(0,t._)`(${P})`}}(ce);var G={};Object.defineProperty(G,"__esModule",{value:!0}),G.checkStrictMode=G.getErrorPath=G.Type=G.useFunc=G.setEvaluated=G.evaluatedPropsToName=G.mergeEvaluated=G.eachItem=G.unescapeJsonPointer=G.escapeJsonPointer=G.escapeFragment=G.unescapeFragment=G.schemaRefOrVal=G.schemaHasRulesButRef=G.schemaHasRules=G.checkUnknownRules=G.alwaysValidSchema=G.toHash=void 0;const xe=ce,P7=uo;function R7(e){const t={};for(const n of e)t[n]=!0;return t}G.toHash=R7;function O7(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?!0:(dh(e,t),!ph(t,e.self.RULES.all))}G.alwaysValidSchema=O7;function dh(e,t=e.schema){const{opts:n,self:r}=e;if(!n.strictSchema||typeof t=="boolean")return;const o=r.RULES.keywords;for(const s in t)o[s]||vh(e,`unknown keyword: "${s}"`)}G.checkUnknownRules=dh;function ph(e,t){if(typeof e=="boolean")return!e;for(const n in e)if(t[n])return!0;return!1}G.schemaHasRules=ph;function N7(e,t){if(typeof e=="boolean")return!e;for(const n in e)if(n!=="$ref"&&t.all[n])return!0;return!1}G.schemaHasRulesButRef=N7;function M7({topSchemaRef:e,schemaPath:t},n,r,o){if(!o){if(typeof n=="number"||typeof n=="boolean")return n;if(typeof n=="string")return(0,xe._)`${n}`}return(0,xe._)`${e}${t}${(0,xe.getProperty)(r)}`}G.schemaRefOrVal=M7;function A7(e){return fh(decodeURIComponent(e))}G.unescapeFragment=A7;function L7(e){return encodeURIComponent(el(e))}G.escapeFragment=L7;function el(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}G.escapeJsonPointer=el;function fh(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}G.unescapeJsonPointer=fh;function j7(e,t){if(Array.isArray(e))for(const n of e)t(n);else t(e)}G.eachItem=j7;function hh({mergeNames:e,mergeToName:t,mergeValues:n,resultToName:r}){return(o,s,i,a)=>{const l=i===void 0?s:i instanceof xe.Name?(s instanceof xe.Name?e(o,s,i):t(o,s,i),i):s instanceof xe.Name?(t(o,i,s),s):n(s,i);return a===xe.Name&&!(l instanceof xe.Name)?r(o,l):l}}G.mergeEvaluated={props:hh({mergeNames:(e,t,n)=>e.if((0,xe._)`${n} !== true && ${t} !== undefined`,()=>{e.if((0,xe._)`${t} === true`,()=>e.assign(n,!0),()=>e.assign(n,(0,xe._)`${n} || {}`).code((0,xe._)`Object.assign(${n}, ${t})`))}),mergeToName:(e,t,n)=>e.if((0,xe._)`${n} !== true`,()=>{t===!0?e.assign(n,!0):(e.assign(n,(0,xe._)`${n} || {}`),tl(e,n,t))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:mh}),items:hh({mergeNames:(e,t,n)=>e.if((0,xe._)`${n} !== true && ${t} !== undefined`,()=>e.assign(n,(0,xe._)`${t} === true ? true : ${n} > ${t} ? ${n} : ${t}`)),mergeToName:(e,t,n)=>e.if((0,xe._)`${n} !== true`,()=>e.assign(n,t===!0?!0:(0,xe._)`${n} > ${t} ? ${n} : ${t}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})};function mh(e,t){if(t===!0)return e.var("props",!0);const n=e.var("props",(0,xe._)`{}`);return t!==void 0&&tl(e,n,t),n}G.evaluatedPropsToName=mh;function tl(e,t,n){Object.keys(n).forEach(r=>e.assign((0,xe._)`${t}${(0,xe.getProperty)(r)}`,!0))}G.setEvaluated=tl;const gh={};function z7(e,t){return e.scopeValue("func",{ref:t,code:gh[t.code]||(gh[t.code]=new P7._Code(t.code))})}G.useFunc=z7;var nl;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(nl||(G.Type=nl={}));function D7(e,t,n){if(e instanceof xe.Name){const r=t===nl.Num;return n?r?(0,xe._)`"[" + ${e} + "]"`:(0,xe._)`"['" + ${e} + "']"`:r?(0,xe._)`"/" + ${e}`:(0,xe._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return n?(0,xe.getProperty)(e).toString():"/"+el(e)}G.getErrorPath=D7;function vh(e,t,n=e.opts.strictSchema){if(n){if(t=`strict mode: ${t}`,n===!0)throw new Error(t);e.self.logger.warn(t)}}G.checkStrictMode=vh;var tn={};Object.defineProperty(tn,"__esModule",{value:!0});const tt=ce,U7={data:new tt.Name("data"),valCxt:new tt.Name("valCxt"),instancePath:new tt.Name("instancePath"),parentData:new tt.Name("parentData"),parentDataProperty:new tt.Name("parentDataProperty"),rootData:new tt.Name("rootData"),dynamicAnchors:new tt.Name("dynamicAnchors"),vErrors:new tt.Name("vErrors"),errors:new tt.Name("errors"),this:new tt.Name("this"),self:new tt.Name("self"),scope:new tt.Name("scope"),json:new tt.Name("json"),jsonPos:new tt.Name("jsonPos"),jsonLen:new tt.Name("jsonLen"),jsonPart:new tt.Name("jsonPart")};tn.default=U7,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;const t=ce,n=G,r=tn;e.keywordError={message:({keyword:m})=>(0,t.str)`must pass "${m}" keyword validation`},e.keyword$DataError={message:({keyword:m,schemaType:d})=>d?(0,t.str)`"${m}" keyword must be ${d} ($data)`:(0,t.str)`"${m}" keyword is invalid ($data)`};function o(m,d=e.keywordError,w,y){const{it:b}=m,{gen:k,compositeRule:x,allErrors:T}=b,D=h(m,d,w);y??(x||T)?l(k,D):c(b,(0,t._)`[${D}]`)}e.reportError=o;function s(m,d=e.keywordError,w){const{it:y}=m,{gen:b,compositeRule:k,allErrors:x}=y,T=h(m,d,w);l(b,T),k||x||c(y,r.default.vErrors)}e.reportExtraError=s;function i(m,d){m.assign(r.default.errors,d),m.if((0,t._)`${r.default.vErrors} !== null`,()=>m.if(d,()=>m.assign((0,t._)`${r.default.vErrors}.length`,d),()=>m.assign(r.default.vErrors,null)))}e.resetErrorsCount=i;function a({gen:m,keyword:d,schemaValue:w,data:y,errsCount:b,it:k}){if(b===void 0)throw new Error("ajv implementation error");const x=m.name("err");m.forRange("i",b,r.default.errors,T=>{m.const(x,(0,t._)`${r.default.vErrors}[${T}]`),m.if((0,t._)`${x}.instancePath === undefined`,()=>m.assign((0,t._)`${x}.instancePath`,(0,t.strConcat)(r.default.instancePath,k.errorPath))),m.assign((0,t._)`${x}.schemaPath`,(0,t.str)`${k.errSchemaPath}/${d}`),k.opts.verbose&&(m.assign((0,t._)`${x}.schema`,w),m.assign((0,t._)`${x}.data`,y))})}e.extendErrors=a;function l(m,d){const w=m.const("err",d);m.if((0,t._)`${r.default.vErrors} === null`,()=>m.assign(r.default.vErrors,(0,t._)`[${w}]`),(0,t._)`${r.default.vErrors}.push(${w})`),m.code((0,t._)`${r.default.errors}++`)}function c(m,d){const{gen:w,validateName:y,schemaEnv:b}=m;b.$async?w.throw((0,t._)`new ${m.ValidationError}(${d})`):(w.assign((0,t._)`${y}.errors`,d),w.return(!1))}const u={keyword:new t.Name("keyword"),schemaPath:new t.Name("schemaPath"),params:new t.Name("params"),propertyName:new t.Name("propertyName"),message:new t.Name("message"),schema:new t.Name("schema"),parentSchema:new t.Name("parentSchema")};function h(m,d,w){const{createErrors:y}=m.it;return y===!1?(0,t._)`{}`:_(m,d,w)}function _(m,d,w={}){const{gen:y,it:b}=m,k=[f(b,w),g(m,w)];return v(m,d,k),y.object(...k)}function f({errorPath:m},{instancePath:d}){const w=d?(0,t.str)`${m}${(0,n.getErrorPath)(d,n.Type.Str)}`:m;return[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,w)]}function g({keyword:m,it:{errSchemaPath:d}},{schemaPath:w,parentSchema:y}){let b=y?d:(0,t.str)`${d}/${m}`;return w&&(b=(0,t.str)`${b}${(0,n.getErrorPath)(w,n.Type.Str)}`),[u.schemaPath,b]}function v(m,{params:d,message:w},y){const{keyword:b,data:k,schemaValue:x,it:T}=m,{opts:D,propertyName:U,topSchemaRef:H,schemaPath:q}=T;y.push([u.keyword,b],[u.params,typeof d=="function"?d(m):d||(0,t._)`{}`]),D.messages&&y.push([u.message,typeof w=="function"?w(m):w]),D.verbose&&y.push([u.schema,x],[u.parentSchema,(0,t._)`${H}${q}`],[r.default.data,k]),U&&y.push([u.propertyName,U])}}(co),Object.defineProperty(fr,"__esModule",{value:!0}),fr.boolOrEmptySchema=fr.topBoolOrEmptySchema=void 0;const q7=co,Z7=ce,F7=tn,V7={message:"boolean schema is false"};function B7(e){const{gen:t,schema:n,validateName:r}=e;n===!1?_h(e,!1):typeof n=="object"&&n.$async===!0?t.return(F7.default.data):(t.assign((0,Z7._)`${r}.errors`,null),t.return(!0))}fr.topBoolOrEmptySchema=B7;function H7(e,t){const{gen:n,schema:r}=e;r===!1?(n.var(t,!1),_h(e)):n.var(t,!0)}fr.boolOrEmptySchema=H7;function _h(e,t){const{gen:n,data:r}=e,o={gen:n,keyword:"false schema",data:r,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,q7.reportError)(o,V7,void 0,t)}var Ue={},Yn={};Object.defineProperty(Yn,"__esModule",{value:!0}),Yn.getRules=Yn.isJSONType=void 0;const J7=["string","number","integer","boolean","null","object","array"],G7=new Set(J7);function W7(e){return typeof e=="string"&&G7.has(e)}Yn.isJSONType=W7;function K7(){const e={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}Yn.getRules=K7;var dn={};Object.defineProperty(dn,"__esModule",{value:!0}),dn.shouldUseRule=dn.shouldUseGroup=dn.schemaHasRulesForType=void 0;function Y7({schema:e,self:t},n){const r=t.RULES.types[n];return r&&r!==!0&&yh(e,r)}dn.schemaHasRulesForType=Y7;function yh(e,t){return t.rules.some(n=>wh(e,n))}dn.shouldUseGroup=yh;function wh(e,t){var n;return e[t.keyword]!==void 0||((n=t.definition.implements)===null||n===void 0?void 0:n.some(r=>e[r]!==void 0))}dn.shouldUseRule=wh,Object.defineProperty(Ue,"__esModule",{value:!0}),Ue.reportTypeError=Ue.checkDataTypes=Ue.checkDataType=Ue.coerceAndCheckDataType=Ue.getJSONTypes=Ue.getSchemaTypes=Ue.DataType=void 0;const Q7=Yn,X7=dn,e$=co,ae=ce,bh=G;var hr;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(hr||(Ue.DataType=hr={}));function t$(e){const t=$h(e.type);if(t.includes("null")){if(e.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!t.length&&e.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');e.nullable===!0&&t.push("null")}return t}Ue.getSchemaTypes=t$;function $h(e){const t=Array.isArray(e)?e:e?[e]:[];if(t.every(Q7.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}Ue.getJSONTypes=$h;function n$(e,t){const{gen:n,data:r,opts:o}=e,s=r$(t,o.coerceTypes),i=t.length>0&&!(s.length===0&&t.length===1&&(0,X7.schemaHasRulesForType)(e,t[0]));if(i){const a=ol(t,r,o.strictNumbers,hr.Wrong);n.if(a,()=>{s.length?o$(e,t,s):sl(e)})}return i}Ue.coerceAndCheckDataType=n$;const Sh=new Set(["string","number","integer","boolean","null"]);function r$(e,t){return t?e.filter(n=>Sh.has(n)||t==="array"&&n==="array"):[]}function o$(e,t,n){const{gen:r,data:o,opts:s}=e,i=r.let("dataType",(0,ae._)`typeof ${o}`),a=r.let("coerced",(0,ae._)`undefined`);s.coerceTypes==="array"&&r.if((0,ae._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>r.assign(o,(0,ae._)`${o}[0]`).assign(i,(0,ae._)`typeof ${o}`).if(ol(t,o,s.strictNumbers),()=>r.assign(a,o))),r.if((0,ae._)`${a} !== undefined`);for(const c of n)(Sh.has(c)||c==="array"&&s.coerceTypes==="array")&&l(c);r.else(),sl(e),r.endIf(),r.if((0,ae._)`${a} !== undefined`,()=>{r.assign(o,a),s$(e,a)});function l(c){switch(c){case"string":r.elseIf((0,ae._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,ae._)`"" + ${o}`).elseIf((0,ae._)`${o} === null`).assign(a,(0,ae._)`""`);return;case"number":r.elseIf((0,ae._)`${i} == "boolean" || ${o} === null
73
+ || (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,ae._)`+${o}`);return;case"integer":r.elseIf((0,ae._)`${i} === "boolean" || ${o} === null
74
+ || (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,ae._)`+${o}`);return;case"boolean":r.elseIf((0,ae._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,ae._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":r.elseIf((0,ae._)`${o} === "" || ${o} === 0 || ${o} === false`),r.assign(a,null);return;case"array":r.elseIf((0,ae._)`${i} === "string" || ${i} === "number"
75
+ || ${i} === "boolean" || ${o} === null`).assign(a,(0,ae._)`[${o}]`)}}}function s$({gen:e,parentData:t,parentDataProperty:n},r){e.if((0,ae._)`${t} !== undefined`,()=>e.assign((0,ae._)`${t}[${n}]`,r))}function rl(e,t,n,r=hr.Correct){const o=r===hr.Correct?ae.operators.EQ:ae.operators.NEQ;let s;switch(e){case"null":return(0,ae._)`${t} ${o} null`;case"array":s=(0,ae._)`Array.isArray(${t})`;break;case"object":s=(0,ae._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":s=i((0,ae._)`!(${t} % 1) && !isNaN(${t})`);break;case"number":s=i();break;default:return(0,ae._)`typeof ${t} ${o} ${e}`}return r===hr.Correct?s:(0,ae.not)(s);function i(a=ae.nil){return(0,ae.and)((0,ae._)`typeof ${t} == "number"`,a,n?(0,ae._)`isFinite(${t})`:ae.nil)}}Ue.checkDataType=rl;function ol(e,t,n,r){if(e.length===1)return rl(e[0],t,n,r);let o;const s=(0,bh.toHash)(e);if(s.array&&s.object){const i=(0,ae._)`typeof ${t} != "object"`;o=s.null?i:(0,ae._)`!${t} || ${i}`,delete s.null,delete s.array,delete s.object}else o=ae.nil;s.number&&delete s.integer;for(const i in s)o=(0,ae.and)(o,rl(i,t,n,r));return o}Ue.checkDataTypes=ol;const i$={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e=="string"?(0,ae._)`{type: ${e}}`:(0,ae._)`{type: ${t}}`};function sl(e){const t=a$(e);(0,e$.reportError)(t,i$)}Ue.reportTypeError=sl;function a$(e){const{gen:t,data:n,schema:r}=e,o=(0,bh.schemaRefOrVal)(e,r,"type");return{gen:t,keyword:"type",data:n,schema:r.type,schemaCode:o,schemaValue:o,parentSchema:r,params:{},it:e}}var Cs={};Object.defineProperty(Cs,"__esModule",{value:!0}),Cs.assignDefaults=void 0;const mr=ce,l$=G;function c$(e,t){const{properties:n,items:r}=e.schema;if(t==="object"&&n)for(const o in n)Ch(e,o,n[o].default);else t==="array"&&Array.isArray(r)&&r.forEach((o,s)=>Ch(e,s,o.default))}Cs.assignDefaults=c$;function Ch(e,t,n){const{gen:r,compositeRule:o,data:s,opts:i}=e;if(n===void 0)return;const a=(0,mr._)`${s}${(0,mr.getProperty)(t)}`;if(o){(0,l$.checkStrictMode)(e,`default is ignored for: ${a}`);return}let l=(0,mr._)`${a} === undefined`;i.useDefaults==="empty"&&(l=(0,mr._)`${l} || ${a} === null || ${a} === ""`),r.if(l,(0,mr._)`${a} = ${(0,mr.stringify)(n)}`)}var nn={},pe={};Object.defineProperty(pe,"__esModule",{value:!0}),pe.validateUnion=pe.validateArray=pe.usePattern=pe.callValidateCode=pe.schemaProperties=pe.allSchemaProperties=pe.noPropertyInData=pe.propertyInData=pe.isOwnProperty=pe.hasPropFunc=pe.reportMissingProp=pe.checkMissingProp=pe.checkReportMissingProp=void 0;const Oe=ce,il=G,En=tn,u$=G;function d$(e,t){const{gen:n,data:r,it:o}=e;n.if(ll(n,r,t,o.opts.ownProperties),()=>{e.setParams({missingProperty:(0,Oe._)`${t}`},!0),e.error()})}pe.checkReportMissingProp=d$;function p$({gen:e,data:t,it:{opts:n}},r,o){return(0,Oe.or)(...r.map(s=>(0,Oe.and)(ll(e,t,s,n.ownProperties),(0,Oe._)`${o} = ${s}`)))}pe.checkMissingProp=p$;function f$(e,t){e.setParams({missingProperty:t},!0),e.error()}pe.reportMissingProp=f$;function Eh(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Oe._)`Object.prototype.hasOwnProperty`})}pe.hasPropFunc=Eh;function al(e,t,n){return(0,Oe._)`${Eh(e)}.call(${t}, ${n})`}pe.isOwnProperty=al;function h$(e,t,n,r){const o=(0,Oe._)`${t}${(0,Oe.getProperty)(n)} !== undefined`;return r?(0,Oe._)`${o} && ${al(e,t,n)}`:o}pe.propertyInData=h$;function ll(e,t,n,r){const o=(0,Oe._)`${t}${(0,Oe.getProperty)(n)} === undefined`;return r?(0,Oe.or)(o,(0,Oe.not)(al(e,t,n))):o}pe.noPropertyInData=ll;function kh(e){return e?Object.keys(e).filter(t=>t!=="__proto__"):[]}pe.allSchemaProperties=kh;function m$(e,t){return kh(t).filter(n=>!(0,il.alwaysValidSchema)(e,t[n]))}pe.schemaProperties=m$;function g$({schemaCode:e,data:t,it:{gen:n,topSchemaRef:r,schemaPath:o,errorPath:s},it:i},a,l,c){const u=c?(0,Oe._)`${e}, ${t}, ${r}${o}`:t,h=[[En.default.instancePath,(0,Oe.strConcat)(En.default.instancePath,s)],[En.default.parentData,i.parentData],[En.default.parentDataProperty,i.parentDataProperty],[En.default.rootData,En.default.rootData]];i.opts.dynamicRef&&h.push([En.default.dynamicAnchors,En.default.dynamicAnchors]);const _=(0,Oe._)`${u}, ${n.object(...h)}`;return l!==Oe.nil?(0,Oe._)`${a}.call(${l}, ${_})`:(0,Oe._)`${a}(${_})`}pe.callValidateCode=g$;const v$=(0,Oe._)`new RegExp`;function _$({gen:e,it:{opts:t}},n){const r=t.unicodeRegExp?"u":"",{regExp:o}=t.code,s=o(n,r);return e.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,Oe._)`${o.code==="new RegExp"?v$:(0,u$.useFunc)(e,o)}(${n}, ${r})`})}pe.usePattern=_$;function y$(e){const{gen:t,data:n,keyword:r,it:o}=e,s=t.name("valid");if(o.allErrors){const a=t.let("valid",!0);return i(()=>t.assign(a,!1)),a}return t.var(s,!0),i(()=>t.break()),s;function i(a){const l=t.const("len",(0,Oe._)`${n}.length`);t.forRange("i",0,l,c=>{e.subschema({keyword:r,dataProp:c,dataPropType:il.Type.Num},s),t.if((0,Oe.not)(s),a)})}}pe.validateArray=y$;function w$(e){const{gen:t,schema:n,keyword:r,it:o}=e;if(!Array.isArray(n))throw new Error("ajv implementation error");if(n.some(l=>(0,il.alwaysValidSchema)(o,l))&&!o.opts.unevaluated)return;const i=t.let("valid",!1),a=t.name("_valid");t.block(()=>n.forEach((l,c)=>{const u=e.subschema({keyword:r,schemaProp:c,compositeRule:!0},a);t.assign(i,(0,Oe._)`${i} || ${a}`),e.mergeValidEvaluated(u,a)||t.if((0,Oe.not)(i))})),e.result(i,()=>e.reset(),()=>e.error(!0))}pe.validateUnion=w$,Object.defineProperty(nn,"__esModule",{value:!0}),nn.validateKeywordUsage=nn.validSchemaType=nn.funcKeywordCode=nn.macroKeywordCode=void 0;const lt=ce,Qn=tn,b$=pe,$$=co;function S$(e,t){const{gen:n,keyword:r,schema:o,parentSchema:s,it:i}=e,a=t.macro.call(i.self,o,s,i),l=Th(n,r,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);const c=n.name("valid");e.subschema({schema:a,schemaPath:lt.nil,errSchemaPath:`${i.errSchemaPath}/${r}`,topSchemaRef:l,compositeRule:!0},c),e.pass(c,()=>e.error(!0))}nn.macroKeywordCode=S$;function C$(e,t){var n;const{gen:r,keyword:o,schema:s,parentSchema:i,$data:a,it:l}=e;k$(l,t);const c=!a&&t.compile?t.compile.call(l.self,s,i,l):t.validate,u=Th(r,o,c),h=r.let("valid");e.block$data(h,_),e.ok((n=t.valid)!==null&&n!==void 0?n:h);function _(){if(t.errors===!1)v(),t.modifying&&Ih(e),m(()=>e.error());else{const d=t.async?f():g();t.modifying&&Ih(e),m(()=>E$(e,d))}}function f(){const d=r.let("ruleErrs",null);return r.try(()=>v((0,lt._)`await `),w=>r.assign(h,!1).if((0,lt._)`${w} instanceof ${l.ValidationError}`,()=>r.assign(d,(0,lt._)`${w}.errors`),()=>r.throw(w))),d}function g(){const d=(0,lt._)`${u}.errors`;return r.assign(d,null),v(lt.nil),d}function v(d=t.async?(0,lt._)`await `:lt.nil){const w=l.opts.passContext?Qn.default.this:Qn.default.self,y=!("compile"in t&&!a||t.schema===!1);r.assign(h,(0,lt._)`${d}${(0,b$.callValidateCode)(e,u,w,y)}`,t.modifying)}function m(d){var w;r.if((0,lt.not)((w=t.valid)!==null&&w!==void 0?w:h),d)}}nn.funcKeywordCode=C$;function Ih(e){const{gen:t,data:n,it:r}=e;t.if(r.parentData,()=>t.assign(n,(0,lt._)`${r.parentData}[${r.parentDataProperty}]`))}function E$(e,t){const{gen:n}=e;n.if((0,lt._)`Array.isArray(${t})`,()=>{n.assign(Qn.default.vErrors,(0,lt._)`${Qn.default.vErrors} === null ? ${t} : ${Qn.default.vErrors}.concat(${t})`).assign(Qn.default.errors,(0,lt._)`${Qn.default.vErrors}.length`),(0,$$.extendErrors)(e)},()=>e.error())}function k$({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}function Th(e,t,n){if(n===void 0)throw new Error(`keyword "${t}" failed to compile`);return e.scopeValue("keyword",typeof n=="function"?{ref:n}:{ref:n,code:(0,lt.stringify)(n)})}function I$(e,t,n=!1){return!t.length||t.some(r=>r==="array"?Array.isArray(e):r==="object"?e&&typeof e=="object"&&!Array.isArray(e):typeof e==r||n&&typeof e>"u")}nn.validSchemaType=I$;function T$({schema:e,opts:t,self:n,errSchemaPath:r},o,s){if(Array.isArray(o.keyword)?!o.keyword.includes(s):o.keyword!==s)throw new Error("ajv implementation error");const i=o.dependencies;if(i!=null&&i.some(a=>!Object.prototype.hasOwnProperty.call(e,a)))throw new Error(`parent schema must have dependencies of ${s}: ${i.join(",")}`);if(o.validateSchema&&!o.validateSchema(e[s])){const l=`keyword "${s}" value is invalid at path "${r}": `+n.errorsText(o.validateSchema.errors);if(t.validateSchema==="log")n.logger.error(l);else throw new Error(l)}}nn.validateKeywordUsage=T$;var kn={};Object.defineProperty(kn,"__esModule",{value:!0}),kn.extendSubschemaMode=kn.extendSubschemaData=kn.getSubschema=void 0;const rn=ce,xh=G;function x$(e,{keyword:t,schemaProp:n,schema:r,schemaPath:o,errSchemaPath:s,topSchemaRef:i}){if(t!==void 0&&r!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(t!==void 0){const a=e.schema[t];return n===void 0?{schema:a,schemaPath:(0,rn._)`${e.schemaPath}${(0,rn.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:a[n],schemaPath:(0,rn._)`${e.schemaPath}${(0,rn.getProperty)(t)}${(0,rn.getProperty)(n)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,xh.escapeFragment)(n)}`}}if(r!==void 0){if(o===void 0||s===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:r,schemaPath:o,topSchemaRef:i,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}kn.getSubschema=x$;function P$(e,t,{dataProp:n,dataPropType:r,data:o,dataTypes:s,propertyName:i}){if(o!==void 0&&n!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');const{gen:a}=t;if(n!==void 0){const{errorPath:c,dataPathArr:u,opts:h}=t,_=a.let("data",(0,rn._)`${t.data}${(0,rn.getProperty)(n)}`,!0);l(_),e.errorPath=(0,rn.str)`${c}${(0,xh.getErrorPath)(n,r,h.jsPropertySyntax)}`,e.parentDataProperty=(0,rn._)`${n}`,e.dataPathArr=[...u,e.parentDataProperty]}if(o!==void 0){const c=o instanceof rn.Name?o:a.let("data",o,!0);l(c),i!==void 0&&(e.propertyName=i)}s&&(e.dataTypes=s);function l(c){e.data=c,e.dataLevel=t.dataLevel+1,e.dataTypes=[],t.definedProperties=new Set,e.parentData=t.data,e.dataNames=[...t.dataNames,c]}}kn.extendSubschemaData=P$;function R$(e,{jtdDiscriminator:t,jtdMetadata:n,compositeRule:r,createErrors:o,allErrors:s}){r!==void 0&&(e.compositeRule=r),o!==void 0&&(e.createErrors=o),s!==void 0&&(e.allErrors=s),e.jtdDiscriminator=t,e.jtdMetadata=n}kn.extendSubschemaMode=R$;var We={},Ph=function e(t,n){if(t===n)return!0;if(t&&n&&typeof t=="object"&&typeof n=="object"){if(t.constructor!==n.constructor)return!1;var r,o,s;if(Array.isArray(t)){if(r=t.length,r!=n.length)return!1;for(o=r;o--!==0;)if(!e(t[o],n[o]))return!1;return!0}if(t.constructor===RegExp)return t.source===n.source&&t.flags===n.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===n.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===n.toString();if(s=Object.keys(t),r=s.length,r!==Object.keys(n).length)return!1;for(o=r;o--!==0;)if(!Object.prototype.hasOwnProperty.call(n,s[o]))return!1;for(o=r;o--!==0;){var i=s[o];if(!e(t[i],n[i]))return!1}return!0}return t!==t&&n!==n},Rh={exports:{}},In=Rh.exports=function(e,t,n){typeof t=="function"&&(n=t,t={}),n=t.cb||n;var r=typeof n=="function"?n:n.pre||function(){},o=n.post||function(){};Es(t,r,o,e,"",e)};In.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},In.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},In.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},In.skipKeywords={default:!0,enum:!0,const:!0,required:!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};function Es(e,t,n,r,o,s,i,a,l,c){if(r&&typeof r=="object"&&!Array.isArray(r)){t(r,o,s,i,a,l,c);for(var u in r){var h=r[u];if(Array.isArray(h)){if(u in In.arrayKeywords)for(var _=0;_<h.length;_++)Es(e,t,n,h[_],o+"/"+u+"/"+_,s,o,u,r,_)}else if(u in In.propsKeywords){if(h&&typeof h=="object")for(var f in h)Es(e,t,n,h[f],o+"/"+u+"/"+O$(f),s,o,u,r,f)}else(u in In.keywords||e.allKeys&&!(u in In.skipKeywords))&&Es(e,t,n,h,o+"/"+u,s,o,u,r)}n(r,o,s,i,a,l,c)}}function O$(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}var N$=Rh.exports;Object.defineProperty(We,"__esModule",{value:!0}),We.getSchemaRefs=We.resolveUrl=We.normalizeId=We._getFullPath=We.getFullPath=We.inlineRef=void 0;const M$=G,A$=Ph,L$=N$,j$=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function z$(e,t=!0){return typeof e=="boolean"?!0:t===!0?!cl(e):t?Oh(e)<=t:!1}We.inlineRef=z$;const D$=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function cl(e){for(const t in e){if(D$.has(t))return!0;const n=e[t];if(Array.isArray(n)&&n.some(cl)||typeof n=="object"&&cl(n))return!0}return!1}function Oh(e){let t=0;for(const n in e){if(n==="$ref")return 1/0;if(t++,!j$.has(n)&&(typeof e[n]=="object"&&(0,M$.eachItem)(e[n],r=>t+=Oh(r)),t===1/0))return 1/0}return t}function Nh(e,t="",n){n!==!1&&(t=gr(t));const r=e.parse(t);return Mh(e,r)}We.getFullPath=Nh;function Mh(e,t){return e.serialize(t).split("#")[0]+"#"}We._getFullPath=Mh;const U$=/#\/?$/;function gr(e){return e?e.replace(U$,""):""}We.normalizeId=gr;function q$(e,t,n){return n=gr(n),e.resolve(t,n)}We.resolveUrl=q$;const Z$=/^[a-z_][-a-z0-9._]*$/i;function F$(e,t){if(typeof e=="boolean")return{};const{schemaId:n,uriResolver:r}=this.opts,o=gr(e[n]||t),s={"":o},i=Nh(r,o,!1),a={},l=new Set;return L$(e,{allKeys:!0},(h,_,f,g)=>{if(g===void 0)return;const v=i+_;let m=s[g];typeof h[n]=="string"&&(m=d.call(this,h[n])),w.call(this,h.$anchor),w.call(this,h.$dynamicAnchor),s[_]=m;function d(y){const b=this.opts.uriResolver.resolve;if(y=gr(m?b(m,y):y),l.has(y))throw u(y);l.add(y);let k=this.refs[y];return typeof k=="string"&&(k=this.refs[k]),typeof k=="object"?c(h,k.schema,y):y!==gr(v)&&(y[0]==="#"?(c(h,a[y],y),a[y]=h):this.refs[y]=v),y}function w(y){if(typeof y=="string"){if(!Z$.test(y))throw new Error(`invalid anchor "${y}"`);d.call(this,`#${y}`)}}}),a;function c(h,_,f){if(_!==void 0&&!A$(h,_))throw u(f)}function u(h){return new Error(`reference "${h}" resolves to more than one schema`)}}We.getSchemaRefs=F$,Object.defineProperty(Zt,"__esModule",{value:!0}),Zt.getData=Zt.KeywordCxt=Zt.validateFunctionCode=void 0;const Ah=fr,Lh=Ue,ul=dn,ks=Ue,V$=Cs,po=nn,dl=kn,K=ce,re=tn,B$=We,pn=G,fo=co;function H$(e){if(Uh(e)&&(qh(e),Dh(e))){W$(e);return}jh(e,()=>(0,Ah.topBoolOrEmptySchema)(e))}Zt.validateFunctionCode=H$;function jh({gen:e,validateName:t,schema:n,schemaEnv:r,opts:o},s){o.code.es5?e.func(t,(0,K._)`${re.default.data}, ${re.default.valCxt}`,r.$async,()=>{e.code((0,K._)`"use strict"; ${zh(n,o)}`),G$(e,o),e.code(s)}):e.func(t,(0,K._)`${re.default.data}, ${J$(o)}`,r.$async,()=>e.code(zh(n,o)).code(s))}function J$(e){return(0,K._)`{${re.default.instancePath}="", ${re.default.parentData}, ${re.default.parentDataProperty}, ${re.default.rootData}=${re.default.data}${e.dynamicRef?(0,K._)`, ${re.default.dynamicAnchors}={}`:K.nil}}={}`}function G$(e,t){e.if(re.default.valCxt,()=>{e.var(re.default.instancePath,(0,K._)`${re.default.valCxt}.${re.default.instancePath}`),e.var(re.default.parentData,(0,K._)`${re.default.valCxt}.${re.default.parentData}`),e.var(re.default.parentDataProperty,(0,K._)`${re.default.valCxt}.${re.default.parentDataProperty}`),e.var(re.default.rootData,(0,K._)`${re.default.valCxt}.${re.default.rootData}`),t.dynamicRef&&e.var(re.default.dynamicAnchors,(0,K._)`${re.default.valCxt}.${re.default.dynamicAnchors}`)},()=>{e.var(re.default.instancePath,(0,K._)`""`),e.var(re.default.parentData,(0,K._)`undefined`),e.var(re.default.parentDataProperty,(0,K._)`undefined`),e.var(re.default.rootData,re.default.data),t.dynamicRef&&e.var(re.default.dynamicAnchors,(0,K._)`{}`)})}function W$(e){const{schema:t,opts:n,gen:r}=e;jh(e,()=>{n.$comment&&t.$comment&&Fh(e),eS(e),r.let(re.default.vErrors,null),r.let(re.default.errors,0),n.unevaluated&&K$(e),Zh(e),rS(e)})}function K$(e){const{gen:t,validateName:n}=e;e.evaluated=t.const("evaluated",(0,K._)`${n}.evaluated`),t.if((0,K._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,K._)`${e.evaluated}.props`,(0,K._)`undefined`)),t.if((0,K._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,K._)`${e.evaluated}.items`,(0,K._)`undefined`))}function zh(e,t){const n=typeof e=="object"&&e[t.schemaId];return n&&(t.code.source||t.code.process)?(0,K._)`/*# sourceURL=${n} */`:K.nil}function Y$(e,t){if(Uh(e)&&(qh(e),Dh(e))){Q$(e,t);return}(0,Ah.boolOrEmptySchema)(e,t)}function Dh({schema:e,self:t}){if(typeof e=="boolean")return!e;for(const n in e)if(t.RULES.all[n])return!0;return!1}function Uh(e){return typeof e.schema!="boolean"}function Q$(e,t){const{schema:n,gen:r,opts:o}=e;o.$comment&&n.$comment&&Fh(e),tS(e),nS(e);const s=r.const("_errs",re.default.errors);Zh(e,s),r.var(t,(0,K._)`${s} === ${re.default.errors}`)}function qh(e){(0,pn.checkUnknownRules)(e),X$(e)}function Zh(e,t){if(e.opts.jtd)return Vh(e,[],!1,t);const n=(0,Lh.getSchemaTypes)(e.schema),r=(0,Lh.coerceAndCheckDataType)(e,n);Vh(e,n,!r,t)}function X$(e){const{schema:t,errSchemaPath:n,opts:r,self:o}=e;t.$ref&&r.ignoreKeywordsWithRef&&(0,pn.schemaHasRulesButRef)(t,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function eS(e){const{schema:t,opts:n}=e;t.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,pn.checkStrictMode)(e,"default is ignored in the schema root")}function tS(e){const t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,B$.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function nS(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}function Fh({gen:e,schemaEnv:t,schema:n,errSchemaPath:r,opts:o}){const s=n.$comment;if(o.$comment===!0)e.code((0,K._)`${re.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){const i=(0,K.str)`${r}/$comment`,a=e.scopeValue("root",{ref:t.root});e.code((0,K._)`${re.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function rS(e){const{gen:t,schemaEnv:n,validateName:r,ValidationError:o,opts:s}=e;n.$async?t.if((0,K._)`${re.default.errors} === 0`,()=>t.return(re.default.data),()=>t.throw((0,K._)`new ${o}(${re.default.vErrors})`)):(t.assign((0,K._)`${r}.errors`,re.default.vErrors),s.unevaluated&&oS(e),t.return((0,K._)`${re.default.errors} === 0`))}function oS({gen:e,evaluated:t,props:n,items:r}){n instanceof K.Name&&e.assign((0,K._)`${t}.props`,n),r instanceof K.Name&&e.assign((0,K._)`${t}.items`,r)}function Vh(e,t,n,r){const{gen:o,schema:s,data:i,allErrors:a,opts:l,self:c}=e,{RULES:u}=c;if(s.$ref&&(l.ignoreKeywordsWithRef||!(0,pn.schemaHasRulesButRef)(s,u))){o.block(()=>Gh(e,"$ref",u.all.$ref.definition));return}l.jtd||sS(e,t),o.block(()=>{for(const _ of u.rules)h(_);h(u.post)});function h(_){(0,ul.shouldUseGroup)(s,_)&&(_.type?(o.if((0,ks.checkDataType)(_.type,i,l.strictNumbers)),Bh(e,_),t.length===1&&t[0]===_.type&&n&&(o.else(),(0,ks.reportTypeError)(e)),o.endIf()):Bh(e,_),a||o.if((0,K._)`${re.default.errors} === ${r||0}`))}}function Bh(e,t){const{gen:n,schema:r,opts:{useDefaults:o}}=e;o&&(0,V$.assignDefaults)(e,t.type),n.block(()=>{for(const s of t.rules)(0,ul.shouldUseRule)(r,s)&&Gh(e,s.keyword,s.definition,t.type)})}function sS(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(iS(e,t),e.opts.allowUnionTypes||aS(e,t),lS(e,e.dataTypes))}function iS(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(n=>{Hh(e.dataTypes,n)||pl(e,`type "${n}" not allowed by context "${e.dataTypes.join(",")}"`)}),uS(e,t)}}function aS(e,t){t.length>1&&!(t.length===2&&t.includes("null"))&&pl(e,"use allowUnionTypes to allow union type keyword")}function lS(e,t){const n=e.self.RULES.all;for(const r in n){const o=n[r];if(typeof o=="object"&&(0,ul.shouldUseRule)(e.schema,o)){const{type:s}=o.definition;s.length&&!s.some(i=>cS(t,i))&&pl(e,`missing type "${s.join(",")}" for keyword "${r}"`)}}}function cS(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}function Hh(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}function uS(e,t){const n=[];for(const r of e.dataTypes)Hh(t,r)?n.push(r):t.includes("integer")&&r==="number"&&n.push("integer");e.dataTypes=n}function pl(e,t){const n=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${n}" (strictTypes)`,(0,pn.checkStrictMode)(e,t,e.opts.strictTypes)}class Jh{constructor(t,n,r){if((0,po.validateKeywordUsage)(t,n,r),this.gen=t.gen,this.allErrors=t.allErrors,this.keyword=r,this.data=t.data,this.schema=t.schema[r],this.$data=n.$data&&t.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,pn.schemaRefOrVal)(t,this.schema,r,this.$data),this.schemaType=n.schemaType,this.parentSchema=t.schema,this.params={},this.it=t,this.def=n,this.$data)this.schemaCode=t.gen.const("vSchema",Wh(this.$data,t));else if(this.schemaCode=this.schemaValue,!(0,po.validSchemaType)(this.schema,n.schemaType,n.allowUndefined))throw new Error(`${r} value must be ${JSON.stringify(n.schemaType)}`);("code"in n?n.trackErrors:n.errors!==!1)&&(this.errsCount=t.gen.const("_errs",re.default.errors))}result(t,n,r){this.failResult((0,K.not)(t),n,r)}failResult(t,n,r){this.gen.if(t),r?r():this.error(),n?(this.gen.else(),n(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(t,n){this.failResult((0,K.not)(t),void 0,n)}fail(t){if(t===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(t),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(t){if(!this.$data)return this.fail(t);const{schemaCode:n}=this;this.fail((0,K._)`${n} !== undefined && (${(0,K.or)(this.invalid$data(),t)})`)}error(t,n,r){if(n){this.setParams(n),this._error(t,r),this.setParams({});return}this._error(t,r)}_error(t,n){(t?fo.reportExtraError:fo.reportError)(this,this.def.error,n)}$dataError(){(0,fo.reportError)(this,this.def.$dataError||fo.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,fo.resetErrorsCount)(this.gen,this.errsCount)}ok(t){this.allErrors||this.gen.if(t)}setParams(t,n){n?Object.assign(this.params,t):this.params=t}block$data(t,n,r=K.nil){this.gen.block(()=>{this.check$data(t,r),n()})}check$data(t=K.nil,n=K.nil){if(!this.$data)return;const{gen:r,schemaCode:o,schemaType:s,def:i}=this;r.if((0,K.or)((0,K._)`${o} === undefined`,n)),t!==K.nil&&r.assign(t,!0),(s.length||i.validateSchema)&&(r.elseIf(this.invalid$data()),this.$dataError(),t!==K.nil&&r.assign(t,!1)),r.else()}invalid$data(){const{gen:t,schemaCode:n,schemaType:r,def:o,it:s}=this;return(0,K.or)(i(),a());function i(){if(r.length){if(!(n instanceof K.Name))throw new Error("ajv implementation error");const l=Array.isArray(r)?r:[r];return(0,K._)`${(0,ks.checkDataTypes)(l,n,s.opts.strictNumbers,ks.DataType.Wrong)}`}return K.nil}function a(){if(o.validateSchema){const l=t.scopeValue("validate$data",{ref:o.validateSchema});return(0,K._)`!${l}(${n})`}return K.nil}}subschema(t,n){const r=(0,dl.getSubschema)(this.it,t);(0,dl.extendSubschemaData)(r,this.it,t),(0,dl.extendSubschemaMode)(r,t);const o={...this.it,...r,items:void 0,props:void 0};return Y$(o,n),o}mergeEvaluated(t,n){const{it:r,gen:o}=this;r.opts.unevaluated&&(r.props!==!0&&t.props!==void 0&&(r.props=pn.mergeEvaluated.props(o,t.props,r.props,n)),r.items!==!0&&t.items!==void 0&&(r.items=pn.mergeEvaluated.items(o,t.items,r.items,n)))}mergeValidEvaluated(t,n){const{it:r,gen:o}=this;if(r.opts.unevaluated&&(r.props!==!0||r.items!==!0))return o.if(n,()=>this.mergeEvaluated(t,K.Name)),!0}}Zt.KeywordCxt=Jh;function Gh(e,t,n,r){const o=new Jh(e,n,t);"code"in n?n.code(o,r):o.$data&&n.validate?(0,po.funcKeywordCode)(o,n):"macro"in n?(0,po.macroKeywordCode)(o,n):(n.compile||n.validate)&&(0,po.funcKeywordCode)(o,n)}const dS=/^\/(?:[^~]|~0|~1)*$/,pS=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Wh(e,{dataLevel:t,dataNames:n,dataPathArr:r}){let o,s;if(e==="")return re.default.rootData;if(e[0]==="/"){if(!dS.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);o=e,s=re.default.rootData}else{const c=pS.exec(e);if(!c)throw new Error(`Invalid JSON-pointer: ${e}`);const u=+c[1];if(o=c[2],o==="#"){if(u>=t)throw new Error(l("property/index",u));return r[t-u]}if(u>t)throw new Error(l("data",u));if(s=n[t-u],!o)return s}let i=s;const a=o.split("/");for(const c of a)c&&(s=(0,K._)`${s}${(0,K.getProperty)((0,pn.unescapeJsonPointer)(c))}`,i=(0,K._)`${i} && ${s}`);return i;function l(c,u){return`Cannot access ${c} ${u} levels up, current level is ${t}`}}Zt.getData=Wh;var ho={};Object.defineProperty(ho,"__esModule",{value:!0});class fS extends Error{constructor(t){super("validation failed"),this.errors=t,this.ajv=this.validation=!0}}ho.default=fS;var vr={};Object.defineProperty(vr,"__esModule",{value:!0});const fl=We;class hS extends Error{constructor(t,n,r,o){super(o||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,fl.resolveUrl)(t,n,r),this.missingSchema=(0,fl.normalizeId)((0,fl.getFullPath)(t,this.missingRef))}}vr.default=hS;var pt={};Object.defineProperty(pt,"__esModule",{value:!0}),pt.resolveSchema=pt.getCompilingSchema=pt.resolveRef=pt.compileSchema=pt.SchemaEnv=void 0;const Ft=ce,mS=ho,Xn=tn,Vt=We,Kh=G,gS=Zt;class Is{constructor(t){var n;this.refs={},this.dynamicAnchors={};let r;typeof t.schema=="object"&&(r=t.schema),this.schema=t.schema,this.schemaId=t.schemaId,this.root=t.root||this,this.baseId=(n=t.baseId)!==null&&n!==void 0?n:(0,Vt.normalizeId)(r==null?void 0:r[t.schemaId||"$id"]),this.schemaPath=t.schemaPath,this.localRefs=t.localRefs,this.meta=t.meta,this.$async=r==null?void 0:r.$async,this.refs={}}}pt.SchemaEnv=Is;function hl(e){const t=Yh.call(this,e);if(t)return t;const n=(0,Vt.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:r,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new Ft.CodeGen(this.scope,{es5:r,lines:o,ownProperties:s});let a;e.$async&&(a=i.scopeValue("Error",{ref:mS.default,code:(0,Ft._)`require("ajv/dist/runtime/validation_error").default`}));const l=i.scopeName("validate");e.validateName=l;const c={gen:i,allErrors:this.opts.allErrors,data:Xn.default.data,parentData:Xn.default.parentData,parentDataProperty:Xn.default.parentDataProperty,dataNames:[Xn.default.data],dataPathArr:[Ft.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,Ft.stringify)(e.schema)}:{ref:e.schema}),validateName:l,ValidationError:a,schema:e.schema,schemaEnv:e,rootId:n,baseId:e.baseId||n,schemaPath:Ft.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Ft._)`""`,opts:this.opts,self:this};let u;try{this._compilations.add(e),(0,gS.validateFunctionCode)(c),i.optimize(this.opts.code.optimize);const h=i.toString();u=`${i.scopeRefs(Xn.default.scope)}return ${h}`,this.opts.code.process&&(u=this.opts.code.process(u,e));const f=new Function(`${Xn.default.self}`,`${Xn.default.scope}`,u)(this,this.scope.get());if(this.scope.value(l,{ref:f}),f.errors=null,f.schema=e.schema,f.schemaEnv=e,e.$async&&(f.$async=!0),this.opts.code.source===!0&&(f.source={validateName:l,validateCode:h,scopeValues:i._values}),this.opts.unevaluated){const{props:g,items:v}=c;f.evaluated={props:g instanceof Ft.Name?void 0:g,items:v instanceof Ft.Name?void 0:v,dynamicProps:g instanceof Ft.Name,dynamicItems:v instanceof Ft.Name},f.source&&(f.source.evaluated=(0,Ft.stringify)(f.evaluated))}return e.validate=f,e}catch(h){throw delete e.validate,delete e.validateName,u&&this.logger.error("Error compiling schema, function code:",u),h}finally{this._compilations.delete(e)}}pt.compileSchema=hl;function vS(e,t,n){var r;n=(0,Vt.resolveUrl)(this.opts.uriResolver,t,n);const o=e.refs[n];if(o)return o;let s=wS.call(this,e,n);if(s===void 0){const i=(r=e.localRefs)===null||r===void 0?void 0:r[n],{schemaId:a}=this.opts;i&&(s=new Is({schema:i,schemaId:a,root:e,baseId:t}))}if(s!==void 0)return e.refs[n]=_S.call(this,s)}pt.resolveRef=vS;function _S(e){return(0,Vt.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:hl.call(this,e)}function Yh(e){for(const t of this._compilations)if(yS(t,e))return t}pt.getCompilingSchema=Yh;function yS(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function wS(e,t){let n;for(;typeof(n=this.refs[t])=="string";)t=n;return n||this.schemas[t]||Ts.call(this,e,t)}function Ts(e,t){const n=this.opts.uriResolver.parse(t),r=(0,Vt._getFullPath)(this.opts.uriResolver,n);let o=(0,Vt.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&r===o)return ml.call(this,n,e);const s=(0,Vt.normalizeId)(r),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){const a=Ts.call(this,e,i);return typeof(a==null?void 0:a.schema)!="object"?void 0:ml.call(this,n,a)}if(typeof(i==null?void 0:i.schema)=="object"){if(i.validate||hl.call(this,i),s===(0,Vt.normalizeId)(t)){const{schema:a}=i,{schemaId:l}=this.opts,c=a[l];return c&&(o=(0,Vt.resolveUrl)(this.opts.uriResolver,o,c)),new Is({schema:a,schemaId:l,root:e,baseId:o})}return ml.call(this,n,i)}}pt.resolveSchema=Ts;const bS=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function ml(e,{baseId:t,schema:n,root:r}){var o;if(((o=e.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(const a of e.fragment.slice(1).split("/")){if(typeof n=="boolean")return;const l=n[(0,Kh.unescapeFragment)(a)];if(l===void 0)return;n=l;const c=typeof n=="object"&&n[this.opts.schemaId];!bS.has(a)&&c&&(t=(0,Vt.resolveUrl)(this.opts.uriResolver,t,c))}let s;if(typeof n!="boolean"&&n.$ref&&!(0,Kh.schemaHasRulesButRef)(n,this.RULES)){const a=(0,Vt.resolveUrl)(this.opts.uriResolver,t,n.$ref);s=Ts.call(this,r,a)}const{schemaId:i}=this.opts;if(s=s||new Is({schema:n,schemaId:i,root:r,baseId:t}),s.schema!==s.root.schema)return s}const $S={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1};var gl={},xs={exports:{}};const SS=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Qh=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function Xh(e){let t="",n=0,r=0;for(r=0;r<e.length;r++)if(n=e[r].charCodeAt(0),n!==48){if(!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";t+=e[r];break}for(r+=1;r<e.length;r++){if(n=e[r].charCodeAt(0),!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";t+=e[r]}return t}const CS=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function e2(e){return e.length=0,!0}function ES(e,t,n){if(e.length){const r=Xh(e);if(r!=="")t.push(r);else return n.error=!0,!1;e.length=0}return!0}function kS(e){let t=0;const n={error:!1,address:"",zone:""},r=[],o=[];let s=!1,i=!1,a=ES;for(let l=0;l<e.length;l++){const c=e[l];if(!(c==="["||c==="]"))if(c===":"){if(s===!0&&(i=!0),!a(o,r,n))break;if(++t>7){n.error=!0;break}l>0&&e[l-1]===":"&&(s=!0),r.push(":");continue}else if(c==="%"){if(!a(o,r,n))break;a=e2}else{o.push(c);continue}}return o.length&&(a===e2?n.zone=o.join(""):i?r.push(o.join("")):r.push(Xh(o))),n.address=r.join(""),n}function t2(e){if(IS(e,":")<2)return{host:e,isIPV6:!1};const t=kS(e);if(t.error)return{host:e,isIPV6:!1};{let n=t.address,r=t.address;return t.zone&&(n+="%"+t.zone,r+="%25"+t.zone),{host:n,isIPV6:!0,escapedHost:r}}}function IS(e,t){let n=0;for(let r=0;r<e.length;r++)e[r]===t&&n++;return n}function TS(e){let t=e;const n=[];let r=-1,o=0;for(;o=t.length;){if(o===1){if(t===".")break;if(t==="/"){n.push("/");break}else{n.push(t);break}}else if(o===2){if(t[0]==="."){if(t[1]===".")break;if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"&&(t[1]==="."||t[1]==="/")){n.push("/");break}}else if(o===3&&t==="/.."){n.length!==0&&n.pop(),n.push("/");break}if(t[0]==="."){if(t[1]==="."){if(t[2]==="/"){t=t.slice(3);continue}}else if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"&&t[1]==="."){if(t[2]==="/"){t=t.slice(2);continue}else if(t[2]==="."&&t[3]==="/"){t=t.slice(3),n.length!==0&&n.pop();continue}}if((r=t.indexOf("/",1))===-1){n.push(t);break}else n.push(t.slice(0,r)),t=t.slice(r)}return n.join("")}function xS(e,t){const n=t!==!0?escape:unescape;return e.scheme!==void 0&&(e.scheme=n(e.scheme)),e.userinfo!==void 0&&(e.userinfo=n(e.userinfo)),e.host!==void 0&&(e.host=n(e.host)),e.path!==void 0&&(e.path=n(e.path)),e.query!==void 0&&(e.query=n(e.query)),e.fragment!==void 0&&(e.fragment=n(e.fragment)),e}function PS(e){const t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push("@")),e.host!==void 0){let n=unescape(e.host);if(!Qh(n)){const r=t2(n);r.isIPV6===!0?n=`[${r.escapedHost}]`:n=e.host}t.push(n)}return(typeof e.port=="number"||typeof e.port=="string")&&(t.push(":"),t.push(String(e.port))),t.length?t.join(""):void 0}var n2={nonSimpleDomain:CS,recomposeAuthority:PS,normalizeComponentEncoding:xS,removeDotSegments:TS,isIPv4:Qh,isUUID:SS,normalizeIPv6:t2};const{isUUID:RS}=n2,OS=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu;function r2(e){return e.secure===!0?!0:e.secure===!1?!1:e.scheme?e.scheme.length===3&&(e.scheme[0]==="w"||e.scheme[0]==="W")&&(e.scheme[1]==="s"||e.scheme[1]==="S")&&(e.scheme[2]==="s"||e.scheme[2]==="S"):!1}function o2(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function s2(e){const t=String(e.scheme).toLowerCase()==="https";return(e.port===(t?443:80)||e.port==="")&&(e.port=void 0),e.path||(e.path="/"),e}function NS(e){return e.secure=r2(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}function MS(e){if((e.port===(r2(e)?443:80)||e.port==="")&&(e.port=void 0),typeof e.secure=="boolean"&&(e.scheme=e.secure?"wss":"ws",e.secure=void 0),e.resourceName){const[t,n]=e.resourceName.split("?");e.path=t&&t!=="/"?t:void 0,e.query=n,e.resourceName=void 0}return e.fragment=void 0,e}function AS(e,t){if(!e.path)return e.error="URN can not be parsed",e;const n=e.path.match(OS);if(n){const r=t.scheme||e.scheme||"urn";e.nid=n[1].toLowerCase(),e.nss=n[2];const o=`${r}:${t.nid||e.nid}`,s=vl(o);e.path=void 0,s&&(e=s.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e}function LS(e,t){if(e.nid===void 0)throw new Error("URN without nid cannot be serialized");const n=t.scheme||e.scheme||"urn",r=e.nid.toLowerCase(),o=`${n}:${t.nid||r}`,s=vl(o);s&&(e=s.serialize(e,t));const i=e,a=e.nss;return i.path=`${r||t.nid}:${a}`,t.skipEscape=!0,i}function jS(e,t){const n=e;return n.uuid=n.nss,n.nss=void 0,!t.tolerant&&(!n.uuid||!RS(n.uuid))&&(n.error=n.error||"UUID is not valid."),n}function zS(e){const t=e;return t.nss=(e.uuid||"").toLowerCase(),t}const i2={scheme:"http",domainHost:!0,parse:o2,serialize:s2},DS={scheme:"https",domainHost:i2.domainHost,parse:o2,serialize:s2},Ps={scheme:"ws",domainHost:!0,parse:NS,serialize:MS},US={scheme:"wss",domainHost:Ps.domainHost,parse:Ps.parse,serialize:Ps.serialize},Rs={http:i2,https:DS,ws:Ps,wss:US,urn:{scheme:"urn",parse:AS,serialize:LS,skipNormalize:!0},"urn:uuid":{scheme:"urn:uuid",parse:jS,serialize:zS,skipNormalize:!0}};Object.setPrototypeOf(Rs,null);function vl(e){return e&&(Rs[e]||Rs[e.toLowerCase()])||void 0}var qS={SCHEMES:Rs,getSchemeHandler:vl};const{normalizeIPv6:ZS,removeDotSegments:mo,recomposeAuthority:FS,normalizeComponentEncoding:Os,isIPv4:VS,nonSimpleDomain:BS}=n2,{SCHEMES:HS,getSchemeHandler:a2}=qS;function JS(e,t){return typeof e=="string"?e=on(fn(e,t),t):typeof e=="object"&&(e=fn(on(e,t),t)),e}function GS(e,t,n){const r=n?Object.assign({scheme:"null"},n):{scheme:"null"},o=l2(fn(e,r),fn(t,r),r,!0);return r.skipEscape=!0,on(o,r)}function l2(e,t,n,r){const o={};return r||(e=fn(on(e,n),n),t=fn(on(t,n),n)),n=n||{},!n.tolerant&&t.scheme?(o.scheme=t.scheme,o.userinfo=t.userinfo,o.host=t.host,o.port=t.port,o.path=mo(t.path||""),o.query=t.query):(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0?(o.userinfo=t.userinfo,o.host=t.host,o.port=t.port,o.path=mo(t.path||""),o.query=t.query):(t.path?(t.path[0]==="/"?o.path=mo(t.path):((e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)&&!e.path?o.path="/"+t.path:e.path?o.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path:o.path=t.path,o.path=mo(o.path)),o.query=t.query):(o.path=e.path,t.query!==void 0?o.query=t.query:o.query=e.query),o.userinfo=e.userinfo,o.host=e.host,o.port=e.port),o.scheme=e.scheme),o.fragment=t.fragment,o}function WS(e,t,n){return typeof e=="string"?(e=unescape(e),e=on(Os(fn(e,n),!0),{...n,skipEscape:!0})):typeof e=="object"&&(e=on(Os(e,!0),{...n,skipEscape:!0})),typeof t=="string"?(t=unescape(t),t=on(Os(fn(t,n),!0),{...n,skipEscape:!0})):typeof t=="object"&&(t=on(Os(t,!0),{...n,skipEscape:!0})),e.toLowerCase()===t.toLowerCase()}function on(e,t){const n={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:""},r=Object.assign({},t),o=[],s=a2(r.scheme||n.scheme);s&&s.serialize&&s.serialize(n,r),n.path!==void 0&&(r.skipEscape?n.path=unescape(n.path):(n.path=escape(n.path),n.scheme!==void 0&&(n.path=n.path.split("%3A").join(":")))),r.reference!=="suffix"&&n.scheme&&o.push(n.scheme,":");const i=FS(n);if(i!==void 0&&(r.reference!=="suffix"&&o.push("//"),o.push(i),n.path&&n.path[0]!=="/"&&o.push("/")),n.path!==void 0){let a=n.path;!r.absolutePath&&(!s||!s.absolutePath)&&(a=mo(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),o.push(a)}return n.query!==void 0&&o.push("?",n.query),n.fragment!==void 0&&o.push("#",n.fragment),o.join("")}const KS=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function fn(e,t){const n=Object.assign({},t),r={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0};let o=!1;n.reference==="suffix"&&(n.scheme?e=n.scheme+":"+e:e="//"+e);const s=e.match(KS);if(s){if(r.scheme=s[1],r.userinfo=s[3],r.host=s[4],r.port=parseInt(s[5],10),r.path=s[6]||"",r.query=s[7],r.fragment=s[8],isNaN(r.port)&&(r.port=s[5]),r.host)if(VS(r.host)===!1){const l=ZS(r.host);r.host=l.host.toLowerCase(),o=l.isIPV6}else o=!0;r.scheme===void 0&&r.userinfo===void 0&&r.host===void 0&&r.port===void 0&&r.query===void 0&&!r.path?r.reference="same-document":r.scheme===void 0?r.reference="relative":r.fragment===void 0?r.reference="absolute":r.reference="uri",n.reference&&n.reference!=="suffix"&&n.reference!==r.reference&&(r.error=r.error||"URI is not a "+n.reference+" reference.");const i=a2(n.scheme||r.scheme);if(!n.unicodeSupport&&(!i||!i.unicodeSupport)&&r.host&&(n.domainHost||i&&i.domainHost)&&o===!1&&BS(r.host))try{r.host=URL.domainToASCII(r.host.toLowerCase())}catch(a){r.error=r.error||"Host's domain name can not be converted to ASCII: "+a}(!i||i&&!i.skipNormalize)&&(e.indexOf("%")!==-1&&(r.scheme!==void 0&&(r.scheme=unescape(r.scheme)),r.host!==void 0&&(r.host=unescape(r.host))),r.path&&(r.path=escape(unescape(r.path))),r.fragment&&(r.fragment=encodeURI(decodeURIComponent(r.fragment)))),i&&i.parse&&i.parse(r,n)}else r.error=r.error||"URI can not be parsed.";return r}const _l={SCHEMES:HS,normalize:JS,resolve:GS,resolveComponent:l2,equal:WS,serialize:on,parse:fn};xs.exports=_l,xs.exports.default=_l,xs.exports.fastUri=_l;var YS=xs.exports;Object.defineProperty(gl,"__esModule",{value:!0});const c2=YS;c2.code='require("ajv/dist/runtime/uri").default',gl.default=c2,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=void 0;var t=Zt;Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var n=ce;Object.defineProperty(e,"_",{enumerable:!0,get:function(){return n._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return n.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return n.CodeGen}});const r=ho,o=vr,s=Yn,i=pt,a=ce,l=We,c=Ue,u=G,h=$S,_=gl,f=(L,I)=>new RegExp(L,I);f.code="new RegExp";const g=["removeAdditional","useDefaults","coerceTypes"],v=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),m={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},d={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},w=200;function y(L){var I,M,P,C,E,$,j,z,de,oe,_e,Rt,Ne,ve,ye,Le,fe,Ze,gt,J,$e,Ot,Se,vt,mn;const _t=L.strict,Ye=(I=L.code)===null||I===void 0?void 0:I.optimize,Nt=Ye===!0||Ye===void 0?1:Ye||0,Nn=(P=(M=L.code)===null||M===void 0?void 0:M.regExp)!==null&&P!==void 0?P:f,Mn=(C=L.uriResolver)!==null&&C!==void 0?C:_.default;return{strictSchema:($=(E=L.strictSchema)!==null&&E!==void 0?E:_t)!==null&&$!==void 0?$:!0,strictNumbers:(z=(j=L.strictNumbers)!==null&&j!==void 0?j:_t)!==null&&z!==void 0?z:!0,strictTypes:(oe=(de=L.strictTypes)!==null&&de!==void 0?de:_t)!==null&&oe!==void 0?oe:"log",strictTuples:(Rt=(_e=L.strictTuples)!==null&&_e!==void 0?_e:_t)!==null&&Rt!==void 0?Rt:"log",strictRequired:(ve=(Ne=L.strictRequired)!==null&&Ne!==void 0?Ne:_t)!==null&&ve!==void 0?ve:!1,code:L.code?{...L.code,optimize:Nt,regExp:Nn}:{optimize:Nt,regExp:Nn},loopRequired:(ye=L.loopRequired)!==null&&ye!==void 0?ye:w,loopEnum:(Le=L.loopEnum)!==null&&Le!==void 0?Le:w,meta:(fe=L.meta)!==null&&fe!==void 0?fe:!0,messages:(Ze=L.messages)!==null&&Ze!==void 0?Ze:!0,inlineRefs:(gt=L.inlineRefs)!==null&&gt!==void 0?gt:!0,schemaId:(J=L.schemaId)!==null&&J!==void 0?J:"$id",addUsedSchema:($e=L.addUsedSchema)!==null&&$e!==void 0?$e:!0,validateSchema:(Ot=L.validateSchema)!==null&&Ot!==void 0?Ot:!0,validateFormats:(Se=L.validateFormats)!==null&&Se!==void 0?Se:!0,unicodeRegExp:(vt=L.unicodeRegExp)!==null&&vt!==void 0?vt:!0,int32range:(mn=L.int32range)!==null&&mn!==void 0?mn:!0,uriResolver:Mn}}class b{constructor(I={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,I=this.opts={...I,...y(I)};const{es5:M,lines:P}=this.opts.code;this.scope=new a.ValueScope({scope:{},prefixes:v,es5:M,lines:P}),this.logger=F(I.logger);const C=I.validateFormats;I.validateFormats=!1,this.RULES=(0,s.getRules)(),k.call(this,m,I,"NOT SUPPORTED"),k.call(this,d,I,"DEPRECATED","warn"),this._metaOpts=H.call(this),I.formats&&D.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),I.keywords&&U.call(this,I.keywords),typeof I.meta=="object"&&this.addMetaSchema(I.meta),T.call(this),I.validateFormats=C}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){const{$data:I,meta:M,schemaId:P}=this.opts;let C=h;P==="id"&&(C={...h},C.id=C.$id,delete C.$id),M&&I&&this.addMetaSchema(C,C[P],!1)}defaultMeta(){const{meta:I,schemaId:M}=this.opts;return this.opts.defaultMeta=typeof I=="object"?I[M]||I:void 0}validate(I,M){let P;if(typeof I=="string"){if(P=this.getSchema(I),!P)throw new Error(`no schema with key or ref "${I}"`)}else P=this.compile(I);const C=P(M);return"$async"in P||(this.errors=P.errors),C}compile(I,M){const P=this._addSchema(I,M);return P.validate||this._compileSchemaEnv(P)}compileAsync(I,M){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");const{loadSchema:P}=this.opts;return C.call(this,I,M);async function C(oe,_e){await E.call(this,oe.$schema);const Rt=this._addSchema(oe,_e);return Rt.validate||$.call(this,Rt)}async function E(oe){oe&&!this.getSchema(oe)&&await C.call(this,{$ref:oe},!0)}async function $(oe){try{return this._compileSchemaEnv(oe)}catch(_e){if(!(_e instanceof o.default))throw _e;return j.call(this,_e),await z.call(this,_e.missingSchema),$.call(this,oe)}}function j({missingSchema:oe,missingRef:_e}){if(this.refs[oe])throw new Error(`AnySchema ${oe} is loaded but ${_e} cannot be resolved`)}async function z(oe){const _e=await de.call(this,oe);this.refs[oe]||await E.call(this,_e.$schema),this.refs[oe]||this.addSchema(_e,oe,M)}async function de(oe){const _e=this._loading[oe];if(_e)return _e;try{return await(this._loading[oe]=P(oe))}finally{delete this._loading[oe]}}}addSchema(I,M,P,C=this.opts.validateSchema){if(Array.isArray(I)){for(const $ of I)this.addSchema($,void 0,P,C);return this}let E;if(typeof I=="object"){const{schemaId:$}=this.opts;if(E=I[$],E!==void 0&&typeof E!="string")throw new Error(`schema ${$} must be string`)}return M=(0,l.normalizeId)(M||E),this._checkUnique(M),this.schemas[M]=this._addSchema(I,P,M,C,!0),this}addMetaSchema(I,M,P=this.opts.validateSchema){return this.addSchema(I,M,!0,P),this}validateSchema(I,M){if(typeof I=="boolean")return!0;let P;if(P=I.$schema,P!==void 0&&typeof P!="string")throw new Error("$schema must be a string");if(P=P||this.opts.defaultMeta||this.defaultMeta(),!P)return this.logger.warn("meta-schema not available"),this.errors=null,!0;const C=this.validate(P,I);if(!C&&M){const E="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(E);else throw new Error(E)}return C}getSchema(I){let M;for(;typeof(M=x.call(this,I))=="string";)I=M;if(M===void 0){const{schemaId:P}=this.opts,C=new i.SchemaEnv({schema:{},schemaId:P});if(M=i.resolveSchema.call(this,C,I),!M)return;this.refs[I]=M}return M.validate||this._compileSchemaEnv(M)}removeSchema(I){if(I instanceof RegExp)return this._removeAllSchemas(this.schemas,I),this._removeAllSchemas(this.refs,I),this;switch(typeof I){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{const M=x.call(this,I);return typeof M=="object"&&this._cache.delete(M.schema),delete this.schemas[I],delete this.refs[I],this}case"object":{const M=I;this._cache.delete(M);let P=I[this.opts.schemaId];return P&&(P=(0,l.normalizeId)(P),delete this.schemas[P],delete this.refs[P]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(I){for(const M of I)this.addKeyword(M);return this}addKeyword(I,M){let P;if(typeof I=="string")P=I,typeof M=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),M.keyword=P);else if(typeof I=="object"&&M===void 0){if(M=I,P=M.keyword,Array.isArray(P)&&!P.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(V.call(this,P,M),!M)return(0,u.eachItem)(P,E=>se.call(this,E)),this;te.call(this,M);const C={...M,type:(0,c.getJSONTypes)(M.type),schemaType:(0,c.getJSONTypes)(M.schemaType)};return(0,u.eachItem)(P,C.type.length===0?E=>se.call(this,E,C):E=>C.type.forEach($=>se.call(this,E,C,$))),this}getKeyword(I){const M=this.RULES.all[I];return typeof M=="object"?M.definition:!!M}removeKeyword(I){const{RULES:M}=this;delete M.keywords[I],delete M.all[I];for(const P of M.rules){const C=P.rules.findIndex(E=>E.keyword===I);C>=0&&P.rules.splice(C,1)}return this}addFormat(I,M){return typeof M=="string"&&(M=new RegExp(M)),this.formats[I]=M,this}errorsText(I=this.errors,{separator:M=", ",dataVar:P="data"}={}){return!I||I.length===0?"No errors":I.map(C=>`${P}${C.instancePath} ${C.message}`).reduce((C,E)=>C+M+E)}$dataMetaSchema(I,M){const P=this.RULES.all;I=JSON.parse(JSON.stringify(I));for(const C of M){const E=C.split("/").slice(1);let $=I;for(const j of E)$=$[j];for(const j in P){const z=P[j];if(typeof z!="object")continue;const{$data:de}=z.definition,oe=$[j];de&&oe&&($[j]=le(oe))}}return I}_removeAllSchemas(I,M){for(const P in I){const C=I[P];(!M||M.test(P))&&(typeof C=="string"?delete I[P]:C&&!C.meta&&(this._cache.delete(C.schema),delete I[P]))}}_addSchema(I,M,P,C=this.opts.validateSchema,E=this.opts.addUsedSchema){let $;const{schemaId:j}=this.opts;if(typeof I=="object")$=I[j];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof I!="boolean")throw new Error("schema must be object or boolean")}let z=this._cache.get(I);if(z!==void 0)return z;P=(0,l.normalizeId)($||P);const de=l.getSchemaRefs.call(this,I,P);return z=new i.SchemaEnv({schema:I,schemaId:j,meta:M,baseId:P,localRefs:de}),this._cache.set(z.schema,z),E&&!P.startsWith("#")&&(P&&this._checkUnique(P),this.refs[P]=z),C&&this.validateSchema(I,!0),z}_checkUnique(I){if(this.schemas[I]||this.refs[I])throw new Error(`schema with key or id "${I}" already exists`)}_compileSchemaEnv(I){if(I.meta?this._compileMetaSchema(I):i.compileSchema.call(this,I),!I.validate)throw new Error("ajv implementation error");return I.validate}_compileMetaSchema(I){const M=this.opts;this.opts=this._metaOpts;try{i.compileSchema.call(this,I)}finally{this.opts=M}}}b.ValidationError=r.default,b.MissingRefError=o.default,e.default=b;function k(L,I,M,P="error"){for(const C in L){const E=C;E in I&&this.logger[P](`${M}: option ${C}. ${L[E]}`)}}function x(L){return L=(0,l.normalizeId)(L),this.schemas[L]||this.refs[L]}function T(){const L=this.opts.schemas;if(L)if(Array.isArray(L))this.addSchema(L);else for(const I in L)this.addSchema(L[I],I)}function D(){for(const L in this.opts.formats){const I=this.opts.formats[L];I&&this.addFormat(L,I)}}function U(L){if(Array.isArray(L)){this.addVocabulary(L);return}this.logger.warn("keywords option as map is deprecated, pass array");for(const I in L){const M=L[I];M.keyword||(M.keyword=I),this.addKeyword(M)}}function H(){const L={...this.opts};for(const I of g)delete L[I];return L}const q={log(){},warn(){},error(){}};function F(L){if(L===!1)return q;if(L===void 0)return console;if(L.log&&L.warn&&L.error)return L;throw new Error("logger must implement log, warn and error methods")}const B=/^[a-z_$][a-z0-9_$:-]*$/i;function V(L,I){const{RULES:M}=this;if((0,u.eachItem)(L,P=>{if(M.keywords[P])throw new Error(`Keyword ${P} is already defined`);if(!B.test(P))throw new Error(`Keyword ${P} has invalid name`)}),!!I&&I.$data&&!("code"in I||"validate"in I))throw new Error('$data keyword must have "code" or "validate" function')}function se(L,I,M){var P;const C=I==null?void 0:I.post;if(M&&C)throw new Error('keyword with "post" flag cannot have "type"');const{RULES:E}=this;let $=C?E.post:E.rules.find(({type:z})=>z===M);if($||($={type:M,rules:[]},E.rules.push($)),E.keywords[L]=!0,!I)return;const j={keyword:L,definition:{...I,type:(0,c.getJSONTypes)(I.type),schemaType:(0,c.getJSONTypes)(I.schemaType)}};I.before?ge.call(this,$,j,I.before):$.rules.push(j),E.all[L]=j,(P=I.implements)===null||P===void 0||P.forEach(z=>this.addKeyword(z))}function ge(L,I,M){const P=L.rules.findIndex(C=>C.keyword===M);P>=0?L.rules.splice(P,0,I):(L.rules.push(I),this.logger.warn(`rule ${M} is not defined`))}function te(L){let{metaSchema:I}=L;I!==void 0&&(L.$data&&this.opts.$data&&(I=le(I)),L.validateSchema=this.compile(I,!0))}const ue={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function le(L){return{anyOf:[L,ue]}}}(uh);var yl={},wl={},bl={};Object.defineProperty(bl,"__esModule",{value:!0});const QS={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};bl.default=QS;var er={};Object.defineProperty(er,"__esModule",{value:!0}),er.callRef=er.getValidate=void 0;const XS=vr,u2=pe,ft=ce,_r=tn,d2=pt,Ns=G,eC={keyword:"$ref",schemaType:"string",code(e){const{gen:t,schema:n,it:r}=e,{baseId:o,schemaEnv:s,validateName:i,opts:a,self:l}=r,{root:c}=s;if((n==="#"||n==="#/")&&o===c.baseId)return h();const u=d2.resolveRef.call(l,c,o,n);if(u===void 0)throw new XS.default(r.opts.uriResolver,o,n);if(u instanceof d2.SchemaEnv)return _(u);return f(u);function h(){if(s===c)return Ms(e,i,s,s.$async);const g=t.scopeValue("root",{ref:c});return Ms(e,(0,ft._)`${g}.validate`,c,c.$async)}function _(g){const v=p2(e,g);Ms(e,v,g,g.$async)}function f(g){const v=t.scopeValue("schema",a.code.source===!0?{ref:g,code:(0,ft.stringify)(g)}:{ref:g}),m=t.name("valid"),d=e.subschema({schema:g,dataTypes:[],schemaPath:ft.nil,topSchemaRef:v,errSchemaPath:n},m);e.mergeEvaluated(d),e.ok(m)}}};function p2(e,t){const{gen:n}=e;return t.validate?n.scopeValue("validate",{ref:t.validate}):(0,ft._)`${n.scopeValue("wrapper",{ref:t})}.validate`}er.getValidate=p2;function Ms(e,t,n,r){const{gen:o,it:s}=e,{allErrors:i,schemaEnv:a,opts:l}=s,c=l.passContext?_r.default.this:ft.nil;r?u():h();function u(){if(!a.$async)throw new Error("async schema referenced by sync schema");const g=o.let("valid");o.try(()=>{o.code((0,ft._)`await ${(0,u2.callValidateCode)(e,t,c)}`),f(t),i||o.assign(g,!0)},v=>{o.if((0,ft._)`!(${v} instanceof ${s.ValidationError})`,()=>o.throw(v)),_(v),i||o.assign(g,!1)}),e.ok(g)}function h(){e.result((0,u2.callValidateCode)(e,t,c),()=>f(t),()=>_(t))}function _(g){const v=(0,ft._)`${g}.errors`;o.assign(_r.default.vErrors,(0,ft._)`${_r.default.vErrors} === null ? ${v} : ${_r.default.vErrors}.concat(${v})`),o.assign(_r.default.errors,(0,ft._)`${_r.default.vErrors}.length`)}function f(g){var v;if(!s.opts.unevaluated)return;const m=(v=n==null?void 0:n.validate)===null||v===void 0?void 0:v.evaluated;if(s.props!==!0)if(m&&!m.dynamicProps)m.props!==void 0&&(s.props=Ns.mergeEvaluated.props(o,m.props,s.props));else{const d=o.var("props",(0,ft._)`${g}.evaluated.props`);s.props=Ns.mergeEvaluated.props(o,d,s.props,ft.Name)}if(s.items!==!0)if(m&&!m.dynamicItems)m.items!==void 0&&(s.items=Ns.mergeEvaluated.items(o,m.items,s.items));else{const d=o.var("items",(0,ft._)`${g}.evaluated.items`);s.items=Ns.mergeEvaluated.items(o,d,s.items,ft.Name)}}}er.callRef=Ms,er.default=eC,Object.defineProperty(wl,"__esModule",{value:!0});const tC=bl,nC=er,rC=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",tC.default,nC.default];wl.default=rC;var $l={},Sl={};Object.defineProperty(Sl,"__esModule",{value:!0});const As=ce,Tn=As.operators,Ls={maximum:{okStr:"<=",ok:Tn.LTE,fail:Tn.GT},minimum:{okStr:">=",ok:Tn.GTE,fail:Tn.LT},exclusiveMaximum:{okStr:"<",ok:Tn.LT,fail:Tn.GTE},exclusiveMinimum:{okStr:">",ok:Tn.GT,fail:Tn.LTE}},oC={message:({keyword:e,schemaCode:t})=>(0,As.str)`must be ${Ls[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,As._)`{comparison: ${Ls[e].okStr}, limit: ${t}}`},sC={keyword:Object.keys(Ls),type:"number",schemaType:"number",$data:!0,error:oC,code(e){const{keyword:t,data:n,schemaCode:r}=e;e.fail$data((0,As._)`${n} ${Ls[t].fail} ${r} || isNaN(${n})`)}};Sl.default=sC;var Cl={};Object.defineProperty(Cl,"__esModule",{value:!0});const go=ce,iC={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:{message:({schemaCode:e})=>(0,go.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,go._)`{multipleOf: ${e}}`},code(e){const{gen:t,data:n,schemaCode:r,it:o}=e,s=o.opts.multipleOfPrecision,i=t.let("res"),a=s?(0,go._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,go._)`${i} !== parseInt(${i})`;e.fail$data((0,go._)`(${r} === 0 || (${i} = ${n}/${r}, ${a}))`)}};Cl.default=iC;var El={},kl={};Object.defineProperty(kl,"__esModule",{value:!0});function f2(e){const t=e.length;let n=0,r=0,o;for(;r<t;)n++,o=e.charCodeAt(r++),o>=55296&&o<=56319&&r<t&&(o=e.charCodeAt(r),(o&64512)===56320&&r++);return n}kl.default=f2,f2.code='require("ajv/dist/runtime/ucs2length").default',Object.defineProperty(El,"__esModule",{value:!0});const tr=ce,aC=G,lC=kl,cC={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:{message({keyword:e,schemaCode:t}){const n=e==="maxLength"?"more":"fewer";return(0,tr.str)`must NOT have ${n} than ${t} characters`},params:({schemaCode:e})=>(0,tr._)`{limit: ${e}}`},code(e){const{keyword:t,data:n,schemaCode:r,it:o}=e,s=t==="maxLength"?tr.operators.GT:tr.operators.LT,i=o.opts.unicode===!1?(0,tr._)`${n}.length`:(0,tr._)`${(0,aC.useFunc)(e.gen,lC.default)}(${n})`;e.fail$data((0,tr._)`${i} ${s} ${r}`)}};El.default=cC;var Il={};Object.defineProperty(Il,"__esModule",{value:!0});const uC=pe,js=ce,dC={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:{message:({schemaCode:e})=>(0,js.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,js._)`{pattern: ${e}}`},code(e){const{data:t,$data:n,schema:r,schemaCode:o,it:s}=e,i=s.opts.unicodeRegExp?"u":"",a=n?(0,js._)`(new RegExp(${o}, ${i}))`:(0,uC.usePattern)(e,r);e.fail$data((0,js._)`!${a}.test(${t})`)}};Il.default=dC;var Tl={};Object.defineProperty(Tl,"__esModule",{value:!0});const vo=ce,pC={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:{message({keyword:e,schemaCode:t}){const n=e==="maxProperties"?"more":"fewer";return(0,vo.str)`must NOT have ${n} than ${t} properties`},params:({schemaCode:e})=>(0,vo._)`{limit: ${e}}`},code(e){const{keyword:t,data:n,schemaCode:r}=e,o=t==="maxProperties"?vo.operators.GT:vo.operators.LT;e.fail$data((0,vo._)`Object.keys(${n}).length ${o} ${r}`)}};Tl.default=pC;var xl={};Object.defineProperty(xl,"__esModule",{value:!0});const _o=pe,yo=ce,fC=G,hC={keyword:"required",type:"object",schemaType:"array",$data:!0,error:{message:({params:{missingProperty:e}})=>(0,yo.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,yo._)`{missingProperty: ${e}}`},code(e){const{gen:t,schema:n,schemaCode:r,data:o,$data:s,it:i}=e,{opts:a}=i;if(!s&&n.length===0)return;const l=n.length>=a.loopRequired;if(i.allErrors?c():u(),a.strictRequired){const f=e.parentSchema.properties,{definedProperties:g}=e.it;for(const v of n)if((f==null?void 0:f[v])===void 0&&!g.has(v)){const m=i.schemaEnv.baseId+i.errSchemaPath,d=`required property "${v}" is not defined at "${m}" (strictRequired)`;(0,fC.checkStrictMode)(i,d,i.opts.strictRequired)}}function c(){if(l||s)e.block$data(yo.nil,h);else for(const f of n)(0,_o.checkReportMissingProp)(e,f)}function u(){const f=t.let("missing");if(l||s){const g=t.let("valid",!0);e.block$data(g,()=>_(f,g)),e.ok(g)}else t.if((0,_o.checkMissingProp)(e,n,f)),(0,_o.reportMissingProp)(e,f),t.else()}function h(){t.forOf("prop",r,f=>{e.setParams({missingProperty:f}),t.if((0,_o.noPropertyInData)(t,o,f,a.ownProperties),()=>e.error())})}function _(f,g){e.setParams({missingProperty:f}),t.forOf(f,r,()=>{t.assign(g,(0,_o.propertyInData)(t,o,f,a.ownProperties)),t.if((0,yo.not)(g),()=>{e.error(),t.break()})},yo.nil)}}};xl.default=hC;var Pl={};Object.defineProperty(Pl,"__esModule",{value:!0});const wo=ce,mC={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:{message({keyword:e,schemaCode:t}){const n=e==="maxItems"?"more":"fewer";return(0,wo.str)`must NOT have ${n} than ${t} items`},params:({schemaCode:e})=>(0,wo._)`{limit: ${e}}`},code(e){const{keyword:t,data:n,schemaCode:r}=e,o=t==="maxItems"?wo.operators.GT:wo.operators.LT;e.fail$data((0,wo._)`${n}.length ${o} ${r}`)}};Pl.default=mC;var Rl={},bo={};Object.defineProperty(bo,"__esModule",{value:!0});const h2=Ph;h2.code='require("ajv/dist/runtime/equal").default',bo.default=h2,Object.defineProperty(Rl,"__esModule",{value:!0});const Ol=Ue,Ke=ce,gC=G,vC=bo,_C={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:{message:({params:{i:e,j:t}})=>(0,Ke.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,Ke._)`{i: ${e}, j: ${t}}`},code(e){const{gen:t,data:n,$data:r,schema:o,parentSchema:s,schemaCode:i,it:a}=e;if(!r&&!o)return;const l=t.let("valid"),c=s.items?(0,Ol.getSchemaTypes)(s.items):[];e.block$data(l,u,(0,Ke._)`${i} === false`),e.ok(l);function u(){const g=t.let("i",(0,Ke._)`${n}.length`),v=t.let("j");e.setParams({i:g,j:v}),t.assign(l,!0),t.if((0,Ke._)`${g} > 1`,()=>(h()?_:f)(g,v))}function h(){return c.length>0&&!c.some(g=>g==="object"||g==="array")}function _(g,v){const m=t.name("item"),d=(0,Ol.checkDataTypes)(c,m,a.opts.strictNumbers,Ol.DataType.Wrong),w=t.const("indices",(0,Ke._)`{}`);t.for((0,Ke._)`;${g}--;`,()=>{t.let(m,(0,Ke._)`${n}[${g}]`),t.if(d,(0,Ke._)`continue`),c.length>1&&t.if((0,Ke._)`typeof ${m} == "string"`,(0,Ke._)`${m} += "_"`),t.if((0,Ke._)`typeof ${w}[${m}] == "number"`,()=>{t.assign(v,(0,Ke._)`${w}[${m}]`),e.error(),t.assign(l,!1).break()}).code((0,Ke._)`${w}[${m}] = ${g}`)})}function f(g,v){const m=(0,gC.useFunc)(t,vC.default),d=t.name("outer");t.label(d).for((0,Ke._)`;${g}--;`,()=>t.for((0,Ke._)`${v} = ${g}; ${v}--;`,()=>t.if((0,Ke._)`${m}(${n}[${g}], ${n}[${v}])`,()=>{e.error(),t.assign(l,!1).break(d)})))}}};Rl.default=_C;var Nl={};Object.defineProperty(Nl,"__esModule",{value:!0});const Ml=ce,yC=G,wC=bo,bC={keyword:"const",$data:!0,error:{message:"must be equal to constant",params:({schemaCode:e})=>(0,Ml._)`{allowedValue: ${e}}`},code(e){const{gen:t,data:n,$data:r,schemaCode:o,schema:s}=e;r||s&&typeof s=="object"?e.fail$data((0,Ml._)`!${(0,yC.useFunc)(t,wC.default)}(${n}, ${o})`):e.fail((0,Ml._)`${s} !== ${n}`)}};Nl.default=bC;var Al={};Object.defineProperty(Al,"__esModule",{value:!0});const $o=ce,$C=G,SC=bo,CC={keyword:"enum",schemaType:"array",$data:!0,error:{message:"must be equal to one of the allowed values",params:({schemaCode:e})=>(0,$o._)`{allowedValues: ${e}}`},code(e){const{gen:t,data:n,$data:r,schema:o,schemaCode:s,it:i}=e;if(!r&&o.length===0)throw new Error("enum must have non-empty array");const a=o.length>=i.opts.loopEnum;let l;const c=()=>l??(l=(0,$C.useFunc)(t,SC.default));let u;if(a||r)u=t.let("valid"),e.block$data(u,h);else{if(!Array.isArray(o))throw new Error("ajv implementation error");const f=t.const("vSchema",s);u=(0,$o.or)(...o.map((g,v)=>_(f,v)))}e.pass(u);function h(){t.assign(u,!1),t.forOf("v",s,f=>t.if((0,$o._)`${c()}(${n}, ${f})`,()=>t.assign(u,!0).break()))}function _(f,g){const v=o[g];return typeof v=="object"&&v!==null?(0,$o._)`${c()}(${n}, ${f}[${g}])`:(0,$o._)`${n} === ${v}`}}};Al.default=CC,Object.defineProperty($l,"__esModule",{value:!0});const EC=Sl,kC=Cl,IC=El,TC=Il,xC=Tl,PC=xl,RC=Pl,OC=Rl,NC=Nl,MC=Al,AC=[EC.default,kC.default,IC.default,TC.default,xC.default,PC.default,RC.default,OC.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},NC.default,MC.default];$l.default=AC;var Ll={},yr={};Object.defineProperty(yr,"__esModule",{value:!0}),yr.validateAdditionalItems=void 0;const nr=ce,jl=G,LC={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:{message:({params:{len:e}})=>(0,nr.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,nr._)`{limit: ${e}}`},code(e){const{parentSchema:t,it:n}=e,{items:r}=t;if(!Array.isArray(r)){(0,jl.checkStrictMode)(n,'"additionalItems" is ignored when "items" is not an array of schemas');return}m2(e,r)}};function m2(e,t){const{gen:n,schema:r,data:o,keyword:s,it:i}=e;i.items=!0;const a=n.const("len",(0,nr._)`${o}.length`);if(r===!1)e.setParams({len:t.length}),e.pass((0,nr._)`${a} <= ${t.length}`);else if(typeof r=="object"&&!(0,jl.alwaysValidSchema)(i,r)){const c=n.var("valid",(0,nr._)`${a} <= ${t.length}`);n.if((0,nr.not)(c),()=>l(c)),e.ok(c)}function l(c){n.forRange("i",t.length,a,u=>{e.subschema({keyword:s,dataProp:u,dataPropType:jl.Type.Num},c),i.allErrors||n.if((0,nr.not)(c),()=>n.break())})}}yr.validateAdditionalItems=m2,yr.default=LC;var zl={},wr={};Object.defineProperty(wr,"__esModule",{value:!0}),wr.validateTuple=void 0;const g2=ce,zs=G,jC=pe,zC={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){const{schema:t,it:n}=e;if(Array.isArray(t))return v2(e,"additionalItems",t);n.items=!0,!(0,zs.alwaysValidSchema)(n,t)&&e.ok((0,jC.validateArray)(e))}};function v2(e,t,n=e.schema){const{gen:r,parentSchema:o,data:s,keyword:i,it:a}=e;u(o),a.opts.unevaluated&&n.length&&a.items!==!0&&(a.items=zs.mergeEvaluated.items(r,n.length,a.items));const l=r.name("valid"),c=r.const("len",(0,g2._)`${s}.length`);n.forEach((h,_)=>{(0,zs.alwaysValidSchema)(a,h)||(r.if((0,g2._)`${c} > ${_}`,()=>e.subschema({keyword:i,schemaProp:_,dataProp:_},l)),e.ok(l))});function u(h){const{opts:_,errSchemaPath:f}=a,g=n.length,v=g===h.minItems&&(g===h.maxItems||h[t]===!1);if(_.strictTuples&&!v){const m=`"${i}" is ${g}-tuple, but minItems or maxItems/${t} are not specified or different at path "${f}"`;(0,zs.checkStrictMode)(a,m,_.strictTuples)}}}wr.validateTuple=v2,wr.default=zC,Object.defineProperty(zl,"__esModule",{value:!0});const DC=wr,UC={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,DC.validateTuple)(e,"items")};zl.default=UC;var Dl={};Object.defineProperty(Dl,"__esModule",{value:!0});const _2=ce,qC=G,ZC=pe,FC=yr,VC={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:{message:({params:{len:e}})=>(0,_2.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,_2._)`{limit: ${e}}`},code(e){const{schema:t,parentSchema:n,it:r}=e,{prefixItems:o}=n;r.items=!0,!(0,qC.alwaysValidSchema)(r,t)&&(o?(0,FC.validateAdditionalItems)(e,o):e.ok((0,ZC.validateArray)(e)))}};Dl.default=VC;var Ul={};Object.defineProperty(Ul,"__esModule",{value:!0});const Pt=ce,Ds=G,BC={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:{message:({params:{min:e,max:t}})=>t===void 0?(0,Pt.str)`must contain at least ${e} valid item(s)`:(0,Pt.str)`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>t===void 0?(0,Pt._)`{minContains: ${e}}`:(0,Pt._)`{minContains: ${e}, maxContains: ${t}}`},code(e){const{gen:t,schema:n,parentSchema:r,data:o,it:s}=e;let i,a;const{minContains:l,maxContains:c}=r;s.opts.next?(i=l===void 0?1:l,a=c):i=1;const u=t.const("len",(0,Pt._)`${o}.length`);if(e.setParams({min:i,max:a}),a===void 0&&i===0){(0,Ds.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,Ds.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,Ds.alwaysValidSchema)(s,n)){let v=(0,Pt._)`${u} >= ${i}`;a!==void 0&&(v=(0,Pt._)`${v} && ${u} <= ${a}`),e.pass(v);return}s.items=!0;const h=t.name("valid");a===void 0&&i===1?f(h,()=>t.if(h,()=>t.break())):i===0?(t.let(h,!0),a!==void 0&&t.if((0,Pt._)`${o}.length > 0`,_)):(t.let(h,!1),_()),e.result(h,()=>e.reset());function _(){const v=t.name("_valid"),m=t.let("count",0);f(v,()=>t.if(v,()=>g(m)))}function f(v,m){t.forRange("i",0,u,d=>{e.subschema({keyword:"contains",dataProp:d,dataPropType:Ds.Type.Num,compositeRule:!0},v),m()})}function g(v){t.code((0,Pt._)`${v}++`),a===void 0?t.if((0,Pt._)`${v} >= ${i}`,()=>t.assign(h,!0).break()):(t.if((0,Pt._)`${v} > ${a}`,()=>t.assign(h,!1).break()),i===1?t.assign(h,!0):t.if((0,Pt._)`${v} >= ${i}`,()=>t.assign(h,!0)))}}};Ul.default=BC;var y2={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;const t=ce,n=G,r=pe;e.error={message:({params:{property:l,depsCount:c,deps:u}})=>{const h=c===1?"property":"properties";return(0,t.str)`must have ${h} ${u} when property ${l} is present`},params:({params:{property:l,depsCount:c,deps:u,missingProperty:h}})=>(0,t._)`{property: ${l},
76
+ missingProperty: ${h},
77
+ depsCount: ${c},
78
+ deps: ${u}}`};const o={keyword:"dependencies",type:"object",schemaType:"object",error:e.error,code(l){const[c,u]=s(l);i(l,c),a(l,u)}};function s({schema:l}){const c={},u={};for(const h in l){if(h==="__proto__")continue;const _=Array.isArray(l[h])?c:u;_[h]=l[h]}return[c,u]}function i(l,c=l.schema){const{gen:u,data:h,it:_}=l;if(Object.keys(c).length===0)return;const f=u.let("missing");for(const g in c){const v=c[g];if(v.length===0)continue;const m=(0,r.propertyInData)(u,h,g,_.opts.ownProperties);l.setParams({property:g,depsCount:v.length,deps:v.join(", ")}),_.allErrors?u.if(m,()=>{for(const d of v)(0,r.checkReportMissingProp)(l,d)}):(u.if((0,t._)`${m} && (${(0,r.checkMissingProp)(l,v,f)})`),(0,r.reportMissingProp)(l,f),u.else())}}e.validatePropertyDeps=i;function a(l,c=l.schema){const{gen:u,data:h,keyword:_,it:f}=l,g=u.name("valid");for(const v in c)(0,n.alwaysValidSchema)(f,c[v])||(u.if((0,r.propertyInData)(u,h,v,f.opts.ownProperties),()=>{const m=l.subschema({keyword:_,schemaProp:v},g);l.mergeValidEvaluated(m,g)},()=>u.var(g,!0)),l.ok(g))}e.validateSchemaDeps=a,e.default=o})(y2);var ql={};Object.defineProperty(ql,"__esModule",{value:!0});const w2=ce,HC=G,JC={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:{message:"property name must be valid",params:({params:e})=>(0,w2._)`{propertyName: ${e.propertyName}}`},code(e){const{gen:t,schema:n,data:r,it:o}=e;if((0,HC.alwaysValidSchema)(o,n))return;const s=t.name("valid");t.forIn("key",r,i=>{e.setParams({propertyName:i}),e.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},s),t.if((0,w2.not)(s),()=>{e.error(!0),o.allErrors||t.break()})}),e.ok(s)}};ql.default=JC;var Us={};Object.defineProperty(Us,"__esModule",{value:!0});const qs=pe,Bt=ce,GC=tn,Zs=G,WC={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:{message:"must NOT have additional properties",params:({params:e})=>(0,Bt._)`{additionalProperty: ${e.additionalProperty}}`},code(e){const{gen:t,schema:n,parentSchema:r,data:o,errsCount:s,it:i}=e;if(!s)throw new Error("ajv implementation error");const{allErrors:a,opts:l}=i;if(i.props=!0,l.removeAdditional!=="all"&&(0,Zs.alwaysValidSchema)(i,n))return;const c=(0,qs.allSchemaProperties)(r.properties),u=(0,qs.allSchemaProperties)(r.patternProperties);h(),e.ok((0,Bt._)`${s} === ${GC.default.errors}`);function h(){t.forIn("key",o,m=>{!c.length&&!u.length?g(m):t.if(_(m),()=>g(m))})}function _(m){let d;if(c.length>8){const w=(0,Zs.schemaRefOrVal)(i,r.properties,"properties");d=(0,qs.isOwnProperty)(t,w,m)}else c.length?d=(0,Bt.or)(...c.map(w=>(0,Bt._)`${m} === ${w}`)):d=Bt.nil;return u.length&&(d=(0,Bt.or)(d,...u.map(w=>(0,Bt._)`${(0,qs.usePattern)(e,w)}.test(${m})`))),(0,Bt.not)(d)}function f(m){t.code((0,Bt._)`delete ${o}[${m}]`)}function g(m){if(l.removeAdditional==="all"||l.removeAdditional&&n===!1){f(m);return}if(n===!1){e.setParams({additionalProperty:m}),e.error(),a||t.break();return}if(typeof n=="object"&&!(0,Zs.alwaysValidSchema)(i,n)){const d=t.name("valid");l.removeAdditional==="failing"?(v(m,d,!1),t.if((0,Bt.not)(d),()=>{e.reset(),f(m)})):(v(m,d),a||t.if((0,Bt.not)(d),()=>t.break()))}}function v(m,d,w){const y={keyword:"additionalProperties",dataProp:m,dataPropType:Zs.Type.Str};w===!1&&Object.assign(y,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(y,d)}}};Us.default=WC;var Zl={};Object.defineProperty(Zl,"__esModule",{value:!0});const KC=Zt,b2=pe,Fl=G,$2=Us,YC={keyword:"properties",type:"object",schemaType:"object",code(e){const{gen:t,schema:n,parentSchema:r,data:o,it:s}=e;s.opts.removeAdditional==="all"&&r.additionalProperties===void 0&&$2.default.code(new KC.KeywordCxt(s,$2.default,"additionalProperties"));const i=(0,b2.allSchemaProperties)(n);for(const h of i)s.definedProperties.add(h);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=Fl.mergeEvaluated.props(t,(0,Fl.toHash)(i),s.props));const a=i.filter(h=>!(0,Fl.alwaysValidSchema)(s,n[h]));if(a.length===0)return;const l=t.name("valid");for(const h of a)c(h)?u(h):(t.if((0,b2.propertyInData)(t,o,h,s.opts.ownProperties)),u(h),s.allErrors||t.else().var(l,!0),t.endIf()),e.it.definedProperties.add(h),e.ok(l);function c(h){return s.opts.useDefaults&&!s.compositeRule&&n[h].default!==void 0}function u(h){e.subschema({keyword:"properties",schemaProp:h,dataProp:h},l)}}};Zl.default=YC;var Vl={};Object.defineProperty(Vl,"__esModule",{value:!0});const S2=pe,Fs=ce,C2=G,E2=G,QC={keyword:"patternProperties",type:"object",schemaType:"object",code(e){const{gen:t,schema:n,data:r,parentSchema:o,it:s}=e,{opts:i}=s,a=(0,S2.allSchemaProperties)(n),l=a.filter(v=>(0,C2.alwaysValidSchema)(s,n[v]));if(a.length===0||l.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;const c=i.strictSchema&&!i.allowMatchingProperties&&o.properties,u=t.name("valid");s.props!==!0&&!(s.props instanceof Fs.Name)&&(s.props=(0,E2.evaluatedPropsToName)(t,s.props));const{props:h}=s;_();function _(){for(const v of a)c&&f(v),s.allErrors?g(v):(t.var(u,!0),g(v),t.if(u))}function f(v){for(const m in c)new RegExp(v).test(m)&&(0,C2.checkStrictMode)(s,`property ${m} matches pattern ${v} (use allowMatchingProperties)`)}function g(v){t.forIn("key",r,m=>{t.if((0,Fs._)`${(0,S2.usePattern)(e,v)}.test(${m})`,()=>{const d=l.includes(v);d||e.subschema({keyword:"patternProperties",schemaProp:v,dataProp:m,dataPropType:E2.Type.Str},u),s.opts.unevaluated&&h!==!0?t.assign((0,Fs._)`${h}[${m}]`,!0):!d&&!s.allErrors&&t.if((0,Fs.not)(u),()=>t.break())})})}}};Vl.default=QC;var Bl={};Object.defineProperty(Bl,"__esModule",{value:!0});const XC=G,eE={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){const{gen:t,schema:n,it:r}=e;if((0,XC.alwaysValidSchema)(r,n)){e.fail();return}const o=t.name("valid");e.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),e.failResult(o,()=>e.reset(),()=>e.error())},error:{message:"must NOT be valid"}};Bl.default=eE;var Hl={};Object.defineProperty(Hl,"__esModule",{value:!0});const tE={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:pe.validateUnion,error:{message:"must match a schema in anyOf"}};Hl.default=tE;var Jl={};Object.defineProperty(Jl,"__esModule",{value:!0});const Vs=ce,nE=G,rE={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:{message:"must match exactly one schema in oneOf",params:({params:e})=>(0,Vs._)`{passingSchemas: ${e.passing}}`},code(e){const{gen:t,schema:n,parentSchema:r,it:o}=e;if(!Array.isArray(n))throw new Error("ajv implementation error");if(o.opts.discriminator&&r.discriminator)return;const s=n,i=t.let("valid",!1),a=t.let("passing",null),l=t.name("_valid");e.setParams({passing:a}),t.block(c),e.result(i,()=>e.reset(),()=>e.error(!0));function c(){s.forEach((u,h)=>{let _;(0,nE.alwaysValidSchema)(o,u)?t.var(l,!0):_=e.subschema({keyword:"oneOf",schemaProp:h,compositeRule:!0},l),h>0&&t.if((0,Vs._)`${l} && ${i}`).assign(i,!1).assign(a,(0,Vs._)`[${a}, ${h}]`).else(),t.if(l,()=>{t.assign(i,!0),t.assign(a,h),_&&e.mergeEvaluated(_,Vs.Name)})})}}};Jl.default=rE;var Gl={};Object.defineProperty(Gl,"__esModule",{value:!0});const oE=G,sE={keyword:"allOf",schemaType:"array",code(e){const{gen:t,schema:n,it:r}=e;if(!Array.isArray(n))throw new Error("ajv implementation error");const o=t.name("valid");n.forEach((s,i)=>{if((0,oE.alwaysValidSchema)(r,s))return;const a=e.subschema({keyword:"allOf",schemaProp:i},o);e.ok(o),e.mergeEvaluated(a)})}};Gl.default=sE;var Wl={};Object.defineProperty(Wl,"__esModule",{value:!0});const Bs=ce,k2=G,iE={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:{message:({params:e})=>(0,Bs.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,Bs._)`{failingKeyword: ${e.ifClause}}`},code(e){const{gen:t,parentSchema:n,it:r}=e;n.then===void 0&&n.else===void 0&&(0,k2.checkStrictMode)(r,'"if" without "then" and "else" is ignored');const o=I2(r,"then"),s=I2(r,"else");if(!o&&!s)return;const i=t.let("valid",!0),a=t.name("_valid");if(l(),e.reset(),o&&s){const u=t.let("ifClause");e.setParams({ifClause:u}),t.if(a,c("then",u),c("else",u))}else o?t.if(a,c("then")):t.if((0,Bs.not)(a),c("else"));e.pass(i,()=>e.error(!0));function l(){const u=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);e.mergeEvaluated(u)}function c(u,h){return()=>{const _=e.subschema({keyword:u},a);t.assign(i,a),e.mergeValidEvaluated(_,i),h?t.assign(h,(0,Bs._)`${u}`):e.setParams({ifClause:u})}}}};function I2(e,t){const n=e.schema[t];return n!==void 0&&!(0,k2.alwaysValidSchema)(e,n)}Wl.default=iE;var Kl={};Object.defineProperty(Kl,"__esModule",{value:!0});const aE=G,lE={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:n}){t.if===void 0&&(0,aE.checkStrictMode)(n,`"${e}" without "if" is ignored`)}};Kl.default=lE,Object.defineProperty(Ll,"__esModule",{value:!0});const cE=yr,uE=zl,dE=wr,pE=Dl,fE=Ul,hE=y2,mE=ql,gE=Us,vE=Zl,_E=Vl,yE=Bl,wE=Hl,bE=Jl,$E=Gl,SE=Wl,CE=Kl;function EE(e=!1){const t=[yE.default,wE.default,bE.default,$E.default,SE.default,CE.default,mE.default,gE.default,hE.default,vE.default,_E.default];return e?t.push(uE.default,pE.default):t.push(cE.default,dE.default),t.push(fE.default),t}Ll.default=EE;var Yl={},Ql={};Object.defineProperty(Ql,"__esModule",{value:!0});const ze=ce,kE={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:{message:({schemaCode:e})=>(0,ze.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,ze._)`{format: ${e}}`},code(e,t){const{gen:n,data:r,$data:o,schema:s,schemaCode:i,it:a}=e,{opts:l,errSchemaPath:c,schemaEnv:u,self:h}=a;if(!l.validateFormats)return;o?_():f();function _(){const g=n.scopeValue("formats",{ref:h.formats,code:l.code.formats}),v=n.const("fDef",(0,ze._)`${g}[${i}]`),m=n.let("fType"),d=n.let("format");n.if((0,ze._)`typeof ${v} == "object" && !(${v} instanceof RegExp)`,()=>n.assign(m,(0,ze._)`${v}.type || "string"`).assign(d,(0,ze._)`${v}.validate`),()=>n.assign(m,(0,ze._)`"string"`).assign(d,v)),e.fail$data((0,ze.or)(w(),y()));function w(){return l.strictSchema===!1?ze.nil:(0,ze._)`${i} && !${d}`}function y(){const b=u.$async?(0,ze._)`(${v}.async ? await ${d}(${r}) : ${d}(${r}))`:(0,ze._)`${d}(${r})`,k=(0,ze._)`(typeof ${d} == "function" ? ${b} : ${d}.test(${r}))`;return(0,ze._)`${d} && ${d} !== true && ${m} === ${t} && !${k}`}}function f(){const g=h.formats[s];if(!g){w();return}if(g===!0)return;const[v,m,d]=y(g);v===t&&e.pass(b());function w(){if(l.strictSchema===!1){h.logger.warn(k());return}throw new Error(k());function k(){return`unknown format "${s}" ignored in schema at path "${c}"`}}function y(k){const x=k instanceof RegExp?(0,ze.regexpCode)(k):l.code.formats?(0,ze._)`${l.code.formats}${(0,ze.getProperty)(s)}`:void 0,T=n.scopeValue("formats",{key:s,ref:k,code:x});return typeof k=="object"&&!(k instanceof RegExp)?[k.type||"string",k.validate,(0,ze._)`${T}.validate`]:["string",k,T]}function b(){if(typeof g=="object"&&!(g instanceof RegExp)&&g.async){if(!u.$async)throw new Error("async format in sync schema");return(0,ze._)`await ${d}(${r})`}return typeof m=="function"?(0,ze._)`${d}(${r})`:(0,ze._)`${d}.test(${r})`}}}};Ql.default=kE,Object.defineProperty(Yl,"__esModule",{value:!0});const IE=[Ql.default];Yl.default=IE;var br={};Object.defineProperty(br,"__esModule",{value:!0}),br.contentVocabulary=br.metadataVocabulary=void 0,br.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],br.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"],Object.defineProperty(yl,"__esModule",{value:!0});const TE=wl,xE=$l,PE=Ll,RE=Yl,T2=br,OE=[TE.default,xE.default,(0,PE.default)(),RE.default,T2.metadataVocabulary,T2.contentVocabulary];yl.default=OE;var Xl={},Hs={};Object.defineProperty(Hs,"__esModule",{value:!0}),Hs.DiscrError=void 0;var x2;(function(e){e.Tag="tag",e.Mapping="mapping"})(x2||(Hs.DiscrError=x2={})),Object.defineProperty(Xl,"__esModule",{value:!0});const $r=ce,ec=Hs,P2=pt,NE=vr,ME=G,AE={keyword:"discriminator",type:"object",schemaType:"object",error:{message:({params:{discrError:e,tagName:t}})=>e===ec.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:n}})=>(0,$r._)`{error: ${e}, tag: ${n}, tagValue: ${t}}`},code(e){const{gen:t,data:n,schema:r,parentSchema:o,it:s}=e,{oneOf:i}=o;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");const a=r.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(r.mapping)throw new Error("discriminator: mapping is not supported");if(!i)throw new Error("discriminator: requires oneOf keyword");const l=t.let("valid",!1),c=t.const("tag",(0,$r._)`${n}${(0,$r.getProperty)(a)}`);t.if((0,$r._)`typeof ${c} == "string"`,()=>u(),()=>e.error(!1,{discrError:ec.DiscrError.Tag,tag:c,tagName:a})),e.ok(l);function u(){const f=_();t.if(!1);for(const g in f)t.elseIf((0,$r._)`${c} === ${g}`),t.assign(l,h(f[g]));t.else(),e.error(!1,{discrError:ec.DiscrError.Mapping,tag:c,tagName:a}),t.endIf()}function h(f){const g=t.name("valid"),v=e.subschema({keyword:"oneOf",schemaProp:f},g);return e.mergeEvaluated(v,$r.Name),g}function _(){var f;const g={},v=d(o);let m=!0;for(let b=0;b<i.length;b++){let k=i[b];if(k!=null&&k.$ref&&!(0,ME.schemaHasRulesButRef)(k,s.self.RULES)){const T=k.$ref;if(k=P2.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,T),k instanceof P2.SchemaEnv&&(k=k.schema),k===void 0)throw new NE.default(s.opts.uriResolver,s.baseId,T)}const x=(f=k==null?void 0:k.properties)===null||f===void 0?void 0:f[a];if(typeof x!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);m=m&&(v||d(k)),w(x,b)}if(!m)throw new Error(`discriminator: "${a}" must be required`);return g;function d({required:b}){return Array.isArray(b)&&b.includes(a)}function w(b,k){if(b.const)y(b.const,k);else if(b.enum)for(const x of b.enum)y(x,k);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function y(b,k){if(typeof b!="string"||b in g)throw new Error(`discriminator: "${a}" values must be unique strings`);g[b]=k}}}};Xl.default=AE;const LE={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0};(function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.MissingRefError=t.ValidationError=t.CodeGen=t.Name=t.nil=t.stringify=t.str=t._=t.KeywordCxt=t.Ajv=void 0;const n=uh,r=yl,o=Xl,s=LE,i=["/properties"],a="http://json-schema.org/draft-07/schema";class l extends n.default{_addVocabularies(){super._addVocabularies(),r.default.forEach(g=>this.addVocabulary(g)),this.opts.discriminator&&this.addKeyword(o.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;const g=this.opts.$data?this.$dataMetaSchema(s,i):s;this.addMetaSchema(g,a,!1),this.refs["http://json-schema.org/schema"]=a}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(a)?a:void 0)}}t.Ajv=l,e.exports=t=l,e.exports.Ajv=l,Object.defineProperty(t,"__esModule",{value:!0}),t.default=l;var c=Zt;Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return c.KeywordCxt}});var u=ce;Object.defineProperty(t,"_",{enumerable:!0,get:function(){return u._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return u.str}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return u.stringify}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return u.nil}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return u.Name}}),Object.defineProperty(t,"CodeGen",{enumerable:!0,get:function(){return u.CodeGen}});var h=ho;Object.defineProperty(t,"ValidationError",{enumerable:!0,get:function(){return h.default}});var _=vr;Object.defineProperty(t,"MissingRefError",{enumerable:!0,get:function(){return _.default}})})(Qa,Qa.exports);var R2=Qa.exports,tc={exports:{}},O2={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.formatNames=e.fastFormats=e.fullFormats=void 0;function t(q,F){return{validate:q,compare:F}}e.fullFormats={date:t(s,i),time:t(l(!0),c),"date-time":t(_(!0),f),"iso-time":t(l(),u),"iso-date-time":t(_(),g),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:d,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|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-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:H,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:y,int32:{type:"number",validate:x},int64:{type:"number",validate:T},float:{type:"number",validate:D},double:{type:"number",validate:D},password:!0,binary:!0},e.fastFormats={...e.fullFormats,date:t(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,i),time:t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,c),"date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,f),"iso-time":t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,u),"iso-date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,g),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},e.formatNames=Object.keys(e.fullFormats);function n(q){return q%4===0&&(q%100!==0||q%400===0)}const r=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,o=[0,31,28,31,30,31,30,31,31,30,31,30,31];function s(q){const F=r.exec(q);if(!F)return!1;const B=+F[1],V=+F[2],se=+F[3];return V>=1&&V<=12&&se>=1&&se<=(V===2&&n(B)?29:o[V])}function i(q,F){if(q&&F)return q>F?1:q<F?-1:0}const a=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function l(q){return function(B){const V=a.exec(B);if(!V)return!1;const se=+V[1],ge=+V[2],te=+V[3],ue=V[4],le=V[5]==="-"?-1:1,L=+(V[6]||0),I=+(V[7]||0);if(L>23||I>59||q&&!ue)return!1;if(se<=23&&ge<=59&&te<60)return!0;const M=ge-I*le,P=se-L*le-(M<0?1:0);return(P===23||P===-1)&&(M===59||M===-1)&&te<61}}function c(q,F){if(!(q&&F))return;const B=new Date("2020-01-01T"+q).valueOf(),V=new Date("2020-01-01T"+F).valueOf();if(B&&V)return B-V}function u(q,F){if(!(q&&F))return;const B=a.exec(q),V=a.exec(F);if(B&&V)return q=B[1]+B[2]+B[3],F=V[1]+V[2]+V[3],q>F?1:q<F?-1:0}const h=/t|\s/i;function _(q){const F=l(q);return function(V){const se=V.split(h);return se.length===2&&s(se[0])&&F(se[1])}}function f(q,F){if(!(q&&F))return;const B=new Date(q).valueOf(),V=new Date(F).valueOf();if(B&&V)return B-V}function g(q,F){if(!(q&&F))return;const[B,V]=q.split(h),[se,ge]=F.split(h),te=i(B,se);if(te!==void 0)return te||c(V,ge)}const v=/\/|:/,m=/^(?:[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 d(q){return v.test(q)&&m.test(q)}const w=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function y(q){return w.lastIndex=0,w.test(q)}const b=-2147483648,k=2**31-1;function x(q){return Number.isInteger(q)&&q<=k&&q>=b}function T(q){return Number.isInteger(q)}function D(){return!0}const U=/[^\\]\\Z/;function H(q){if(U.test(q))return!1;try{return new RegExp(q),!0}catch{return!1}}})(O2);var N2={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;const t=R2,n=ce,r=n.operators,o={formatMaximum:{okStr:"<=",ok:r.LTE,fail:r.GT},formatMinimum:{okStr:">=",ok:r.GTE,fail:r.LT},formatExclusiveMaximum:{okStr:"<",ok:r.LT,fail:r.GTE},formatExclusiveMinimum:{okStr:">",ok:r.GT,fail:r.LTE}},s={message:({keyword:a,schemaCode:l})=>(0,n.str)`should be ${o[a].okStr} ${l}`,params:({keyword:a,schemaCode:l})=>(0,n._)`{comparison: ${o[a].okStr}, limit: ${l}}`};e.formatLimitDefinition={keyword:Object.keys(o),type:"string",schemaType:"string",$data:!0,error:s,code(a){const{gen:l,data:c,schemaCode:u,keyword:h,it:_}=a,{opts:f,self:g}=_;if(!f.validateFormats)return;const v=new t.KeywordCxt(_,g.RULES.all.format.definition,"format");v.$data?m():d();function m(){const y=l.scopeValue("formats",{ref:g.formats,code:f.code.formats}),b=l.const("fmt",(0,n._)`${y}[${v.schemaCode}]`);a.fail$data((0,n.or)((0,n._)`typeof ${b} != "object"`,(0,n._)`${b} instanceof RegExp`,(0,n._)`typeof ${b}.compare != "function"`,w(b)))}function d(){const y=v.schema,b=g.formats[y];if(!b||b===!0)return;if(typeof b!="object"||b instanceof RegExp||typeof b.compare!="function")throw new Error(`"${h}": format "${y}" does not define "compare" function`);const k=l.scopeValue("formats",{key:y,ref:b,code:f.code.formats?(0,n._)`${f.code.formats}${(0,n.getProperty)(y)}`:void 0});a.fail$data(w(k))}function w(y){return(0,n._)`${y}.compare(${c}, ${u}) ${o[h].fail} 0`}},dependencies:["format"]};const i=a=>(a.addKeyword(e.formatLimitDefinition),a);e.default=i})(N2),function(e,t){Object.defineProperty(t,"__esModule",{value:!0});const n=O2,r=N2,o=ce,s=new o.Name("fullFormats"),i=new o.Name("fastFormats"),a=(c,u={keywords:!0})=>{if(Array.isArray(u))return l(c,u,n.fullFormats,s),c;const[h,_]=u.mode==="fast"?[n.fastFormats,i]:[n.fullFormats,s],f=u.formats||n.formatNames;return l(c,f,h,_),u.keywords&&(0,r.default)(c),c};a.get=(c,u="full")=>{const _=(u==="fast"?n.fastFormats:n.fullFormats)[c];if(!_)throw new Error(`Unknown format "${c}"`);return _};function l(c,u,h,_){var f,g;(f=(g=c.opts.code).formats)!==null&&f!==void 0||(g.formats=(0,o._)`require("ajv-formats/dist/formats").${_}`);for(const v of u)c.addFormat(v,h[v])}e.exports=t=a,Object.defineProperty(t,"__esModule",{value:!0}),t.default=a}(tc,tc.exports);var jE=tc.exports;const zE=Wy(jE);function DE(){const e=new R2.Ajv({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return zE(e),e}class UE{constructor(t){this._ajv=t??DE()}getValidator(t){var n;const r="$id"in t&&typeof t.$id=="string"?(n=this._ajv.getSchema(t.$id))!==null&&n!==void 0?n:this._ajv.compile(t):this._ajv.compile(t);return o=>r(o)?{valid:!0,data:o,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}}function Js(e,t){if(!(!e||t===null||typeof t!="object")){if(e.type==="object"&&e.properties&&typeof e.properties=="object"){const n=t,r=e.properties;for(const o of Object.keys(r)){const s=r[o];n[o]===void 0&&Object.prototype.hasOwnProperty.call(s,"default")&&(n[o]=s.default),n[o]!==void 0&&Js(s,n[o])}}if(Array.isArray(e.anyOf))for(const n of e.anyOf)Js(n,t);if(Array.isArray(e.oneOf))for(const n of e.oneOf)Js(n,t)}}function qE(e){if(!e)return{supportsFormMode:!1,supportsUrlMode:!1};const t=e.form!==void 0,n=e.url!==void 0;return{supportsFormMode:t||!t&&!n,supportsUrlMode:n}}class Gs extends T7{constructor(t,n){var r,o;super(n),this._clientInfo=t,this._cachedToolOutputValidators=new Map,this._capabilities=(r=n==null?void 0:n.capabilities)!==null&&r!==void 0?r:{},this._jsonSchemaValidator=(o=n==null?void 0:n.jsonSchemaValidator)!==null&&o!==void 0?o:new UE}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=x7(this._capabilities,t)}setRequestHandler(t,n){var r,o,s;const i=ih(t),a=i==null?void 0:i.method;if(!a)throw new Error("Schema is missing a method literal");let l;if($s(a)){const u=a,h=(r=u._zod)===null||r===void 0?void 0:r.def;l=(o=h==null?void 0:h.value)!==null&&o!==void 0?o:u.value}else{const u=a,h=u._def;l=(s=h==null?void 0:h.value)!==null&&s!==void 0?s:u.value}if(typeof l!="string")throw new Error("Schema method literal must be a string");if(l==="elicitation/create"){const u=async(h,_)=>{var f,g,v;const m=Ss(Sa,h);if(!m.success){const U=m.error instanceof Error?m.error.message:String(m.error);throw new ot(Xe.InvalidParams,`Invalid elicitation request: ${U}`)}const{params:d}=m.data,w=(f=d.mode)!==null&&f!==void 0?f:"form",{supportsFormMode:y,supportsUrlMode:b}=qE(this._capabilities.elicitation);if(w==="form"&&!y)throw new ot(Xe.InvalidParams,"Client does not support form-mode elicitation requests");if(w==="url"&&!b)throw new ot(Xe.InvalidParams,"Client does not support URL-mode elicitation requests");const k=await Promise.resolve(n(h,_)),x=Ss(Ca,k);if(!x.success){const U=x.error instanceof Error?x.error.message:String(x.error);throw new ot(Xe.InvalidParams,`Invalid elicitation result: ${U}`)}const T=x.data,D=w==="form"?d.requestedSchema:void 0;if(w==="form"&&T.action==="accept"&&T.content&&D&&!((v=(g=this._capabilities.elicitation)===null||g===void 0?void 0:g.form)===null||v===void 0)&&v.applyDefaults)try{Js(D,T.content)}catch{}return T};return super.setRequestHandler(t,u)}return super.setRequestHandler(t,n)}assertCapability(t,n){var r;if(!(!((r=this._serverCapabilities)===null||r===void 0)&&r[t]))throw new Error(`Server does not support ${t} (required for ${n})`)}async connect(t,n){if(await super.connect(t),t.sessionId===void 0)try{const r=await this.request({method:"initialize",params:{protocolVersion:ss,capabilities:this._capabilities,clientInfo:this._clientInfo}},Bp,n);if(r===void 0)throw new Error(`Server sent invalid initialize result: ${r}`);if(!U9.includes(r.protocolVersion))throw new Error(`Server's protocol version is not supported: ${r.protocolVersion}`);this._serverCapabilities=r.capabilities,this._serverVersion=r.serverInfo,t.setProtocolVersion&&t.setProtocolVersion(r.protocolVersion),this._instructions=r.instructions,await this.notification({method:"notifications/initialized"})}catch(r){throw this.close(),r}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(t){var n,r,o,s,i;switch(t){case"logging/setLevel":if(!(!((n=this._serverCapabilities)===null||n===void 0)&&n.logging))throw new Error(`Server does not support logging (required for ${t})`);break;case"prompts/get":case"prompts/list":if(!(!((r=this._serverCapabilities)===null||r===void 0)&&r.prompts))throw new Error(`Server does not support prompts (required for ${t})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!(!((o=this._serverCapabilities)===null||o===void 0)&&o.resources))throw new Error(`Server does not support resources (required for ${t})`);if(t==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${t})`);break;case"tools/call":case"tools/list":if(!(!((s=this._serverCapabilities)===null||s===void 0)&&s.tools))throw new Error(`Server does not support tools (required for ${t})`);break;case"completion/complete":if(!(!((i=this._serverCapabilities)===null||i===void 0)&&i.completions))throw new Error(`Server does not support completions (required for ${t})`);break}}assertNotificationCapability(t){var n;switch(t){case"notifications/roots/list_changed":if(!(!((n=this._capabilities.roots)===null||n===void 0)&&n.listChanged))throw new Error(`Client does not support roots list changed notifications (required for ${t})`);break}}assertRequestHandlerCapability(t){switch(t){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${t})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${t})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${t})`);break}}async ping(t){return this.request({method:"ping"},Jn,t)}async complete(t,n){return this.request({method:"completion/complete",params:t},gf,n)}async setLoggingLevel(t,n){return this.request({method:"logging/setLevel",params:{level:t}},Jn,n)}async getPrompt(t,n){return this.request({method:"prompts/get",params:t},af,n)}async listPrompts(t,n){return this.request({method:"prompts/list",params:t},nf,n)}async listResources(t,n){return this.request({method:"resources/list",params:t},Yp,n)}async listResourceTemplates(t,n){return this.request({method:"resources/templates/list",params:t},Qp,n)}async readResource(t,n){return this.request({method:"resources/read",params:t},Xp,n)}async subscribeResource(t,n){return this.request({method:"resources/subscribe",params:t},Jn,n)}async unsubscribeResource(t,n){return this.request({method:"resources/unsubscribe",params:t},Jn,n)}async callTool(t,n=us,r){const o=await this.request({method:"tools/call",params:t},n,r),s=this.getToolOutputValidator(t.name);if(s){if(!o.structuredContent&&!o.isError)throw new ot(Xe.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`);if(o.structuredContent)try{const i=s(o.structuredContent);if(!i.valid)throw new ot(Xe.InvalidParams,`Structured content does not match the tool's output schema: ${i.errorMessage}`)}catch(i){throw i instanceof ot?i:new ot(Xe.InvalidParams,`Failed to validate structured content: ${i instanceof Error?i.message:String(i)}`)}}return o}cacheToolOutputSchemas(t){this._cachedToolOutputValidators.clear();for(const n of t)if(n.outputSchema){const r=this._jsonSchemaValidator.getValidator(n.outputSchema);this._cachedToolOutputValidators.set(n.name,r)}}getToolOutputValidator(t){return this._cachedToolOutputValidators.get(t)}async listTools(t,n){const r=await this.request({method:"tools/list",params:t},uf,n);return this.cacheToolOutputSchemas(r.tools),r}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}class M2 extends Event{constructor(t,n){var r,o;super(t),this.code=(r=n==null?void 0:n.code)!=null?r:void 0,this.message=(o=n==null?void 0:n.message)!=null?o:void 0}[Symbol.for("nodejs.util.inspect.custom")](t,n,r){return r(A2(this),n)}[Symbol.for("Deno.customInspect")](t,n){return t(A2(this),n)}}function ZE(e){const t=globalThis.DOMException;return typeof t=="function"?new t(e,"SyntaxError"):new SyntaxError(e)}function nc(e){return e instanceof Error?"errors"in e&&Array.isArray(e.errors)?e.errors.map(nc).join(", "):"cause"in e&&e.cause instanceof Error?`${e}: ${nc(e.cause)}`:e.message:`${e}`}function A2(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var L2=e=>{throw TypeError(e)},rc=(e,t,n)=>t.has(e)||L2("Cannot "+n),he=(e,t,n)=>(rc(e,t,"read from private field"),n?n.call(e):t.get(e)),qe=(e,t,n)=>t.has(e)?L2("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),Ae=(e,t,n,r)=>(rc(e,t,"write to private field"),t.set(e,n),n),hn=(e,t,n)=>(rc(e,t,"access private method"),n),ht,rr,Sr,Ws,Ks,So,Cr,Co,xn,Er,kr,Ir,Eo,Ht,oc,sc,ic,j2,ac,lc,ko,cc,uc;class Ys extends EventTarget{constructor(t,n){var r,o;super(),qe(this,Ht),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,qe(this,ht),qe(this,rr),qe(this,Sr),qe(this,Ws),qe(this,Ks),qe(this,So),qe(this,Cr),qe(this,Co,null),qe(this,xn),qe(this,Er),qe(this,kr,null),qe(this,Ir,null),qe(this,Eo,null),qe(this,sc,async s=>{var i;he(this,Er).reset();const{body:a,redirected:l,status:c,headers:u}=s;if(c===204){hn(this,Ht,ko).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(l?Ae(this,Sr,new URL(s.url)):Ae(this,Sr,void 0),c!==200){hn(this,Ht,ko).call(this,`Non-200 status code (${c})`,c);return}if(!(u.get("content-type")||"").startsWith("text/event-stream")){hn(this,Ht,ko).call(this,'Invalid content type, expected "text/event-stream"',c);return}if(he(this,ht)===this.CLOSED)return;Ae(this,ht,this.OPEN);const h=new Event("open");if((i=he(this,Eo))==null||i.call(this,h),this.dispatchEvent(h),typeof a!="object"||!a||!("getReader"in a)){hn(this,Ht,ko).call(this,"Invalid response body, expected a web ReadableStream",c),this.close();return}const _=new TextDecoder,f=a.getReader();let g=!0;do{const{done:v,value:m}=await f.read();m&&he(this,Er).feed(_.decode(m,{stream:!v})),v&&(g=!1,he(this,Er).reset(),hn(this,Ht,cc).call(this))}while(g)}),qe(this,ic,s=>{Ae(this,xn,void 0),!(s.name==="AbortError"||s.type==="aborted")&&hn(this,Ht,cc).call(this,nc(s))}),qe(this,ac,s=>{typeof s.id=="string"&&Ae(this,Co,s.id);const i=new MessageEvent(s.event||"message",{data:s.data,origin:he(this,Sr)?he(this,Sr).origin:he(this,rr).origin,lastEventId:s.id||""});he(this,Ir)&&(!s.event||s.event==="message")&&he(this,Ir).call(this,i),this.dispatchEvent(i)}),qe(this,lc,s=>{Ae(this,So,s)}),qe(this,uc,()=>{Ae(this,Cr,void 0),he(this,ht)===this.CONNECTING&&hn(this,Ht,oc).call(this)});try{if(t instanceof URL)Ae(this,rr,t);else if(typeof t=="string")Ae(this,rr,new URL(t,FE()));else throw new Error("Invalid URL")}catch{throw ZE("An invalid or illegal string was specified")}Ae(this,Er,vu({onEvent:he(this,ac),onRetry:he(this,lc)})),Ae(this,ht,this.CONNECTING),Ae(this,So,3e3),Ae(this,Ks,(r=n==null?void 0:n.fetch)!=null?r:globalThis.fetch),Ae(this,Ws,(o=n==null?void 0:n.withCredentials)!=null?o:!1),hn(this,Ht,oc).call(this)}get readyState(){return he(this,ht)}get url(){return he(this,rr).href}get withCredentials(){return he(this,Ws)}get onerror(){return he(this,kr)}set onerror(t){Ae(this,kr,t)}get onmessage(){return he(this,Ir)}set onmessage(t){Ae(this,Ir,t)}get onopen(){return he(this,Eo)}set onopen(t){Ae(this,Eo,t)}addEventListener(t,n,r){const o=n;super.addEventListener(t,o,r)}removeEventListener(t,n,r){const o=n;super.removeEventListener(t,o,r)}close(){he(this,Cr)&&clearTimeout(he(this,Cr)),he(this,ht)!==this.CLOSED&&(he(this,xn)&&he(this,xn).abort(),Ae(this,ht,this.CLOSED),Ae(this,xn,void 0))}}ht=new WeakMap,rr=new WeakMap,Sr=new WeakMap,Ws=new WeakMap,Ks=new WeakMap,So=new WeakMap,Cr=new WeakMap,Co=new WeakMap,xn=new WeakMap,Er=new WeakMap,kr=new WeakMap,Ir=new WeakMap,Eo=new WeakMap,Ht=new WeakSet,oc=function(){Ae(this,ht,this.CONNECTING),Ae(this,xn,new AbortController),he(this,Ks)(he(this,rr),hn(this,Ht,j2).call(this)).then(he(this,sc)).catch(he(this,ic))},sc=new WeakMap,ic=new WeakMap,j2=function(){var e;const t={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...he(this,Co)?{"Last-Event-ID":he(this,Co)}:void 0},cache:"no-store",signal:(e=he(this,xn))==null?void 0:e.signal};return"window"in globalThis&&(t.credentials=this.withCredentials?"include":"same-origin"),t},ac=new WeakMap,lc=new WeakMap,ko=function(e,t){var n;he(this,ht)!==this.CLOSED&&Ae(this,ht,this.CLOSED);const r=new M2("error",{code:t,message:e});(n=he(this,kr))==null||n.call(this,r),this.dispatchEvent(r)},cc=function(e,t){var n;if(he(this,ht)===this.CLOSED)return;Ae(this,ht,this.CONNECTING);const r=new M2("error",{code:t,message:e});(n=he(this,kr))==null||n.call(this,r),this.dispatchEvent(r),Ae(this,Cr,setTimeout(he(this,uc),he(this,So)))},uc=new WeakMap,Ys.CONNECTING=0,Ys.OPEN=1,Ys.CLOSED=2;function FE(){const e="document"in globalThis?globalThis.document:void 0;return e&&typeof e=="object"&&"baseURI"in e&&typeof e.baseURI=="string"?e.baseURI:void 0}class VE extends Error{constructor(t,n,r){super(`SSE error: ${n}`),this.code=t,this.event=r}}class dc{constructor(t,n){this._url=t,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=n==null?void 0:n.eventSourceInit,this._requestInit=n==null?void 0:n.requestInit,this._authProvider=n==null?void 0:n.authProvider,this._fetch=n==null?void 0:n.fetch,this._fetchWithInit=Lp(n==null?void 0:n.fetch,n==null?void 0:n.requestInit)}async _authThenStart(){var t;if(!this._authProvider)throw new Tt("No auth provider");let n;try{n=await Gn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw(t=this.onerror)===null||t===void 0||t.call(this,r),r}if(n!=="AUTHORIZED")throw new Tt;return await this._startOrAuth()}async _commonHeaders(){var t;const n={};if(this._authProvider){const r=await this._authProvider.tokens();r&&(n.Authorization=`Bearer ${r.access_token}`)}return this._protocolVersion&&(n["mcp-protocol-version"]=this._protocolVersion),new Headers({...n,...(t=this._requestInit)===null||t===void 0?void 0:t.headers})}_startOrAuth(){var t,n,r;const o=(r=(n=(t=this===null||this===void 0?void 0:this._eventSourceInit)===null||t===void 0?void 0:t.fetch)!==null&&n!==void 0?n:this._fetch)!==null&&r!==void 0?r:fetch;return new Promise((s,i)=>{this._eventSource=new Ys(this._url.href,{...this._eventSourceInit,fetch:async(a,l)=>{const c=await this._commonHeaders();c.set("Accept","text/event-stream");const u=await o(a,{...l,headers:c});if(u.status===401&&u.headers.has("www-authenticate")){const{resourceMetadataUrl:h,scope:_}=gs(u);this._resourceMetadataUrl=h,this._scope=_}return u}}),this._abortController=new AbortController,this._eventSource.onerror=a=>{var l;if(a.code===401&&this._authProvider){this._authThenStart().then(s,i);return}const c=new VE(a.code,a.message,a);i(c),(l=this.onerror)===null||l===void 0||l.call(this,c)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",a=>{var l;const c=a;try{if(this._endpoint=new URL(c.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(u){i(u),(l=this.onerror)===null||l===void 0||l.call(this,u),this.close();return}s()}),this._eventSource.onmessage=a=>{var l,c;const u=a;let h;try{h=Hn.parse(JSON.parse(u.data))}catch(_){(l=this.onerror)===null||l===void 0||l.call(this,_);return}(c=this.onmessage)===null||c===void 0||c.call(this,h)}})}async start(){if(this._eventSource)throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(t){if(!this._authProvider)throw new Tt("No auth provider");if(await Gn(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Tt("Failed to authorize")}async close(){var t,n,r;(t=this._abortController)===null||t===void 0||t.abort(),(n=this._eventSource)===null||n===void 0||n.close(),(r=this.onclose)===null||r===void 0||r.call(this)}async send(t){var n,r,o;if(!this._endpoint)throw new Error("Not connected");try{const s=await this._commonHeaders();s.set("content-type","application/json");const i={...this._requestInit,method:"POST",headers:s,body:JSON.stringify(t),signal:(n=this._abortController)===null||n===void 0?void 0:n.signal},a=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._endpoint,i);if(!a.ok){if(a.status===401&&this._authProvider){const{resourceMetadataUrl:c,scope:u}=gs(a);if(this._resourceMetadataUrl=c,this._scope=u,await Gn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Tt;return this.send(t)}const l=await a.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${a.status}): ${l}`)}}catch(s){throw(o=this.onerror)===null||o===void 0||o.call(this,s),s}}setProtocolVersion(t){this._protocolVersion=t}}const BE="mcp";class z2{constructor(t){this._url=t}start(){if(this._socket)throw new Error("WebSocketClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((t,n)=>{this._socket=new WebSocket(this._url,BE),this._socket.onerror=r=>{var o;const s="error"in r?r.error:new Error(`WebSocket error: ${JSON.stringify(r)}`);n(s),(o=this.onerror)===null||o===void 0||o.call(this,s)},this._socket.onopen=()=>{t()},this._socket.onclose=()=>{var r;(r=this.onclose)===null||r===void 0||r.call(this)},this._socket.onmessage=r=>{var o,s;let i;try{i=Hn.parse(JSON.parse(r.data))}catch(a){(o=this.onerror)===null||o===void 0||o.call(this,a);return}(s=this.onmessage)===null||s===void 0||s.call(this,i)}})}async close(){var t;(t=this._socket)===null||t===void 0||t.close()}send(t){return new Promise((n,r)=>{var o;if(!this._socket){r(new Error("Not connected"));return}(o=this._socket)===null||o===void 0||o.send(JSON.stringify(t)),n()})}}function Qs(){const e=["224340fQYLJj","function","onmessage","port2","341XVdnBD","313767JEBgqL","950bpstaX","1354759gUhUbE","wRKyh","onclose","2044SvCTUj","endpoint","24msSkHx","164VuWYGY","mOWMr","EkZCC","addEventListener","postMessage","120705iyGzUz","8878392ivIdKn","close","_listen","3619482FaLQHc","start","_endpoint","kgkem","bzNYT","MessageChannel transport error: ","stringify","onmessageerror","HvyCv","undefined","Jwyua","message","_globalObject","parse","authInfo","thraG","220pGvxgp","_port","EGhzU","onerror","data","MhriV"];return Qs=function(){return e},Qs()}(function(e,t){const n=nt,r=nt,o=e();for(;;)try{if(parseInt(n(417))/1*(parseInt(n(421))/2)+parseInt(n(433))/3+parseInt(n(424))/4*(-parseInt(r(429))/5)+parseInt(r(423))/6*(-parseInt(r(418))/7)+-parseInt(r(430))/8+-parseInt(n(416))/9*(-parseInt(n(405))/10)+-parseInt(n(415))/11*(-parseInt(n(411))/12)===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(Qs,650197);const HE=()=>{const e=nt,t={EGhzU:function(n,r){return n!==r},kIrDB:"undefined",llYQe:function(n,r){return n!==r},PZfJg:function(n,r){return n(r)},Jwyua:"return this"};return typeof globalThis<"u"?globalThis:t[e(407)](typeof window,t.kIrDB)?window:t.llYQe(typeof global,t.kIrDB)?global:typeof self!==e(398)?self:t.PZfJg(Function,t[e(399)])()},JE=(e,t,n)=>{const r=nt,o=nt,s={};s[r(410)]=o(398),s.dBkaX=function(a,l){return a===l},s[o(393)]="function";const i=s;typeof window!==i[o(410)]?e.postMessage(t,"*",n):o(428)in e&&i.dBkaX(typeof e.postMessage,i[r(393)])&&e.postMessage(t,n)};class D2{constructor(t){const n=nt;this[n(406)]=t}async start(){const t=nt,n=nt;this[t(406)]&&(this[t(406)][t(413)]=r=>{var o,s;const i=t,a=n;try{const l=Hn[i(402)](r.data[i(400)]);(o=this[i(413)])==null||o.call(this,l,r[a(409)].extra)}catch(l){const c=new Error("MessageChannel failed to parse message: "+l);(s=this[a(408)])==null||s.call(this,c)}},this._port[t(396)]=r=>{var o;const s=n,i=n,a=new Error(s(394)+JSON[i(395)](r));(o=this.onerror)==null||o.call(this,a)},this[t(406)][t(434)]())}async send(t,n){const r={lEyuq:function(o){return o()},YihNw:function(o,s){return o(s)}};return new Promise((o,s)=>{var i;const a=nt,l=nt;try{const c={};c[a(403)]=n==null?void 0:n[a(403)];const u={};u[l(400)]=t,u.extra=c,this[l(406)]&&this[a(406)].postMessage(u),r.lEyuq(o)}catch(c){const u=c instanceof Error?c:new Error(r.YihNw(String,c));(i=this[l(408)])==null||i.call(this,u),s(u)}})}async close(){var t,n;const r=nt,o=nt;(t=this._port)==null||t[r(431)](),this._port=void 0,(n=this[o(420)])==null||n.call(this)}}class GE extends D2{constructor(t,n=HE()){const r=nt,o=nt,s={EkZCC:function(a,l,c,u){return a(l,c,u)}};super(),this[r(391)]=t,this[o(401)]=n;const i=new MessageChannel;this[o(406)]=i.port1,s[o(426)](JE,this[r(401)],{endpoint:this[o(391)]},[i[o(414)]])}}function nt(e,t){const n=Qs();return nt=function(r,o){return r=r-(17*-491+-669+9407),n[r]},nt(e,t)}(function(e,t){const n=Pe,r=Pe,o=e();for(;;)try{if(parseInt(n(355))/1+-parseInt(n(356))/2*(-parseInt(n(373))/3)+-parseInt(n(337))/4+parseInt(r(357))/5+-parseInt(r(389))/6*(-parseInt(n(396))/7)+parseInt(r(325))/8*(parseInt(n(382))/9)+-parseInt(n(366))/10===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(Xs,-763475+-52067*10+1724410);const WE=async(e,t,n)=>{var r;const o=Pe,s=Pe,i={};i[o(345)]="tools/list",i.rqstG="tools/call",i.WqUnk="resources/list",i[o(329)]=s(358),i[o(365)]=o(335),i.ookoz="resources/unsubscribe",i[o(385)]=o(340),i.VTIWq="prompts/list",i.SkoRK=o(376),i.QUtUV=o(388),i.XtowM=s(332);const a=i,{id:l,method:c,params:u}=n;let h={};switch(c){case a[s(345)]:h=await t.listTools(u);break;case a.rqstG:h=await t.callTool(u);break;case a[o(334)]:h=await t[o(350)](u);break;case a[s(329)]:h=await t.listResourceTemplates(u);break;case o(372):h=await t[o(383)](u);break;case a.HgYgW:h=await t.subscribeResource(u);break;case a.ookoz:h=await t.unsubscribeResource(u);break;case a[o(385)]:h=await t.getPrompt(u);break;case a.VTIWq:h=await t.listPrompts(u);break;case a[o(344)]:h=await t[o(376)]();break;case a.QUtUV:h=await t.complete(u);break;case o(390):h=await t[o(336)](u==null?void 0:u.level);break}const _={};_[o(361)]=h,_[o(394)]=a[o(364)],_.id=l,await((r=e==null?void 0:e.transport)==null?void 0:r[o(392)](_))},KE=async(e,t,n)=>{var r;const o=Pe,s=Pe,i={};i.jQBBS="sampling/createMessage",i.EZqgC="elicitation/create",i[o(370)]=s(376),i.aVeaL=s(332);const a=i,{id:l,method:c,params:u}=n;let h={};switch(c){case o(368):const f={};f.method=c,f[s(367)]=u,h=await t.request(f,_f);break;case a[s(391)]:const g={};g.method=c,g[s(367)]=u,h=await t[s(381)](g,mf);break;case a.EZqgC:const v={};v.method=c,v.params=u,h=await t.request(v,Ca);break;case a[s(370)]:const m={};m.method=c,h=await t[s(381)](m,Jn);break}const _={};return _[s(361)]=h,_.jsonrpc=a[s(387)],_.id=l,await((r=e==null?void 0:e[o(371)])==null?void 0:r.send(_)),h},YE=(e,t)=>{const n=Pe,r={gXsjT:function(s,i){return s===i},oegpC:n(351),lZOUC:function(s,i,a,l){return s(i,a,l)},ifIKG:"2.0"},o=e._onrequest;e._onrequest=async(s,i)=>{var a,l,c,u,h;const _=n,f=n,{id:g,method:v}=s;try{r[_(333)](v,r.oegpC)?await o[_(386)](e,s,i):await r.lZOUC(WE,e,t,s)}catch(m){const{code:d,message:w,data:y}=m;try{if(d){const b={};b.code=d,b.message=w,b.data=y;const k={};k.error=b,k[_(394)]=r[f(331)],k.id=g,await((a=e==null?void 0:e.transport)==null?void 0:a.send(k))}else(c=(l=e==null?void 0:e[f(371)])==null?void 0:l.onerror)==null||c.call(l,m)}catch(b){(h=(u=e==null?void 0:e[_(371)])==null?void 0:u.onerror)==null||h.call(u,b)}}}},QE=(e,t)=>{const n=Pe,r=Pe,o={};o[n(363)]=function(i,a){return i!==a},o[n(398)]=n(353),o.hzhyg="notifications/cancelled";const s=o;e._onnotification=async i=>{var a,l;const c=n,u=r,{method:h,params:_}=i;if(s[c(363)](h,s[u(398)])&&(s[c(363)](h,s.hzhyg)||_!=null&&_.forward))try{await t.notification(i)}catch(f){(l=(a=e==null?void 0:e.transport)==null?void 0:a.onerror)==null||l.call(a,f)}}},XE=(e,t)=>async n=>{var r,o,s,i,a;const l=Pe,c=Pe,u={};u.SEmWX=l(332);const h=u;try{return await KE(e,t,n)}catch(_){const{code:f,message:g,data:v}=_;try{if(f){const m={};m[c(377)]=f,m.message=g,m.data=v;const d={};d[c(348)]=m,d.jsonrpc=h[l(338)],d.id=n.id,await((r=e==null?void 0:e.transport)==null?void 0:r[c(392)](d))}else(s=(o=e==null?void 0:e.transport)==null?void 0:o[c(339)])==null||s.call(o,_)}catch(m){(a=(i=e==null?void 0:e[l(371)])==null?void 0:i[c(339)])==null||a.call(i,m)}}},ek=(e,t)=>async n=>{var r,o,s;const i=Pe,a=Pe,l={};l.dtUgZ=function(_,f){return _!==f},l.jgCIb=i(353),l.uUjKY="2.0";const c=l,{method:u,params:h}=n;if(c.dtUgZ(u,c.jgCIb)&&(u!==i(400)||h!=null&&h.forward))try{const _={...n};_[i(394)]=c[a(352)],await((r=t==null?void 0:t[i(371)])==null?void 0:r[i(392)](_))}catch(_){(s=(o=e==null?void 0:e[i(371)])==null?void 0:o[a(339)])==null||s.call(o,_)}};function Pe(e,t){const n=Xs();return Pe=function(r,o){return r=r-(9*-113+-1439*-1+-97),n[r]},Pe(e,t)}const tk=(e,t)=>async n=>{var r,o,s,i,a,l;const c=Pe,u=Pe,h={};h[c(401)]=u(332);const _=h;try{await((r=t==null?void 0:t.transport)==null?void 0:r.send(n))}catch(f){const{code:g,message:v,data:m}=f;try{if(g){const d={};d.code=g,d[c(399)]=v,d.data=m;const w={};w[c(348)]=d,w[c(394)]=_.OhJjz,w.id=n.id,await((o=e==null?void 0:e[c(371)])==null?void 0:o.send(w))}else(i=(s=e==null?void 0:e.transport)==null?void 0:s[u(339)])==null||i.call(s,f)}catch(d){(l=(a=e==null?void 0:e.transport)==null?void 0:a.onerror)==null||l.call(a,d)}}},pc=()=>{const e=Pe,t=Pe,n={vnkqu:function(c,u){return c!==u},wxDWr:function(c,u){return c(u)},GdkkV:function(c,u){return c===u}},r=[],o=(c,u)=>{const h=Pe,_=Pe;if(u){const f=[];for(const g of r)try{f.push(g(c,u))}catch{}for(const g of f)if(n[h(379)](g,null))return g}else for(const f of r)try{n[_(343)](f,c)}catch{}},s=c=>{const u=Pe;n[u(384)](typeof c,u(369))&&!r.includes(c)&&r.push(c)},i=c=>{const u=r.indexOf(c);u!==-1&&r.splice(u,1*-6854+8*-33+7119)},a=()=>{const c=Pe;r[c(374)]=7102*1+5522+-526*24},l={};return l[e(346)]=o,l[t(330)]=s,l.removeListener=i,l[e(359)]=a,l},nk=e=>{const t=Pe,n=Pe,r={xwPeb:function(o){return o()},Mfvzm:function(o){return o()}};{const{handleListener:o,addListener:s,removeListener:i,clearListener:a}=r[t(326)](pc);e._onresponse=o,e[t(395)]=s,e.removeResponseListener=i,e.clearResponseListener=a}{const{handleListener:o,addListener:s,removeListener:i,clearListener:a}=r[n(326)](pc);e[n(328)]=o,e.addRequestListener=s,e[n(354)]=i,e[n(341)]=a}{const{handleListener:o,addListener:s,removeListener:i,clearListener:a}=r[t(375)](pc);e[t(342)]=o,e[t(327)]=s,e.removeNotificationListener=i,e.clearNotificationListener=a}};function Xs(){const e=["uUjKY","notifications/initialized","removeRequestListener","96194JysfjF","36346SGEWAV","1357830AJaOeY","resources/templates/list","clearListener","iQqcJ","result","tqDZP","sSeCz","XtowM","HgYgW","3913230mjiatC","params","roots/list","function","bfmJT","transport","resources/read","27FNuDmk","length","Mfvzm","ping","code","_onresponse","vnkqu","cjSoZ","request","9gIMIPC","readResource","GdkkV","ptMjy","call","aVeaL","completion/complete","5035122lFbpzR","logging/setLevel","jQBBS","send","_requestHandlers","jsonrpc","addResponseListener","7SpcenI","ElOQH","MDIkN","message","notifications/cancelled","OhJjz","clear","672216JzFEyR","xwPeb","addNotificationListener","fallbackRequestHandler","sYzPD","addListener","ifIKG","2.0","gXsjT","WqUnk","resources/subscribe","setLoggingLevel","2491772kFUWFh","SEmWX","onerror","prompts/get","clearRequestListener","fallbackNotificationHandler","wxDWr","SkoRK","uTeHc","handleListener","Zybtx","error","originalOnResponse","listResources","initialize"];return Xs=function(){return e},Xs()}const rk=(e,{beforeInit:t,afterInit:n}={})=>{const r=Pe,o=Pe,s={tqDZP:function(a,l){return a===l},cjSoZ:"function",iQqcJ:r(378),Zybtx:function(a,l){return a(l)},ElOQH:function(a){return a()}},i=new Map(e._notificationHandlers);e[r(393)][r(402)](),e._notificationHandlers[r(402)](),s.tqDZP(typeof t,s[r(380)])&&t(),s[r(362)](e._onresponse.name,s[r(360)])&&(e[o(349)]=e._onresponse),s[r(347)](nk,e),e.addResponseListener(a=>{const l=o;e.originalOnResponse[l(386)](e,a)}),s.tqDZP(typeof n,s[o(380)])&&s[r(397)](n),e[o(327)](a=>{const{method:l}=a,c=i.get(l);s.tqDZP(typeof c,s.cjSoZ)&&c(a)})},ok=sn,sk=sn;(function(e,t){const n=sn,r=sn,o=e();for(;;)try{if(-parseInt(n(393))/1+parseInt(n(397))/2*(-parseInt(n(400))/3)+-parseInt(r(398))/4+parseInt(n(390))/5*(parseInt(r(388))/6)+-parseInt(n(389))/7+-parseInt(n(402))/8*(-parseInt(r(395))/9)+parseInt(r(399))/10*(parseInt(r(385))/11)===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(ei,-1*-881393+2*180895+1*-644809);function sn(e,t){const n=ei();return sn=function(r,o){return r=r-(-1861+-499*4+4241),n[r]},sn(e,t)}function ei(){const e=["toString","getRandomValues","2101mUsYMI","EQHzo","padStart","30UvDAkd","1609706yzlqYx","974735GrhZVO","randomUUID","REzPF","562771BvAnoG","dHTfU","2047455boiYXf","randomBytes","14664qHAdbF","3772144jLpQch","52310AkWksx","318MkjaVb","from","40WRwnSc"];return ei=function(){return e},ei()}const ik=()=>{const e=sn,t=sn,n={};n.REzPF=function(o,s){return o&s},n.suJHI=function(o,s){return o===s},n[e(386)]=function(o,s){return o&s},n[t(394)]="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";const r=n;return r.suJHI(typeof crypto,"object")&&crypto.randomUUID?crypto[t(391)]():r.dHTfU.replace(/[xy]/g,o=>{const s=e,i=e,a=r[s(392)](crypto[s(384)](new Uint8Array(-25*-62+7113+2*-4331))[741*2+-1385*-2+4252*-1],8648+-107*62+-1999);return(r.suJHI(o,"x")?a:r[i(386)](a,-4377+4*1095)|5079+461*-11).toString(9449+4*-461+-7589)})},ak=e=>{const t=sn,n=sn,r=new Uint8Array(e);return crypto.getRandomValues(r),Array[t(401)](r,o=>o[n(403)](-3*1739+-6509+2*5871)[t(387)](2,"0")).join("")},Pn={};Pn[ok(391)]=ik,Pn[sk(396)]=ak;const Ct=an;(function(e,t){const n=an,r=an,o=e();for(;;)try{if(parseInt(n(521))/1*(parseInt(r(499))/2)+parseInt(r(543))/3*(parseInt(r(514))/4)+parseInt(n(502))/5*(parseInt(r(539))/6)+parseInt(n(553))/7+parseInt(n(516))/8*(-parseInt(n(518))/9)+-parseInt(n(531))/10+-parseInt(n(545))/11*(parseInt(n(541))/12)===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(ti,1472653*1+-2*-897917+-2275789);const lk=(e,t)=>{const n=an,r=an,o={FyYHt:function(l,c,u){return l(c,u)},Fxtoq:function(l,c,u){return l(c,u)}};YE(e,t),QE(e,t);const s=XE(t,e),i=o[n(510)](tk,t,e),a=o[r(549)](ek,t,e);t[r(537)](s),t[n(519)](i),t.addNotificationListener(a),e[r(556)]=()=>{const l=r;t.removeRequestListener(s),t[l(530)](i),t[l(529)](a)}},fc=(e,t,n)=>{const r=an,o={pMiva:function(a,l){return a instanceof l},TeTEy:r(546),fyZbd:function(a,l,c){return a(l,c)}},s=()=>{var a;const l=r;o.pMiva(n,dc)&&((a=n._eventSource)==null||a.addEventListener(o[l(547)],()=>{var c;const u=l;(c=n[u(509)])==null||c[u(546)]()})),lk(e,t)},i={};i.afterInit=s,o.fyZbd(rk,t,i)},U2=(e,t=Pn.randomUUID())=>{const n=an,r=an,o={OfssH:function(u,h,_){return u(h,_)}},s={};s[n(528)]=t;const i=s,a={};a[n(528)]=t;const l={};l[r(558)]=a,l[n(534)]=n(524);const c={requestInit:l,eventSourceInit:{async fetch(u,h){const _=n,f=r,g=new Headers((h==null?void 0:h[_(558)])||{});Object.entries(i)[f(498)](([m,d])=>{g[f(527)](m,d)});const v={...h};return v[f(558)]=g,o.OfssH(fetch,u,v)},withCredentials:!0}};return e&&(c.requestInit[n(558)].Authorization=n(533)+e,i.Authorization="Bearer "+e),c},q2=(e,t=Pn[Ct(517)]())=>{const n=Ct,r=Ct,o={};o.nwQhY="include";const s=o,i={};i["stream-session-id"]=t;const a={};a.headers=i,a.credentials=s[n(520)];const l={};l[n(544)]=a;const c=l;return e&&(c.requestInit.headers[r(552)]=r(533)+e),c},hc=async(e,t,n)=>{const r=Ct,o=Ct,s={CFfFC:function(a){return a()},egwVO:function(a,l,c,u){return a(l,c,u)}},i=s.CFfFC(n);try{return await e[r(538)](i),i}catch(a){if(a instanceof Tt){const l=await t();return await i[o(505)](l),await s[r(525)](hc,e,t,n)}else throw a}};function an(e,t){const n=ti();return an=function(r,o){return r=r-(74*-67+-8341+-73*-189),n[r]},an(e,t)}const Z2=(e,t)=>{const n=Ct,r=Ct,o={};o.RsKXs=function(i,a){return i in a},o.PBhps="waitForOAuthCode",o[n(535)]="function",o[n(507)]="waitForOAuthCode need to be provided when authProvider is provided";const s=o;if(s.RsKXs(s[r(551)],e))return e[r(523)];if(typeof t===s.yTKoP)return t;throw new Error(s.RZhOv)},ck=async e=>{const t=Ct,n=Ct,r={TFSRn:function(U,H,q){return U(H,q)},HwvVa:"mcp-sse-proxy-client",ufTHS:function(U){return U()},WIVYl:function(U,H,q,F){return U(H,q,F)},jniGY:"sessionId"},{client:o,url:s,token:i,sessionId:a,authProvider:l,requestInit:c,eventSourceInit:u,waitForOAuthCode:h}=e,_={};_.authProvider=l,_.requestInit=c,_.eventSourceInit=u;const f=_,g=a||Pn.randomUUID(),v=r[t(506)](U2,i,g);if(c){const U={...v.requestInit,...c};U.headers={...v[t(544)].headers,...c.headers},f.requestInit=U}else f[n(544)]=v.requestInit;if(u){const U={...v[t(559)],...u};f.eventSourceInit=U}else f.eventSourceInit=v.eventSourceInit;const m={};m.listChanged=!0;const d={};d.roots=m,d.sampling={},d[t(511)]={};const w=d,y={};y[n(536)]=r.HwvVa,y.version=t(526);const b={};b.capabilities=w;const k=new Gs(y,b),x=()=>new dc(new URL(s),f);let T=r[n(504)](x);if(l){const U=r[t(506)](Z2,l,h);T=await r[n(513)](hc,k,U,x)}else await k[t(538)](T);r[n(513)](fc,k,o,T),T[n(557)]=T[n(542)].searchParams[n(532)](r.jniGY);const D={};return D.transport=T,D.sessionId=T[t(557)],D};function ti(){const e=["ufTHS","finishAuth","TFSRn","RZhOv","Vajmx","_eventSource","FyYHt","elicitation","transport","WIVYl","13320uyrBtN","sampling","8WTwLJD","randomUUID","6438654bkJHij","addResponseListener","nwQhY","11721GVgRMJ","?sessionId=","waitForOAuthCode","include","egwVO","1.0.0","set","sse-session-id","removeNotificationListener","removeResponseListener","11838520fNkjrV","get","Bearer ","credentials","yTKoP","name","addRequestListener","connect","18VhCgQv","mcp-socket-proxy-client","2819364JNqkQZ","_endpoint","699JyrxCR","requestInit","44ofbsvb","close","TeTEy","QgzDy","Fxtoq","roots","PBhps","Authorization","11309130xGCFwl","&token=","version","onclose","sessionId","headers","eventSourceInit","forEach","62FcOkCa","mcp-stream-proxy-client","zXcpO","1794855cQEXDT","biJOc"];return ti=function(){return e},ti()}const uk=async e=>{const t=Ct,n=Ct,r={Vajmx:t(500),biJOc:function(U){return U()},zXcpO:function(U,H,q){return U(H,q)},zDnjZ:function(U,H,q,F){return U(H,q,F)},FQMAh:function(U,H,q,F){return U(H,q,F)}},{client:o,url:s,token:i,sessionId:a,authProvider:l,requestInit:c,reconnectionOptions:u,waitForOAuthCode:h}=e,_={};_.authProvider=l,_.requestInit=c,_.reconnectionOptions=u;const f=_,g=a||Pn.randomUUID(),v=q2(i,g);if(c){const U={...v.requestInit,...c};U.headers={...v.requestInit.headers,...c.headers},f[t(544)]=U}else f.requestInit=v.requestInit;const m={};m.listChanged=!0;const d={};d[n(550)]=m,d.sampling={},d.elicitation={};const w=d,y={};y[t(536)]=r[n(508)],y[t(555)]="1.0.0";const b={};b.capabilities=w;const k=new Gs(y,b),x=()=>new vs(new URL(s),f);let T=r[t(503)](x);if(l){const U=r[t(501)](Z2,l,h);T=await r.zDnjZ(hc,k,U,x)}else await k.connect(T);r.FQMAh(fc,k,o,T);const D={};return D.transport=T,D[n(557)]=T.sessionId,D},dk=async e=>{const t=Ct,n=Ct,r={QgzDy:t(540),jkaVB:function(d,w,y,b){return d(w,y,b)}},{client:o,url:s,token:i,sessionId:a}=e,l={};l.listChanged=!0;const c={};c[t(550)]=l,c[t(515)]={},c[n(511)]={};const u=c,h={};h.name=r[n(548)],h[n(555)]=n(526);const _={};_.capabilities=u;const f=new Gs(h,_),g=a||Pn[n(517)](),v=new z2(new URL(s+t(522)+g+n(554)+i));await f.connect(v),r.jkaVB(fc,f,o,v);const m={};return m[t(512)]=v,m[n(557)]=g,m},Io=mt,ni=mt;function mt(e,t){const n=ri();return mt=function(r,o){return r=r-(-16761+51*337),n[r]},mt(e,t)}(function(e,t){const n=mt,r=mt,o=e();for(;;)try{if(-parseInt(n(440))/1+-parseInt(n(458))/2*(parseInt(n(448))/3)+-parseInt(n(451))/4*(parseInt(r(449))/5)+-parseInt(r(455))/6+-parseInt(n(427))/7+-parseInt(r(438))/8*(parseInt(r(459))/9)+parseInt(n(430))/10*(parseInt(r(436))/11)===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(ri,-220880+1*-333337+-2*-384996);function ri(){const e=["650XPHLhD","redirectToAuthorization","10856jPvMVb","GET","qcFPW","_redirectUrl","2187414WnlGuZ","resolve","tokens","3976YyOqUl","27ejNHsa","Content-Type","waitForOAuthCode","2903796yvWZFa","_clientMetadata","application/x-www-form-urlencoded","10beEWJk","json","code","_callBackPromise","reject","saveClientInformation","20776349mLNCcF","_codeVerifier","629912aTknXq","_tokens","52074GwcpRo","state","_state","_redirectCallback","_clientInformation","redirect_uris","Failed to redirect: ","clientInformation","381aduWsB"];return ri=function(){return e},ri()}const pk=()=>Pn.randomBytes(3485*1+-261+-3184);class XI{constructor(t){const n=mt,r=mt;this._callBackPromise={};const{clientMetadata:o,state:s,redirectCallback:i,getAuthCodeByState:a,waitForOAuthCode:l}=t;this[n(428)]=o,this[n(454)]=o[n(445)][0],this._state=s||pk(),this._redirectCallback=i||this.redirectCallbackFunction,this._getAuthCodeByState=a||this.getAuthCodeByStateFunction,this[r(426)]=l||this.waitForOAuthCodeFunction()}async redirectCallbackFunction(t){var n,r,o,s,i,a;const l=mt,c=mt,u={qITTp:function(g,v,m){return g(v,m)},qcFPW:l(452)},h=await u.qITTp(fetch,t,{method:u[l(453)]});!h.ok&&((r=(n=this._callBackPromise).reject)==null||r.call(n,c(446)+h.statusText));const _=await this._getAuthCodeByState(this[c(454)],this[l(442)]);if(!_.ok){(s=(o=this[l(433)]).reject)==null||s.call(o,"Failed to fetch auth code: "+_.statusText);return}const f=await _[l(431)]();(a=(i=this[c(433)])[l(456)])==null||a.call(i,f[l(432)])}async getAuthCodeByStateFunction(t,n){const r=mt,o=mt,s={};s.tuSmb=r(429);const i=s,a={};a[r(460)]=i.tuSmb;const l={};return l[o(441)]=n,fetch(t,{method:"POST",headers:a,body:new URLSearchParams(l)})}waitForOAuthCodeFunction(){const t=mt,n=this[t(433)];return()=>new Promise((r,o)=>{const s=t;n.resolve=r,n[s(434)]=o})}get redirectUrl(){return this[mt(454)]}get clientMetadata(){return this._clientMetadata}state(){return this._state}[Io(447)](){return this[Io(444)]}[ni(435)](t){const n=Io;this[n(444)]=t}[ni(457)](){return this[ni(439)]}saveTokens(t){this._tokens=t}[ni(450)](t){this[Io(443)](t)}saveCodeVerifier(t){this._codeVerifier=t}codeVerifier(){if(!this[Io(437)])throw new Error("No code verifier saved");return this._codeVerifier}}(function(e,t){for(var n=si,r=si,o=e();;)try{var s=parseInt(n(361))/1*(parseInt(r(363))/2)+-parseInt(n(358))/3+parseInt(n(359))/4*(parseInt(n(357))/5)+parseInt(r(354))/6*(parseInt(n(360))/7)+parseInt(r(362))/8+parseInt(r(364))/9+-parseInt(r(356))/10*(parseInt(n(355))/11);if(s===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(oi,-73523*-3+1*-407717+530518);function oi(){var e=["40ecBYYe","1095owKKYD","486870YOVwZy","5752xWiyTO","561484biNVMw","1fWJmxQ","1866064SPnyhb","1109522vMiuMX","1602351pPEGwH","12sVyMLL","2573296LTwOhv"];return oi=function(){return e},oi()}function si(e,t){var n=oi();return si=function(r,o){r=r-(-1*-642+503*-5+2227);var s=n[r];return s},si(e,t)}class fk{constructor(t,n){const r={name:"web-mcp-client",version:"1.0.0"},o={roots:{listChanged:!0},sampling:{},elicitation:{}};this.client=new Gs(t||r,n||{capabilities:o}),this.client.onclose=()=>{var s;(s=this.onclose)==null||s.call(this)},this.client.onerror=s=>{var i;(i=this.onerror)==null||i.call(this,s)}}async connect(t){if(typeof t.start=="function")return this.transport=t,this.transport.onclose=void 0,this.transport.onerror=void 0,this.transport.onmessage=void 0,await this.client.connect(this.transport),{transport:this.transport,sessionId:this.transport.sessionId};const{url:n,token:r,sessionId:o,type:s,agent:i,onError:a}=t;if(i===!0){const u={client:this.client,url:n,token:r,sessionId:o};let h;return await(async()=>{const{transport:f,sessionId:g}=s==="sse"?await ck(u):s==="socket"?await dk(u):await uk(u);f.onerror=async v=>{a==null||a(v)},h={transport:f,sessionId:g}})(),h}const l=new URL(n);let c;if(s==="channel"&&(c=new GE(n),await this.client.connect(c)),s==="sse"){const u=U2(r,o);c=new dc(l,u),await this.client.connect(c)}if(s==="socket"&&(c=new z2(new URL(`${n}?sessionId=${o}&token=${r}`)),c.sessionId=o,await this.client.connect(c)),typeof c>"u"){const u=q2(r,o);c=new vs(l,u),await this.client.connect(c)}return this.transport=c,{transport:this.transport,sessionId:this.transport.sessionId}}async close(){await this.client.close()}getServerCapabilities(){return this.client.getServerCapabilities()}getServerVersion(){return this.client.getServerVersion()}getInstructions(){return this.client.getInstructions()}async ping(t){return await this.client.ping(t)}async complete(t,n){return await this.client.complete(t,n)}async setLoggingLevel(t,n){return await this.client.setLoggingLevel(t,n)}async getPrompt(t,n){return await this.client.getPrompt(t,n)}async listPrompts(t,n){return await this.client.listPrompts(t,n)}async listResources(t,n){return await this.client.listResources(t,n)}async listResourceTemplates(t,n){return await this.client.listResourceTemplates(t,n)}async readResource(t,n){return await this.client.readResource(t,n)}async subscribeResource(t,n){return await this.client.subscribeResource(t,n)}async unsubscribeResource(t,n){return await this.client.unsubscribeResource(t,n)}async callTool(t,n){return await this.client.callTool(t,us,n)}async listTools(t,n){return await this.client.listTools(t,n)}async sendRootsListChanged(){return await this.client.sendRootsListChanged()}request(t,n,r){return this.client.request(t,n,r)}async notification(t,n){return await this.client.notification(t,n)}setRequestHandler(t,n){this.client.setRequestHandler(t,n)}removeRequestHandler(t){this.client.removeRequestHandler(t)}setNotificationHandler(t,n){this.client.setNotificationHandler(t,n)}removeNotificationHandler(t){this.client.removeNotificationHandler(t)}onElicit(t){this.client.setRequestHandler(Sa,t)}onCreateMessage(t){this.client.setRequestHandler(hf,t)}onListRoots(t){this.client.setRequestHandler(vf,t)}onToolListChanged(t){this.client.setNotificationHandler(df,t)}onPromptListChanged(t){this.client.setNotificationHandler(lf,t)}onResourceListChanged(t){this.client.setNotificationHandler(ef,t)}onResourceUpdated(t){this.client.setNotificationHandler(tf,t)}onLoggingMessage(t){this.client.setNotificationHandler(ff,t)}async onPagehide(t){t.persisted||(hk(this.transport)?await this.transport.terminateSession():this.transport&&typeof this.transport.close=="function"&&await this.transport.close())}}const hk=e=>e instanceof vs,F2=async e=>{const t={};try{const n=await e.listTools();for(const{name:r,description:o,inputSchema:s}of n.tools){const i=async(a,l)=>e.callTool({name:r,arguments:a},{signal:l==null?void 0:l.abortSignal});t[r]=$d({description:o,inputSchema:Jr({...s,properties:s.properties??{},additionalProperties:!1}),execute:i})}return t}catch(n){throw n}},mk={openai:Xf,deepseek:sh};class gk{constructor({llmConfig:t,mcpServers:n}){if(this.mcpServers={},this.mcpClients={},this.mcpTools={},this.ignoreToolnames=[],this.messages=[],!t)throw new Error("llmConfig is required to initialize AgentModelProvider");if(this.mcpServers=n||{},this.mcpClients={},this.mcpTools={},t.llm)this.llm=t.llm;else if(t.providerType){const r=t.providerType;let o;typeof r=="string"?o=mk[r]:o=r,this.llm=o({apiKey:t.apiKey,baseURL:t.baseURL})}else throw new Error("Either llmConfig.llm or llmConfig.providerType must be provided")}async _createOneClient(t){try{let n;if("type"in t&&t.type.toLocaleLowerCase()==="streamablehttp"?n=new vs(new URL(t.url)):"type"in t&&t.type==="extension"?n=new E7(t.sessionId):n=t,t.useAISdkClient??!1){const o=await z9({transport:n});return o.__transport__=n,o}else{const o=new fk({name:"mcp-web-client",version:"1.0.0"},{capabilities:{roots:{listChanged:!0},sampling:{},elicitation:{}}});return await o.connect(n),o.__transport__=n,o}}catch(n){return this.onError&&this.onError((n==null?void 0:n.message)||"Failed to create MCP client",n),console.error("Failed to create MCP client",t,n),null}}async _closeOneClient(t){var n,r,o;try{const s=t.__transport__;if(s&&s instanceof _s||s&&s instanceof D2)return;await((n=s==null?void 0:s.terminateSession)==null?void 0:n.call(s)),await((r=s==null?void 0:s.close)==null?void 0:r.call(s)),await((o=t==null?void 0:t.close)==null?void 0:o.call(t))}catch{}}async _createMpcClients(){const t=Object.entries(this.mcpServers),n=await Promise.all(t.map(async([r,o])=>{const s=await this._createOneClient(o);return{serverName:r,client:s}}));this.mcpClients={},n.forEach(({serverName:r,client:o})=>{this.mcpClients[r]=o})}async _getClientTools(t,n){if(!t)return null;try{return typeof t.tools=="function"?await t.tools():await F2(t)}catch(r){return this.onError&&this.onError((r==null?void 0:r.message)||`Failed to query tools for ${n}`,r),console.error(`Failed to query tools for ${n}`,r),null}}async _createMpcTools(){const t=Object.entries(this.mcpClients),n=await Promise.all(t.map(async([r,o])=>{const s=await this._getClientTools(o,r);return{serverName:r,tools:s}}));this.mcpTools={},n.forEach(({serverName:r,tools:o})=>{const s=o&&typeof o=="object"?o:{};this.mcpTools[r]=s})}async closeAll(){await Promise.all(Object.values(this.mcpClients).map(async t=>{try{await this._closeOneClient(t)}catch(n){this.onError&&this.onError((n==null?void 0:n.message)||"Failed to close client",n),console.error("Failed to close client",n)}}))}async initClientsAndTools(){var t;await this._createMpcClients(),await this._createMpcTools(),(t=this.onUpdatedTools)==null||t.call(this)}async updateMcpServers(t){await this.closeAll(),this.mcpServers=t||this.mcpServers,await this.initClientsAndTools()}async insertMcpServer(t,n){var s,i;if(this.mcpServers[t])return!1;const r=await this._createOneClient(n);if(!r)return(s=this.onError)==null||s.call(this,`Failed to create MCP client: ${t}`),null;this.mcpClients[t]=r;const o=await this._getClientTools(r,t);return this.mcpTools[t]=o&&typeof o=="object"?o:{},this.mcpServers[t]=n,(i=this.onUpdatedTools)==null||i.call(this),r}async removeMcpServer(t){var o;if(!this.mcpServers[t])return;delete this.mcpServers[t];const n=this.mcpClients[t];delete this.mcpClients[t];try{await this._closeOneClient(n)}catch{}const r=this.mcpTools[t];delete this.mcpTools[t],r&&Object.keys(r).forEach(s=>{this.ignoreToolnames=this.ignoreToolnames.filter(i=>i!==s)}),(o=this.onUpdatedTools)==null||o.call(this)}_tempMergeTools(t={}){const n=Object.values(this.mcpTools).reduce((r,o)=>({...r,...o}),{});return Object.assign(n,t),this.ignoreToolnames.forEach(r=>{delete n[r]}),n}async _chat(t,{model:n,maxSteps:r=5,...o}){var a;if(!this.llm)throw new Error("LLM is not initialized");await this.initClientsAndTools();const s={model:this.llm(n),stopWhen:ua(r),...o,tools:this._tempMergeTools(o.tools)};o.message&&!o.messages&&(this.messages.push({role:"user",content:o.message}),s.messages=[...this.messages]);const i=t(s);return(a=i==null?void 0:i.response)==null||a.then(l=>{this.messages.push(...l.messages)}),i}async chat(t){return this._chat(Vb,t)}async chatStream(t){return this._chat(c9,t)}}var Tr={},vk=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then},V2={},Et={};let mc;const _k=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];Et.getSymbolSize=function(t){if(!t)throw new Error('"version" cannot be null or undefined');if(t<1||t>40)throw new Error('"version" should be in range from 1 to 40');return t*4+17},Et.getSymbolTotalCodewords=function(t){return _k[t]},Et.getBCHDigit=function(e){let t=0;for(;e!==0;)t++,e>>>=1;return t},Et.setToSJISFunction=function(t){if(typeof t!="function")throw new Error('"toSJISFunc" is not a valid function.');mc=t},Et.isKanjiModeEnabled=function(){return typeof mc<"u"},Et.toSJIS=function(t){return mc(t)};var ii={};(function(e){e.L={bit:1},e.M={bit:0},e.Q={bit:3},e.H={bit:2};function t(n){if(typeof n!="string")throw new Error("Param is not a string");switch(n.toLowerCase()){case"l":case"low":return e.L;case"m":case"medium":return e.M;case"q":case"quartile":return e.Q;case"h":case"high":return e.H;default:throw new Error("Unknown EC Level: "+n)}}e.isValid=function(r){return r&&typeof r.bit<"u"&&r.bit>=0&&r.bit<4},e.from=function(r,o){if(e.isValid(r))return r;try{return t(r)}catch{return o}}})(ii);function B2(){this.buffer=[],this.length=0}B2.prototype={get:function(e){const t=Math.floor(e/8);return(this.buffer[t]>>>7-e%8&1)===1},put:function(e,t){for(let n=0;n<t;n++)this.putBit((e>>>t-n-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(e){const t=Math.floor(this.length/8);this.buffer.length<=t&&this.buffer.push(0),e&&(this.buffer[t]|=128>>>this.length%8),this.length++}};var yk=B2;function To(e){if(!e||e<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=e,this.data=new Uint8Array(e*e),this.reservedBit=new Uint8Array(e*e)}To.prototype.set=function(e,t,n,r){const o=e*this.size+t;this.data[o]=n,r&&(this.reservedBit[o]=!0)},To.prototype.get=function(e,t){return this.data[e*this.size+t]},To.prototype.xor=function(e,t,n){this.data[e*this.size+t]^=n},To.prototype.isReserved=function(e,t){return this.reservedBit[e*this.size+t]};var wk=To,H2={};(function(e){const t=Et.getSymbolSize;e.getRowColCoords=function(r){if(r===1)return[];const o=Math.floor(r/7)+2,s=t(r),i=s===145?26:Math.ceil((s-13)/(2*o-2))*2,a=[s-7];for(let l=1;l<o-1;l++)a[l]=a[l-1]-i;return a.push(6),a.reverse()},e.getPositions=function(r){const o=[],s=e.getRowColCoords(r),i=s.length;for(let a=0;a<i;a++)for(let l=0;l<i;l++)a===0&&l===0||a===0&&l===i-1||a===i-1&&l===0||o.push([s[a],s[l]]);return o}})(H2);var J2={};const bk=Et.getSymbolSize,G2=7;J2.getPositions=function(t){const n=bk(t);return[[0,0],[n-G2,0],[0,n-G2]]};var W2={};(function(e){e.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};const t={N1:3,N2:3,N3:40,N4:10};e.isValid=function(o){return o!=null&&o!==""&&!isNaN(o)&&o>=0&&o<=7},e.from=function(o){return e.isValid(o)?parseInt(o,10):void 0},e.getPenaltyN1=function(o){const s=o.size;let i=0,a=0,l=0,c=null,u=null;for(let h=0;h<s;h++){a=l=0,c=u=null;for(let _=0;_<s;_++){let f=o.get(h,_);f===c?a++:(a>=5&&(i+=t.N1+(a-5)),c=f,a=1),f=o.get(_,h),f===u?l++:(l>=5&&(i+=t.N1+(l-5)),u=f,l=1)}a>=5&&(i+=t.N1+(a-5)),l>=5&&(i+=t.N1+(l-5))}return i},e.getPenaltyN2=function(o){const s=o.size;let i=0;for(let a=0;a<s-1;a++)for(let l=0;l<s-1;l++){const c=o.get(a,l)+o.get(a,l+1)+o.get(a+1,l)+o.get(a+1,l+1);(c===4||c===0)&&i++}return i*t.N2},e.getPenaltyN3=function(o){const s=o.size;let i=0,a=0,l=0;for(let c=0;c<s;c++){a=l=0;for(let u=0;u<s;u++)a=a<<1&2047|o.get(c,u),u>=10&&(a===1488||a===93)&&i++,l=l<<1&2047|o.get(u,c),u>=10&&(l===1488||l===93)&&i++}return i*t.N3},e.getPenaltyN4=function(o){let s=0;const i=o.data.length;for(let l=0;l<i;l++)s+=o.data[l];return Math.abs(Math.ceil(s*100/i/5)-10)*t.N4};function n(r,o,s){switch(r){case e.Patterns.PATTERN000:return(o+s)%2===0;case e.Patterns.PATTERN001:return o%2===0;case e.Patterns.PATTERN010:return s%3===0;case e.Patterns.PATTERN011:return(o+s)%3===0;case e.Patterns.PATTERN100:return(Math.floor(o/2)+Math.floor(s/3))%2===0;case e.Patterns.PATTERN101:return o*s%2+o*s%3===0;case e.Patterns.PATTERN110:return(o*s%2+o*s%3)%2===0;case e.Patterns.PATTERN111:return(o*s%3+(o+s)%2)%2===0;default:throw new Error("bad maskPattern:"+r)}}e.applyMask=function(o,s){const i=s.size;for(let a=0;a<i;a++)for(let l=0;l<i;l++)s.isReserved(l,a)||s.xor(l,a,n(o,l,a))},e.getBestMask=function(o,s){const i=Object.keys(e.Patterns).length;let a=0,l=1/0;for(let c=0;c<i;c++){s(c),e.applyMask(c,o);const u=e.getPenaltyN1(o)+e.getPenaltyN2(o)+e.getPenaltyN3(o)+e.getPenaltyN4(o);e.applyMask(c,o),u<l&&(l=u,a=c)}return a}})(W2);var ai={};const Rn=ii,li=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],ci=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];ai.getBlocksCount=function(t,n){switch(n){case Rn.L:return li[(t-1)*4+0];case Rn.M:return li[(t-1)*4+1];case Rn.Q:return li[(t-1)*4+2];case Rn.H:return li[(t-1)*4+3];default:return}},ai.getTotalCodewordsCount=function(t,n){switch(n){case Rn.L:return ci[(t-1)*4+0];case Rn.M:return ci[(t-1)*4+1];case Rn.Q:return ci[(t-1)*4+2];case Rn.H:return ci[(t-1)*4+3];default:return}};var K2={},ui={};const xo=new Uint8Array(512),di=new Uint8Array(256);(function(){let t=1;for(let n=0;n<255;n++)xo[n]=t,di[t]=n,t<<=1,t&256&&(t^=285);for(let n=255;n<512;n++)xo[n]=xo[n-255]})(),ui.log=function(t){if(t<1)throw new Error("log("+t+")");return di[t]},ui.exp=function(t){return xo[t]},ui.mul=function(t,n){return t===0||n===0?0:xo[di[t]+di[n]]},function(e){const t=ui;e.mul=function(r,o){const s=new Uint8Array(r.length+o.length-1);for(let i=0;i<r.length;i++)for(let a=0;a<o.length;a++)s[i+a]^=t.mul(r[i],o[a]);return s},e.mod=function(r,o){let s=new Uint8Array(r);for(;s.length-o.length>=0;){const i=s[0];for(let l=0;l<o.length;l++)s[l]^=t.mul(o[l],i);let a=0;for(;a<s.length&&s[a]===0;)a++;s=s.slice(a)}return s},e.generateECPolynomial=function(r){let o=new Uint8Array([1]);for(let s=0;s<r;s++)o=e.mul(o,new Uint8Array([1,t.exp(s)]));return o}}(K2);const Y2=K2;function gc(e){this.genPoly=void 0,this.degree=e,this.degree&&this.initialize(this.degree)}gc.prototype.initialize=function(t){this.degree=t,this.genPoly=Y2.generateECPolynomial(this.degree)},gc.prototype.encode=function(t){if(!this.genPoly)throw new Error("Encoder not initialized");const n=new Uint8Array(t.length+this.degree);n.set(t);const r=Y2.mod(n,this.genPoly),o=this.degree-r.length;if(o>0){const s=new Uint8Array(this.degree);return s.set(r,o),s}return r};var $k=gc,Q2={},On={},vc={};vc.isValid=function(t){return!isNaN(t)&&t>=1&&t<=40};var ln={};const X2="[0-9]+",Sk="[A-Z $%*+\\-./:]+";let Po="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";Po=Po.replace(/u/g,"\\u");const Ck="(?:(?![A-Z0-9 $%*+\\-./:]|"+Po+`)(?:.|[\r
79
+ ]))+`;ln.KANJI=new RegExp(Po,"g"),ln.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),ln.BYTE=new RegExp(Ck,"g"),ln.NUMERIC=new RegExp(X2,"g"),ln.ALPHANUMERIC=new RegExp(Sk,"g");const Ek=new RegExp("^"+Po+"$"),kk=new RegExp("^"+X2+"$"),Ik=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");ln.testKanji=function(t){return Ek.test(t)},ln.testNumeric=function(t){return kk.test(t)},ln.testAlphanumeric=function(t){return Ik.test(t)},function(e){const t=vc,n=ln;e.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]},e.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]},e.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]},e.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]},e.MIXED={bit:-1},e.getCharCountIndicator=function(s,i){if(!s.ccBits)throw new Error("Invalid mode: "+s);if(!t.isValid(i))throw new Error("Invalid version: "+i);return i>=1&&i<10?s.ccBits[0]:i<27?s.ccBits[1]:s.ccBits[2]},e.getBestModeForData=function(s){return n.testNumeric(s)?e.NUMERIC:n.testAlphanumeric(s)?e.ALPHANUMERIC:n.testKanji(s)?e.KANJI:e.BYTE},e.toString=function(s){if(s&&s.id)return s.id;throw new Error("Invalid mode")},e.isValid=function(s){return s&&s.bit&&s.ccBits};function r(o){if(typeof o!="string")throw new Error("Param is not a string");switch(o.toLowerCase()){case"numeric":return e.NUMERIC;case"alphanumeric":return e.ALPHANUMERIC;case"kanji":return e.KANJI;case"byte":return e.BYTE;default:throw new Error("Unknown mode: "+o)}}e.from=function(s,i){if(e.isValid(s))return s;try{return r(s)}catch{return i}}}(On),function(e){const t=Et,n=ai,r=ii,o=On,s=vc,i=7973,a=t.getBCHDigit(i);function l(_,f,g){for(let v=1;v<=40;v++)if(f<=e.getCapacity(v,g,_))return v}function c(_,f){return o.getCharCountIndicator(_,f)+4}function u(_,f){let g=0;return _.forEach(function(v){const m=c(v.mode,f);g+=m+v.getBitsLength()}),g}function h(_,f){for(let g=1;g<=40;g++)if(u(_,g)<=e.getCapacity(g,f,o.MIXED))return g}e.from=function(f,g){return s.isValid(f)?parseInt(f,10):g},e.getCapacity=function(f,g,v){if(!s.isValid(f))throw new Error("Invalid QR Code version");typeof v>"u"&&(v=o.BYTE);const m=t.getSymbolTotalCodewords(f),d=n.getTotalCodewordsCount(f,g),w=(m-d)*8;if(v===o.MIXED)return w;const y=w-c(v,f);switch(v){case o.NUMERIC:return Math.floor(y/10*3);case o.ALPHANUMERIC:return Math.floor(y/11*2);case o.KANJI:return Math.floor(y/13);case o.BYTE:default:return Math.floor(y/8)}},e.getBestVersionForData=function(f,g){let v;const m=r.from(g,r.M);if(Array.isArray(f)){if(f.length>1)return h(f,m);if(f.length===0)return 1;v=f[0]}else v=f;return l(v.mode,v.getLength(),m)},e.getEncodedBits=function(f){if(!s.isValid(f)||f<7)throw new Error("Invalid QR Code version");let g=f<<12;for(;t.getBCHDigit(g)-a>=0;)g^=i<<t.getBCHDigit(g)-a;return f<<12|g}}(Q2);var em={};const _c=Et,tm=1335,Tk=21522,nm=_c.getBCHDigit(tm);em.getEncodedBits=function(t,n){const r=t.bit<<3|n;let o=r<<10;for(;_c.getBCHDigit(o)-nm>=0;)o^=tm<<_c.getBCHDigit(o)-nm;return(r<<10|o)^Tk};var rm={};const xk=On;function xr(e){this.mode=xk.NUMERIC,this.data=e.toString()}xr.getBitsLength=function(t){return 10*Math.floor(t/3)+(t%3?t%3*3+1:0)},xr.prototype.getLength=function(){return this.data.length},xr.prototype.getBitsLength=function(){return xr.getBitsLength(this.data.length)},xr.prototype.write=function(t){let n,r,o;for(n=0;n+3<=this.data.length;n+=3)r=this.data.substr(n,3),o=parseInt(r,10),t.put(o,10);const s=this.data.length-n;s>0&&(r=this.data.substr(n),o=parseInt(r,10),t.put(o,s*3+1))};var Pk=xr;const Rk=On,yc=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function Pr(e){this.mode=Rk.ALPHANUMERIC,this.data=e}Pr.getBitsLength=function(t){return 11*Math.floor(t/2)+6*(t%2)},Pr.prototype.getLength=function(){return this.data.length},Pr.prototype.getBitsLength=function(){return Pr.getBitsLength(this.data.length)},Pr.prototype.write=function(t){let n;for(n=0;n+2<=this.data.length;n+=2){let r=yc.indexOf(this.data[n])*45;r+=yc.indexOf(this.data[n+1]),t.put(r,11)}this.data.length%2&&t.put(yc.indexOf(this.data[n]),6)};var Ok=Pr;const Nk=On;function Rr(e){this.mode=Nk.BYTE,typeof e=="string"?this.data=new TextEncoder().encode(e):this.data=new Uint8Array(e)}Rr.getBitsLength=function(t){return t*8},Rr.prototype.getLength=function(){return this.data.length},Rr.prototype.getBitsLength=function(){return Rr.getBitsLength(this.data.length)},Rr.prototype.write=function(e){for(let t=0,n=this.data.length;t<n;t++)e.put(this.data[t],8)};var Mk=Rr;const Ak=On,Lk=Et;function Or(e){this.mode=Ak.KANJI,this.data=e}Or.getBitsLength=function(t){return t*13},Or.prototype.getLength=function(){return this.data.length},Or.prototype.getBitsLength=function(){return Or.getBitsLength(this.data.length)},Or.prototype.write=function(e){let t;for(t=0;t<this.data.length;t++){let n=Lk.toSJIS(this.data[t]);if(n>=33088&&n<=40956)n-=33088;else if(n>=57408&&n<=60351)n-=49472;else throw new Error("Invalid SJIS character: "+this.data[t]+`
80
+ Make sure your charset is UTF-8`);n=(n>>>8&255)*192+(n&255),e.put(n,13)}};var jk=Or,om={exports:{}};(function(e){var t={single_source_shortest_paths:function(n,r,o){var s={},i={};i[r]=0;var a=t.PriorityQueue.make();a.push(r,0);for(var l,c,u,h,_,f,g,v,m;!a.empty();){l=a.pop(),c=l.value,h=l.cost,_=n[c]||{};for(u in _)_.hasOwnProperty(u)&&(f=_[u],g=h+f,v=i[u],m=typeof i[u]>"u",(m||v>g)&&(i[u]=g,a.push(u,g),s[u]=c))}if(typeof o<"u"&&typeof i[o]>"u"){var d=["Could not find a path from ",r," to ",o,"."].join("");throw new Error(d)}return s},extract_shortest_path_from_predecessor_list:function(n,r){for(var o=[],s=r;s;)o.push(s),n[s],s=n[s];return o.reverse(),o},find_path:function(n,r,o){var s=t.single_source_shortest_paths(n,r,o);return t.extract_shortest_path_from_predecessor_list(s,o)},PriorityQueue:{make:function(n){var r=t.PriorityQueue,o={},s;n=n||{};for(s in r)r.hasOwnProperty(s)&&(o[s]=r[s]);return o.queue=[],o.sorter=n.sorter||r.default_sorter,o},default_sorter:function(n,r){return n.cost-r.cost},push:function(n,r){var o={value:n,cost:r};this.queue.push(o),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};e.exports=t})(om);var zk=om.exports;(function(e){const t=On,n=Pk,r=Ok,o=Mk,s=jk,i=ln,a=Et,l=zk;function c(d){return unescape(encodeURIComponent(d)).length}function u(d,w,y){const b=[];let k;for(;(k=d.exec(y))!==null;)b.push({data:k[0],index:k.index,mode:w,length:k[0].length});return b}function h(d){const w=u(i.NUMERIC,t.NUMERIC,d),y=u(i.ALPHANUMERIC,t.ALPHANUMERIC,d);let b,k;return a.isKanjiModeEnabled()?(b=u(i.BYTE,t.BYTE,d),k=u(i.KANJI,t.KANJI,d)):(b=u(i.BYTE_KANJI,t.BYTE,d),k=[]),w.concat(y,b,k).sort(function(T,D){return T.index-D.index}).map(function(T){return{data:T.data,mode:T.mode,length:T.length}})}function _(d,w){switch(w){case t.NUMERIC:return n.getBitsLength(d);case t.ALPHANUMERIC:return r.getBitsLength(d);case t.KANJI:return s.getBitsLength(d);case t.BYTE:return o.getBitsLength(d)}}function f(d){return d.reduce(function(w,y){const b=w.length-1>=0?w[w.length-1]:null;return b&&b.mode===y.mode?(w[w.length-1].data+=y.data,w):(w.push(y),w)},[])}function g(d){const w=[];for(let y=0;y<d.length;y++){const b=d[y];switch(b.mode){case t.NUMERIC:w.push([b,{data:b.data,mode:t.ALPHANUMERIC,length:b.length},{data:b.data,mode:t.BYTE,length:b.length}]);break;case t.ALPHANUMERIC:w.push([b,{data:b.data,mode:t.BYTE,length:b.length}]);break;case t.KANJI:w.push([b,{data:b.data,mode:t.BYTE,length:c(b.data)}]);break;case t.BYTE:w.push([{data:b.data,mode:t.BYTE,length:c(b.data)}])}}return w}function v(d,w){const y={},b={start:{}};let k=["start"];for(let x=0;x<d.length;x++){const T=d[x],D=[];for(let U=0;U<T.length;U++){const H=T[U],q=""+x+U;D.push(q),y[q]={node:H,lastCount:0},b[q]={};for(let F=0;F<k.length;F++){const B=k[F];y[B]&&y[B].node.mode===H.mode?(b[B][q]=_(y[B].lastCount+H.length,H.mode)-_(y[B].lastCount,H.mode),y[B].lastCount+=H.length):(y[B]&&(y[B].lastCount=H.length),b[B][q]=_(H.length,H.mode)+4+t.getCharCountIndicator(H.mode,w))}}k=D}for(let x=0;x<k.length;x++)b[k[x]].end=0;return{map:b,table:y}}function m(d,w){let y;const b=t.getBestModeForData(d);if(y=t.from(w,b),y!==t.BYTE&&y.bit<b.bit)throw new Error('"'+d+'" cannot be encoded with mode '+t.toString(y)+`.
81
+ Suggested mode is: `+t.toString(b));switch(y===t.KANJI&&!a.isKanjiModeEnabled()&&(y=t.BYTE),y){case t.NUMERIC:return new n(d);case t.ALPHANUMERIC:return new r(d);case t.KANJI:return new s(d);case t.BYTE:return new o(d)}}e.fromArray=function(w){return w.reduce(function(y,b){return typeof b=="string"?y.push(m(b,null)):b.data&&y.push(m(b.data,b.mode)),y},[])},e.fromString=function(w,y){const b=h(w,a.isKanjiModeEnabled()),k=g(b),x=v(k,y),T=l.find_path(x.map,"start","end"),D=[];for(let U=1;U<T.length-1;U++)D.push(x.table[T[U]].node);return e.fromArray(f(D))},e.rawSplit=function(w){return e.fromArray(h(w,a.isKanjiModeEnabled()))}})(rm);const pi=Et,wc=ii,Dk=yk,Uk=wk,qk=H2,Zk=J2,bc=W2,$c=ai,Fk=$k,fi=Q2,Vk=em,Bk=On,Sc=rm;function Hk(e,t){const n=e.size,r=Zk.getPositions(t);for(let o=0;o<r.length;o++){const s=r[o][0],i=r[o][1];for(let a=-1;a<=7;a++)if(!(s+a<=-1||n<=s+a))for(let l=-1;l<=7;l++)i+l<=-1||n<=i+l||(a>=0&&a<=6&&(l===0||l===6)||l>=0&&l<=6&&(a===0||a===6)||a>=2&&a<=4&&l>=2&&l<=4?e.set(s+a,i+l,!0,!0):e.set(s+a,i+l,!1,!0))}}function Jk(e){const t=e.size;for(let n=8;n<t-8;n++){const r=n%2===0;e.set(n,6,r,!0),e.set(6,n,r,!0)}}function Gk(e,t){const n=qk.getPositions(t);for(let r=0;r<n.length;r++){const o=n[r][0],s=n[r][1];for(let i=-2;i<=2;i++)for(let a=-2;a<=2;a++)i===-2||i===2||a===-2||a===2||i===0&&a===0?e.set(o+i,s+a,!0,!0):e.set(o+i,s+a,!1,!0)}}function Wk(e,t){const n=e.size,r=fi.getEncodedBits(t);let o,s,i;for(let a=0;a<18;a++)o=Math.floor(a/3),s=a%3+n-8-3,i=(r>>a&1)===1,e.set(o,s,i,!0),e.set(s,o,i,!0)}function Cc(e,t,n){const r=e.size,o=Vk.getEncodedBits(t,n);let s,i;for(s=0;s<15;s++)i=(o>>s&1)===1,s<6?e.set(s,8,i,!0):s<8?e.set(s+1,8,i,!0):e.set(r-15+s,8,i,!0),s<8?e.set(8,r-s-1,i,!0):s<9?e.set(8,15-s-1+1,i,!0):e.set(8,15-s-1,i,!0);e.set(r-8,8,1,!0)}function Kk(e,t){const n=e.size;let r=-1,o=n-1,s=7,i=0;for(let a=n-1;a>0;a-=2)for(a===6&&a--;;){for(let l=0;l<2;l++)if(!e.isReserved(o,a-l)){let c=!1;i<t.length&&(c=(t[i]>>>s&1)===1),e.set(o,a-l,c),s--,s===-1&&(i++,s=7)}if(o+=r,o<0||n<=o){o-=r,r=-r;break}}}function Yk(e,t,n){const r=new Dk;n.forEach(function(l){r.put(l.mode.bit,4),r.put(l.getLength(),Bk.getCharCountIndicator(l.mode,e)),l.write(r)});const o=pi.getSymbolTotalCodewords(e),s=$c.getTotalCodewordsCount(e,t),i=(o-s)*8;for(r.getLengthInBits()+4<=i&&r.put(0,4);r.getLengthInBits()%8!==0;)r.putBit(0);const a=(i-r.getLengthInBits())/8;for(let l=0;l<a;l++)r.put(l%2?17:236,8);return Qk(r,e,t)}function Qk(e,t,n){const r=pi.getSymbolTotalCodewords(t),o=$c.getTotalCodewordsCount(t,n),s=r-o,i=$c.getBlocksCount(t,n),a=r%i,l=i-a,c=Math.floor(r/i),u=Math.floor(s/i),h=u+1,_=c-u,f=new Fk(_);let g=0;const v=new Array(i),m=new Array(i);let d=0;const w=new Uint8Array(e.buffer);for(let T=0;T<i;T++){const D=T<l?u:h;v[T]=w.slice(g,g+D),m[T]=f.encode(v[T]),g+=D,d=Math.max(d,D)}const y=new Uint8Array(r);let b=0,k,x;for(k=0;k<d;k++)for(x=0;x<i;x++)k<v[x].length&&(y[b++]=v[x][k]);for(k=0;k<_;k++)for(x=0;x<i;x++)y[b++]=m[x][k];return y}function Xk(e,t,n,r){let o;if(Array.isArray(e))o=Sc.fromArray(e);else if(typeof e=="string"){let c=t;if(!c){const u=Sc.rawSplit(e);c=fi.getBestVersionForData(u,n)}o=Sc.fromString(e,c||40)}else throw new Error("Invalid data");const s=fi.getBestVersionForData(o,n);if(!s)throw new Error("The amount of data is too big to be stored in a QR Code");if(!t)t=s;else if(t<s)throw new Error(`
71
82
  The chosen QR Code version cannot contain this amount of data.
72
83
  Minimum version required to store current data is: `+s+`.
73
- `);const o=LC(e,r,n),i=vo.getSymbolSize(e),l=new PC(i);return NC(l,e),MC(l),DC(l,e),Zl(l,r,0),e>=7&&jC(l,e),zC(l,o),isNaN(a)&&(a=Ul.getBestMask(l,Zl.bind(null,l,r))),Ul.applyMask(a,l),Zl(l,r,a),{modules:l,version:e,errorCorrectionLevel:r,maskPattern:a,segments:n}}cm.create=function(e,r){if(typeof e>"u"||e==="")throw new Error("No input text");let a=Ll.M,n,s;return typeof r<"u"&&(a=Ll.from(r.errorCorrectionLevel,Ll.M),n=go.from(r.version),s=Ul.from(r.maskPattern),r.toSJISFunc&&vo.setToSJISFunction(r.toSJISFunc)),FC(e,n,a,s)};var Im={},Vl={};(function(t){function e(r){if(typeof r=="number"&&(r=r.toString()),typeof r!="string")throw new Error("Color should be defined as hex string");let a=r.slice().replace("#","").split("");if(a.length<3||a.length===5||a.length>8)throw new Error("Invalid hex color: "+r);(a.length===3||a.length===4)&&(a=Array.prototype.concat.apply([],a.map(function(s){return[s,s]}))),a.length===6&&a.push("F","F");const n=parseInt(a.join(""),16);return{r:n>>24&255,g:n>>16&255,b:n>>8&255,a:n&255,hex:"#"+a.slice(0,6).join("")}}t.getOptions=function(a){a||(a={}),a.color||(a.color={});const n=typeof a.margin>"u"||a.margin===null||a.margin<0?4:a.margin,s=a.width&&a.width>=21?a.width:void 0,o=a.scale||4;return{width:s,scale:s?4:o,margin:n,color:{dark:e(a.color.dark||"#000000ff"),light:e(a.color.light||"#ffffffff")},type:a.type,rendererOpts:a.rendererOpts||{}}},t.getScale=function(a,n){return n.width&&n.width>=a+n.margin*2?n.width/(a+n.margin*2):n.scale},t.getImageWidth=function(a,n){const s=t.getScale(a,n);return Math.floor((a+n.margin*2)*s)},t.qrToImageData=function(a,n,s){const o=n.modules.size,i=n.modules.data,l=t.getScale(o,s),u=Math.floor((o+s.margin*2)*l),d=s.margin*l,v=[s.color.light,s.color.dark];for(let m=0;m<u;m++)for(let c=0;c<u;c++){let h=(m*u+c)*4,g=s.color.light;if(m>=d&&c>=d&&m<u-d&&c<u-d){const f=Math.floor((m-d)/l),p=Math.floor((c-d)/l);g=v[i[f*o+p]?1:0]}a[h++]=g.r,a[h++]=g.g,a[h++]=g.b,a[h]=g.a}}})(Vl),function(t){const e=Vl;function r(n,s,o){n.clearRect(0,0,s.width,s.height),s.style||(s.style={}),s.height=o,s.width=o,s.style.height=o+"px",s.style.width=o+"px"}function a(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}t.render=function(s,o,i){let l=i,u=o;typeof l>"u"&&(!o||!o.getContext)&&(l=o,o=void 0),o||(u=a()),l=e.getOptions(l);const d=e.getImageWidth(s.modules.size,l),v=u.getContext("2d"),m=v.createImageData(d,d);return e.qrToImageData(m.data,s,l),r(v,u,d),v.putImageData(m,0,0),u},t.renderToDataURL=function(s,o,i){let l=i;typeof l>"u"&&(!o||!o.getContext)&&(l=o,o=void 0),l||(l={});const u=t.render(s,o,l),d=l.type||"image/png",v=l.rendererOpts||{};return u.toDataURL(d,v.quality)}}(Im);var km={};const qC=Vl;function Tm(t,e){const r=t.a/255,a=e+'="'+t.hex+'"';return r<1?a+" "+e+'-opacity="'+r.toFixed(2).slice(1)+'"':a}function Bl(t,e,r){let a=t+e;return typeof r<"u"&&(a+=" "+r),a}function ZC(t,e,r){let a="",n=0,s=!1,o=0;for(let i=0;i<t.length;i++){const l=Math.floor(i%e),u=Math.floor(i/e);!l&&!s&&(s=!0),t[i]?(o++,i>0&&l>0&&t[i-1]||(a+=s?Bl("M",l+r,.5+u+r):Bl("m",n,0),n=0,s=!1),l+1<e&&t[i+1]||(a+=Bl("h",o),o=0)):n++}return a}km.render=function(e,r,a){const n=qC.getOptions(r),s=e.modules.size,o=e.modules.data,i=s+n.margin*2,l=n.color.light.a?"<path "+Tm(n.color.light,"fill")+' d="M0 0h'+i+"v"+i+'H0z"/>':"",u="<path "+Tm(n.color.dark,"stroke")+' d="'+ZC(o,s,n.margin)+'"/>',d='viewBox="0 0 '+i+" "+i+'"',m='<svg xmlns="http://www.w3.org/2000/svg" '+(n.width?'width="'+n.width+'" height="'+n.width+'" ':"")+d+' shape-rendering="crispEdges">'+l+u+`</svg>
74
- `;return typeof a=="function"&&a(null,m),m};const VC=sC,Hl=cm,Pm=Im,BC=km;function Jl(t,e,r,a,n){const s=[].slice.call(arguments,1),o=s.length,i=typeof s[o-1]=="function";if(!i&&!VC())throw new Error("Callback required as last argument");if(i){if(o<2)throw new Error("Too few arguments provided");o===2?(n=r,r=e,e=a=void 0):o===3&&(e.getContext&&typeof n>"u"?(n=a,a=void 0):(n=a,a=r,r=e,e=void 0))}else{if(o<1)throw new Error("Too few arguments provided");return o===1?(r=e,e=a=void 0):o===2&&!e.getContext&&(a=r,r=e,e=void 0),new Promise(function(l,u){try{const d=Hl.create(r,a);l(t(d,e,a))}catch(d){u(d)}})}try{const l=Hl.create(r,a);n(null,t(l,e,a))}catch(l){n(l)}}Un.create=Hl.create,Un.toCanvas=Jl.bind(null,Pm.render),Un.toDataURL=Jl.bind(null,Pm.renderToDataURL),Un.toString=Jl.bind(null,function(t,e,r){return BC.render(t,r)});class Cm{constructor(e,{size:r=200,margin:a=4,color:n="#000",bgColor:s="#fff"}){this.value=e,this.size=r,this.margin=a,this.color=n,this.bgColor=s}get qrCodeOption(){return{width:this.size,margin:this.margin,color:{dark:this.color,light:this.bgColor}}}async toDataURL(){return Un.toDataURL(this.value,this.qrCodeOption)}async toCanvas(e){return Un.toCanvas(e,this.value,this.qrCodeOption)}async toImage(e){e.src=await this.toDataURL()}}const HC="https://agent.opentiny.design/tiny-robot",Rm="https://ai.opentiny.design/next-remoter",Om=t=>[{action:"qr-code",show:!0,text:"弹出二维码",icon:`<svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
75
- <rect x="3" y="3" width="6" height="6" rx="1" stroke="currentColor" stroke-width="2" fill="none"/>
76
- <rect x="15" y="3" width="6" height="6" rx="1" stroke="currentColor" stroke-width="2" fill="none"/>
77
- <rect x="3" y="15" width="6" height="6" rx="1" stroke="currentColor" stroke-width="2" fill="none"/>
78
- <line x1="9" y1="6" x2="9" y2="18" stroke="currentColor" stroke-width="1.5"/>
79
- <line x1="15" y1="6" x2="15" y2="18" stroke="currentColor" stroke-width="1.5"/>
80
- <line x1="6" y1="9" x2="18" y2="9" stroke="currentColor" stroke-width="1.5"/>
81
- <line x1="6" y1="15" x2="18" y2="15" stroke="currentColor" stroke-width="1.5"/>
82
- <circle cx="12" cy="12" r="1" fill="currentColor"/>
83
- </svg>`},{action:"ai-chat",show:!0,text:"弹出 AI 对话框",icon:`<svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
84
- <path d="M20 2H4C2.9 2 2 2.9 2 4V22L6 18H20C21.1 18 22 17.1 22 16V4C22 2.9 21.1 2 20 2ZM20 16H6L4 18V4H20V16Z" fill="currentColor"/>
85
- <path d="M7 9H17V11H7V9Z" fill="currentColor"/>
86
- <path d="M7 12H14V14H7V12Z" fill="currentColor"/>
87
- </svg>`},{action:"remote-control",show:!0,text:`识别码:${t.sessionId.slice(-6)}`,showCopyIcon:!0,icon:`<svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
88
- <rect x="3" y="3" width="18" height="18" rx="2" stroke="currentColor" stroke-width="2" fill="none"/>
89
- <rect x="6" y="6" width="3" height="2" rx="0.5" fill="currentColor"/>
90
- <rect x="10" y="6" width="3" height="2" rx="0.5" fill="currentColor"/>
91
- <rect x="14" y="6" width="3" height="2" rx="0.5" fill="currentColor"/>
92
- <rect x="6" y="9" width="3" height="2" rx="0.5" fill="currentColor"/>
93
- <rect x="10" y="9" width="3" height="2" rx="0.5" fill="currentColor"/>
94
- <rect x="14" y="9" width="3" height="2" rx="0.5" fill="currentColor"/>
95
- <rect x="6" y="12" width="3" height="2" rx="0.5" fill="currentColor"/>
96
- <rect x="10" y="12" width="3" height="2" rx="0.5" fill="currentColor"/>
97
- <rect x="14" y="12" width="3" height="2" rx="0.5" fill="currentColor"/>
98
- </svg>`},{action:"remote-url",show:!0,text:`${t.remoteUrl}`,tip:t.remoteUrl,showCopyIcon:!0,icon:`<svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
99
- <path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" fill="none"/>
100
- <path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" fill="none"/>
101
- </svg>`}];class JC{constructor(e){if(this.isExpanded=!1,!e.sessionId)throw new Error("sessionId is required");this.options={...e,qrCodeUrl:e.qrCodeUrl||Rm,remoteUrl:e.remoteUrl||HC},this.menuItems=this.mergeMenuItems(e.menuItems),this.init()}get sessionPrefix(){var e;return(e=this.options.qrCodeUrl)!=null&&e.includes("?")?"&sessionId=":"?sessionId="}mergeMenuItems(e){return e?Om(this.options).map(r=>{const a=e.find(n=>n.action===r.action);return a?{...r,...a,show:a.show!==void 0?a.show:r.show}:r}):Om(this.options)}init(){this.createFloatingBlock(),this.createDropdownMenu(),this.bindEvents(),this.addStyles()}createFloatingBlock(){this.floatingBlock=document.createElement("div"),this.floatingBlock.className="tiny-remoter-floating-block",this.floatingBlock.innerHTML=`
84
+ `);const i=Yk(t,n,o),a=pi.getSymbolSize(t),l=new Uk(a);return Hk(l,t),Jk(l),Gk(l,t),Cc(l,n,0),t>=7&&Wk(l,t),Kk(l,i),isNaN(r)&&(r=bc.getBestMask(l,Cc.bind(null,l,n))),bc.applyMask(r,l),Cc(l,n,r),{modules:l,version:t,errorCorrectionLevel:n,maskPattern:r,segments:o}}V2.create=function(t,n){if(typeof t>"u"||t==="")throw new Error("No input text");let r=wc.M,o,s;return typeof n<"u"&&(r=wc.from(n.errorCorrectionLevel,wc.M),o=fi.from(n.version),s=bc.from(n.maskPattern),n.toSJISFunc&&pi.setToSJISFunction(n.toSJISFunc)),Xk(t,o,r,s)};var sm={},Ec={};(function(e){function t(n){if(typeof n=="number"&&(n=n.toString()),typeof n!="string")throw new Error("Color should be defined as hex string");let r=n.slice().replace("#","").split("");if(r.length<3||r.length===5||r.length>8)throw new Error("Invalid hex color: "+n);(r.length===3||r.length===4)&&(r=Array.prototype.concat.apply([],r.map(function(s){return[s,s]}))),r.length===6&&r.push("F","F");const o=parseInt(r.join(""),16);return{r:o>>24&255,g:o>>16&255,b:o>>8&255,a:o&255,hex:"#"+r.slice(0,6).join("")}}e.getOptions=function(r){r||(r={}),r.color||(r.color={});const o=typeof r.margin>"u"||r.margin===null||r.margin<0?4:r.margin,s=r.width&&r.width>=21?r.width:void 0,i=r.scale||4;return{width:s,scale:s?4:i,margin:o,color:{dark:t(r.color.dark||"#000000ff"),light:t(r.color.light||"#ffffffff")},type:r.type,rendererOpts:r.rendererOpts||{}}},e.getScale=function(r,o){return o.width&&o.width>=r+o.margin*2?o.width/(r+o.margin*2):o.scale},e.getImageWidth=function(r,o){const s=e.getScale(r,o);return Math.floor((r+o.margin*2)*s)},e.qrToImageData=function(r,o,s){const i=o.modules.size,a=o.modules.data,l=e.getScale(i,s),c=Math.floor((i+s.margin*2)*l),u=s.margin*l,h=[s.color.light,s.color.dark];for(let _=0;_<c;_++)for(let f=0;f<c;f++){let g=(_*c+f)*4,v=s.color.light;if(_>=u&&f>=u&&_<c-u&&f<c-u){const m=Math.floor((_-u)/l),d=Math.floor((f-u)/l);v=h[a[m*i+d]?1:0]}r[g++]=v.r,r[g++]=v.g,r[g++]=v.b,r[g]=v.a}}})(Ec),function(e){const t=Ec;function n(o,s,i){o.clearRect(0,0,s.width,s.height),s.style||(s.style={}),s.height=i,s.width=i,s.style.height=i+"px",s.style.width=i+"px"}function r(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}e.render=function(s,i,a){let l=a,c=i;typeof l>"u"&&(!i||!i.getContext)&&(l=i,i=void 0),i||(c=r()),l=t.getOptions(l);const u=t.getImageWidth(s.modules.size,l),h=c.getContext("2d"),_=h.createImageData(u,u);return t.qrToImageData(_.data,s,l),n(h,c,u),h.putImageData(_,0,0),c},e.renderToDataURL=function(s,i,a){let l=a;typeof l>"u"&&(!i||!i.getContext)&&(l=i,i=void 0),l||(l={});const c=e.render(s,i,l),u=l.type||"image/png",h=l.rendererOpts||{};return c.toDataURL(u,h.quality)}}(sm);var im={};const eI=Ec;function am(e,t){const n=e.a/255,r=t+'="'+e.hex+'"';return n<1?r+" "+t+'-opacity="'+n.toFixed(2).slice(1)+'"':r}function kc(e,t,n){let r=e+t;return typeof n<"u"&&(r+=" "+n),r}function tI(e,t,n){let r="",o=0,s=!1,i=0;for(let a=0;a<e.length;a++){const l=Math.floor(a%t),c=Math.floor(a/t);!l&&!s&&(s=!0),e[a]?(i++,a>0&&l>0&&e[a-1]||(r+=s?kc("M",l+n,.5+c+n):kc("m",o,0),o=0,s=!1),l+1<t&&e[a+1]||(r+=kc("h",i),i=0)):o++}return r}im.render=function(t,n,r){const o=eI.getOptions(n),s=t.modules.size,i=t.modules.data,a=s+o.margin*2,l=o.color.light.a?"<path "+am(o.color.light,"fill")+' d="M0 0h'+a+"v"+a+'H0z"/>':"",c="<path "+am(o.color.dark,"stroke")+' d="'+tI(i,s,o.margin)+'"/>',u='viewBox="0 0 '+a+" "+a+'"',_='<svg xmlns="http://www.w3.org/2000/svg" '+(o.width?'width="'+o.width+'" height="'+o.width+'" ':"")+u+' shape-rendering="crispEdges">'+l+c+`</svg>
85
+ `;return typeof r=="function"&&r(null,_),_};const nI=vk,Ic=V2,lm=sm,rI=im;function Tc(e,t,n,r,o){const s=[].slice.call(arguments,1),i=s.length,a=typeof s[i-1]=="function";if(!a&&!nI())throw new Error("Callback required as last argument");if(a){if(i<2)throw new Error("Too few arguments provided");i===2?(o=n,n=t,t=r=void 0):i===3&&(t.getContext&&typeof o>"u"?(o=r,r=void 0):(o=r,r=n,n=t,t=void 0))}else{if(i<1)throw new Error("Too few arguments provided");return i===1?(n=t,t=r=void 0):i===2&&!t.getContext&&(r=n,n=t,t=void 0),new Promise(function(l,c){try{const u=Ic.create(n,r);l(e(u,t,r))}catch(u){c(u)}})}try{const l=Ic.create(n,r);o(null,e(l,t,r))}catch(l){o(l)}}Tr.create=Ic.create,Tr.toCanvas=Tc.bind(null,lm.render),Tr.toDataURL=Tc.bind(null,lm.renderToDataURL),Tr.toString=Tc.bind(null,function(e,t,n){return rI.render(e,n)});class cm{constructor(t,{size:n=200,margin:r=4,color:o="#000",bgColor:s="#fff"}){this.value=t,this.size=n,this.margin=r,this.color=o,this.bgColor=s}get qrCodeOption(){return{width:this.size,margin:this.margin,color:{dark:this.color,light:this.bgColor}}}async toDataURL(){return Tr.toDataURL(this.value,this.qrCodeOption)}async toCanvas(t){return Tr.toCanvas(t,this.value,this.qrCodeOption)}async toImage(t){t.src=await this.toDataURL()}}const oI={content:"",placement:"top",trigger:"hover",delay:150,hideDelay:150,container:document.body,className:"tiny-remoter-native-tooltip"};class sI{constructor(t,n={}){if(this.tip=null,this.showTimer=0,this.hideTimer=0,this.clickOutside=null,this.el=typeof t=="string"?document.querySelector(t):t,!this.el)throw new Error("Tooltip: invalid element");this.opts={...oI,...n},this.bindEvents()}open(){this.isShown()||(this.clearTimer(),this.showTimer=window.setTimeout(()=>{this.render(),this.opts.container.appendChild(this.tip),this.reposition(),this.attachExtraEvents()},this.opts.delay))}close(){this.clearTimer(),this.hideTimer=window.setTimeout(()=>{var t;(t=this.tip)==null||t.remove(),this.detachExtraEvents()},this.opts.hideDelay)}toggle(){this.isShown()?this.close():this.open()}destroy(){this.close();const t=this.opts.trigger;this.el.removeEventListener("mouseenter",this.open),this.el.removeEventListener("mouseleave",this.close),this.el.removeEventListener("focus",this.open),this.el.removeEventListener("blur",this.close),t==="click"&&this.el.removeEventListener("click",this.toggle)}bindEvents(){const t=this.opts.trigger;t==="hover"?(this.el.addEventListener("mouseenter",()=>this.open()),this.el.addEventListener("mouseleave",()=>this.close())):t==="focus"?(this.el.addEventListener("focus",()=>this.open()),this.el.addEventListener("blur",()=>this.close())):t==="click"&&this.el.addEventListener("click",()=>this.toggle())}render(){if(this.tip)return;const t=typeof this.opts.content=="function"?this.opts.content():this.opts.content;this.tip=document.createElement("div"),this.tip.className=`${this.opts.className} ${this.opts.className}--${this.opts.placement}`,this.tip.innerHTML=`
86
+ <div class="${this.opts.className}__arrow"></div>
87
+ <div class="${this.opts.className}__inner">${t}</div>
88
+ `}reposition(){const t=this.placementList(this.opts.placement);for(const n of t){const r=this.calcStyle(n);if(this.checkViewport(r)){this.applyStyle(r),this.tip.className=`${this.opts.className} ${this.opts.className}--${n}`;return}}this.applyStyle(this.calcStyle("top"))}calcStyle(t){const n=this.el.getBoundingClientRect(),r=this.tip.getBoundingClientRect(),o=window.pageYOffset||document.documentElement.scrollTop,s=window.pageXOffset||document.documentElement.scrollLeft,i=6,[a,l="center"]=t.split("-");let c=0,u=0;return a==="top"?c=n.top+o-r.height-i:a==="bottom"?c=n.bottom+o+i:a==="left"?u=n.left+s-r.width-i:a==="right"&&(u=n.right+s+i),(a==="top"||a==="bottom")&&(l==="start"?u=n.left+s:l==="end"?u=n.right+s-r.width:u=(n.left+n.right)/2+s-r.width/2),(a==="left"||a==="right")&&(l==="start"?c=n.top+o:l==="end"?c=n.bottom+o-r.height:c=(n.top+n.bottom)/2+o-r.height/2),{top:Math.round(c),left:Math.round(u)}}applyStyle({top:t,left:n}){Object.assign(this.tip.style,{position:"absolute",top:`${t}px`,left:`${n}px`})}checkViewport({top:t,left:n}){const o=window.innerWidth,s=window.innerHeight,i=this.tip.getBoundingClientRect();return n>=5&&t>=5&&n+i.width<=o-5&&t+i.height<=s-5}placementList(t){const n={top:["top","bottom","top-start","bottom-start","top-end","bottom-end"],bottom:["bottom","top","bottom-start","top-start","bottom-end","top-end"],left:["left","right","left-start","right-start","left-end","right-end"],right:["right","left","right-start","left-start","right-end","left-end"]};return n[t.split("-")[0]]||n.top}attachExtraEvents(){this.opts.trigger==="click"?(this.clickOutside=t=>{const n=t.composedPath();!n.includes(this.el)&&!n.includes(this.tip)&&this.close()},document.addEventListener("mousedown",this.clickOutside)):this.opts.trigger==="hover"&&(this.tip.addEventListener("mouseenter",()=>this.clearTimer()),this.tip.addEventListener("mouseleave",()=>this.close()))}detachExtraEvents(){this.clickOutside&&(document.removeEventListener("mousedown",this.clickOutside),this.clickOutside=null)}clearTimer(){clearTimeout(this.showTimer),clearTimeout(this.hideTimer)}isShown(){var t;return!!((t=this.tip)!=null&&t.parentNode)}}const um="tiny-remoter-native-tooltip-style";(()=>{if(document.getElementById(um))return;const e=document.createElement("style");e.id=um,e.textContent=`
89
+ .tiny-remoter-native-tooltip {
90
+ position: absolute;
91
+ z-index: 9999;
92
+ max-width: 200px;
93
+ padding: 6px 10px;
94
+ font-size: 12px;
95
+ line-height: 1.4;
96
+ color: #fff;
97
+ background: #191919;
98
+ border-radius: 4px;
99
+ pointer-events: none;
100
+ box-shadow: 0px 4px 8px 0px rgba(0, 0, 0, 0.2);
101
+ }
102
+ .tiny-remoter-native-tooltip__arrow {
103
+ position: absolute;
104
+ width: 0; height: 0;
105
+ border: 6px solid transparent;
106
+ }
107
+ .tiny-remoter-native-tooltip--top
108
+ .tiny-remoter-native-tooltip__arrow {
109
+ bottom: -12px;
110
+ left: 50%; transform:
111
+ translateX(-50%);
112
+ border-top-color: rgba(0,0,0,.75);
113
+ }
114
+ .tiny-remoter-native-tooltip--bottom
115
+ .tiny-remoter-native-tooltip__arrow {
116
+ top: -12px;
117
+ left: 50%; transform:
118
+ translateX(-50%);
119
+ border-bottom-color: rgba(0,0,0,.75);
120
+ }
121
+ .tiny-remoter-native-tooltip--left
122
+ .tiny-remoter-native-tooltip__arrow {
123
+ right: -12px;
124
+ top: 50%;
125
+ transform: translateY(-50%);
126
+ border-left-color: rgba(0,0,0,.75);
127
+ }
128
+ .tiny-remoter-native-tooltip--right
129
+ .tiny-remoter-native-tooltip__arrow {
130
+ left: -12px;
131
+ top: 50%;
132
+ transform: translateY(-50%);
133
+ border-right-color: rgba(0,0,0,.75);
134
+ }
135
+ `,document.head.appendChild(e)})();const iI="data:image/svg+xml,%3csvg%20viewBox='0%200%2040%2039.9692'%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%20width='40.000000'%20height='39.969238'%20fill='none'%20customFrame='url(%23clipPath_3)'%3e%3cdefs%3e%3cclipPath%20id='clipPath_3'%3e%3crect%20width='40.000000'%20height='39.969238'%20x='0.000000'%20y='0.000000'%20rx='12.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_4'%3e%3crect%20width='24.000000'%20height='24.000000'%20x='8.000000'%20y='7.984619'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_5'%3e%3crect%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='9.984619'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_6'%3e%3crect%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='9.984619'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_7'%3e%3crect%20width='21.666666'%20height='13.333333'%20x='20.000000'%20y='9.984619'%20rx='6.666667'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_8'%3e%3crect%20width='6.666667'%20height='6.666667'%20x='23.333496'%20y='9.984619'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3c/defs%3e%3crect%20id='2'%20width='40.000000'%20height='39.969238'%20x='0.000000'%20y='0.000000'%20rx='12.000000'%20fill='rgb(239,246,255)'%20/%3e%3cg%20id='物业'%20clip-path='url(%23clipPath_4)'%20customFrame='url(%23clipPath_4)'%3e%3crect%20id='物业'%20width='24.000000'%20height='24.000000'%20x='8.000000'%20y='7.984619'%20/%3e%3cg%20id='物业服务'%3e%3cg%20id='00公共/红点/图标+红点'%20customFrame='url(%23clipPath_5)'%3e%3crect%20id='00公共/红点/图标+红点'%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='9.984619'%20/%3e%3cg%20id='common_chats_line'%20customFrame='url(%23clipPath_6)'%3e%3crect%20id='common_chats_line'%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='9.984619'%20/%3e%3cpath%20id='形状'%20d='M28.3332%2019.9847C28.3332%2015.3823%2024.6022%2011.6514%2019.9998%2011.6514C15.3975%2011.6514%2011.6665%2015.3823%2011.6665%2019.9847C11.6665%2024.5871%2015.3975%2028.318%2019.9998%2028.318C21.0018%2028.318%2021.9624%2028.1412%2022.8522%2027.8171L26.581%2028.1578C26.7205%2028.1706%2026.8611%2028.1598%2026.9971%2028.1259C27.6669%2027.959%2028.0746%2027.2806%2027.9077%2026.6108L27.2716%2024.0578C27.9477%2022.8535%2028.3332%2021.4641%2028.3332%2019.9847ZM19.9998%2013.1514C16.2259%2013.1514%2013.1665%2016.2108%2013.1665%2019.9847C13.1665%2023.7586%2016.2259%2026.818%2019.9998%2026.818C20.8089%2026.818%2021.5967%2026.678%2022.3388%2026.4077C22.505%2026.3471%2022.6803%2026.3166%2022.8565%2026.3171L22.9887%2026.3233L26.3665%2026.6322L25.8161%2024.4205C25.7352%2024.0958%2025.7655%2023.7548%2025.8997%2023.4512L25.9636%2023.3236C26.5311%2022.3126%2026.8332%2021.1723%2026.8332%2019.9847C26.8332%2016.2108%2023.7738%2013.1514%2019.9998%2013.1514ZM23.1152%2021.2468C23.352%2020.9069%2023.2684%2020.4394%2022.9286%2020.2026C22.5887%2019.9659%2022.1212%2020.0494%2021.8845%2020.3893C21.2894%2021.2433%2020.4268%2021.7347%2019.5102%2021.7347C18.9513%2021.7347%2018.4132%2021.554%2017.9375%2021.2122C17.6011%2020.9705%2017.1325%2021.0472%2016.8908%2021.3836C16.6491%2021.7199%2016.7258%2022.1886%2017.0622%2022.4303C17.7879%2022.9518%2018.6305%2023.2347%2019.5102%2023.2347C20.9394%2023.2347%2022.2505%2022.4878%2023.1152%2021.2468Z'%20fill='rgb(65,142,255)'%20fill-rule='evenodd'%20/%3e%3c/g%3e%3cg%20id='00公共/3位数红点'%20opacity='0'%20customFrame='url(%23clipPath_7)'%3e%3crect%20id='00公共/3位数红点'%20width='21.666666'%20height='13.333333'%20x='20.000000'%20y='9.984619'%20rx='6.666667'%20opacity='0'%20fill='rgb(243,111,100)'%20/%3e%3cpath%20id='文本'%20d='M26.0421%2013.4421C26.4259%2013.4421%2026.7677%2013.5255%2027.0675%2013.6923C27.3672%2013.8591%2027.6005%2014.0931%2027.7673%2014.3942C27.9342%2014.694%2028.0176%2015.0351%2028.0176%2015.4176C28.0176%2015.7173%2027.9633%2015.994%2027.8548%2016.2476C27.7463%2016.4999%2027.5673%2016.8315%2027.3177%2017.2425L25.859%2019.6432L25.0167%2019.6432L26.276%2017.5924C26.3534%2017.4704%2026.4307%2017.3564%2026.508%2017.2507C26.3357%2017.3063%2026.1445%2017.3341%2025.9342%2017.3341C25.5721%2017.3341%2025.2493%2017.2479%2024.9658%2017.0757C24.6837%2016.9034%2024.4633%2016.6701%2024.3046%2016.3758C24.1459%2016.0815%2024.0666%2015.7566%2024.0666%2015.4013C24.0666%2015.0351%2024.1513%2014.7021%2024.3209%2014.4023C24.4904%2014.1012%2024.7264%2013.8659%2025.0289%2013.6964C25.3314%2013.5268%2025.6691%2013.4421%2026.0421%2013.4421ZM26.0421%2016.6505C26.4029%2016.6505%2026.6904%2016.5325%2026.9047%2016.2965C27.119%2016.0605%2027.2262%2015.7539%2027.2262%2015.3769C27.2262%2014.9985%2027.119%2014.694%2026.9047%2014.4634C26.6904%2014.2328%2026.4029%2014.1175%2026.0421%2014.1175C25.6867%2014.1175%2025.4019%2014.2342%2025.1876%2014.4674C24.9733%2014.7007%2024.8661%2015.0039%2024.8661%2015.3769C24.8661%2015.7539%2024.9719%2016.0605%2025.1835%2016.2965C25.3951%2016.5325%2025.6813%2016.6505%2026.0421%2016.6505ZM30.7921%2013.4421C31.1759%2013.4421%2031.5177%2013.5255%2031.8175%2013.6923C32.1172%2013.8591%2032.3505%2014.0931%2032.5173%2014.3942C32.6842%2014.694%2032.7676%2015.0351%2032.7676%2015.4176C32.7676%2015.7173%2032.7133%2015.994%2032.6048%2016.2476C32.4963%2016.4999%2032.3173%2016.8315%2032.0677%2017.2425L30.609%2019.6432L29.7667%2019.6432L31.026%2017.5924C31.1034%2017.4704%2031.1807%2017.3564%2031.258%2017.2507C31.0857%2017.3063%2030.8945%2017.3341%2030.6842%2017.3341C30.3221%2017.3341%2029.9993%2017.2479%2029.7158%2017.0757C29.4337%2016.9034%2029.2133%2016.6701%2029.0546%2016.3758C28.8959%2016.0815%2028.8166%2015.7566%2028.8166%2015.4013C28.8166%2015.0351%2028.9013%2014.7021%2029.0709%2014.4023C29.2404%2014.1012%2029.4764%2013.8659%2029.7789%2013.6964C30.0814%2013.5268%2030.4191%2013.4421%2030.7921%2013.4421ZM30.7921%2016.6505C31.1529%2016.6505%2031.4404%2016.5325%2031.6547%2016.2965C31.869%2016.0605%2031.9762%2015.7539%2031.9762%2015.3769C31.9762%2014.9985%2031.869%2014.694%2031.6547%2014.4634C31.4404%2014.2328%2031.1529%2014.1175%2030.7921%2014.1175C30.4367%2014.1175%2030.1519%2014.2342%2029.9376%2014.4674C29.7233%2014.7007%2029.6161%2015.0039%2029.6161%2015.3769C29.6161%2015.7539%2029.7219%2016.0605%2029.9335%2016.2965C30.1451%2016.5325%2030.4313%2016.6505%2030.7921%2016.6505ZM35.2674%2014.6851L35.9001%2014.6851L35.9001%2016.3188L37.5339%2016.3188L37.5339%2016.9516L35.9001%2016.9516L35.9001%2018.5853L35.2674%2018.5853L35.2674%2016.9516L33.6337%2016.9516L33.6337%2016.3188L35.2674%2016.3188L35.2674%2014.6851Z'%20fill='rgb(255,255,255)'%20fill-rule='nonzero'%20/%3e%3c/g%3e%3cg%20id='00公共/单红点'%20opacity='0'%20customFrame='url(%23clipPath_8)'%3e%3crect%20id='00公共/单红点'%20width='6.666667'%20height='6.666667'%20x='23.333496'%20y='9.984619'%20opacity='0'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20/%3e%3ccircle%20id='红点'%20cx='26.6668301'%20cy='13.3179522'%20r='3.33333325'%20fill='rgb(243,111,100)'%20/%3e%3c/g%3e%3c/g%3e%3c/g%3e%3c/g%3e%3c/svg%3e",aI="data:image/svg+xml,%3csvg%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%20width='40.000000'%20height='40.000000'%20fill='none'%20customFrame='url(%23clipPath_12)'%3e%3cdefs%3e%3cclipPath%20id='clipPath_12'%3e%3crect%20width='40.000000'%20height='40.000000'%20x='0.000000'%20y='0.000000'%20rx='12.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_13'%3e%3crect%20width='24.000000'%20height='24.000000'%20x='8.000000'%20y='8.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_14'%3e%3crect%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='10.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3c/defs%3e%3crect%20id='4'%20width='40.000000'%20height='40.000000'%20x='0.000000'%20y='0.000000'%20rx='12.000000'%20fill='rgb(234,255,244)'%20/%3e%3cg%20id='我的信息'%20clip-path='url(%23clipPath_13)'%20customFrame='url(%23clipPath_13)'%3e%3crect%20id='我的信息'%20width='24.000000'%20height='24.000000'%20x='8.000000'%20y='8.000000'%20/%3e%3cg%20id='组合%208'%20customFrame='url(%23clipPath_14)'%3e%3crect%20id='组合%208'%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='10.000000'%20/%3e%3cpath%20id='合并'%20d='M28.4994%2012.3142C28.4994%2012.2578%2028.4937%2012.2018%2028.4825%2012.1465C28.4713%2012.0911%2028.4547%2012.0373%2028.4327%2011.9851C28.4107%2011.933%2028.3836%2011.8835%2028.3516%2011.8365C28.3197%2011.7896%2028.2834%2011.7461%2028.2427%2011.7062C28.202%2011.6663%2028.1579%2011.6307%2028.1101%2011.5993C28.0622%2011.568%2028.0117%2011.5415%2027.9585%2011.5199C27.9054%2011.4983%2027.8506%2011.4819%2027.7942%2011.4709C27.7378%2011.4599%2027.6806%2011.4544%2027.6231%2011.4544L24.1832%2011.5199L24.1832%2010L29.0796%2010C29.1472%2010%2029.2143%2010.0065%2029.2806%2010.0194C29.347%2010.0324%2029.4114%2010.0516%2029.4739%2010.077C29.5364%2010.1024%2029.5961%2010.1336%2029.6523%2010.1705C29.7086%2010.2074%2029.7605%2010.2493%2029.8084%2010.2963C29.8562%2010.3433%2029.8991%2010.3944%2029.9367%2010.4496C29.9743%2010.5048%2030.006%2010.5631%2030.0319%2010.6244C30.0578%2010.6858%2030.0773%2010.7491%2030.0905%2010.8142C30.1037%2010.8794%2030.1104%2010.9451%2030.1104%2011.0115L30.1832%2014.4522L28.4992%2014.5L28.4994%2012.3142ZM11.6995%2012.3143C11.6995%2012.2579%2011.7051%2012.2019%2011.7163%2012.1466C11.7275%2012.0912%2011.7441%2012.0374%2011.7661%2011.9852C11.7882%2011.9331%2011.8152%2011.8836%2011.8472%2011.8366C11.8791%2011.7897%2011.9155%2011.7462%2011.9562%2011.7063C11.9968%2011.6664%2012.0409%2011.6308%2012.0888%2011.5994C12.1366%2011.5681%2012.1871%2011.5416%2012.2403%2011.52C12.2934%2011.4984%2012.3482%2011.482%2012.4046%2011.471C12.4611%2011.46%2012.5182%2011.4545%2012.5758%2011.4545L16.0157%2011.52L16.0157%2010.0001L11.1193%2010.0001C11.0516%2010.0001%2010.9846%2010.0066%2010.9182%2010.0196C10.8518%2010.0325%2010.7874%2010.0517%2010.7249%2010.0771C10.6624%2010.1025%2010.6028%2010.1337%2010.5465%2010.1706C10.4902%2010.2075%2010.4383%2010.2494%2010.3904%2010.2964C10.3426%2010.3434%2010.2997%2010.3945%2010.2621%2010.4497C10.2245%2010.5049%2010.1929%2010.5632%2010.167%2010.6245C10.1411%2010.6859%2010.1215%2010.7492%2010.1083%2010.8143C10.0951%2010.8795%2010.0885%2010.9452%2010.0884%2011.0116L10.0157%2014.4523L11.6997%2014.5L11.6995%2012.3143ZM25.3135%2021.8051L25.3135%2022.8167C25.7656%2022.8929%2026.2209%2022.9249%2026.6792%2022.9127C28.3381%2022.9127%2029.1675%2022.326%2029.1675%2021.1527C29.1733%2020.9869%2029.151%2020.825%2029.1006%2020.667C29.0503%2020.509%2028.9747%2020.3641%2028.8742%2020.2322C28.767%2020.1025%2028.6403%2019.9963%2028.4938%2019.9134C28.3474%2019.8306%2028.191%2019.7767%2028.0246%2019.7517L28.0246%2019.7011C28.0971%2019.6839%2028.1676%2019.6606%2028.236%2019.6311C28.3044%2019.6016%2028.3698%2019.5665%2028.4321%2019.5257C28.4944%2019.4848%2028.5526%2019.4389%2028.6069%2019.3879C28.6613%2019.3369%2028.7109%2019.2816%2028.7556%2019.222C28.8003%2019.1624%2028.8394%2019.0994%2028.8732%2019.033C28.9069%2018.9665%2028.9346%2018.8977%2028.9564%2018.8265C28.9782%2018.7552%2028.9937%2018.6826%2029.0028%2018.6086C29.0119%2018.5347%2029.0145%2018.4605%2029.0107%2018.3861C29.0217%2018.2675%2029.0176%2018.1495%2028.9984%2018.0319C28.9791%2017.9144%2028.9454%2017.8012%2028.8971%2017.6923C28.8489%2017.5834%2028.7875%2017.4823%2028.7134%2017.3891C28.6393%2017.2959%2028.5547%2017.2135%2028.4595%2017.1419C28.219%2017.0003%2027.963%2016.8972%2027.6915%2016.8326C27.4199%2016.7679%2027.1449%2016.7446%2026.8664%2016.7626C26.6258%2016.7621%2026.3864%2016.7791%2026.1482%2016.8132C25.9479%2016.8386%2025.7504%2016.8791%2025.5563%2016.9346L25.5563%2017.8854C25.743%2017.8264%2025.9337%2017.7842%2026.128%2017.759C26.3276%2017.73%2026.5282%2017.7148%2026.7298%2017.7134C27.0252%2017.6949%2027.3049%2017.7523%2027.5692%2017.8854C27.6168%2017.9161%2027.6595%2017.9525%2027.6972%2017.9947C27.7348%2018.037%2027.766%2018.0835%2027.791%2018.1343C27.816%2018.1851%2027.8337%2018.2383%2027.8441%2018.294C27.8545%2018.3496%2027.8573%2018.4056%2027.8525%2018.462C27.8566%2018.5278%2027.8514%2018.5927%2027.8367%2018.657C27.822%2018.7212%2027.7986%2018.7821%2027.7663%2018.8395C27.734%2018.897%2027.694%2018.9487%2027.6468%2018.9946C27.5995%2019.0405%2027.5468%2019.0787%2027.4885%2019.1093C27.1544%2019.2631%2026.8037%2019.3306%2026.4364%2019.3117L25.9862%2019.3117L25.9862%2020.1917L26.4466%2020.1917C26.8409%2020.1669%2027.2202%2020.2309%2027.5845%2020.3839C27.6459%2020.4167%2027.7011%2020.4576%2027.7505%2020.5066C27.7999%2020.5556%2027.8412%2020.6107%2027.8745%2020.6718C27.9077%2020.733%2027.9315%2020.7976%2027.9458%2020.8656C27.9602%2020.9337%2027.9644%2021.0024%2027.9587%2021.0717C27.9648%2021.1402%2027.9612%2021.2083%2027.9478%2021.2757C27.9344%2021.3432%2027.912%2021.4074%2027.8801%2021.4683C27.8483%2021.5293%2027.8086%2021.5846%2027.7609%2021.6341C27.7132%2021.6837%2027.6593%2021.7254%2027.5996%2021.7596C27.2884%2021.9045%2026.9613%2021.9685%2026.6184%2021.9518C26.1786%2021.9465%2025.7436%2021.8977%2025.3135%2021.8051ZM21.3382%2018.6238C21.3445%2018.5593%2021.343%2018.495%2021.3335%2018.4308C21.3241%2018.3667%2021.3069%2018.3046%2021.2822%2018.2447C21.2575%2018.1847%2021.226%2018.1287%2021.1876%2018.0765C21.1492%2018.0242%2021.1049%2017.9774%2021.055%2017.936C20.9359%2017.8608%2020.808%2017.806%2020.6714%2017.7714C20.5349%2017.7368%2020.3964%2017.7242%2020.2558%2017.7337C19.8009%2017.7395%2019.356%2017.8087%2018.9208%2017.9411L18.9208%2016.9598C19.4252%2016.8181%2019.9393%2016.7524%2020.4633%2016.7626C20.7322%2016.7484%2020.9964%2016.7773%2021.256%2016.8491C21.5156%2016.9209%2021.7571%2017.032%2021.9806%2017.1824C22.0729%2017.2601%2022.1548%2017.3474%2022.2263%2017.4446C22.2978%2017.5418%2022.3567%2017.646%2022.4034%2017.7573C22.45%2017.8686%2022.483%2017.9838%2022.5021%2018.1029C22.5213%2018.222%2022.5261%2018.3417%2022.5167%2018.462C22.5245%2018.7882%2022.4655%2019.1017%2022.3396%2019.4027C22.1879%2019.7384%2021.984%2020.0384%2021.7277%2020.3029C21.3021%2020.7337%2020.8502%2021.135%2020.3721%2021.5067L19.9928%2021.8051L19.9928%2021.8759L22.6938%2021.8759L22.6938%2022.8419L18.5464%2022.8419L18.5464%2021.7697C19.2882%2021.1796%2019.8579%2020.6975%2020.2558%2020.3232C20.574%2020.0432%2020.8523%2019.728%2021.0905%2019.3774C21.1675%2019.2665%2021.2269%2019.1469%2021.2691%2019.0187C21.3113%2018.8904%2021.3344%2018.7588%2021.3382%2018.6238ZM12.3102%2017.2127L12.3102%2018.1939L13.7769%2017.9107L13.7769%2022.8419L14.9605%2022.8419L14.9605%2016.8486L14.0957%2016.8486L12.3102%2017.2127ZM28.5524%2028.0475C28.5524%2028.104%2028.5467%2028.1599%2028.5353%2028.2152C28.5239%2028.2706%2028.5071%2028.3244%2028.4849%2028.3766C28.4626%2028.4287%2028.4352%2028.4782%2028.4028%2028.5252C28.3705%2028.5721%2028.3337%2028.6156%2028.2925%2028.6555C28.2513%2028.6954%2028.2067%2028.731%2028.1583%2028.7624C28.1098%2028.7937%2028.0587%2028.8202%2028.0049%2028.8418C27.9511%2028.8634%2027.8957%2028.8798%2027.8385%2028.8908C27.7814%2028.9018%2027.7235%2028.9073%2027.6653%2028.9073L24.1832%2028.8418L24.1832%2030.3617L29.1397%2030.3617C29.2082%2030.3617%2029.276%2030.3552%2029.3432%2030.3423C29.4104%2030.3293%2029.4756%2030.3101%2029.5389%2030.2847C29.6022%2030.2593%2029.6625%2030.2281%2029.7195%2030.1912C29.7765%2030.1543%2029.829%2030.1124%2029.8774%2030.0654C29.9259%2030.0184%2029.9693%2029.9673%2030.0074%2029.9121C30.0454%2029.8569%2030.0774%2029.7986%2030.1037%2029.7373C30.1299%2029.6759%2030.1497%2029.6126%2030.163%2029.5475C30.1764%2029.4823%2030.1831%2029.4166%2030.1832%2029.3502L30.1832%2026.0478L28.4785%2026L28.5524%2028.0475ZM11.6308%2028.0099C11.6308%2028.0664%2011.6365%2028.1223%2011.6479%2028.1777C11.6592%2028.233%2011.676%2028.2868%2011.6983%2028.339C11.7206%2028.3911%2011.748%2028.4406%2011.7803%2028.4876C11.8127%2028.5345%2011.8495%2028.578%2011.8906%2028.6179C11.9318%2028.6578%2011.9765%2028.6934%2012.0249%2028.7248C12.0733%2028.7562%2012.1244%2028.7826%2012.1783%2028.8042C12.2321%2028.8259%2012.2875%2028.8422%2012.3446%2028.8532C12.4017%2028.8642%2012.4596%2028.8697%2012.5178%2028.8698L16%2028.8042L16%2030.3241L11.0435%2030.3241C10.975%2030.3241%2010.9071%2030.3176%2010.8399%2030.3047C10.7727%2030.2917%2010.7076%2030.2725%2010.6443%2030.2471C10.581%2030.2217%2010.5206%2030.1906%2010.4637%2030.1537C10.4067%2030.1168%2010.3542%2030.0748%2010.3057%2030.0278C10.2573%2029.9809%2010.2138%2029.9298%2010.1758%2029.8745C10.1377%2029.8193%2010.1057%2029.7611%2010.0795%2029.6997C10.0533%2029.6383%2010.0335%2029.575%2010.0201%2029.5099C10.0068%2029.4448%2010%2029.379%2010%2029.3126L10%2026.0478L11.7047%2026L11.6308%2028.0099Z'%20fill='rgb(14,191,241)'%20fill-rule='evenodd'%20/%3e%3c/g%3e%3c/g%3e%3c/svg%3e",lI="data:image/svg+xml,%3csvg%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%20width='40.000000'%20height='40.000000'%20fill='none'%20customFrame='url(%23clipPath_9)'%3e%3cdefs%3e%3cclipPath%20id='clipPath_9'%3e%3crect%20width='40.000000'%20height='40.000000'%20x='0.000000'%20y='0.000000'%20rx='12.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_10'%3e%3crect%20width='24.000000'%20height='24.000000'%20x='8.000000'%20y='8.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_11'%3e%3crect%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='10.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3c/defs%3e%3crect%20id='3'%20width='40.000000'%20height='40.000000'%20x='0.000000'%20y='0.000000'%20rx='12.000000'%20fill='rgb(236,250,254)'%20/%3e%3cg%20id='画板%202310'%20customFrame='url(%23clipPath_10)'%3e%3crect%20id='画板%202310'%20width='24.000000'%20height='24.000000'%20x='8.000000'%20y='8.000000'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20/%3e%3cg%20id='人事服务'%3e%3cg%20id='ic_public_link'%20clip-path='url(%23clipPath_11)'%20customFrame='url(%23clipPath_11)'%3e%3crect%20id='ic_public_link'%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='10.000000'%20/%3e%3cpath%20id='path1'%20d='M9.9999%2019.9917C9.9999%2018.4292%209.99573%2016.8667%209.9999%2015.3042C9.99573%2014.5459%2010.0916%2013.7917%2010.2749%2013.0626C10.6874%2011.5126%2011.6957%2010.5917%2013.2457%2010.2334C14.0207%2010.0667%2014.8166%209.98756%2015.6082%2010.0001C18.6041%2010.0001%2021.5999%2010.0001%2024.5999%2010.0001C25.3541%209.99589%2026.1082%2010.0792%2026.8457%2010.2584C28.4416%2010.6459%2029.3999%2011.6584%2029.7624%2013.2501C29.9291%2014.0001%2030.0041%2014.7667%2029.9957%2015.5376C29.9957%2018.5667%2029.9957%2021.5959%2029.9957%2024.6209C29.9999%2025.3709%2029.9166%2026.1209%2029.7416%2026.8459C29.3499%2028.4459%2028.3332%2029.3959%2026.7457%2029.7626C25.9666%2029.9292%2025.1749%2030.0084%2024.3791%2029.9959C21.3957%2029.9959%2018.4124%2029.9959%2015.4291%2029.9959C14.6666%2030.0042%2013.9082%2029.9167%2013.1666%2029.7417C11.5624%2029.3542%2010.5999%2028.3376%2010.2374%2026.7376C10.0499%2025.9251%209.9999%2025.1126%209.9999%2024.2917C9.9999%2022.8584%209.9999%2021.4251%209.9999%2019.9917Z'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20fill-rule='evenodd'%20/%3e%3ccircle%20id='path2'%20cx='20'%20cy='20'%20r='10'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20/%3e%3cpath%20id='path3'%20d='M25.0333%2021.8666L26.9%2020C28.8083%2018.0916%2028.8083%2015%2026.9%2013.0958C24.9958%2011.1875%2021.9041%2011.1875%2020%2013.0958L18.1291%2014.9625M21.8666%2025.0333L20%2026.9C18.0916%2028.8083%2015%2028.8083%2013.0958%2026.9C11.1875%2024.9958%2011.1875%2021.9041%2013.0958%2020L14.9625%2018.1291'%20fill-rule='nonzero'%20stroke='rgb(14,191,241)'%20stroke-linecap='round'%20stroke-width='1.25'%20/%3e%3cpath%20id='pah4'%20d='M18.125%2021.875L21.875%2018.125'%20stroke='rgb(14,191,241)'%20stroke-linecap='round'%20stroke-linejoin='round'%20stroke-width='1.25'%20/%3e%3cpath%20id='path5'%20d='M25.8207%2019.2626L24.0457%2021.0376C23.7998%2021.2834%2023.6748%2021.5292%2023.6748%2021.7751C23.6748%2022.0209%2023.7998%2022.2667%2024.0457%2022.5126C24.1498%2022.6167%2024.2665%2022.6959%2024.3915%2022.7459C24.5123%2022.7917%2024.6415%2022.8167%2024.779%2022.8167C24.9207%2022.8167%2025.0498%2022.7917%2025.1665%2022.7459C25.2957%2022.6959%2025.4123%2022.6167%2025.5165%2022.5126L27.2915%2020.7334C27.8165%2020.2126%2028.2165%2019.6334%2028.4957%2019.0001C28.5082%2018.9667%2028.5248%2018.9334%2028.5373%2018.8959C28.554%2018.8626%2028.5665%2018.8292%2028.579%2018.7917C28.8332%2018.1501%2028.9582%2017.4584%2028.9582%2016.7209C28.9582%2015.9792%2028.8332%2015.2876%2028.579%2014.6459C28.5665%2014.6084%2028.554%2014.5751%2028.5373%2014.5417C28.5248%2014.5042%2028.5082%2014.4709%2028.4957%2014.4376C28.2165%2013.8042%2027.8165%2013.2292%2027.2915%2012.7042C26.7707%2012.1792%2026.1915%2011.7792%2025.5582%2011.5001C25.5248%2011.4876%2025.4915%2011.4709%2025.454%2011.4584C25.4207%2011.4417%2025.3873%2011.4292%2025.354%2011.4167C24.7082%2011.1667%2024.0165%2011.0417%2023.279%2011.0417C22.5373%2011.0417%2021.8457%2011.1667%2021.204%2011.4167C21.1665%2011.4292%2021.1332%2011.4417%2021.0998%2011.4584C21.0623%2011.4709%2021.029%2011.4876%2020.9957%2011.5001C20.3623%2011.7792%2019.7832%2012.1792%2019.2623%2012.7042L17.4832%2014.4792C17.379%2014.5834%2017.2998%2014.7001%2017.2498%2014.8292C17.204%2014.9501%2017.179%2015.0751%2017.179%2015.2167C17.179%2015.3542%2017.204%2015.4834%2017.2498%2015.6042C17.2998%2015.7292%2017.379%2015.8459%2017.4832%2015.9542C17.5915%2016.0584%2017.7082%2016.1376%2017.8332%2016.1876C17.954%2016.2334%2018.0832%2016.2584%2018.2207%2016.2584C18.3623%2016.2584%2018.4915%2016.2334%2018.6082%2016.1876C18.7373%2016.1376%2018.854%2016.0584%2018.9582%2015.9542L20.7332%2014.1751C21.0873%2013.8209%2021.4748%2013.5584%2021.8957%2013.3834C22.3165%2013.2084%2022.779%2013.1251%2023.279%2013.1251C23.7748%2013.1251%2024.2373%2013.2084%2024.6582%2013.3834C25.079%2013.5584%2025.4665%2013.8209%2025.8207%2014.1751C26.1748%2014.5292%2026.4373%2014.9167%2026.6123%2015.3376C26.7873%2015.7584%2026.8748%2016.2167%2026.8748%2016.7209C26.8748%2017.2209%2026.7873%2017.6792%2026.6123%2018.1001C26.4373%2018.5209%2026.1748%2018.9084%2025.8207%2019.2626ZM13.3832%2021.8959C13.5582%2021.4751%2013.8207%2021.0876%2014.1748%2020.7334L15.954%2018.9584C16.0582%2018.8542%2016.1373%2018.7376%2016.1873%2018.6084C16.2332%2018.4876%2016.2582%2018.3626%2016.2582%2018.2209C16.2582%2018.0834%2016.2332%2017.9542%2016.1873%2017.8334C16.1373%2017.7084%2016.0582%2017.5917%2015.954%2017.4834C15.7082%2017.2417%2015.4623%2017.1167%2015.2165%2017.1167C14.9707%2017.1167%2014.7248%2017.2417%2014.479%2017.4834L12.704%2019.2626C12.179%2019.7876%2011.779%2020.3626%2011.4998%2020.9959C11.4873%2021.0292%2011.4707%2021.0626%2011.4582%2021.1001C11.4415%2021.1334%2011.429%2021.1667%2011.4165%2021.2042C11.1665%2021.8459%2011.0415%2022.5376%2011.0415%2023.2792C11.0415%2024.0167%2011.1665%2024.7084%2011.4165%2025.3542C11.429%2025.3876%2011.4415%2025.4209%2011.4582%2025.4584C11.4707%2025.4917%2011.4873%2025.5251%2011.4998%2025.5584C11.779%2026.1917%2012.179%2026.7709%2012.704%2027.2917C13.2248%2027.8167%2013.804%2028.2167%2014.4373%2028.4959C14.4707%2028.5084%2014.504%2028.5251%2014.5415%2028.5376C14.5748%2028.5542%2014.6082%2028.5667%2014.6457%2028.5792C15.2873%2028.8292%2015.979%2028.9584%2016.7207%2028.9584C17.4582%2028.9584%2018.1498%2028.8292%2018.7915%2028.5792C18.829%2028.5667%2018.8623%2028.5542%2018.8957%2028.5376C18.9332%2028.5251%2018.9665%2028.5084%2018.9998%2028.4959C19.6332%2028.2167%2020.2123%2027.8167%2020.7332%2027.2917L22.5123%2025.5167C22.6165%2025.4126%2022.6957%2025.2959%2022.7457%2025.1667C22.7915%2025.0459%2022.8165%2024.9209%2022.8165%2024.7792C22.8165%2024.6417%2022.7915%2024.5126%2022.7457%2024.3917C22.6957%2024.2667%2022.6165%2024.1501%2022.5123%2024.0417C22.2665%2023.8001%2022.0207%2023.6751%2021.7748%2023.6751C21.529%2023.6751%2021.2832%2023.8001%2021.0373%2024.0417L19.2623%2025.8209C18.9082%2026.1751%2018.5207%2026.4376%2018.0998%2026.6126C17.679%2026.7876%2017.2165%2026.8751%2016.7207%2026.8751C16.2207%2026.8751%2015.7582%2026.7876%2015.3373%2026.6126C14.9165%2026.4376%2014.529%2026.1751%2014.1748%2025.8209C13.8207%2025.4667%2013.5582%2025.0792%2013.3832%2024.6584C13.2082%2024.2376%2013.1248%2023.7792%2013.1248%2023.2792C13.1248%2022.7751%2013.2082%2022.3167%2013.3832%2021.8959Z'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20fill-rule='evenodd'%20/%3e%3cpath%20id='path6'%20d='M21.8127%2016.7458C21.746%2016.7874%2021.6877%2016.8374%2021.6293%2016.8916L16.8918%2021.6291C16.8377%2021.6874%2016.7877%2021.7499%2016.746%2021.8124C16.7127%2021.8624%2016.6877%2021.9166%2016.6627%2021.9749C16.6377%2022.0374%2016.6168%2022.1041%2016.6043%2022.1708C16.5918%2022.2333%2016.5835%2022.2999%2016.5835%2022.3666C16.5835%2022.4333%2016.5918%2022.4999%2016.6043%2022.5666C16.6168%2022.6333%2016.6377%2022.6999%2016.6627%2022.7624C16.6877%2022.8166%2016.7127%2022.8708%2016.746%2022.9208C16.7877%2022.9874%2016.8377%2023.0499%2016.8918%2023.1041C16.946%2023.1583%2017.0085%2023.2083%2017.0752%2023.2499C17.1252%2023.2833%2017.1793%2023.3083%2017.2335%2023.3333C17.3002%2023.3583%2017.3627%2023.3791%2017.4293%2023.3916C17.496%2023.4041%2017.5627%2023.4124%2017.6293%2023.4124C17.696%2023.4124%2017.7627%2023.4041%2017.8252%2023.3916C17.8918%2023.3791%2017.9585%2023.3583%2018.021%2023.3333C18.0793%2023.3083%2018.1335%2023.2833%2018.1835%2023.2499C18.246%2023.2083%2018.3085%2023.1583%2018.3668%2023.1041L23.1043%2018.3666C23.1585%2018.3083%2023.2085%2018.2499%2023.2502%2018.1833C23.2835%2018.1333%2023.3085%2018.0791%2023.3335%2018.0208C23.3585%2017.9583%2023.3793%2017.8916%2023.3918%2017.8249C23.4043%2017.7624%2023.4127%2017.6958%2023.4127%2017.6291C23.4127%2017.5624%2023.4043%2017.4958%2023.3918%2017.4291C23.3793%2017.3624%2023.3585%2017.2999%2023.3335%2017.2333C23.3085%2017.1791%2023.2835%2017.1249%2023.2502%2017.0749C23.2085%2017.0083%2023.1585%2016.9458%2023.1043%2016.8916C23.046%2016.8374%2022.9877%2016.7874%2022.921%2016.7458C22.871%2016.7124%2022.8168%2016.6874%2022.7627%2016.6624C22.696%2016.6374%2022.6335%2016.6166%2022.5668%2016.6041C22.5002%2016.5916%2022.4335%2016.5833%2022.3668%2016.5833C22.3002%2016.5833%2022.2335%2016.5916%2022.171%2016.6041C22.1043%2016.6166%2022.0377%2016.6374%2021.9752%2016.6624C21.9168%2016.6874%2021.8627%2016.7124%2021.8127%2016.7458Z'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20fill-rule='evenodd'%20/%3e%3c/g%3e%3c/g%3e%3c/g%3e%3c/svg%3e",cI="data:image/svg+xml,%3csvg%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%20width='40.000000'%20height='40.000000'%20fill='none'%20customFrame='url(%23clipPath_0)'%3e%3cdefs%3e%3cclipPath%20id='clipPath_0'%3e%3crect%20width='40.000000'%20height='40.000000'%20x='0.000000'%20y='0.000000'%20rx='12.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_1'%3e%3crect%20width='24.000000'%20height='24.000000'%20x='8.000000'%20y='8.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_2'%3e%3crect%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='10.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3c/defs%3e%3crect%20id='1'%20width='40.000000'%20height='40.000000'%20x='0.000000'%20y='0.000000'%20rx='12.000000'%20fill='rgb(236,250,254)'%20/%3e%3cg%20id='车辆'%20clip-path='url(%23clipPath_1)'%20customFrame='url(%23clipPath_1)'%3e%3crect%20id='车辆'%20width='24.000000'%20height='24.000000'%20x='8.000000'%20y='8.000000'%20/%3e%3cg%20id='编组'%3e%3cg%20id='ic_public_qrcode'%20clip-path='url(%23clipPath_2)'%20customFrame='url(%23clipPath_2)'%3e%3crect%20id='ic_public_qrcode'%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='10.000000'%20/%3e%3cg%20id='ic_public_qrcode_1_1'%3e%3cpath%20id='ic_public_qrcode_2_0'%20d='M10.6273%2019.9924C10.6273%2018.5277%2010.6222%2017.0631%2010.6273%2015.5985C10.6243%2014.8898%2010.7114%2014.1836%2010.8865%2013.4968C11.2702%2012.0432%2012.2171%2011.1805%2013.6693%2010.8458C14.3974%2010.6885%2015.1411%2010.6148%2015.886%2010.6261C18.6946%2010.6261%2021.5035%2010.6261%2024.3127%2010.6261C25.0221%2010.6217%2025.7295%2010.7029%2026.4195%2010.8678C27.9156%2011.2339%2028.8134%2012.1816%2029.1554%2013.6725C29.3092%2014.3772%2029.3826%2015.097%2029.3744%2015.8182C29.3744%2018.6571%2029.3744%2021.4963%2029.3744%2024.3357C29.3782%2025.0383%2029.2973%2025.7388%2029.1334%2026.422C28.7673%2027.9189%2027.8153%2028.8123%2026.3243%2029.1543C25.5961%2029.311%2024.8524%2029.3847%2024.1076%2029.374C21.3107%2029.374%2018.514%2029.374%2015.7176%2029.374C15.0027%2029.3798%2014.2897%2029.2999%2013.5939%2029.136C12.0912%2028.7698%2011.189%2027.8178%2010.8477%2026.3195C10.6734%2025.5579%2010.6273%2024.7941%2010.6273%2024.0237C10.6273%2022.6802%2010.6273%2021.3364%2010.6273%2019.9924Z'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20fill-rule='nonzero'%20/%3e%3cpath%20id='ic_public_qrcode_2_0'%20d='M10.6273%2015.5985C10.6243%2014.8898%2010.7114%2014.1836%2010.8865%2013.4968C11.2702%2012.0432%2012.2171%2011.1805%2013.6693%2010.8458C14.3974%2010.6885%2015.1411%2010.6148%2015.886%2010.6261C18.6946%2010.6261%2021.5035%2010.6261%2024.3127%2010.6261C25.0221%2010.6217%2025.7295%2010.7029%2026.4195%2010.8678C27.9156%2011.2339%2028.8134%2012.1816%2029.1554%2013.6725C29.3092%2014.3772%2029.3826%2015.097%2029.3744%2015.8182C29.3744%2018.6571%2029.3744%2021.4963%2029.3744%2024.3357C29.3782%2025.0383%2029.2973%2025.7388%2029.1334%2026.422C28.7673%2027.9189%2027.8153%2028.8123%2026.3243%2029.1543C25.5961%2029.311%2024.8524%2029.3847%2024.1076%2029.374C21.3107%2029.374%2018.514%2029.374%2015.7176%2029.374C15.0027%2029.3798%2014.2897%2029.2999%2013.5939%2029.136C12.0912%2028.7698%2011.189%2027.8178%2010.8477%2026.3195C10.6734%2025.5579%2010.6273%2024.7941%2010.6273%2024.0237C10.6273%2022.6802%2010.6273%2021.3364%2010.6273%2019.9924C10.6273%2018.5277%2010.6222%2017.0631%2010.6273%2015.5985Z'%20fill-rule='nonzero'%20stroke='rgb(255,255,255)'%20stroke-opacity='0'%20stroke-width='1.25'%20/%3e%3cpath%20id='ic_public_qrcode_2_1'%20d='M10.6273%2015.5985C10.6243%2014.8898%2010.7114%2014.1836%2010.8865%2013.4968C11.2702%2012.0432%2012.2171%2011.1805%2013.6693%2010.8458C14.3974%2010.6885%2015.1411%2010.6148%2015.886%2010.6261C18.6946%2010.6261%2021.5035%2010.6261%2024.3127%2010.6261C25.0221%2010.6217%2025.7295%2010.7029%2026.4195%2010.8678C27.9156%2011.2339%2028.8134%2012.1816%2029.1554%2013.6725C29.3092%2014.3772%2029.3826%2015.097%2029.3744%2015.8182C29.3744%2018.6571%2029.3744%2021.4963%2029.3744%2024.3357C29.3782%2025.0383%2029.2973%2025.7388%2029.1334%2026.422C28.7673%2027.9189%2027.8153%2028.8123%2026.3243%2029.1543C25.5961%2029.311%2024.8524%2029.3847%2024.1076%2029.374C21.3107%2029.374%2018.514%2029.374%2015.7176%2029.374C15.0027%2029.3798%2014.2897%2029.2999%2013.5939%2029.136C12.0912%2028.7698%2011.189%2027.8178%2010.8477%2026.3195C10.6734%2025.5579%2010.6273%2024.7941%2010.6273%2024.0237C10.6273%2022.6802%2010.6273%2021.3364%2010.6273%2019.9924C10.6273%2018.5277%2010.6222%2017.0631%2010.6273%2015.5985Z'%20opacity='0.200000003'%20fill-rule='nonzero'%20stroke='rgb(255,255,255)'%20stroke-opacity='0'%20stroke-width='1.25'%20/%3e%3ccircle%20id='ic_public_qrcode_2_2'%20cx='20'%20cy='20'%20r='10'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20/%3e%3cpath%20id='ic_public_qrcode_2_3'%20d='M17.5%2011.25C17.9602%2011.25%2018.3333%2011.6231%2018.3333%2012.0833L18.3333%2017.5C18.3333%2017.9602%2017.9602%2018.3333%2017.5%2018.3333L12.0833%2018.3333C11.6231%2018.3333%2011.25%2017.9602%2011.25%2017.5L11.25%2012.0833C11.25%2011.6231%2011.6231%2011.25%2012.0833%2011.25L17.5%2011.25ZM17.5%2021.6667C17.9602%2021.6667%2018.3333%2022.0398%2018.3333%2022.5L18.3333%2027.9167C18.3333%2028.3769%2017.9602%2028.75%2017.5%2028.75L12.0833%2028.75C11.6231%2028.75%2011.25%2028.3769%2011.25%2027.9167L11.25%2022.5C11.25%2022.0398%2011.6231%2021.6667%2012.0833%2021.6667L17.5%2021.6667ZM27.9167%2011.25C28.3769%2011.25%2028.75%2011.6231%2028.75%2012.0833L28.75%2017.5C28.75%2017.9602%2028.3769%2018.3333%2027.9167%2018.3333L22.5%2018.3333C22.0398%2018.3333%2021.6667%2017.9602%2021.6667%2017.5L21.6667%2012.0833C21.6667%2011.6231%2022.0398%2011.25%2022.5%2011.25L27.9167%2011.25Z'%20fill-rule='evenodd'%20stroke='rgb(14,191,241)'%20stroke-linecap='round'%20stroke-linejoin='round'%20stroke-width='1.25'%20/%3e%3cpath%20id='ic_public_qrcode_2_4'%20d='M17.5002%2010.8333C18.1905%2010.8333%2018.7502%2011.3929%2018.7502%2012.0833L18.7502%2017.4999C18.7502%2018.1903%2018.1905%2018.7499%2017.5002%2018.7499L12.0835%2018.7499C11.3931%2018.7499%2010.8335%2018.1903%2010.8335%2017.4999L10.8335%2012.0833C10.8335%2011.3929%2011.3931%2010.8333%2012.0835%2010.8333L17.5002%2010.8333ZM17.5002%2011.6666L12.0835%2011.6666C11.8534%2011.6666%2011.6668%2011.8531%2011.6668%2012.0833L11.6668%2017.4999C11.6668%2017.73%2011.8534%2017.9166%2012.0835%2017.9166L17.5002%2017.9166C17.7303%2017.9166%2017.9168%2017.73%2017.9168%2017.4999L17.9168%2012.0833C17.9168%2011.8531%2017.7303%2011.6666%2017.5002%2011.6666ZM17.5002%2021.2499C18.1905%2021.2499%2018.7502%2021.8096%2018.7502%2022.4999L18.7502%2027.9166C18.7502%2028.6069%2018.1905%2029.1666%2017.5002%2029.1666L12.0835%2029.1666C11.3931%2029.1666%2010.8335%2028.6069%2010.8335%2027.9166L10.8335%2022.4999C10.8335%2021.8096%2011.3931%2021.2499%2012.0835%2021.2499L17.5002%2021.2499ZM17.5002%2022.0833L12.0835%2022.0833C11.8534%2022.0833%2011.6668%2022.2698%2011.6668%2022.4999L11.6668%2027.9166C11.6668%2028.1467%2011.8534%2028.3333%2012.0835%2028.3333L17.5002%2028.3333C17.7303%2028.3333%2017.9168%2028.1467%2017.9168%2027.9166L17.9168%2022.4999C17.9168%2022.2698%2017.7303%2022.0833%2017.5002%2022.0833ZM27.9168%2010.8333C28.6072%2010.8333%2029.1668%2011.3929%2029.1668%2012.0833L29.1668%2017.4999C29.1668%2018.1903%2028.6072%2018.7499%2027.9168%2018.7499L22.5002%2018.7499C21.8098%2018.7499%2021.2502%2018.1903%2021.2502%2017.4999L21.2502%2012.0833C21.2502%2011.3929%2021.8098%2010.8333%2022.5002%2010.8333L27.9168%2010.8333ZM27.9168%2011.6666L22.5002%2011.6666C22.27%2011.6666%2022.0835%2011.8531%2022.0835%2012.0833L22.0835%2017.4999C22.0835%2017.73%2022.27%2017.9166%2022.5002%2017.9166L27.9168%2017.9166C28.1469%2017.9166%2028.3335%2017.73%2028.3335%2017.4999L28.3335%2012.0833C28.3335%2011.8531%2028.1469%2011.6666%2027.9168%2011.6666Z'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20fill-rule='nonzero'%20/%3e%3cpath%20id='ic_public_qrcode_2_4'%20d='M18.7502%2012.0833L18.7502%2017.4999C18.7502%2018.1903%2018.1905%2018.7499%2017.5002%2018.7499L12.0835%2018.7499C11.3931%2018.7499%2010.8335%2018.1903%2010.8335%2017.4999L10.8335%2012.0833C10.8335%2011.3929%2011.3931%2010.8333%2012.0835%2010.8333L17.5002%2010.8333C18.1905%2010.8333%2018.7502%2011.3929%2018.7502%2012.0833ZM12.0835%2011.6666C11.8534%2011.6666%2011.6668%2011.8531%2011.6668%2012.0833L11.6668%2017.4999C11.6668%2017.73%2011.8534%2017.9166%2012.0835%2017.9166L17.5002%2017.9166C17.7303%2017.9166%2017.9168%2017.73%2017.9168%2017.4999L17.9168%2012.0833C17.9168%2011.8531%2017.7303%2011.6666%2017.5002%2011.6666L12.0835%2011.6666ZM18.7502%2022.4999L18.7502%2027.9166C18.7502%2028.6069%2018.1905%2029.1666%2017.5002%2029.1666L12.0835%2029.1666C11.3931%2029.1666%2010.8335%2028.6069%2010.8335%2027.9166L10.8335%2022.4999C10.8335%2021.8096%2011.3931%2021.2499%2012.0835%2021.2499L17.5002%2021.2499C18.1905%2021.2499%2018.7502%2021.8096%2018.7502%2022.4999ZM12.0835%2022.0833C11.8534%2022.0833%2011.6668%2022.2698%2011.6668%2022.4999L11.6668%2027.9166C11.6668%2028.1467%2011.8534%2028.3333%2012.0835%2028.3333L17.5002%2028.3333C17.7303%2028.3333%2017.9168%2028.1467%2017.9168%2027.9166L17.9168%2022.4999C17.9168%2022.2698%2017.7303%2022.0833%2017.5002%2022.0833L12.0835%2022.0833ZM29.1668%2012.0833L29.1668%2017.4999C29.1668%2018.1903%2028.6072%2018.7499%2027.9168%2018.7499L22.5002%2018.7499C21.8098%2018.7499%2021.2502%2018.1903%2021.2502%2017.4999L21.2502%2012.0833C21.2502%2011.3929%2021.8098%2010.8333%2022.5002%2010.8333L27.9168%2010.8333C28.6072%2010.8333%2029.1668%2011.3929%2029.1668%2012.0833ZM22.5002%2011.6666C22.27%2011.6666%2022.0835%2011.8531%2022.0835%2012.0833L22.0835%2017.4999C22.0835%2017.73%2022.27%2017.9166%2022.5002%2017.9166L27.9168%2017.9166C28.1469%2017.9166%2028.3335%2017.73%2028.3335%2017.4999L28.3335%2012.0833C28.3335%2011.8531%2028.1469%2011.6666%2027.9168%2011.6666L22.5002%2011.6666Z'%20fill-rule='nonzero'%20stroke='rgb(255,255,255)'%20stroke-opacity='0'%20stroke-linejoin='round'%20stroke-width='1.25'%20/%3e%3cpath%20id='ic_public_qrcode_2_5'%20d='M27.9165%2021.6667L27.9165%2024.5834L28.7498%2024.5834L28.7498%2021.6667L27.9165%2021.6667ZM24.5832%2021.6667L24.5832%2022.639L24.5828%2022.6388L24.5832%2024.5834L23.6109%2024.5834L23.6107%2022.6388L21.6665%2022.639L21.6665%2021.6667L24.5832%2021.6667ZM21.6665%2025.8334L21.6665%2028.7501L22.4998%2028.7501L22.4998%2025.8334L21.6665%2025.8334ZM27.9165%2027.9167L27.9165%2028.7501L28.7498%2028.7501L28.7498%2027.9167L27.9165%2027.9167ZM25.8332%2025.8334L25.8332%2026.6667L26.6665%2026.6667L26.6665%2025.8334L25.8332%2025.8334Z'%20fill='rgb(14,191,241)'%20fill-rule='nonzero'%20/%3e%3cpath%20id='ic_public_qrcode_2_5'%20d='M27.9165%2024.5834L28.7498%2024.5834L28.7498%2021.6667L27.9165%2021.6667L27.9165%2024.5834ZM24.5832%2022.639L24.5828%2022.6388L24.5832%2024.5834L23.6109%2024.5834L23.6107%2022.6388L21.6665%2022.639L21.6665%2021.6667L24.5832%2021.6667L24.5832%2022.639ZM21.6665%2028.7501L22.4998%2028.7501L22.4998%2025.8334L21.6665%2025.8334L21.6665%2028.7501ZM27.9165%2028.7501L28.7498%2028.7501L28.7498%2027.9167L27.9165%2027.9167L27.9165%2028.7501ZM25.8332%2026.6667L26.6665%2026.6667L26.6665%2025.8334L25.8332%2025.8334L25.8332%2026.6667Z'%20fill-rule='nonzero'%20stroke='rgb(14,191,241)'%20stroke-linejoin='round'%20stroke-width='1.25'%20/%3e%3cpath%20id='ic_public_qrcode_2_6'%20d='M14.375%2014.375L14.375%2015.2083L15.2083%2015.2083L15.2083%2014.375L14.375%2014.375ZM14.375%2024.7917L14.375%2025.625L15.2083%2025.625L15.2083%2024.7917L14.375%2024.7917ZM24.7917%2014.375L24.7917%2015.2083L25.625%2015.2083L25.625%2014.375L24.7917%2014.375Z'%20fill='rgb(14,191,241)'%20fill-rule='nonzero'%20/%3e%3cpath%20id='ic_public_qrcode_2_6'%20d='M14.375%2015.2083L15.2083%2015.2083L15.2083%2014.375L14.375%2014.375L14.375%2015.2083ZM14.375%2025.625L15.2083%2025.625L15.2083%2024.7917L14.375%2024.7917L14.375%2025.625ZM24.7917%2015.2083L25.625%2015.2083L25.625%2014.375L24.7917%2014.375L24.7917%2015.2083Z'%20fill-rule='nonzero'%20stroke='rgb(14,191,241)'%20stroke-linejoin='round'%20stroke-width='1.25'%20/%3e%3c/g%3e%3c/g%3e%3c/g%3e%3c/g%3e%3c/svg%3e",uI="data:image/svg+xml,%3csvg%20viewBox='0%200%2012%2012'%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%20width='12.000000'%20height='12.000000'%20fill='none'%3e%3cdefs%3e%3cfilter%20id='pixso_custom_mask_type_luminance'%3e%3cfeColorMatrix%20type='matrix'%20values='1%200%200%200%200%200%201%200%200%200%200%200%201%200%200%200%200%200%201%200%20'%20/%3e%3c/filter%3e%3c/defs%3e%3cmask%20id='mask_0'%20width='11.999876'%20height='11.999876'%20x='0.000000'%20y='0.000000'%20maskUnits='userSpaceOnUse'%3e%3cg%20filter='url(%23pixso_custom_mask_type_luminance)'%3e%3cg%20id='mask401_19830'%3e%3cpath%20id='蒙版'%20d='M0%200L11.9999%200L11.9999%2011.9999L0%2011.9999L0%200ZM2.69992%201.34999L8.09977%201.34999C9.5082%201.34999%2010.6498%202.49167%2010.6498%203.89998L10.6498%209.2999C10.6498%2010.7082%209.5082%2011.8499%208.09977%2011.8499L2.69992%2011.8499C1.29149%2011.8499%200.149901%2010.7082%200.149901%209.2999L0.149901%203.89998C0.149901%202.49167%201.29149%201.34999%202.69992%201.34999Z'%20fill='rgb(196,196,196)'%20fill-rule='evenodd'%20/%3e%3c/g%3e%3c/g%3e%3c/mask%3e%3crect%20id='ic_public_copy'%20width='12.000000'%20height='12.000000'%20x='0.000000'%20y='0.000000'%20/%3e%3crect%20id='ic_public_copy-复制/base/ic_public_copy'%20width='11.999876'%20height='11.999876'%20x='0.000000'%20y='0.000000'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20/%3e%3cpath%20id='path1'%20d='M0.000134537%205.99497C0.000134537%205.05748%20-0.00236544%204.11999%200.000134537%203.1825C-0.00236544%202.72751%200.055134%202.27501%200.165133%201.83752C0.41263%200.907526%201.01762%200.355032%201.94761%200.140034C2.41261%200.040035%202.8901%20-0.00746449%203.3651%203.54269e-05C5.16258%203.54269e-05%206.96006%203.54269e-05%208.76004%203.54269e-05C9.21254%20-0.00246455%209.66503%200.0475349%2010.1075%200.155034C11.065%200.387531%2011.64%200.995025%2011.8575%201.95002C11.9575%202.40001%2012.005%202.86001%2011.9975%203.3225C11.9975%205.13998%2011.9975%206.95746%2011.9975%208.77244C12%209.22244%2011.95%209.67243%2011.845%2010.1099C11.61%2011.0674%2011%2011.6374%2010.0475%2011.8574C9.58003%2011.9574%209.10504%2012.0049%208.62754%2011.9974C6.83756%2011.9974%205.04758%2011.9974%203.2576%2011.9974C2.80011%2012.0024%202.34511%2011.9499%201.90011%2011.8449C0.937625%2011.6124%200.360131%2011.0024%200.142633%2010.0424C0.0301342%209.55494%200.000134537%209.06744%200.000134537%208.57495C0.000134537%207.71495%200.000134537%206.85496%200.000134537%205.99497Z'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20fill-rule='evenodd'%20/%3e%3ccircle%20id='path2'%20cx='5.99993801'%20cy='5.99993801'%20r='5.99993801'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20/%3e%3cg%20id='mask'%20mask='url(%23mask_0)'%3e%3cg%20id='组合%208'%3e%3cpath%20id='path'%20d='M11.1%203.89993L11.1%206.8999C11.1%208.55488%209.75502%209.89737%208.10004%209.89737L5.10007%209.89737C3.44258%209.89737%202.1001%208.55488%202.1001%206.8999L2.1001%203.89993C2.1001%202.24245%203.44258%200.897461%205.10007%200.897461L8.10004%200.897461C9.75502%200.897461%2011.1%202.24245%2011.1%203.89993Z'%20fill-rule='nonzero'%20stroke='rgb(25,25,25)'%20stroke-linejoin='round'%20stroke-width='0.749992251'%20/%3e%3c/g%3e%3c/g%3e%3cpath%20id='path4'%20d='M2.10008%202.39746L8.10002%202.39746C8.92751%202.39746%209.6%203.06995%209.6%203.89995L9.6%209.89738C9.6%2010.7274%208.92751%2011.3999%208.10002%2011.3999L2.10008%2011.3999C1.27009%2011.3999%200.600098%2010.7274%200.600098%209.89738L0.600098%203.89995C0.600098%203.06995%201.27009%202.39746%202.10008%202.39746Z'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20fill-rule='evenodd'%20/%3e%3cpath%20id='path4'%20d='M9.6%203.89995L9.6%209.89738C9.6%2010.7274%208.92751%2011.3999%208.10002%2011.3999L2.10008%2011.3999C1.27009%2011.3999%200.600098%2010.7274%200.600098%209.89738L0.600098%203.89995C0.600098%203.06995%201.27009%202.39746%202.10008%202.39746L8.10002%202.39746C8.92751%202.39746%209.6%203.06995%209.6%203.89995Z'%20fill-rule='nonzero'%20stroke='rgb(25,25,25)'%20stroke-linejoin='round'%20stroke-width='0.749992251'%20/%3e%3c/svg%3e",dI="https://agent.opentiny.design/tiny-robot",dm="https://ai.opentiny.design/next-remoter",pm=e=>[{action:"qr-code",show:!0,text:"扫码登录",desc:"使用手机遥控页面",icon:cI},{action:"ai-chat",show:!0,text:"打开对话框",desc:"支持在网页端操作AI",icon:iI},{action:"remote-url",show:!0,text:"遥控器链接",desc:`${e.remoteUrl}`,active:!0,tip:e.remoteUrl,showCopyIcon:!0,icon:lI},{action:"remote-control",show:!0,text:"识别码",desc:`${e.sessionId.slice(-6)}`,know:!0,showCopyIcon:!0,icon:aI}];class pI{constructor(t){if(this.isExpanded=!1,this.getImageUrl=n=>{if(!n)return;const r=new Image;return r.src=n,r},this.renderItem=()=>{this.menuItems.filter(n=>n.show!==!1).map(n=>{const r=document.getElementById(`tiny-remoter-icon-item-${n.action}`);if(!r)return;r.innerHTML="";const o=this.getImageUrl(n.icon);o&&r.appendChild(o)})},this.readyTips=n=>{const r=document.getElementById(n);r&&new sI(r,{content:"复制",placement:"top",trigger:"hover"})},!t.sessionId)throw new Error("sessionId is required");this.options={...t,qrCodeUrl:t.qrCodeUrl||dm,remoteUrl:t.remoteUrl||dI},this.menuItems=this.mergeMenuItems(t.menuItems),this.init()}get sessionPrefix(){var t;return(t=this.options.qrCodeUrl)!=null&&t.includes("?")?"&sessionId=":"?sessionId="}mergeMenuItems(t){return t?pm(this.options).map(n=>{const r=t.find(o=>o.action===n.action);return r?{...n,...r,show:r.show!==void 0?r.show:n.show}:n}):pm(this.options)}init(){this.createFloatingBlock(),this.createDropdownMenu(),this.bindEvents(),this.addStyles()}createFloatingBlock(){this.floatingBlock=document.createElement("div"),this.floatingBlock.className="tiny-remoter-floating-block",this.floatingBlock.innerHTML=`
102
136
  <div class="tiny-remoter-floating-block__icon">
103
- <img style="display: block; width: 56px;" src="${Rm}/svgs/logo-next-no-bg-left.svg" alt="icon" />
137
+ <img style="display: block; width: 56px;" src="${dm}/svgs/logo-next-no-bg-left.svg" alt="icon" />
104
138
  </div>
105
- `,document.body.appendChild(this.floatingBlock)}createDropdownMenu(){this.dropdownMenu=document.createElement("div"),this.dropdownMenu.className="tiny-remoter-floating-dropdown";const e=this.menuItems.filter(r=>r.show!==!1).map(r=>`
106
- <div class="tiny-remoter-dropdown-item" data-action="${r.action}">
107
- <div class="tiny-remoter-dropdown-item__icon">
108
- ${r.icon}
139
+ `,document.body.appendChild(this.floatingBlock)}createDropdownMenu(){this.dropdownMenu=document.createElement("div"),this.dropdownMenu.className="tiny-remoter-floating-dropdown";const t=this.menuItems.filter(n=>n.show!==!1).map(n=>`
140
+ <div class="tiny-remoter-dropdown-item" data-action="${n.action}">
141
+ <div id="tiny-remoter-icon-item-${n.action}" class="tiny-remoter-dropdown-item__icon">
109
142
  </div>
110
- <span title="${r.tip}">${r.text}</span>
111
- ${r.showCopyIcon?`
112
- <div class="tiny-remoter-copy-icon" data-action="${r.action}">
113
- <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
114
- <path d="M16 1H4C2.9 1 2 1.9 2 3V17H4V3H16V1ZM19 5H8C6.9 5 6 5.9 6 7V21C6 22.1 6.9 23 8 23H19C20.1 23 21 22.1 21 21V7C21 5.9 20.1 5 19 5ZM19 21H8V7H19V21Z" fill="currentColor"/>
115
- </svg>
143
+ <div class="tiny-remoter-dropdown-item__content">
144
+ <div title="${n.tip}">${n.text}</div>
145
+ <div class="tiny-remoter-dropdown-item__desc-wrapper">
146
+ <div class="tiny-remoter-dropdown-item__desc ${n.active?"tiny-remoter-dropdown-item__desc--active":""} ${n.know?"tiny-remoter-dropdown-item__desc--know":""}">${n.desc}</div>
147
+ <div>
148
+ ${n.showCopyIcon?`
149
+ <div class="tiny-remoter-copy-icon" id="${n.action}" data-action="${n.action}">
150
+ <img src="${uI}"/>
151
+ </div>
152
+ `:""}
153
+ </div>
116
154
  </div>
117
- `:""}
155
+ </div>
118
156
  </div>
119
- `).join("");this.dropdownMenu.innerHTML=e,document.body.appendChild(this.dropdownMenu)}bindEvents(){this.floatingBlock.addEventListener("click",()=>{this.toggleDropdown()}),this.dropdownMenu.addEventListener("click",e=>{const r=e.target,a=r.closest(".tiny-remoter-copy-icon");if(a){e.stopPropagation();const o=a.dataset.action;o&&this.handleAction(o);return}const n=r.closest(".tiny-remoter-dropdown-item"),s=n==null?void 0:n.dataset.action;s&&this.handleAction(s)}),document.addEventListener("click",e=>{const r=e.target;!this.floatingBlock.contains(r)&&!this.dropdownMenu.contains(r)&&this.closeDropdown()}),document.addEventListener("keydown",e=>{e.key==="Escape"&&this.closeDropdown()})}toggleDropdown(){this.isExpanded?this.closeDropdown():this.openDropdown()}openDropdown(){this.isExpanded=!0,this.floatingBlock.classList.add("expanded"),this.dropdownMenu.classList.add("show")}closeDropdown(){this.isExpanded=!1,this.floatingBlock.classList.remove("expanded"),this.dropdownMenu.classList.remove("show")}handleAction(e){switch(e){case"qr-code":this.showQRCode();break;case"ai-chat":this.showAIChat();break;case"remote-control":this.copyRemoteControl();break;case"remote-url":this.copyRemoteURL();break}this.closeDropdown()}copyRemoteControl(){this.copyToClipboard(this.options.sessionId.slice(-6))}copyRemoteURL(){this.copyToClipboard(this.options.remoteUrl+this.sessionPrefix+this.options.sessionId)}async copyToClipboard(e){try{if(navigator.clipboard&&window.isSecureContext)await navigator.clipboard.writeText(e),this.showCopyFeedback(!0);else{const r=document.createElement("textarea");r.value=e,r.style.position="fixed",r.style.left="-999999px",r.style.top="-999999px",document.body.appendChild(r),r.focus(),r.select();const a=document.execCommand("copy");document.body.removeChild(r),a?this.showCopyFeedback(!0):this.showCopyFeedback(!1)}}catch(r){console.error("复制失败:",r),this.showCopyFeedback(!1)}}showCopyFeedback(e){const r=e?"复制成功!":"复制失败,请手动复制",a=document.createElement("div");a.className=`tiny-remoter-copy-feedback ${e?"success":"error"}`,a.textContent=r,document.body.appendChild(a),setTimeout(()=>a.classList.add("show"),10),setTimeout(()=>{a.classList.remove("show"),setTimeout(()=>{a.parentNode&&a.parentNode.removeChild(a)},300)},1500)}async showQRCode(){const r=await new Cm((this.options.qrCodeUrl||"")+this.sessionPrefix+this.options.sessionId,{}).toDataURL(),a=this.createModal("扫码前往智能遥控器",`
157
+ `).join("");this.dropdownMenu.innerHTML=t,document.body.appendChild(this.dropdownMenu),this.renderItem(),this.readyTips("remote-control"),this.readyTips("remote-url")}bindEvents(){this.floatingBlock.addEventListener("click",()=>{this.toggleDropdown()}),this.dropdownMenu.addEventListener("click",t=>{const n=t.target,r=n.closest(".tiny-remoter-copy-icon");if(r){t.stopPropagation();const i=r.dataset.action;i&&this.handleAction(i);return}const o=n.closest(".tiny-remoter-dropdown-item"),s=o==null?void 0:o.dataset.action;s&&this.handleAction(s)}),document.addEventListener("click",t=>{const n=t.target;!this.floatingBlock.contains(n)&&!this.dropdownMenu.contains(n)&&this.closeDropdown()}),document.addEventListener("keydown",t=>{t.key==="Escape"&&this.closeDropdown()})}toggleDropdown(){this.isExpanded?this.closeDropdown():this.openDropdown()}openDropdown(){this.isExpanded=!0,this.floatingBlock.classList.add("expanded"),this.dropdownMenu.classList.add("show")}closeDropdown(){this.isExpanded=!1,this.floatingBlock.classList.remove("expanded"),this.dropdownMenu.classList.remove("show")}handleAction(t){switch(t){case"qr-code":this.showQRCode();break;case"ai-chat":this.showAIChat();break;case"remote-control":this.copyRemoteControl();break;case"remote-url":this.copyRemoteURL();break}this.closeDropdown()}copyRemoteControl(){this.copyToClipboard(this.options.sessionId.slice(-6))}copyRemoteURL(){this.copyToClipboard(this.options.remoteUrl+this.sessionPrefix+this.options.sessionId)}async copyToClipboard(t){try{if(navigator.clipboard&&window.isSecureContext)await navigator.clipboard.writeText(t),this.showCopyFeedback(!0);else{const n=document.createElement("textarea");n.value=t,n.style.position="fixed",n.style.left="-999999px",n.style.top="-999999px",document.body.appendChild(n),n.focus(),n.select();const r=document.execCommand("copy");document.body.removeChild(n),r?this.showCopyFeedback(!0):this.showCopyFeedback(!1)}}catch(n){console.error("复制失败:",n),this.showCopyFeedback(!1)}}showCopyFeedback(t){const n=t?"复制成功!":"复制失败,请手动复制",r=document.createElement("div");r.className=`tiny-remoter-copy-feedback ${t?"success":"error"}`,r.textContent=n,document.body.appendChild(r),setTimeout(()=>r.classList.add("show"),10),setTimeout(()=>{r.classList.remove("show"),setTimeout(()=>{r.parentNode&&r.parentNode.removeChild(r)},300)},1500)}async showQRCode(){const n=await new cm((this.options.qrCodeUrl||"")+this.sessionPrefix+this.options.sessionId,{}).toDataURL(),r=this.createModal("扫码前往智能遥控器",`
120
158
  <div style="text-align: center; padding: 32px;">
121
159
  <!-- 二维码容器 - 添加渐变背景和阴影效果 -->
122
160
  <div style="
@@ -154,7 +192,7 @@ Minimum version required to store current data is: `+s+`.
154
192
  position: relative;
155
193
  z-index: 1;
156
194
  ">
157
- <img src="${r}" alt="二维码" style="
195
+ <img src="${n}" alt="二维码" style="
158
196
  width: 100%;
159
197
  height: 100%;
160
198
  object-fit: contain;
@@ -197,18 +235,18 @@ Minimum version required to store current data is: `+s+`.
197
235
  <span>支持微信、浏览器等多种方式</span>
198
236
  </div>
199
237
  </div>
200
- `);this.showModal(a)}showAIChat(){var e,r;(r=(e=this.options).onShowAIChat)==null||r.call(e)}createModal(e,r){const a=document.createElement("div");a.className="tiny-remoter-floating-modal",a.innerHTML=`
238
+ `);this.showModal(r)}showAIChat(){var t,n;(n=(t=this.options).onShowAIChat)==null||n.call(t)}createModal(t,n){const r=document.createElement("div");r.className="tiny-remoter-floating-modal",r.innerHTML=`
201
239
  <div class="tiny-remoter-modal-overlay"></div>
202
240
  <div class="tiny-remoter-modal-content">
203
241
  <div class="tiny-remoter-modal-header">
204
- <h3>${e}</h3>
242
+ <h3>${t}</h3>
205
243
  <button class="tiny-remoter-modal-close">&times;</button>
206
244
  </div>
207
245
  <div class="tiny-remoter-modal-body">
208
- ${r}
246
+ ${n}
209
247
  </div>
210
248
  </div>
211
- `;const n=a.querySelector(".tiny-remoter-modal-close"),s=a.querySelector(".tiny-remoter-modal-overlay");return n.addEventListener("click",()=>this.hideModal(a)),s.addEventListener("click",()=>this.hideModal(a)),a}showModal(e){document.body.appendChild(e),setTimeout(()=>e.classList.add("show"),10)}hideModal(e){e.classList.remove("show"),setTimeout(()=>{e.parentNode&&e.parentNode.removeChild(e)},100)}addStyles(){const e=document.createElement("style");e.textContent=`
249
+ `;const o=r.querySelector(".tiny-remoter-modal-close"),s=r.querySelector(".tiny-remoter-modal-overlay");return o.addEventListener("click",()=>this.hideModal(r)),s.addEventListener("click",()=>this.hideModal(r)),r}showModal(t){document.body.appendChild(t),setTimeout(()=>t.classList.add("show"),10)}hideModal(t){t.classList.remove("show"),setTimeout(()=>{t.parentNode&&t.parentNode.removeChild(t)},100)}addStyles(){const t=document.createElement("style");t.textContent=`
212
250
  /* 浮动块样式 */
213
251
  .tiny-remoter-floating-block {
214
252
  position: fixed;
@@ -246,15 +284,17 @@ Minimum version required to store current data is: `+s+`.
246
284
  bottom: 100px;
247
285
  right: 30px;
248
286
  background: white;
249
- border-radius: 16px;
287
+ border-radius: 18px;
250
288
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.15);
251
- padding: 8px;
289
+ padding: 24px 24px 0px 24px;
252
290
  opacity: 0;
253
291
  visibility: hidden;
254
292
  transform: translateY(20px) scale(0.95);
255
293
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
256
294
  z-index: 999;
257
295
  min-width: 200px;
296
+ width: 223px;
297
+ height: auto;
258
298
  }
259
299
 
260
300
  .tiny-remoter-floating-dropdown.show {
@@ -266,12 +306,16 @@ Minimum version required to store current data is: `+s+`.
266
306
  .tiny-remoter-dropdown-item {
267
307
  display: flex;
268
308
  align-items: center;
269
- gap: 12px;
270
- padding: 12px 16px;
271
309
  border-radius: 12px;
272
310
  cursor: pointer;
273
311
  transition: all 0.2s ease;
274
312
  color: #333;
313
+ margin-bottom: 24px;
314
+ height: 40px;
315
+ }
316
+
317
+ .tiny-remoter-dropdown-item:last-child {
318
+ margin-bottom: 32px;
275
319
  }
276
320
 
277
321
  .tiny-remoter-dropdown-item > span {
@@ -282,22 +326,48 @@ Minimum version required to store current data is: `+s+`.
282
326
  white-space: nowrap;
283
327
  }
284
328
 
285
- .tiny-remoter-dropdown-item:hover {
286
- background: #f8f9fa;
287
- transform: translateX(4px);
288
- }
289
-
290
329
  .tiny-remoter-dropdown-item__icon {
291
330
  display: flex;
292
331
  align-items: center;
293
332
  justify-content: center;
294
- width: 32px;
295
- height: 32px;
333
+ width: 40px;
334
+ height: 40px;
296
335
  background: #f8f9fa;
297
336
  border-radius: 8px;
298
337
  color: #667eea;
299
338
  }
300
339
 
340
+ .tiny-remoter-dropdown-item__content {
341
+ flex: 1;
342
+ display: flex;
343
+ flex-direction: column;
344
+ gap: 4px;
345
+ overflow: hidden;
346
+ font-size: 12px;
347
+ margin-left: 16px;
348
+ }
349
+
350
+ .tiny-remoter-dropdown-item__desc-wrapper {
351
+ display: flex;
352
+ align-items: center;
353
+ gap: 4px;
354
+ }
355
+
356
+ .tiny-remoter-dropdown-item__desc {
357
+ color: #808080;
358
+ overflow: hidden;
359
+ white-space: nowrap;
360
+ text-overflow: ellipsis;
361
+ }
362
+
363
+ .tiny-remoter-dropdown-item__desc--active {
364
+ color: #1476ff;
365
+ }
366
+
367
+ .tiny-remoter-dropdown-item__desc--know {
368
+ color: #191919;
369
+ }
370
+
301
371
  /* 复制图标样式 */
302
372
  .tiny-remoter-copy-icon {
303
373
  display: flex;
@@ -486,13 +556,6 @@ Minimum version required to store current data is: `+s+`.
486
556
  color: white;
487
557
  }
488
558
 
489
- .tiny-remoter-dropdown-item:hover {
490
- background: #2a2a2a;
491
- }
492
-
493
- .tiny-remoter-dropdown-item__icon {
494
- background: #2a2a2a;
495
- }
496
559
 
497
560
  .tiny-remoter-copy-icon {
498
561
  background: #2a2a2a;
@@ -517,4 +580,4 @@ Minimum version required to store current data is: `+s+`.
517
580
  color: white;
518
581
  }
519
582
  }
520
- `,document.head.appendChild(e)}destroy(){this.floatingBlock.parentNode&&this.floatingBlock.parentNode.removeChild(this.floatingBlock),this.dropdownMenu.parentNode&&this.dropdownMenu.parentNode.removeChild(this.dropdownMenu)}}const WC=(t={})=>new JC(t);Ir.AgentModelProvider=aC,Ir.QrCode=Cm,Ir.createRemoter=WC,Ir.getAISDKTools=Al,Object.defineProperty(Ir,Symbol.toStringTag,{value:"Module"})});
583
+ `,document.head.appendChild(t)}destroy(){this.floatingBlock.parentNode&&this.floatingBlock.parentNode.removeChild(this.floatingBlock),this.dropdownMenu.parentNode&&this.dropdownMenu.parentNode.removeChild(this.dropdownMenu)}}const fI=(e={})=>new pI(e);un.AgentModelProvider=gk,un.QrCode=cm,un.createRemoter=fI,un.getAISDKTools=F2,Object.defineProperty(un,Symbol.toStringTag,{value:"Module"})});